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.ClassUtil;
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 long serialVersionUID = 1L;
051        
052            private static final Logger log = Logger.getLogger(SpringServiceFactory.class);
053        
054        public static final String PERSISTENCE_MANAGER_BEAN_NAME = "persistence-manager-bean-name";
055        public static final String ENTITY_MANAGER_FACTORY_BEAN_NAME = "entity-manager-factory-bean-name";
056    
057    
058        @Override
059        public void configure(XMap properties) throws ServiceException {
060            String sServiceExceptionHandler = properties.get("service-exception-handler");
061            if (sServiceExceptionHandler == null) {
062                XMap props = new XMap(properties);
063                props.put("service-exception-handler", ExtendedServiceExceptionHandler.class.getName());
064                super.configure(props);
065            }
066            else
067                super.configure(properties);
068            
069            GraniteContext graniteContext = GraniteContext.getCurrentInstance();
070            try {
071                    graniteContext.getGraniteConfig().registerExceptionConverter(PersistenceExceptionConverter.class);
072            }
073            catch (Throwable t) {
074                    log.info(t, "JPA exception converter not registered (JPA not found on classpath)");
075            }
076        }
077    
078    
079        @Override
080        public ServiceInvoker<?> getServiceInstance(RemotingMessage request) throws ServiceException {
081            
082            String messageType = request.getClass().getName();
083            String destinationId = request.getDestination();
084    
085            GraniteContext context = GraniteContext.getCurrentInstance();
086            Map<String, Object> cache = context.getSessionMap();
087            Destination destination = context.getServicesConfig().findDestinationById(messageType, destinationId);
088            if (destination == null)
089                throw new ServiceException("No matching destination: " + destinationId);
090            
091            String key = TideServiceInvoker.class.getName() + '.' + destinationId;
092            
093            return getServiceInvoker(cache, destination, key);
094            
095        }
096    
097        private ServiceInvoker<?> getServiceInvoker(Map<String, Object> cache, Destination destination, String key) {
098            GraniteContext context = GraniteContext.getCurrentInstance();
099            synchronized (context.getSessionLock()) {
100                ServiceInvoker<?> invoker = (ServiceInvoker<?>)cache.get(key);
101                if (invoker == null) {
102                    SpringServiceContext tideContext = null;
103                    ServletContext sc = ((HttpGraniteContext)context).getServletContext();
104                    ApplicationContext springContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
105                    @SuppressWarnings("unchecked")
106                    Map<String, Object> beans = springContext.getBeansOfType(SpringServiceContext.class);
107                    if (beans.size() > 1)
108                        throw new RuntimeException("More than one SpringServiceContext bean found");
109                    else if (beans.size() == 1)
110                        tideContext = (SpringServiceContext)beans.values().iterator().next();
111                    else {
112                            // Try to create Spring MVC context when Spring MVC available
113                            String className = "org.granite.tide.spring.SpringMVCServiceContext";
114                            try {
115                                    Class<SpringServiceContext> clazz = ClassUtil.forName(className, SpringServiceContext.class);
116                                    tideContext = clazz.newInstance();
117                            }
118                            catch (Exception e) {
119                                    tideContext = new SpringServiceContext();
120                            }
121                    }
122                    
123                    String persistenceManagerBeanName = destination.getProperties().get(PERSISTENCE_MANAGER_BEAN_NAME);
124                    tideContext.setPersistenceManagerBeanName(persistenceManagerBeanName);
125                    
126                    String entityManagerFactoryBeanName = destination.getProperties().get(ENTITY_MANAGER_FACTORY_BEAN_NAME);
127                    tideContext.setEntityManagerFactoryBeanName(entityManagerFactoryBeanName);
128                    
129                    invoker = new TideServiceInvoker<SpringServiceFactory>(destination, this, tideContext);
130                    cache.put(key, invoker);
131                }
132                return invoker;
133            }
134    
135        }
136    }