下面列出了org.junit.rules.MethodRule#javax.enterprise.context.spi.CreationalContext 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@PreDestroy
private void release() {
if (CLOSE_CACHE && defaultCacheResolverFactory != null)
{
defaultCacheResolverFactory.release();
}
for (final CreationalContext<?> cc : toRelease)
{
try
{
cc.release();
}
catch (final RuntimeException re)
{
LOGGER.warning(re.getMessage());
}
}
}
/**
* {@inheritDoc}
*/
@Override
public Object redefineParameterValue(ParameterValue value)
{
CreationalContext<?> ctx = BeanManagerProvider.getInstance().getBeanManager()
.createCreationalContext(declaringBean);
try
{
if (value.getPosition() == handlerMethod.getHandlerParameter().getPosition())
{
return event;
}
return value.getDefaultValue(ctx);
}
finally
{
if (ctx != null)
{
ctx.release();
}
}
}
/**
* Get the instance (create it if it does not exist).
*
* @param <T> the type.
* @param contextual the contextual.
* @param creational the creational.
* @return the instance.
*/
public <T> T get(Contextual<T> contextual, CreationalContext<T> creational) {
T result = get(contextual);
if (result == null) {
String scopeId = (String) request.getAttribute(SCOPE_ID);
if (null == scopeId) {
scopeId = generateScopeId();
}
HttpSession session = request.getSession();
result = contextual.create(creational);
if (contextual instanceof PassivationCapable == false) {
throw new RuntimeException("Unexpected type for contextual");
}
PassivationCapable pc = (PassivationCapable) contextual;
final String sessionKey = SCOPE_ID + "-" + scopeId;
Map<String, Object> scopeMap = (Map<String, Object>) session.getAttribute(sessionKey);
if (null != scopeMap) {
session.setAttribute(sessionKey, scopeMap);
scopeMap.put(INSTANCE + pc.getId(), result);
scopeMap.put(CREATIONAL + pc.getId(), creational);
}
}
return result;
}
/**
* Get the instance (create it if it does not exist).
*
* @param <T> the type.
* @param contextual the contextual.
* @param creational the creational.
* @return the instance.
*/
public <T> T get(Contextual<T> contextual, CreationalContext<T> creational) {
T result = get(contextual);
if (result == null) {
String scopeId = (String) request.getAttribute(SCOPE_ID);
if (null == scopeId) {
scopeId = generateScopeId();
}
HttpSession session = request.getSession();
result = contextual.create(creational);
if (contextual instanceof PassivationCapable == false) {
throw new RuntimeException("Unexpected type for contextual");
}
PassivationCapable pc = (PassivationCapable) contextual;
final String sessionKey = SCOPE_ID + "-" + scopeId;
Map<String, Object> scopeMap = (Map<String, Object>) session.getAttribute(sessionKey);
if (null != scopeMap) {
session.setAttribute(sessionKey, scopeMap);
scopeMap.put(INSTANCE + pc.getId(), result);
scopeMap.put(CREATIONAL + pc.getId(), creational);
}
}
return result;
}
private static <T> T getContextualReference(BeanManager beanManager, Class<T> type)
{
Set<Bean<?>> beans = beanManager.getBeans(type);
if (beans == null || beans.isEmpty())
{
return null;
}
Bean<?> bean = beanManager.resolve(beans);
CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
@SuppressWarnings({ "unchecked", "UnnecessaryLocalVariable" })
T result = (T) beanManager.getReference(bean, type, creationalContext);
if (bean.getScope().equals(Dependent.class))
{
AbstractBeanStorage beanStorage = BeanProvider.getContextualReference(RequestDependentBeanStorage.class);
//noinspection unchecked
beanStorage.add(new DependentBeanEntry(result, bean, creationalContext));
}
return result;
}
public <T> T get(Contextual<T> component, CreationalContext<T> creationalContext)
{
Map<Contextual, TransactionBeanEntry> transactionBeanEntryMap =
TransactionBeanStorage.getInstance().getActiveTransactionContext();
if (transactionBeanEntryMap == null)
{
TransactionBeanStorage.close();
throw new ContextNotActiveException("Not accessed within a transactional method - use @" +
Transactional.class.getName());
}
TransactionBeanEntry transactionBeanEntry = transactionBeanEntryMap.get(component);
if (transactionBeanEntry != null)
{
return (T) transactionBeanEntry.getContextualInstance();
}
// if it doesn't yet exist, we need to create it now!
T instance = component.create(creationalContext);
transactionBeanEntry = new TransactionBeanEntry(component, instance, creationalContext);
transactionBeanEntryMap.put(component, transactionBeanEntry);
return instance;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testCreateNewInstanceAndSubsequentRetrievalOfExistingObject() {
CreationalContext creationalContext = mock(CreationalContext.class);
Contextual contextual = mock(Contextual.class);
when(contextual.create(creationalContext)).thenReturn("test");
Object result = JoynrJeeMessageContext.getInstance().get(contextual, creationalContext);
assertNotNull(result);
assertEquals("test", result);
verify(contextual).create(creationalContext);
assertEquals("test", JoynrJeeMessageContext.getInstance().get(contextual));
reset(contextual);
reset(creationalContext);
assertEquals("test", JoynrJeeMessageContext.getInstance().get(contextual, creationalContext));
verify(contextual, never()).create(creationalContext);
}
@SuppressWarnings("unchecked")
@Override
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
if (contextual == null) {
throw new IllegalArgumentException("Contextual parameter must not be null");
}
Map<Contextual<?>, ContextInstanceHandle<?>> ctx = currentContext.get();
if (ctx == null) {
// Thread local not set - context is not active!
throw new ContextNotActiveException();
}
ContextInstanceHandle<T> instance = (ContextInstanceHandle<T>) ctx.get(contextual);
if (instance == null && creationalContext != null) {
// Bean instance does not exist - create one if we have CreationalContext
instance = new ContextInstanceHandleImpl<T>((InjectableBean<T>) contextual,
contextual.create(creationalContext), creationalContext);
ctx.put(contextual, instance);
}
return instance != null ? instance.get() : null;
}
private <T> T getInstance(final Contextual<T> contextual, final CreationalContext<T> creationalContext) {
T instance;
BeanInstanceBag<T> bag = (BeanInstanceBag<T>) componentInstanceMap.get(contextual);
if (bag == null) {
bag = createContextualBag(contextual, creationalContext);
}
instance = bag.beanInstance;
if (instance != null) {
return instance;
} else {
if (creationalContext == null) {
return null;
} else {
instance = bag.create(contextual);
}
}
return instance;
}
protected T createEjb(final CreationalContext<T> creationalContext) {
final CurrentCreationalContext currentCreationalContext = beanContext.get(CurrentCreationalContext.class);
final CreationalContext existing = currentCreationalContext.get();
currentCreationalContext.set(creationalContext);
try {
final T instance;
if (homeLocalBean != null) {
instance = (T) homeLocalBean.create();
} else if (home != null) {
instance = (T) home.create();
} else if (remote != null) {
instance = (T) remote.create();
} else { // shouldn't be called for an MDB
throw new IllegalStateException("no interface to proxy for ejb " + beanContext.getEjbName() + ", is this is a MDB maybe you shouldn't use a scope?");
}
if (isDependentAndStateful) {
CreationalContextImpl.class.cast(creationalContext).addDependent(this, instance);
}
return instance;
} finally {
currentCreationalContext.set(existing);
}
}
@Override
public Instance load(final String batchId) {
final BeanManager bm = getBeanManager();
if (bm == null) {
return super.load(batchId);
}
final Set<Bean<?>> beans = bm.getBeans(batchId);
final Bean<?> bean = bm.resolve(beans);
if (bean == null) { // fallback to try to instantiate it from TCCL as per the spec
return super.load(batchId);
}
final Class<?> clazz = bean.getBeanClass();
final CreationalContext creationalContext = bm.createCreationalContext(bean);
final Object artifactInstance = bm.getReference(bean, clazz, creationalContext);
if (Dependent.class.equals(bean.getScope()) || !bm.isNormalScope(bean.getScope())) { // need to be released
return new Instance(artifactInstance, new Closeable() {
@Override
public void close() throws IOException {
creationalContext.release();
}
});
}
return new Instance(artifactInstance, null);
}
private static <T> T newInstance(final OpenEjbConfig config, final Class<T> clazz) throws Exception {
final WebBeansContext webBeansContext = AppFinder.findAppContextOrWeb(
Thread.currentThread().getContextClassLoader(), AppFinder.WebBeansContextTransformer.INSTANCE);
if (webBeansContext == null) {
return clazz.newInstance();
}
final BeanManagerImpl beanManager = webBeansContext.getBeanManagerImpl();
if (!beanManager.isInUse()) {
return clazz.newInstance();
}
final AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(clazz);
final InjectionTarget<T> it = beanManager.createInjectionTarget(annotatedType);
final CreationalContext<T> context = beanManager.createCreationalContext(null);
final T instance = it.produce(context);
it.inject(instance, context);
it.postConstruct(instance);
config.releasables.add(new Releasable<>(context, it, instance));
return instance;
}
@Test
@Deployment
public void testExecutionIdInjectableByQualifier() {
getBeanInstance(BusinessProcess.class).startProcessByKey("keyOfTheProcess");
Set<Bean<?>> beans = beanManager.getBeans(String.class, new ExecutionIdLiteral());
Bean<String> bean = (Bean<java.lang.String>) beanManager.resolve(beans);
CreationalContext<String> ctx = beanManager.createCreationalContext(bean);
String executionId = (String) beanManager.getReference(bean, String.class, ctx);
Assert.assertNotNull(executionId);
String processInstanceId = (String) getBeanInstance("processInstanceId");
Assert.assertNotNull(processInstanceId);
assertEquals(processInstanceId, executionId);
}
@Override
public <A extends Annotation> List<Object> getInstancesByAnnotation(Class<A> annotationClass) {
List<Object> list = new ArrayList<>();
BeanManager beanManager = getBeanManager();
if (beanManager != null) {
Set<Bean<?>> beans = beanManager.getBeans(Object.class);
for (Bean<?> bean : beans) {
Class<?> beanClass = bean.getBeanClass();
Optional<A> annotation = ClassUtils.getAnnotation(beanClass, annotationClass);
if (annotation.isPresent()) {
CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
Object object = beanManager.getReference(bean, beanClass, creationalContext);
list.add(object);
}
}
}
return list;
}
@Override
public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
final Thread thread = Thread.currentThread();
ClassLoader oldCL = thread.getContextClassLoader();
boolean unlocked = false;
doLockContext();
try {
ClassLoader newCl = getClassLoader();
if (newCl != null) {
thread.setContextClassLoader(newCl);
}
try (final AutoCloseable closeable = onStart()) {
doUnlockContext(unlocked);
unlocked = true;
started.set(true);
final Collection<CreationalContext<?>> contexts = toInject.stream()
.map(MeecrowaveRuleBase::doInject)
.collect(toList());
try {
base.evaluate();
} finally {
contexts.forEach(CreationalContext::release);
started.set(false);
}
} finally {
thread.setContextClassLoader(oldCL);
}
} finally {
doUnlockContext(unlocked);
}
}
};
}
@Override
public void evaluate() throws Throwable
{
BeanManager beanManager = BeanManagerProvider.getInstance().getBeanManager();
Class<?> type = this.method.getMethod().getDeclaringClass();
Set<Bean<?>> beans = beanManager.getBeans(type);
if (!USE_TEST_CLASS_AS_CDI_BEAN || beans == null || beans.isEmpty())
{
if (!ALLOW_INJECTION_POINT_MANIPULATION)
{
BeanProvider.injectFields(this.originalTarget); //fallback to simple injection
}
invokeMethod(this.originalTarget);
}
else
{
Bean<Object> bean = (Bean<Object>) beanManager.resolve(beans);
CreationalContext<Object> creationalContext = beanManager.createCreationalContext(bean);
Object target = beanManager.getReference(bean, type, creationalContext);
try
{
invokeMethod(target);
}
finally
{
if (bean.getScope().equals(Dependent.class))
{
bean.destroy(target, creationalContext);
}
}
}
}
public <T> AutoCloseable inject(final T instance) {
final BeanManager bm = CDI.current().getBeanManager();
final AnnotatedType<?> annotatedType = bm.createAnnotatedType(instance.getClass());
final InjectionTarget injectionTarget = bm.createInjectionTarget(annotatedType);
final CreationalContext<Object> creationalContext = bm.createCreationalContext(null);
injectionTarget.inject(instance, creationalContext);
return creationalContext::release;
}
@Override
public Object getInjectableReference(final InjectionPoint injectionPoint, final CreationalContext<?> ctx) {
Asserts.assertNotNull(injectionPoint, "injectionPoint parameter");
if(injectionPoint == null) {
return null;
}
final BeanManagerImpl parentBm = getParentBm();
final Boolean existing = USE_PARENT_BM.get();
if (existing != null && existing) { // shortcut the whole logic to keep the threadlocal set up correctly
if (parentBm == null) {
return null;
}
return parentBm.getInjectableReference(injectionPoint, ctx);
}
// we can do it cause there is caching but we shouldn't - easy way to overide OWB actually
final Bean<Object> injectedBean = (Bean<Object>)getInjectionResolver().getInjectionPointBean(injectionPoint);
try {
if (parentBm != null && injectedBean != null && injectedBean == parentBm.getInjectionResolver().getInjectionPointBean(injectionPoint)) {
USE_PARENT_BM.set(true);
try {
return parentBm.getInjectableReference(injectionPoint, ctx);
} finally {
USE_PARENT_BM.remove();
}
}
} catch (final UnsatisfiedResolutionException ure) {
// skip, use this bean
}
return super.getInjectableReference(injectionPoint, ctx);
}
public Object inject(final Object o) throws OpenEJBException {
try {
final WebBeansContext webBeansContext = getWebBeansContext();
// Create bean instance
final Context initialContext = (Context) new InitialContext().lookup("java:");
final Context unwrap = InjectionProcessor.unwrap(initialContext);
final InjectionProcessor injectionProcessor = new InjectionProcessor(o, injections, unwrap);
final Object beanInstance = injectionProcessor.createInstance();
if (webBeansContext != null) {
final ConstructorInjectionBean<Object> beanDefinition = getConstructorInjectionBean(o.getClass(), webBeansContext);
final CreationalContext<Object> creationalContext = webBeansContext.getBeanManagerImpl().createCreationalContext(beanDefinition);
final InjectionTargetBean<Object> bean = InjectionTargetBean.class.cast(beanDefinition);
bean.getInjectionTarget().inject(beanInstance, creationalContext);
if (shouldBeReleased(beanDefinition.getScope())) {
creationalContexts.put(beanInstance, creationalContext);
}
}
return beanInstance;
} catch (final NamingException | OpenEJBException e) {
throw new OpenEJBException(e);
}
}
public BiFunctionBean(Class<?> beanType, Set<Type> types, Set<Annotation> qualifiers,
Class<? extends Annotation> scope,
BiFunction<CreationalContext<Object>, BiFunctionBean<?>, Object> biFunction) {
this.qualifiers = qualifiers;
this.scope = scope;
this.biFunction = biFunction;
this.types = types;
this.beanType = beanType;
}
public Instance(final Object deploymentId, final Object primaryKey, final Object bean, final Map<String, Object> interceptors, final CreationalContext creationalContext, final JtaEntityManagerRegistry.EntityManagerTracker[] entityManagerArray) {
this.beanContext = SystemInstance.get().getComponent(ContainerSystem.class).getBeanContext(deploymentId);
if (beanContext == null) {
throw new IllegalArgumentException("Unknown deployment " + deploymentId);
}
this.primaryKey = primaryKey;
this.bean = bean;
this.interceptors = interceptors;
this.creationalContext = creationalContext;
this.entityManagerArray = entityManagerArray;
}
private WebServer resolveWebServer(BeanManager beanManager) {
Set<Bean<?>> beans = beanManager.getBeans(WebServer.class);
if (beans.size() > 1) {
StringJoiner foundInstances = new StringJoiner(",", "[", "]");
beans.iterator().forEachRemaining(ws -> foundInstances.add(ws.toString()));
throw new RuntimeException("Multiple web server implementations found on the classpath " + foundInstances);
}
if (beans.isEmpty()) {
throw new RuntimeException("No web server implementations found on the classpath");
}
Bean<?> bean = beanManager.resolve(beans);
CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
return (WebServer) beanManager.getReference(bean, WebServer.class, creationalContext);
}
public Instance(final BeanContext beanContext, final Object primaryKey, final Object bean, final Map<String, Object> interceptors, final CreationalContext creationalContext, final Map<EntityManagerFactory, JtaEntityManagerRegistry.EntityManagerTracker> entityManagers) {
this.beanContext = beanContext;
this.primaryKey = primaryKey;
this.bean = bean;
this.interceptors = interceptors;
this.creationalContext = creationalContext;
this.entityManagers = entityManagers;
this.entityManagerArray = null;
}
void inject() {
BeanManager beanManager = container.getBeanManager();
CreationalContext<Object> ctx = beanManager.createCreationalContext(null);
@SuppressWarnings("unchecked")
InjectionTarget<Object> injectionTarget = (InjectionTarget<Object>) beanManager
.getInjectionTargetFactory(beanManager.createAnnotatedType(instance.getClass())).createInjectionTarget(null);
injectionTarget.inject(instance, ctx);
creationalContext = ctx;
}
@Override
public Contextual<?> get(CreationalContext<Contextual<?>> creationalContext) {
// First attempt to obtain the creational context of the interceptor bean and then the creational context of the intercepted bean
CreationalContextImpl<?> parent = unwrap(creationalContext).getParent();
if (parent != null) {
parent = parent.getParent();
return parent != null ? parent.getContextual() : null;
}
return null;
}
@Override
public Object get(CreationalContext<Object> creationalContext) {
InstanceHandle<Object> instance = ArcContainerImpl.instance().getResource(type, annotations);
if (instance != null) {
CreationalContextImpl<?> ctx = CreationalContextImpl.unwrap(creationalContext);
if (ctx.getParent() != null) {
ctx.getParent().addDependentInstance(instance);
}
return instance.get();
}
// TODO log a warning that a resource cannot be injected
return null;
}
/**
*
* @param instance
* @param creationalContext
* @param contextual
*/
ContextualInstance(T instance, CreationalContext<T> creationalContext,
Contextual<T> contextual) {
this.instance = instance;
this.creationalContext = creationalContext;
this.contextual = contextual;
}
@Override
public void init(Properties batchConfig) {
beanManager = BatchCDIInjectionExtension.getInstance().getBeanManager();
Set<Bean<?>> beans = beanManager.getBeans(ThreadExecutorEjb.class);
Bean<?> bean = beanManager.resolve(beans);
CreationalContext cc = beanManager.createCreationalContext(bean);
threadExecutorEjb = (ThreadExecutorEjb) beanManager.getReference(bean, bean.getBeanClass(), cc);
}
void authorize(final InvocationContext ic, final Object returnValue, BeanManager beanManager)
throws IllegalAccessException, IllegalArgumentException
{
if (boundAuthorizerBean == null)
{
lazyInitTargetBean(beanManager);
}
final CreationalContext<?> creationalContext = beanManager.createCreationalContext(boundAuthorizerBean);
Object reference = beanManager.getReference(boundAuthorizerBean,
boundAuthorizerMethod.getJavaMember().getDeclaringClass(), creationalContext);
Object result = boundAuthorizerMethodProxy.invoke(reference, creationalContext,
new SecurityParameterValueRedefiner(creationalContext, ic, returnValue));
if (Boolean.FALSE.equals(result))
{
Set<SecurityViolation> violations = new HashSet<SecurityViolation>();
violations.add(new SecurityViolation()
{
private static final long serialVersionUID = 2358753444038521129L;
@Override
public String getReason()
{
return "Authorization check failed";
}
});
throw new AccessDeniedException(violations);
}
}
@Override
public void destroy(Object instance, CreationalContext<Object> creationalContext) {
CxfTypeSafeClientBuilder builder = builders.remove(instance);
if (builder != null) {
builder.close();
}
}