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    
021    package org.granite.tide.spring;
022    
023    import java.util.Map;
024    
025    import javax.servlet.ServletContext;
026    
027    import org.granite.config.flex.Destination;
028    import org.granite.context.GraniteContext;
029    import org.granite.logging.Logger;
030    import org.granite.messaging.service.ExtendedServiceExceptionHandler;
031    import org.granite.messaging.service.ServiceException;
032    import org.granite.messaging.service.ServiceFactory;
033    import org.granite.messaging.service.ServiceInvoker;
034    import org.granite.messaging.webapp.HttpGraniteContext;
035    import org.granite.tide.TideServiceInvoker;
036    import org.granite.tide.data.PersistenceExceptionConverter;
037    import org.granite.util.TypeUtil;
038    import org.granite.util.XMap;
039    import org.springframework.context.ApplicationContext;
040    import org.springframework.web.context.support.WebApplicationContextUtils;
041    
042    import flex.messaging.messages.RemotingMessage;
043    
044    
045    /**
046     * @author Sebastien Deleuze
047     */
048    public class SpringServiceFactory extends ServiceFactory {
049        
050            private static final Logger log = Logger.getLogger(SpringServiceFactory.class);
051        
052        public static final String PERSISTENCE_MANAGER_BEAN_NAME = "persistence-manager-bean-name";
053        public static final String ENTITY_MANAGER_FACTORY_BEAN_NAME = "entity-manager-factory-bean-name";
054        
055        private ApplicationContext springContext = null;
056        
057        public void setApplicationContext(ApplicationContext applicationContext) {
058            this.springContext = applicationContext;
059        }
060    
061    
062        @Override
063        public void configure(XMap properties) throws ServiceException {
064            String sServiceExceptionHandler = properties.get("service-exception-handler");
065            if (sServiceExceptionHandler == null) {
066                XMap props = new XMap(properties);
067                props.put("service-exception-handler", ExtendedServiceExceptionHandler.class.getName());
068                super.configure(props);
069            }
070            else
071                super.configure(properties);
072            
073            GraniteContext graniteContext = GraniteContext.getCurrentInstance();
074            try {
075                    graniteContext.getGraniteConfig().registerExceptionConverter(PersistenceExceptionConverter.class);
076            }
077            catch (Throwable t) {
078                    log.info(t, "JPA exception converter not registered (JPA not found on classpath)");
079            }
080        }
081    
082    
083        @Override
084        public ServiceInvoker<?> getServiceInstance(RemotingMessage request) throws ServiceException {
085            
086            String messageType = request.getClass().getName();
087            String destinationId = request.getDestination();
088    
089            GraniteContext context = GraniteContext.getCurrentInstance();
090            Map<String, Object> cache = context.getSessionMap();
091            Destination destination = context.getServicesConfig().findDestinationById(messageType, destinationId);
092            if (destination == null)
093                throw new ServiceException("No matching destination: " + destinationId);
094            
095            String key = TideServiceInvoker.class.getName() + '.' + destinationId;
096            
097            return getServiceInvoker(cache, destination, key);
098            
099        }
100    
101        private ServiceInvoker<?> getServiceInvoker(Map<String, Object> cache, Destination destination, String key) {
102            GraniteContext context = GraniteContext.getCurrentInstance();
103            synchronized (context.getSessionLock()) {
104                ServiceInvoker<?> invoker = (ServiceInvoker<?>)cache.get(key);
105                if (invoker == null) {
106                    SpringServiceContext tideContext = null;
107                    ServletContext sc = ((HttpGraniteContext)context).getServletContext();
108                    ApplicationContext springContext = this.springContext != null ? this.springContext : WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
109                    Map<String, ?> beans = springContext.getBeansOfType(SpringServiceContext.class);
110                    if (beans.size() > 1)
111                        throw new RuntimeException("More than one SpringServiceContext bean found");
112                    else if (beans.size() == 1)
113                        tideContext = (SpringServiceContext)beans.values().iterator().next();
114                    else {
115                            // Try to create Spring MVC context when Spring MVC available
116                            String className = "org.granite.tide.spring.SpringMVCServiceContext";
117                            try {
118                                    Class<SpringServiceContext> clazz = TypeUtil.forName(className, SpringServiceContext.class);
119                                    tideContext = clazz.getConstructor(ApplicationContext.class).newInstance(springContext);
120                            }
121                            catch (Exception e) {
122                                    tideContext = new SpringServiceContext(springContext);
123                            }
124                    }
125                    
126                    String persistenceManagerBeanName = destination.getProperties().get(PERSISTENCE_MANAGER_BEAN_NAME);
127                    tideContext.setPersistenceManagerBeanName(persistenceManagerBeanName);
128                    
129                    String entityManagerFactoryBeanName = destination.getProperties().get(ENTITY_MANAGER_FACTORY_BEAN_NAME);
130                    tideContext.setEntityManagerFactoryBeanName(entityManagerFactoryBeanName);
131                    
132                    invoker = new TideServiceInvoker<SpringServiceFactory>(destination, this, tideContext);
133                    cache.put(key, invoker);
134                }
135                return invoker;
136            }
137    
138        }
139    }