Search in sources :

Example 26 with CreationalContext

use of javax.enterprise.context.spi.CreationalContext in project tomee by apache.

the class WebContext method newWeakableInstance.

public <T> Instance newWeakableInstance(final Class<T> beanClass) throws OpenEJBException {
    final WebBeansContext webBeansContext = getWebBeansContext();
    final ConstructorInjectionBean<Object> beanDefinition = getConstructorInjectionBean(beanClass, webBeansContext);
    CreationalContext<Object> creationalContext;
    final Object o;
    if (webBeansContext == null) {
        creationalContext = null;
        try {
            o = beanClass.newInstance();
        } catch (final InstantiationException | IllegalAccessException e) {
            throw new OpenEJBException(e);
        }
    } else {
        creationalContext = webBeansContext.getBeanManagerImpl().createCreationalContext(beanDefinition);
        o = beanDefinition.create(creationalContext);
    }
    // Create bean instance
    final Context unwrap = InjectionProcessor.unwrap(getInitialContext());
    final InjectionProcessor injectionProcessor = new InjectionProcessor(o, injections, unwrap);
    final Object beanInstance;
    try {
        beanInstance = injectionProcessor.createInstance();
        if (webBeansContext != null) {
            final InjectionTargetBean<Object> bean = InjectionTargetBean.class.cast(beanDefinition);
            bean.getInjectionTarget().inject(beanInstance, creationalContext);
            if (shouldBeReleased(bean.getScope())) {
                creationalContexts.put(beanInstance, creationalContext);
            }
        }
    } catch (final OpenEJBException oejbe) {
        if (creationalContext != null) {
            creationalContext.release();
        }
        throw oejbe;
    }
    return new Instance(beanInstance, creationalContext);
}
Also used : CreationalContext(javax.enterprise.context.spi.CreationalContext) Context(javax.naming.Context) InitialContext(javax.naming.InitialContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) AppContext(org.apache.openejb.AppContext) ServletContext(javax.servlet.ServletContext) OpenEJBException(org.apache.openejb.OpenEJBException) WebBeansContext(org.apache.webbeans.config.WebBeansContext) InjectionProcessor(org.apache.openejb.InjectionProcessor)

Example 27 with CreationalContext

use of javax.enterprise.context.spi.CreationalContext in project tomee by apache.

the class WebContext method inject.

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);
    }
}
Also used : CreationalContext(javax.enterprise.context.spi.CreationalContext) Context(javax.naming.Context) InitialContext(javax.naming.InitialContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) AppContext(org.apache.openejb.AppContext) ServletContext(javax.servlet.ServletContext) OpenEJBException(org.apache.openejb.OpenEJBException) WebBeansContext(org.apache.webbeans.config.WebBeansContext) NamingException(javax.naming.NamingException) InjectionProcessor(org.apache.openejb.InjectionProcessor) InitialContext(javax.naming.InitialContext)

Example 28 with CreationalContext

use of javax.enterprise.context.spi.CreationalContext in project Payara by payara.

the class TransactionScopedBeanTest method testAllMethods.

@Test
@SuppressWarnings("unchecked")
public void testAllMethods() {
    LocalBean localBean = new LocalBean();
    EasyMockSupport mockSupport = new EasyMockSupport();
    Contextual<LocalBean> contextual = (Contextual<LocalBean>) mockSupport.createMock(Contextual.class);
    CreationalContext<LocalBean> creationalContext = (CreationalContext<LocalBean>) mockSupport.createMock(CreationalContext.class);
    TransactionScopedContextImpl transactionScopedContext = mockSupport.createMock(TransactionScopedContextImpl.class);
    transactionScopedContext.beansPerTransaction = new ConcurrentHashMap<>();
    // test getContextualInstance
    TransactionScopedBean<LocalBean> transactionScopedBean = getTransactionScopedBean(mockSupport, localBean, contextual, creationalContext, transactionScopedContext);
    assertSame(localBean, transactionScopedBean.getContextualInstance());
    // test afterCompletion
    contextual.destroy(localBean, creationalContext);
    mockSupport.replayAll();
    transactionScopedBean.afterCompletion(0);
    mockSupport.verifyAll();
    mockSupport.resetAll();
}
Also used : CreationalContext(javax.enterprise.context.spi.CreationalContext) EasyMockSupport(org.easymock.EasyMockSupport) Contextual(javax.enterprise.context.spi.Contextual) Test(org.junit.Test)

Example 29 with CreationalContext

use of javax.enterprise.context.spi.CreationalContext in project meecrowave by apache.

the class JpaExtension method initBeans.

