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

com.ocpsoft.rewrite.cdi.CdiServiceEnricher Maven / Gradle / Ivy

There is a newer version: 1.0.0.Alpha11
Show newest version
/*
 * Copyright 2011 Lincoln Baxter, III
 * 
 * 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 com.ocpsoft.rewrite.cdi;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

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

import org.jboss.solder.beanManager.BeanManagerAware;

import com.ocpsoft.common.spi.ServiceEnricher;
import com.ocpsoft.logging.Logger;

/**
 * @author Lincoln Baxter, III
 * 
 */
public class CdiServiceEnricher extends BeanManagerAware implements ServiceEnricher
{
   Logger log = Logger.getLogger(CdiServiceEnricher.class);

   @SuppressWarnings("unchecked")
   @Override
   public  Collection produce(final Class type)
   {
      Collection result = new ArrayList();

      BeanManager manager = getBeanManager();
      Set> beans = manager.getBeans(type);
      for (Bean bean : beans) {
         if (bean != null)
         {
            CreationalContext context = (CreationalContext) manager.createCreationalContext(bean);

            if (context != null)
            {
               result.add((T) manager.getReference(bean, type, context));
               if (log.isDebugEnabled())
               {
                  log.debug("Created CDI enriched service [" + bean.toString() + "]");
               }
            }
         }
      }

      return result;
   }

   @Override
   @SuppressWarnings("unchecked")
   public  void enrich(final T service)
   {
      if (service != null)
      {
         BeanManager manager = getBeanManager();
         CreationalContext context = manager.createCreationalContext(null);
         InjectionTarget injectionTarget = (InjectionTarget) manager
                  .createInjectionTarget(manager.createAnnotatedType(service.getClass()));

         injectionTarget.inject(service, context);

         if ((context != null) && log.isDebugEnabled())
         {
            log.debug("Enriched non-contextual intance of service [" + service.getClass().getName() + "]");
         }
      }
   }

}