001/* 002 GRANITE DATA SERVICES 003 Copyright (C) 2011 GRANITE DATA SERVICES S.A.S. 004 005 This file is part of Granite Data Services. 006 007 Granite Data Services is free software; you can redistribute it and/or modify 008 it under the terms of the GNU Library General Public License as published by 009 the Free Software Foundation; either version 2 of the License, or (at your 010 option) any later version. 011 012 Granite Data Services is distributed in the hope that it will be useful, but 013 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 014 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License 015 for more details. 016 017 You should have received a copy of the GNU Library General Public License 018 along with this library; if not, see <http://www.gnu.org/licenses/>. 019 */ 020 021package org.granite.guice; 022 023import javax.servlet.ServletContext; 024 025import org.granite.config.flex.Destination; 026import org.granite.context.GraniteContext; 027import org.granite.messaging.service.ServiceException; 028import org.granite.messaging.service.ServiceInvoker; 029import org.granite.messaging.service.SimpleServiceFactory; 030import org.granite.messaging.webapp.HttpGraniteContext; 031import org.granite.util.XMap; 032 033import com.google.inject.Injector; 034 035import flex.messaging.messages.RemotingMessage; 036 037/** 038 * @author Matt GIACOMI 039 */ 040public class GuiceServiceFactory extends SimpleServiceFactory { 041 042 private Injector injector = null; 043 044 @Override 045 public void configure(XMap properties)throws ServiceException { 046 super.configure(properties); 047 048 // getting guice injector from container 049 GraniteContext context = GraniteContext.getCurrentInstance(); 050 ServletContext sc = ((HttpGraniteContext)context).getServletContext(); 051 injector = (Injector) sc.getAttribute(Injector.class.getName()); 052 } 053 054 @Override 055 public ServiceInvoker<?> getServiceInstance(RemotingMessage request) throws ServiceException { 056 String messageType = request.getClass().getName(); 057 String destinationId = request.getDestination(); 058 059 GraniteContext context = GraniteContext.getCurrentInstance(); 060 Destination destination = context.getServicesConfig().findDestinationById(messageType, destinationId); 061 if (destination == null) 062 throw new ServiceException("No matching destination: " + destinationId); 063 064 String className = destination.getProperties().get("source"); 065 066 try { 067 Class<?> gclass = Class.forName(className, true, getClass().getClassLoader()); 068 Object gobject = injector.getInstance(gclass); 069 return new GuiceServiceInvoker(destination, this, gobject); 070 } 071 catch(Exception e) { 072 throw new ServiceException("Class not found in classloader: "+ className, e); 073 } 074 } 075 076 @Override 077 public String toString() { 078 return toString("\n Guice Injector: " + injector); 079 } 080}