void initBeans(@Observes final AfterDeploymentValidation adv, final BeanManager bm) {
    if (entityManagerBeans.isEmpty()) {
        return;
    }
    // only not portable part is this config read, could be optional
    final ServletContext sc = ServletContext.class.cast(bm.getReference(bm.resolve(bm.getBeans(ServletContext.class)), ServletContext.class, bm.createCreationalContext(null)));
    final Meecrowave.Builder config = Meecrowave.Builder.class.cast(sc.getAttribute("meecrowave.configuration"));
    final Map<String, String> props = new HashMap<>();
    if (config != null) {
        ofNullable(config.getProperties()).ifPresent(p -> p.stringPropertyNames().stream().filter(k -> k.startsWith("jpa.property.")).forEach(k -> props.put(k.substring("jpa.property.".length()), p.getProperty(k))));
    }
    final Map<String, PersistenceUnitInfo> infoIndex = unitBuilders.stream().map(bean -> {
        final CreationalContext<?> cc = bm.createCreationalContext(null);
        try {
            final Bean<?> resolvedBean = bm.resolve(bm.getBeans(PersistenceUnitInfoBuilder.class, bean.getQualifiers().toArray(new Annotation[bean.getQualifiers().size()])));
            final PersistenceUnitInfoBuilder builder = PersistenceUnitInfoBuilder.class.cast(bm.getReference(resolvedBean, PersistenceUnitInfoBuilder.class, cc));
            if (builder.getManagedClasses().isEmpty()) {
                builder.setManagedClassNames(jpaClasses).setExcludeUnlistedClasses(true);
            }
            props.forEach(builder::addProperty);
            return builder.toInfo();
        } finally {
            cc.release();
        }
    }).collect(toMap(PersistenceUnitInfo::getPersistenceUnitName, identity()));
    entityManagerBeans.forEach((k, e) -> {
        PersistenceUnitInfo info = infoIndex.get(k.unitName);
        if (info == null) {
            info = tryCreateDefaultPersistenceUnit(k.unitName, bm, props);
        }
        if (info == null) {
            // not valid
            adv.addDeploymentProblem(new IllegalArgumentException("Didn't find any PersistenceUnitInfoBuilder for " + k));
        } else {
            e.init(info, bm);
        }
    });
}
Also used : AfterBeanDiscovery(javax.enterprise.inject.spi.AfterBeanDiscovery) MappedSuperclass(javax.persistence.MappedSuperclass) ProcessBean(javax.enterprise.inject.spi.ProcessBean) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CreationalContext(javax.enterprise.context.spi.CreationalContext) BeforeBeanDiscovery(javax.enterprise.inject.spi.BeforeBeanDiscovery) Collectors.toMap(java.util.stream.Collectors.toMap) Observes(javax.enterprise.event.Observes) AfterDeploymentValidation(javax.enterprise.inject.spi.AfterDeploymentValidation) Map(java.util.Map) SynchronizationType(javax.persistence.SynchronizationType) DataSource(javax.sql.DataSource) Jpa(org.apache.meecrowave.jpa.api.Jpa) Entity(javax.persistence.Entity) Extension(javax.enterprise.inject.spi.Extension) Optional.ofNullable(java.util.Optional.ofNullable) PersistenceUnitInfoBuilder(org.apache.meecrowave.jpa.api.PersistenceUnitInfoBuilder) PersistenceUnitInfo(javax.persistence.spi.PersistenceUnitInfo) Collection(java.util.Collection) ProcessAnnotatedType(javax.enterprise.inject.spi.ProcessAnnotatedType) WithAnnotations(javax.enterprise.inject.spi.WithAnnotations) Set(java.util.Set) List(java.util.List) Stream(java.util.stream.Stream) Unit(org.apache.meecrowave.jpa.api.Unit) Annotation(java.lang.annotation.Annotation) Function.identity(java.util.function.Function.identity) ServletContext(javax.servlet.ServletContext) Embeddable(javax.persistence.Embeddable) Meecrowave(org.apache.meecrowave.Meecrowave) Bean(javax.enterprise.inject.spi.Bean) BeanManager(javax.enterprise.inject.spi.BeanManager) PersistenceUnitInfoBuilder(org.apache.meecrowave.jpa.api.PersistenceUnitInfoBuilder) HashMap(java.util.HashMap) PersistenceUnitInfo(javax.persistence.spi.PersistenceUnitInfo) Annotation(java.lang.annotation.Annotation) ProcessBean(javax.enterprise.inject.spi.ProcessBean) Bean(javax.enterprise.inject.spi.Bean) CreationalContext(javax.enterprise.context.spi.CreationalContext) ServletContext(javax.servlet.ServletContext) Meecrowave(org.apache.meecrowave.Meecrowave)

Example 30 with CreationalContext

use of javax.enterprise.context.spi.CreationalContext in project kie-wb-common by kiegroup.

the class ResourceChangeIncrementalBuilderWithoutFullBuildTest method testBatchResourceChanges.

