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

org.datanucleus.CDIHandler Maven / Gradle / Ivy

Go to download

DataNucleus Core provides the primary components of a heterogenous Java persistence solution. It supports persistence API's being layered on top of the core functionality.

There is a newer version: 6.0.9
Show newest version
/**********************************************************************
Copyright (c) 2017 Andy Jefferson and others. All rights reserved. 
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.

Contributors:
    ...
**********************************************************************/
package org.datanucleus;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionTarget;

import org.datanucleus.exceptions.NucleusUserException;

/**
 * Handles the integration of "javax.enterprise.inject" CDI API.
 * Note that this is the only class referring to CDI classes so that it is usable in environments without CDI present.
 * 
 * TODO Make this thread-safe
 */
public class CDIHandler
{
    BeanManager beanManager;

    Set creationalContexts = new HashSet<>();

    /** Cache of InjectionTarget keyed by the object that they created. */
    Map injectionTargets = new HashMap<>();

    public CDIHandler(Object beanMgr)
    {
        if (!(beanMgr instanceof BeanManager))
        {
            throw new NucleusUserException("Attempt to create CDI handler using BeanManager of type " + beanMgr.getClass().getName() + " : unsupported!");
        }
        this.beanManager = (BeanManager) beanMgr;
    }

    /**
     * Method to instantiate an object of the specified type with injected dependencies.
     * @param cls The type to instantiate
     * @return The instance
     * @param  Type of the object
     */
    public  T createObjectWithInjectedDependencies(Class cls)
    {
        AnnotatedType type = beanManager.createAnnotatedType(cls);

        // Create the CreationalContext, and cache them for later closure
        CreationalContext creationalCtx = beanManager.createCreationalContext(null);
        creationalContexts.add(creationalCtx);

        // Create an InjectionTarget, and the bean object with injected dependencies, and cache the InjectionTarget per object so we can dispose of them at closure
        InjectionTarget injectionTarget = beanManager.createInjectionTarget(type);
        T obj = injectionTarget.produce(creationalCtx);
        injectionTarget.inject(obj, creationalCtx);
        injectionTarget.postConstruct(obj);
        injectionTargets.put(obj, injectionTarget);

        return obj;
    }

    public void close()
    {
        if (!injectionTargets.isEmpty())
        {
            Set keys = new HashSet<>();
            synchronized(injectionTargets)
            {
                keys.addAll(injectionTargets.keySet());
                for (Object key : keys)
                {
                    try
                    {
                        InjectionTarget target = injectionTargets.get(key);
                        target.preDestroy(key);
                        target.dispose(key);
                        injectionTargets.remove(key);
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
        }
        if (!creationalContexts.isEmpty())
        {
            Iterator ctxIter = creationalContexts.iterator();
            while (ctxIter.hasNext())
            {
                CreationalContext ctx = ctxIter.next();
                ctx.release();
                ctxIter.remove();
            }
        }
    }
}