All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.atmosphere.cdi.CDIObjectFactory Maven / Gradle / Ivy

/*
 * Copyright 2015 Async-IO.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.atmosphere.cdi;

import org.atmosphere.cpr.AtmosphereConfig;
import org.atmosphere.cpr.AtmosphereObjectFactory;
import org.atmosphere.inject.AtmosphereConfigAware;
import org.atmosphere.inject.CDIProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * CDI support for injecting object
 *
 * @author Jeanfrancois Arcand
 */
public class CDIObjectFactory implements AtmosphereObjectFactory {

    private static final Logger logger = LoggerFactory.getLogger(CDIObjectFactory.class);
    private final ServiceLoader producerServiceLoader = ServiceLoader.load(CDIProducer.class);

    private final BeanManager bm;

    public CDIObjectFactory() {
        BeanManager beanManager = null;
        try {
            beanManager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager");
        } catch (NamingException ex) {
            try {
                beanManager = (BeanManager) new InitialContext().lookup("java:comp/env/BeanManager");
            } catch (NamingException e) {
                logger.error("{}", e);
            }
        }

        this.bm = beanManager;
        for (CDIProducer p : producerServiceLoader) {
            final Iterator> i = bm.getBeans(p.getClass()).iterator();
            if (!i.hasNext()) {
                throw new IllegalStateException();
            }
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public  U newClassInstance(Class classType, Class classToInstantiate) throws InstantiationException, IllegalAccessException {
        CreationalContext cc = null;

        try {
            final Iterator> i = bm.getBeans(classToInstantiate).iterator();
            if (!i.hasNext()) {
                logger.trace("Unable to find {}. Creating the object directly.", classToInstantiate.getName());
                return classToInstantiate.newInstance();
            }
            Bean bean = (Bean) i.next();
            CreationalContext ctx = bm.createCreationalContext(bean);
            U dao = (U) bm.getReference(bean, classToInstantiate, ctx);

            return dao;
        } catch (Exception e) {
            logger.error("Unable to construct {}. Creating the object directly.", classToInstantiate.getName());
            return classToInstantiate.newInstance();
        } finally {
            if (cc != null) cc.release();
        }
    }

    @Override
    public AtmosphereObjectFactory allowInjectionOf(Object o) {
        return this;
    }


    public String toString() {
        return "CDI ObjectFactory";
    }

    @Override
    public void configure(AtmosphereConfig config) {
        try {
            for (CDIProducer p : producerServiceLoader) {
                AtmosphereConfigAware.class.cast(p).configure(config);
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }

}