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.CDIUtils;
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 Logger log = Logger.getLogger(CDIServiceFactory.class);
049        
050        public static final String ENTITY_MANAGER_FACTORY_JNDI_NAME = "entity-manager-factory-jndi-name";
051        public static final String ENTITY_MANAGER_JNDI_NAME = "entity-manager-jndi-name";
052    
053        private BeanManager manager;
054        
055        public BeanManager getManager() {
056            return manager;
057        }
058        
059    
060        @Override
061        public void configure(XMap properties) throws ServiceException {
062            String sServiceExceptionHandler = properties.get("service-exception-handler");
063            if (sServiceExceptionHandler == null) {
064                XMap props = new XMap(properties);
065                props.put("service-exception-handler", "org.granite.messaging.service.ExtendedServiceExceptionHandler");
066                super.configure(props);
067            }
068            else
069                super.configure(properties);
070            
071            GraniteContext graniteContext = GraniteContext.getCurrentInstance();
072            try {
073                    graniteContext.getGraniteConfig().registerExceptionConverter(PersistenceExceptionConverter.class);
074            }
075            catch (Throwable t) {
076                    log.info(t, "JPA exception converter not registered (JPA not found on classpath)");
077            }
078    
079            try {
080                    manager = CDIUtils.lookupBeanManager(((HttpGraniteContext)graniteContext).getServletContext());
081            }
082            catch (Exception e) {
083                    log.warn("Unable to find the CDI Manager in JNDI, lookup in ServletContext");
084                    
085                    manager = (BeanManager)((HttpGraniteContext)graniteContext).getServletContext().getAttribute("javax.enterprise.inject.spi.BeanManager");
086                    if (manager == null) { 
087                            ServiceException se = new ServiceException(e.getMessage());
088                            throw se;
089                    }
090            }
091            
092            // Find the JCDIServiceContext component
093            Set<Bean<?>> cc = manager.getBeans(CDIServiceContext.class);
094            if (cc.size() != 1) {
095                String msg = cc.isEmpty() 
096                    ? "Unable to find the CDIServiceContext bean"
097                    : "More than one CDIServiceContext bean found";
098                log.error(msg);
099                ServiceException e = new ServiceException(msg);
100                throw e;
101            }
102        }
103    
104    
105        @Override
106        public ServiceInvoker<?> getServiceInstance(RemotingMessage request) throws ServiceException {
107            String messageType = request.getClass().getName();
108            String destinationId = request.getDestination();
109    
110            HttpGraniteContext context = (HttpGraniteContext)GraniteContext.getCurrentInstance();
111            Destination destination = context.getServicesConfig().findDestinationById(messageType, destinationId);
112            if (destination == null)
113                throw new ServiceException("No matching destination: " + destinationId);
114            
115            if (!destination.getProperties().containsKey(TideServiceInvoker.VALIDATOR_CLASS_NAME))
116                    destination.getProperties().put(TideServiceInvoker.VALIDATOR_CLASS_NAME, "org.granite.tide.validation.BeanValidation");
117            
118            @SuppressWarnings("unchecked")
119            Bean<PersistenceConfiguration> pcBean = (Bean<PersistenceConfiguration>)manager.getBeans(PersistenceConfiguration.class).iterator().next();
120            PersistenceConfiguration persistenceConfiguration = (PersistenceConfiguration)manager.getReference(pcBean, PersistenceConfiguration.class, manager.createCreationalContext(pcBean));
121            if (destination.getProperties().containsKey(ENTITY_MANAGER_FACTORY_JNDI_NAME))
122                    persistenceConfiguration.setEntityManagerFactoryJndiName(destination.getProperties().get(ENTITY_MANAGER_FACTORY_JNDI_NAME));
123            else if (destination.getProperties().containsKey(ENTITY_MANAGER_JNDI_NAME))
124                    persistenceConfiguration.setEntityManagerJndiName(destination.getProperties().get(ENTITY_MANAGER_JNDI_NAME));
125            
126            // Create an instance of the component
127            CDIServiceInvoker invoker = new CDIServiceInvoker(destination, this);
128            return invoker;
129        }
130    }