@Test
public void testBatchResourceChanges() throws Exception {
    final Bean buildChangeListenerBean = (Bean) beanManager.getBeans(org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder.class).iterator().next();
    final CreationalContext cc = beanManager.createCreationalContext(buildChangeListenerBean);
    final org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder buildChangeListener = (org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder) beanManager.getReference(buildChangeListenerBean, org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder.class, cc);
    final URL resourceUrl1 = this.getClass().getResource("/BuildChangeListenerRepo/src/main/resources/add.drl");
    final org.uberfire.java.nio.file.Path nioResourcePath1 = fs.getPath(resourceUrl1.toURI());
    final Path resourcePath1 = paths.convert(nioResourcePath1);
    final URL resourceUrl2 = this.getClass().getResource("/BuildChangeListenerRepo/src/main/resources/update.drl");
    final org.uberfire.java.nio.file.Path nioResourcePath2 = fs.getPath(resourceUrl2.toURI());
    final Path resourcePath2 = paths.convert(nioResourcePath2);
    final URL resourceUrl3 = this.getClass().getResource("/BuildChangeListenerRepo/src/main/resources/delete.drl");
    final org.uberfire.java.nio.file.Path nioResourcePath3 = fs.getPath(resourceUrl3.toURI());
    final Path resourcePath3 = paths.convert(nioResourcePath3);
    final Map<Path, Collection<ResourceChange>> batch = new HashMap<Path, Collection<ResourceChange>>();
    batch.put(resourcePath1, new ArrayList<ResourceChange>() {

        {
            add(new ResourceAdded(""));
        }
    });
    batch.put(resourcePath2, new ArrayList<ResourceChange>() {

        {
            add(new ResourceUpdated(""));
        }
    });
    batch.put(resourcePath3, new ArrayList<ResourceChange>() {

        {
            add(new ResourceUpdated(""));
        }
    });
    // batch.add( new ResourceChange( ResourceChangeType.ADD,
    // resourcePath1,
    // new SessionInfoImpl( "id",
    // new IdentityImpl( "user",
    // Collections.<Role>emptyList() ) ) ) );
    // batch.add( new ResourceChange( ResourceChangeType.UPDATE,
    // resourcePath2,
    // new SessionInfoImpl( "id",
    // new IdentityImpl( "user",
    // Collections.<Role>emptyList() ) ) ) );
    // batch.add( new ResourceChange( ResourceChangeType.DELETE,
    // resourcePath3,
    // new SessionInfoImpl( "id",
    // new IdentityImpl( "user",
    // Collections.<Role>emptyList() ) ) ) );
    // Perform incremental build (Without a full Build first)
    buildChangeListener.batchResourceChanges(batch);
    waitForBuildResults(buildResultsObserver);
    final BuildResults buildResults = buildResultsObserver.getBuildResults();
    assertNotNull(buildResults);
    assertEquals(0, buildResults.getErrorMessages().size());
    assertEquals(1, buildResults.getInformationMessages().size());
    final IncrementalBuildResults incrementalBuildResults = buildResultsObserver.getIncrementalBuildResults();
    assertNull(incrementalBuildResults);
}
Also used : Path(org.uberfire.backend.vfs.Path) IncrementalBuildResults(org.guvnor.common.services.project.builder.model.IncrementalBuildResults) BuildResults(org.guvnor.common.services.project.builder.model.BuildResults) IncrementalBuildResults(org.guvnor.common.services.project.builder.model.IncrementalBuildResults) HashMap(java.util.HashMap) ResourceAdded(org.uberfire.workbench.events.ResourceAdded) URL(java.net.URL) Bean(javax.enterprise.inject.spi.Bean) CreationalContext(javax.enterprise.context.spi.CreationalContext) Collection(java.util.Collection) ResourceChange(org.uberfire.workbench.events.ResourceChange) ResourceUpdated(org.uberfire.workbench.events.ResourceUpdated) Test(org.junit.Test)

Aggregations

CreationalContext (javax.enterprise.context.spi.CreationalContext)132 Bean (javax.enterprise.inject.spi.Bean)113 Test (org.junit.Test)83 URL (java.net.URL)67 Path (org.uberfire.backend.vfs.Path)67 KieModuleService (org.kie.workbench.common.services.shared.project.KieModuleService)66 Package (org.guvnor.common.services.project.model.Package)43 Module (org.guvnor.common.services.project.model.Module)13 BeanManager (javax.enterprise.inject.spi.BeanManager)11 BuildResults (org.guvnor.common.services.project.builder.model.BuildResults)6 IncrementalBuildResults (org.guvnor.common.services.project.builder.model.IncrementalBuildResults)6 Before (org.junit.Before)6 Weld (org.jboss.weld.environment.se.Weld)5 Context (javax.enterprise.context.spi.Context)4 InjectionTarget (javax.enterprise.inject.spi.InjectionTarget)4 WebBeansContext (org.apache.webbeans.config.WebBeansContext)4 Fabric8Extension (io.fabric8.cdi.Fabric8Extension)3 Annotation (java.lang.annotation.Annotation)3 Method (java.lang.reflect.Method)3 Type (java.lang.reflect.Type)3