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.cdi;
022    
023    import java.util.Set;
024    
025    import javax.enterprise.inject.spi.Bean;
026    import javax.enterprise.inject.spi.BeanManager;
027    
028    import org.granite.cdi.CDIInterceptor;
029    import org.granite.config.flex.Destination;
030    import org.granite.context.GraniteContext;
031    import org.granite.logging.Logger;
032    import org.granite.messaging.service.ServiceException;
033    import org.granite.messaging.service.ServiceFactory;
034    import org.granite.messaging.service.ServiceInvoker;
035    import org.granite.messaging.webapp.HttpGraniteContext;
036    import org.granite.tide.TideServiceInvoker;
037    import org.granite.tide.data.PersistenceExceptionConverter;
038    import org.granite.util.XMap;
039    
040    import flex.messaging.messages.RemotingMessage;
041    
042    
043    /**
044     * @author William DRAI
045     */
046    public class CDIServiceFactory extends ServiceFactory {
047    
048        private static final long serialVersionUID = 1L;
049    
050        private static final Logger log = Logger.getLogger(CDIServiceFactory.class);
051        
052        public static final String ENTITY_MANAGER_FACTORY_JNDI_NAME = "entity-manager-factory-jndi-name";
053        public static final String ENTITY_MANAGER_JNDI_NAME = "entity-manager-jndi-name";
054    
055        private BeanManager manager;
056        
057        public BeanManager getManager() {
058            return manager;
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", "org.granite.messaging.service.ExtendedServiceExceptionHandler");
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            try {
082                    manager = CDIInterceptor.lookupBeanManager();
083            }
084            catch (Exception e) {
085                    log.warn("Unable to find the CDI Manager in JNDI, lookup in ServletContext");
086                    
087                    manager = (BeanManager)((HttpGraniteContext)graniteContext).getServletContext().getAttribute("javax.enterprise.inject.spi.BeanManager");
088                    if (manager == null) { 
089                            ServiceException se = new ServiceException(e.getMessage());
090                            throw se;
091                    }
092            }
093            
094            // Find the JCDIServiceContext component
095            Set<Bean<?>> cc = manager.getBeans(CDIServiceContext.class);
096            if (cc.size() != 1) {
097                String msg = cc.isEmpty() 
098                    ? "Unable to find the CDIServiceContext bean"
099                    : "More than one CDIServiceContext bean found";
100                log.error(msg);
101                ServiceException e = new ServiceException(msg);
102                throw e;
103            }
104        }
105    
106    
107        @Override
108        public ServiceInvoker<?> getServiceInstance(RemotingMessage request) throws ServiceException {
109            String messageType = request.getClass().getName();
110            String destinationId = request.getDestination();
111    
112            HttpGraniteContext context = (HttpGraniteContext)GraniteContext.getCurrentInstance();
113            Destination destination = context.getServicesConfig().findDestinationById(messageType, destinationId);
114            if (destination == null)
115                throw new ServiceException("No matching destination: " + destinationId);
116            
117            if (!destination.getProperties().containsKey(TideServiceInvoker.VALIDATOR_CLASS_NAME))
118                    destination.getProperties().put(TideServiceInvoker.VALIDATOR_CLASS_NAME, "org.granite.tide.validation.BeanValidation");
119            
120            @SuppressWarnings("unchecked")
121            Bean<PersistenceConfiguration> pcBean = (Bean<PersistenceConfiguration>)manager.getBeans(PersistenceConfiguration.class).iterator().next();
122            PersistenceConfiguration persistenceConfiguration = (PersistenceConfiguration)manager.getReference(pcBean, PersistenceConfiguration.class, manager.createCreationalContext(pcBean));
123            if (destination.getProperties().containsKey(ENTITY_MANAGER_FACTORY_JNDI_NAME))
124                    persistenceConfiguration.setEntityManagerFactoryJndiName(destination.getProperties().get(ENTITY_MANAGER_FACTORY_JNDI_NAME));
125            else if (destination.getProperties().containsKey(ENTITY_MANAGER_JNDI_NAME))
126                    persistenceConfiguration.setEntityManagerJndiName(destination.getProperties().get(ENTITY_MANAGER_JNDI_NAME));
127            
128            // Create an instance of the component
129            CDIServiceInvoker invoker = new CDIServiceInvoker(destination, this);
130            return invoker;
131        }
132    
133    }