/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package fr.hhdev.ocelot.web;

import java.lang.annotation.Annotation;
import java.util.Set;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.util.AnnotationLiteral;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author hhfrancois
 */
public abstract class CdiBootstrap {
	private static BeanManager beanManager = null;

	public CdiBootstrap() {
		try {
			InitialContext initialContext = new InitialContext();
			beanManager = (BeanManager) initialContext.lookup("java:comp/env/BeanManager");
		} catch (NamingException e) {
		}
	}
	
	public <T> T getBean(Class<T> cls) {
		Set<Bean<?>> beans = beanManager.getBeans(cls, DEFAULT_AT);
		Bean<?> b = beans.iterator().next();
		final CreationalContext context = beanManager.createCreationalContext(b);
		return cls.cast(beanManager.getReference(b, b.getBeanClass(), context));
	}

	private static final Annotation DEFAULT_AT = new AnnotationLiteral<Default>() {
		private static final long serialVersionUID = 1L;
	};
	
}

@@ -608,16 +608,75 @@
 eption;%0D
+%0Aimport org.slf4j.Logger;%0D%0Aimport org.slf4j.LoggerFactory;%0D
 %0A%0D%0A/**%0D%0A
@@ -745,16 +745,104 @@
 trap %7B%0D%0A
+%0D%0A%09private final static Logger logger = LoggerFactory.getLogger(CdiBootstrap.class);%0D%0A%0D%0A
 %09private
@@ -896,35 +896,81 @@
 lic 
-CdiBootstrap(
+BeanManager getBeanManager() %7B%0D%0A%09%09if (null == beanManager
 ) %7B%0D%0A%09%09
+%09
 try %7B%0D%0A
+%09
 %09%09%09I
@@ -1023,16 +1023,17 @@
 ext();%0D%0A
+%09
 %09%09%09beanM
@@ -1110,16 +1110,17 @@
 r%22);%0D%0A%09%09
+%09
 %7D catch 
@@ -1148,16 +1148,44 @@
 %0D%0A%09%09
-%7D
+%09%7D%0D%0A%09%09%7D%0D%0A%09%09return beanManager;
 %0D%0A%09%7D%0D%0A
-%09
 %0D%0A%09p
@@ -1221,16 +1221,133 @@
 cls) %7B%0D%0A
+%09%09BeanManager bm = getBeanManager();%0D%0A%09%09logger.info(%22Generate bean from %7B%7D, cause native injection doesn't work.%22);%0D%0A
 %09%09Set%3CBe
@@ -1362,26 +1362,17 @@
 eans = b
-eanManager
+m
 .getBean
@@ -1469,26 +1469,17 @@
 text = b
-eanManager
+m
 .createC
@@ -1519,26 +1519,17 @@
 s.cast(b
-eanManager
+m
 .getRefe
@@ -1712,14 +1712,13 @@
 ;%0D%0A%09%7D;%0D%0A
-%09
 %0D%0A%7D%0D%0A

fix tomcat bootstrap in endpoint use static beanManager in enpoint