Java Examples for javax.enterprise.context.ApplicationScoped

The following java examples will help you to understand the usage of javax.enterprise.context.ApplicationScoped. These source code samples are taken from different open source projects.

Example 1
Project: curso-javaee-primefaces-master  File: MailConfigProducer.java View source code
@Produces
@ApplicationScoped
public SessionConfig getMailConfig() throws IOException {
    Properties props = new Properties();
    props.load(getClass().getResourceAsStream("/mail.properties"));
    SimpleMailConfig config = new SimpleMailConfig();
    config.setServerHost(props.getProperty("mail.server.host"));
    config.setServerPort(Integer.parseInt(props.getProperty("mail.server.port")));
    config.setEnableSsl(Boolean.parseBoolean(props.getProperty("mail.enable.ssl")));
    config.setAuth(Boolean.parseBoolean(props.getProperty("mail.auth")));
    config.setUsername(props.getProperty("mail.username"));
    config.setPassword(props.getProperty("mail.password"));
    return config;
}
Example 2
Project: infinispan-master  File: InfinispanExtensionEmbedded.java View source code
/**
    * The default cache manager is an instance of {@link DefaultCacheManager} initialized with the
    * default configuration (either produced by
    * {@link #createDefaultEmbeddedConfigurationBean(BeanManager)} or provided by user). The default
    * cache manager can be overridden by creating a producer which produces the new default cache
    * manager. The cache manager produced must have the scope {@link ApplicationScoped} and the
    * {@linkplain javax.enterprise.inject.Default Default} qualifier.
    *
    * @param beanManager
    * @return a custom bean
    */
private Bean<EmbeddedCacheManager> createDefaultEmbeddedCacheManagerBean(BeanManager beanManager) {
    return new BeanBuilder<EmbeddedCacheManager>(beanManager).beanClass(InfinispanExtensionEmbedded.class).addTypes(Object.class, EmbeddedCacheManager.class).scope(ApplicationScoped.class).qualifiers(defaultQualifiers()).passivationCapable(true).id(InfinispanExtensionEmbedded.class.getSimpleName() + "#" + EmbeddedCacheManager.class.getSimpleName()).beanLifecycle(new ContextualLifecycle<EmbeddedCacheManager>() {

        @Override
        public EmbeddedCacheManager create(Bean<EmbeddedCacheManager> bean, CreationalContext<EmbeddedCacheManager> creationalContext) {
            GlobalConfiguration globalConfiguration = new GlobalConfigurationBuilder().globalJmxStatistics().cacheManagerName(CACHE_NAME).build();
            @SuppressWarnings("unchecked") Bean<Configuration> configurationBean = (Bean<Configuration>) beanManager.resolve(beanManager.getBeans(Configuration.class));
            Configuration defaultConfiguration = (Configuration) beanManager.getReference(configurationBean, Configuration.class, beanManager.createCreationalContext(configurationBean));
            return new DefaultCacheManager(globalConfiguration, defaultConfiguration);
        }

        @Override
        public void destroy(Bean<EmbeddedCacheManager> bean, EmbeddedCacheManager instance, CreationalContext<EmbeddedCacheManager> creationalContext) {
            instance.stop();
        }
    }).create();
}
Example 3
Project: fabric8-master  File: EagerCDIExtension.java View source code
public void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager beanManager) {
    AnnotationLiteral<Eager> annotationLiteral = new AnnotationLiteral<Eager>() {
    };
    Set<Bean<?>> beans = beanManager.getBeans(Object.class, annotationLiteral);
    for (Bean<?> bean : beans) {
        Class<?> beanClass = bean.getBeanClass();
        if (beanClass.isAnnotationPresent(ApplicationScoped.class) || beanClass.isAnnotationPresent(Singleton.class)) {
            beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean)).toString();
        }
    }
}
Example 4
Project: cdi-light-config-master  File: Scopes.java View source code
public static String toScopeClass(final String scope) {
    if (scope == null || "dependent".equalsIgnoreCase(scope) || Dependent.class.getName().equals(scope)) {
        return Dependent.class.getName();
    }
    if ("application".equalsIgnoreCase(scope) || ApplicationScoped.class.getName().equals(scope)) {
        return ApplicationScoped.class.getName();
    }
    if ("session".equalsIgnoreCase(scope) || SessionScoped.class.getName().equals(scope)) {
        return SessionScoped.class.getName();
    }
    if ("request".equalsIgnoreCase(scope) || RequestScoped.class.getName().equals(scope)) {
        return RequestScoped.class.getName();
    }
    return scope;
}
Example 5
Project: cdi-test-master  File: AnnotationReplacementHolderTest.java View source code
@Test
public void simpleReplacementWithComment() {
    createHolder("test-annotations.properties");
    Map<Class<? extends Annotation>, Annotation> replacementMap = holder.getReplacementMap();
    assertEquals(1, replacementMap.size());
    Map.Entry<Class<? extends Annotation>, Annotation> annotationEntry = replacementMap.entrySet().iterator().next();
    assertEquals(SessionScoped.class, annotationEntry.getKey());
    assertTrue(annotationEntry.getValue() instanceof ApplicationScoped);
}
Example 6
Project: jbosstools-integration-tests-master  File: PartialBeanTest.java View source code
@Test
public void testPartialBean() {
    ProjectExplorer pe = new ProjectExplorer();
    pe.open();
    pe.getProject(projectName).select();
    String classesPath = "resources/classes/binding/";
    createClassWithContent("ExamplePartialBeanBinding", classesPath + "ExamplePartialBeanBinding.jav_");
    new WaitWhile(new ClassHasErrorMarker("ExamplePartialBeanBinding"));
    // Each partial bean should be bound to an invocation handler.
    createClassWithContent("ExamplePartialBeanInterface", classesPath + "ExamplePartialBeanInterface.jav_");
    // remove this and use asserErrorExists when JBIDE-18852 will be resolved
    TextEditor ed1 = new TextEditor("ExamplePartialBeanInterface.java");
    try {
        new WaitUntil(new EditorHasValidationMarkers(ed1), TimePeriod.LONG);
    } catch (WaitTimeoutExpiredException ex) {
        fail("this is known issue JBIDE-18852");
    }
    assertEquals(1, ed1.getMarkers().size());
    Marker marker = ed1.getMarkers().get(0);
    assertEquals("Partial bean test.ExamplePartialBeanInterface should have an invocation handler for binding annotation test.ExamplePartialBeanBinding", marker.getText());
    assertEquals("org.eclipse.ui.workbench.texteditor.warning", marker.getType());
    //assertErrorExists("ExamplePartialBeanInterface","Partial bean test.ExamplePartialBeanInterface should have an invocation handler for binding annotation test.ExamplePartialBeanBinding");
    // Each partial bean should be bound to an invocation handler.
    createClassWithContent("ExamplePartialBeanAbstractClass", classesPath + "ExamplePartialBeanAbstractClass.jav_");
    assertErrorExists("ExamplePartialBeanAbstractClass", "Partial bean test.ExamplePartialBeanAbstractClass should have an invocation handler for binding annotation test.ExamplePartialBeanBinding");
    createClassWithContent("ExamplePartialBeanImplementation", classesPath + "ExamplePartialBeanImplementation.jav_");
    new WaitWhile(new ClassHasErrorMarker("ExamplePartialBeanImplementation"));
    new WaitWhile(new ClassHasErrorMarker("ExamplePartialBeanAbstractClass"));
    new WaitWhile(new ClassHasErrorMarker("ExamplePartialBeanInterface"));
    //Class annotated with a binding annotation should be either abstract, or interface, or implement InvocationHandler.
    TextEditor ed = new TextEditor("ExamplePartialBeanImplementation.java");
    ed.setText(ed.getText().replace("import java.lang.reflect.InvocationHandler;", ""));
    ed.setText(ed.getText().replace("implements InvocationHandler", ""));
    ed.save();
    assertErrorExists("ExamplePartialBeanImplementation", "Binding annotation test.ExamplePartialBeanBinding can be applied only to abstract classes, interfaces, and classes implementing InvocationHandler");
    replaceClassContent("ExamplePartialBeanImplementation", classesPath + "ExamplePartialBeanImplementation.jav_");
    new WaitWhile(new ClassHasErrorMarker("ExamplePartialBeanImplementation"));
    //There should be no more than one invocation handler for each binding annotation.
    createClassWithContent("AnotherImplementation", classesPath + "AnotherImplementation.jav_");
    assertErrorExists("AnotherImplementation", "Multiple handlers are found for binding annotation test.ExamplePartialBeanBinding");
    assertErrorExists("ExamplePartialBeanImplementation", "Multiple handlers are found for binding annotation test.ExamplePartialBeanBinding");
    pe.open();
    pe.getProject(projectName).getProjectItem("Java Resources", "src", "test", "AnotherImplementation.java").delete();
    new WaitWhile(new ClassHasErrorMarker("ExamplePartialBeanImplementation"));
    // Invocation handler class should be normal-scoped.
    ed = new TextEditor("ExamplePartialBeanImplementation.java");
    ed.setText(ed.getText().replace("@ApplicationScoped", "@Dependent"));
    ed.setText(ed.getText().replace("import javax.enterprise.context.ApplicationScoped", "import javax.enterprise.context.Dependent"));
    ed.save();
    assertErrorExists("ExamplePartialBeanImplementation", "Invocation handler class should be a normal-scoped bean");
    replaceClassContent("ExamplePartialBeanImplementation", classesPath + "ExamplePartialBeanImplementation.jav_");
    new WaitWhile(new ClassHasErrorMarker("ExamplePartialBeanImplementation"));
    createClassWithContent("AnotherBinding", classesPath + "AnotherBinding.jav_");
    new WaitWhile(new ClassHasErrorMarker("AnotherBinding"));
    //Deltaspike implementation of the extension reads the first binding annotation on a class and ignores the next ones. Hence, they should be marked with a warning:
    ed = new TextEditor("ExamplePartialBeanImplementation.java");
    int pos = ed.getPositionOfText("@ExamplePartialBeanBinding");
    ed.insertText(pos, "@AnotherBinding\n");
    ed.save();
    assertErrorExists("ExamplePartialBeanImplementation", "Binding annotation test.ExamplePartialBeanBinding is ignored because class is already annotated with binding annotation test.AnotherBinding");
}
Example 7
Project: solder-master  File: AnnotatedTypeBuilderTest.java View source code
/**
     * @see <a href="https://issues.jboss.org/browse/SOLDER-103">SOLDER-103</a>
     */
@Test
public void testTypeLevelAnnotationRedefinition() {
    AnnotatedTypeBuilder<Cat> builder = new AnnotatedTypeBuilder<Cat>();
    builder.readFromType(Cat.class);
    builder.redefine(Named.class, new NamedAnnotationRedefiner());
    AnnotatedType<Cat> cat = builder.create();
    assertEquals(3, cat.getAnnotations().size());
    assertTrue(cat.isAnnotationPresent(Named.class));
    assertTrue(cat.isAnnotationPresent(Alternative.class));
    assertTrue(cat.isAnnotationPresent(ApplicationScoped.class));
    assertEquals("tomcat", cat.getAnnotation(Named.class).value());
}
Example 8
Project: spring-data-gemfire-master  File: GemfireCacheRegionProducer.java View source code
@Produces
@ApplicationScoped
public Region<Long, Person> createPeopleRegion() {
    Cache gemfireCache = new CacheFactory().set("name", "SpringDataGemFireCdiTest").set("mcast-port", "0").set("log-level", "warning").create();
    RegionFactory<Long, Person> peopleRegionFactory = gemfireCache.createRegionFactory(RegionShortcut.REPLICATE);
    peopleRegionFactory.setKeyConstraint(Long.class);
    peopleRegionFactory.setValueConstraint(Person.class);
    Region<Long, Person> peopleRegion = peopleRegionFactory.create("People");
    Assert.notNull(peopleRegion);
    return peopleRegion;
}
Example 9
Project: actframework-master  File: App.java View source code
private void initDaemonRegistry() {
    if (null != daemonRegistry) {
        Destroyable.Util.tryDestroyAll(daemonRegistry.values(), ApplicationScoped.class);
    }
    daemonRegistry = C.newMap();
    jobManager.on(AppEventId.START, new Runnable() {

        @Override
        public void run() {
            jobManager.fixedDelay("daemon-keeper", new Runnable() {

                @Override
                public void run() {
                    daemonKeeper();
                }
            }, "1mn");
        }
    });
}
Example 10
Project: blaze-persistence-master  File: CDIShowcaseRunner.java View source code
public static void main(String[] args) {
    CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer();
    cdiContainer.boot();
    ContextControl contextControl = cdiContainer.getContextControl();
    contextControl.startContext(ApplicationScoped.class);
    ServiceLoader<Showcase> showcaseLoader = ServiceLoader.load(Showcase.class);
    Iterator<Metadata<Showcase>> showcaseIterator = showcaseLoader.iterator();
    if (!showcaseIterator.hasNext()) {
        throw new RuntimeException("No showcases found");
    }
    while (showcaseIterator.hasNext()) {
        BeanProvider.injectFields(showcaseIterator.next().getValue()).run();
    }
    cdiContainer.shutdown();
}
Example 11
Project: cdi-tck-master  File: BeanManagerTest.java View source code
@Test
@SpecAssertion(section = BM_DETERMINING_ANNOTATION, id = "aa")
public void testDetermineQualifierType() {
    assertTrue(getCurrentManager().isQualifier(Any.class));
    assertTrue(getCurrentManager().isQualifier(Tame.class));
    assertFalse(getCurrentManager().isQualifier(AnimalStereotype.class));
    assertFalse(getCurrentManager().isQualifier(ApplicationScoped.class));
    assertFalse(getCurrentManager().isQualifier(Transactional.class));
}
Example 12
Project: core-master  File: WeldStartup.java View source code
public TypeDiscoveryConfiguration startExtensions(Iterable<Metadata<Extension>> extensions) {
    setExtensions(extensions);
    // TODO WELD-1624 Weld should fire BeforeBeanDiscovery to allow extensions to register additional scopes
    final Set<Class<? extends Annotation>> beanDefiningAnnotations = ImmutableSet.of(// built-in scopes
    Dependent.class, RequestScoped.class, ConversationScoped.class, SessionScoped.class, ApplicationScoped.class, javax.interceptor.Interceptor.class, javax.decorator.Decorator.class, // built-in stereotype
    Model.class, // meta-annotations
    NormalScope.class, Stereotype.class);
    return new TypeDiscoveryConfigurationImpl(beanDefiningAnnotations);
}
Example 13
Project: dcm4chee-conf-master  File: DicomConfigManagerProducer.java View source code
@Produces
@ApplicationScoped
public DicomConfigurationManager createDicomConfigurationManager() {
    log.info("Constructing DicomConfiguration ...");
    // the init might create a root node, but it will be done in separate tx, in this case the integrity check should succeed
    // if the config is not empty, there will be no modification, and therefore the integrity check will not happen at this point, but only after the upgrade
    CommonDicomConfigurationWithHL7 configurationWithHL7 = new CommonDicomConfigurationWithHL7(providedConfigStorage, extensionsProvider.resolveExtensionsMap(true), true);
    if (upgradeManagerInstance.isUnsatisfied()) {
        log.info("Dicom configuration upgrade is not configured for this deployment, skipping");
    } else
        // Perform upgrade
        try {
            upgradeManagerInstance.get().performUpgrade(configurationWithHL7);
        } catch (Exception e) {
            throw new RuntimeException("DicomConfiguration upgrade failure", e);
        }
    log.info("DicomConfiguration created.");
    return configurationWithHL7;
}
Example 14
Project: deltaspike-master  File: CdiTestRunner.java View source code
void applyBeforeClassConfig(Class testClass) {
    CdiContainer container = CdiContainerLoader.getCdiContainer();
    if (!isContainerStarted()) {
        if (!CdiTestSuiteRunner.isContainerStarted()) {
            container.boot(CdiTestSuiteRunner.getTestContainerConfig());
            setContainerStarted();
            bootExternalContainers(testClass);
        }
    }
    List<Class<? extends Annotation>> restrictedScopes = new ArrayList<Class<? extends Annotation>>();
    //controlled by the container and not supported by weld:
    restrictedScopes.add(ApplicationScoped.class);
    restrictedScopes.add(Singleton.class);
    if (this.parent == null && this.testControl.getClass().equals(TestControlLiteral.class)) {
        //skip scope-handling if @TestControl isn't used explicitly on the test-class -> TODO re-visit it
        restrictedScopes.add(RequestScoped.class);
        restrictedScopes.add(SessionScoped.class);
    }
    startScopes(container, testClass, null, restrictedScopes.toArray(new Class[restrictedScopes.size()]));
}
Example 15
Project: demoiselle-agent-master  File: ManagementProducer.java View source code
@Produces
@ApplicationScoped
public ManagementV1 create() {
    final ManagementService service = new ManagementService(config);
    final ManagementV1 port = service.getManagementPortV1();
    final BindingProvider bindingProvider = (BindingProvider) port;
    final Map<String, Object> requestContext = bindingProvider.getRequestContext();
    requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, this.getEndpointAddress("Management_v1"));
    return port;
}
Example 16
Project: errai-master  File: NavigationGraphGenerator.java View source code
/**
   * Appends a method that destroys the IOC bean associated with a page node if the bean is
   * dependent scope.
   *
   * @param pageImplBuilder
   *          The class builder for the implementation of PageNode we are adding the method to.
   * @param pageClass
   *          The "content type" (Widget subclass) of the page. This is the type the user annotated
   *          with {@code @Page}.
   */
private void appendDestroyMethod(AnonymousClassStructureBuilder pageImplBuilder, MetaClass pageClass) {
    BlockBuilder<?> method = pageImplBuilder.publicMethod(void.class, "destroy", Parameter.of(pageClass, "widget")).body();
    if (pageClass.getAnnotation(Singleton.class) == null && pageClass.getAnnotation(ApplicationScoped.class) == null && pageClass.getAnnotation(EntryPoint.class) == null) {
        method.append(Stmt.loadVariable("bm").invoke("destroyBean", Stmt.loadVariable("widget")));
    }
    method.finish();
}
Example 17
Project: hammock-master  File: ConnectionFactoryProducer.java View source code
@Produces
@ApplicationScoped
public ConnectionFactory createConnectionFactory(RabbitMQConfiguration rabbitMQConfiguration) {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(rabbitMQConfiguration.isAutomaticRecovery());
    connectionFactory.setClientProperties(rabbitMQConfiguration.getClientProperties());
    connectionFactory.setConnectionTimeout(rabbitMQConfiguration.getConnectionTimeout());
    connectionFactory.setExceptionHandler(rabbitMQConfiguration.getExceptionHandler());
    connectionFactory.setHandshakeTimeout(rabbitMQConfiguration.getHandshakeTimeout());
    connectionFactory.setHeartbeatExecutor(rabbitMQConfiguration.getHeartbeatExecutor());
    connectionFactory.setMetricsCollector(rabbitMQConfiguration.getMetricsCollector());
    connectionFactory.setHost(rabbitMQConfiguration.getHost());
    connectionFactory.setNetworkRecoveryInterval(rabbitMQConfiguration.getNetworkRecoveryInterval());
    if (rabbitMQConfiguration.isNio()) {
        connectionFactory.useNio();
        connectionFactory.setNioParams(rabbitMQConfiguration.getNioParams());
    }
    connectionFactory.setPassword(rabbitMQConfiguration.getPassword());
    connectionFactory.setPort(rabbitMQConfiguration.getPort());
    connectionFactory.setRequestedChannelMax(rabbitMQConfiguration.getRequestedChannelMax());
    connectionFactory.setRequestedFrameMax(rabbitMQConfiguration.getRequestedFrameMax());
    connectionFactory.setRequestedHeartbeat(rabbitMQConfiguration.getRequestedHeartbeat());
    connectionFactory.setSaslConfig(rabbitMQConfiguration.getSaslConfig());
    connectionFactory.setSharedExecutor(rabbitMQConfiguration.getSharedExecutor());
    connectionFactory.setShutdownExecutor(rabbitMQConfiguration.getShutdownExecutor());
    connectionFactory.setShutdownTimeout(rabbitMQConfiguration.getShutdownTimeout());
    connectionFactory.setSocketConfigurator(rabbitMQConfiguration.getSocketConf());
    connectionFactory.setSocketFactory(rabbitMQConfiguration.getFactory());
    connectionFactory.setThreadFactory(rabbitMQConfiguration.getThreadFactory());
    connectionFactory.setTopologyRecoveryEnabled(rabbitMQConfiguration.isTopologyRecovery());
    try {
        connectionFactory.setUri(rabbitMQConfiguration.getUri());
    } catch (Exception e) {
        throw new RuntimeException("Unable to populate URI ", e);
    }
    connectionFactory.setUsername(rabbitMQConfiguration.getUsername());
    connectionFactory.setVirtualHost(rabbitMQConfiguration.getVirtualHost());
    if (rabbitMQConfiguration.getSslContext() != null) {
        connectionFactory.useSslProtocol(rabbitMQConfiguration.getSslContext());
    }
    return connectionFactory;
}
Example 18
Project: hot-reload-master  File: App.java View source code
private void initDaemonRegistry() {
    if (null != daemonRegistry) {
        Destroyable.Util.tryDestroyAll(daemonRegistry.values(), ApplicationScoped.class);
    }
    daemonRegistry = C.newMap();
    jobManager.on(AppEventId.START, new Runnable() {

        @Override
        public void run() {
            jobManager.fixedDelay("daemon-keeper", new Runnable() {

                @Override
                public void run() {
                    daemonKeeper();
                }
            }, "1mn");
        }
    });
}
Example 19
Project: HotswapAgent-master  File: HAOpenWebBeansTestLifeCycle.java View source code
public void beforeStopApplication(Object endObject) {
    WebBeansContext webBeansContext = getWebBeansContext();
    ContextsService contextsService = webBeansContext.getContextsService();
    contextsService.endContext(Singleton.class, null);
    contextsService.endContext(ApplicationScoped.class, null);
    contextsService.endContext(RequestScoped.class, null);
    contextsService.endContext(SessionScoped.class, null);
    ELContextStore elStore = ELContextStore.getInstance(false);
    if (elStore == null) {
        return;
    }
    elStore.destroyELContextStore();
}
Example 20
Project: oxAuth-master  File: AppInitializer.java View source code
public void applicationInitialized(@Observes @Initialized(ApplicationScoped.class) Object init) {
    createConnectionProvider();
    configurationFactory.create();
    LdapEntryManager localLdapEntryManager = ldapEntryManagerInstance.get();
    List<GluuLdapConfiguration> ldapAuthConfigs = loadLdapAuthConfigs(localLdapEntryManager);
    createAuthConnectionProviders(ldapAuthConfigs);
    setDefaultAuthenticationMethod(localLdapEntryManager);
    // Initialize python interpreter
    pythonService.initPythonInterpreter(configurationFactory.getLdapConfiguration().getString("pythonModulesDir", null));
    // Initialize script manager
    List<CustomScriptType> supportedCustomScriptTypes = Arrays.asList(CustomScriptType.PERSON_AUTHENTICATION, CustomScriptType.CLIENT_REGISTRATION, CustomScriptType.ID_GENERATOR, CustomScriptType.UMA_AUTHORIZATION_POLICY, CustomScriptType.APPLICATION_SESSION, CustomScriptType.DYNAMIC_SCOPE);
    customScriptManager.init(supportedCustomScriptTypes);
    metricService.init();
    // Start timer
    quartzSchedulerManager.start();
    // Schedule timer tasks
    ldapStatusTimer.initTimer();
    cleanerTimer.initTimer();
    configurationFactory.initTimer();
    keyGeneratorTimer.initTimer();
    initTimer();
}
Example 21
Project: picketlink-master  File: ConfigurationOperations.java View source code
private JavaClass createJavaClass(String className, String packageName) {
    String lineSeparator = System.getProperty("line.separator");
    JavaClass javaClass = javaSourceFactory.create(JavaClass.class).setName(className).setPublic().addAnnotation(ApplicationScoped.class).getOrigin();
    javaClass.setPackage(packageName);
    javaClass.addField("private IdentityConfiguration identityConfig = null;");
    Method<JavaClass> producerMethod = javaClass.addMethod("IdentityConfiguration createConfig() { " + lineSeparator + "  if (identityConfig == null) {" + lineSeparator + "    initConfig();" + lineSeparator + "  }" + lineSeparator + "  return identityConfig;" + lineSeparator + "}");
    producerMethod.addAnnotation(Produces.class);
    javaClass.addMethod("private void initConfig() {" + lineSeparator + "  IdentityConfigurationBuilder builder = new IdentityConfigurationBuilder();" + lineSeparator + "  builder" + lineSeparator + "    .named(\"default\")" + lineSeparator + "      .stores()" + lineSeparator + "        .file()" + lineSeparator + "          .supportAllFeatures();" + lineSeparator + "  identityConfig = builder.build();" + "}");
    javaClass.addImport(IdentityConfigurationBuilder.class);
    javaClass.addImport(IdentityConfiguration.class);
    return javaClass;
}
Example 22
Project: seam-scheduling-master  File: SchedulerProducer.java View source code
@Produces
@Named("org.quartz.Scheduler")
@ApplicationScoped
public Scheduler getScheduler() {
    Scheduler scheduler = null;
    try {
        SchedulerFactory sf = new StdSchedulerFactory();
        scheduler = sf.getScheduler();
    } catch (SchedulerException ex) {
        Logger.getLogger(SchedulerProducer.class.getName()).log(Level.SEVERE, null, ex);
    }
    return scheduler;
}
Example 23
Project: tomee-master  File: AnnotationDeployer.java View source code
private void getBeanClasses(final String uri, final IAnnotationFinder finder, final Map<URL, List<String>> classes, final Map<URL, List<String>> notManaged, final Map<String, Object> altDD) {
    //  What we're hoping in this method is to get lucky and find
    //  that our 'finder' instances is an AnnotationFinder that is
    //  holding an AggregatedArchive so we can get the classes that
    //  that pertain to each URL for CDI purposes.
    //
    //  If not we call finder.getAnnotatedClassNames() which may return
    //  more classes than actually apply to CDI.  This can "pollute"
    //  the CDI class space and break injection points
    // force cast otherwise we would be broken
    final IAnnotationFinder delegate = FinderFactory.ModuleLimitedFinder.class.isInstance(finder) ? FinderFactory.ModuleLimitedFinder.class.cast(finder).getDelegate() : finder;
    if (!AnnotationFinder.class.isInstance(delegate)) {
        // only few tests
        return;
    }
    final AnnotationFinder annotationFinder = AnnotationFinder.class.cast(delegate);
    final Archive archive = annotationFinder.getArchive();
    if (!WebappAggregatedArchive.class.isInstance(archive)) {
        try {
            final List<String> annotatedClassNames = annotationFinder.getAnnotatedClassNames();
            if (!annotatedClassNames.isEmpty()) {
                classes.put(uri == null ? null : new URL(uri), annotatedClassNames);
            }
        } catch (final MalformedURLException e) {
            throw new IllegalStateException(e);
        }
        return;
    }
    final WebappAggregatedArchive aggregatedArchive = (WebappAggregatedArchive) archive;
    final Map<URL, List<String>> map = aggregatedArchive.getClassesMap();
    Collection<Class<?>> discoveredBeans = null;
    List<Class<? extends Extension>> extensions = null;
    final FolderDDMapper ddMapper = SystemInstance.get().getComponent(FolderDDMapper.class);
    for (final Map.Entry<URL, List<String>> entry : map.entrySet()) {
        final URL key = entry.getKey();
        final URL beansXml = hasBeansXml(key, ddMapper);
        final List<String> value = entry.getValue();
        if (beansXml != null) {
            classes.put(beansXml, value);
        } else if (!value.isEmpty()) {
            final Set<String> fastValue = new HashSet<>(value);
            if (discoveredBeans == null) {
                // lazy init for apps not using it, it slows down the app boot and that should be useless
                discoveredBeans = new HashSet<>();
                final Set<Class<? extends Annotation>> containerAnnot = new HashSet<>();
                containerAnnot.add(Stereotype.class);
                containerAnnot.add(NormalScope.class);
                containerAnnot.add(Dependent.class);
                containerAnnot.add(ApplicationScoped.class);
                containerAnnot.add(ConversationScoped.class);
                containerAnnot.add(RequestScoped.class);
                containerAnnot.add(SessionScoped.class);
                containerAnnot.add(Model.class);
                containerAnnot.add(Singleton.class);
                containerAnnot.add(Stateless.class);
                containerAnnot.add(Stateful.class);
                containerAnnot.add(MessageDriven.class);
                containerAnnot.add(javax.interceptor.Interceptor.class);
                containerAnnot.add(Decorator.class);
                final ClassLoader classLoader = ParentClassLoaderFinder.Helper.get();
                try {
                    for (final String name : asList("javax.faces.flow.FlowScoped", "javax.faces.view.ViewScoped")) {
                        containerAnnot.add((Class<? extends Annotation>) classLoader.loadClass(name));
                    }
                } catch (final Throwable e) {
                }
                final Set<Class<?>> newMarkers = new HashSet<>();
                for (final Class<? extends Annotation> a : containerAnnot) {
                    newMarkers.addAll(finder.findAnnotatedClasses(a));
                }
                do {
                    final Set<Class<?>> loopMarkers = new HashSet<>(newMarkers);
                    newMarkers.clear();
                    for (final Class<?> marker : loopMarkers) {
                        discoveredBeans.add(marker);
                        final List<Class<?>> found = finder.findAnnotatedClasses(Class.class.cast(marker));
                        for (final Class<?> c : found) {
                            if (c.isAnnotation()) {
                                newMarkers.add(c);
                            }
                            discoveredBeans.add(c);
                        }
                    }
                } while (!newMarkers.isEmpty());
                for (final Field field : finder.findAnnotatedFields(Delegate.class)) {
                    // should be done for constructors but too slow?
                    discoveredBeans.add(field.getDeclaringClass());
                }
                extensions = finder.findImplementations(Extension.class);
            }
            boolean skip = false;
            for (final Class<?> c : extensions) {
                if (fastValue.contains(c.getName())) {
                    // legacy mode, we should check META-INF/services/... but this mode + having an Extension should be enough
                    skip = true;
                    continue;
                }
            }
            if (skip) {
                continue;
            }
            final Set<String> beans = new HashSet<>();
            for (final Class<?> c : discoveredBeans) {
                final String name = c.getName();
                if (fastValue.contains(name)) {
                    beans.add(name);
                }
            }
            if (beans.isEmpty()) {
                continue;
            }
            // just keep the potential ones to not load all classes during boot
            notManaged.put(entry.getKey(), new ArrayList<String>(beans));
        }
    }
}
Example 24
Project: trimou-master  File: MustacheEngineProducer.java View source code
@ApplicationScoped
@Produces
public MustacheEngine produceMustacheEngine(SimpleStatsCollector simpleStatsCollector) {
    // 9. Collect some basic rendering statistics
    return MustacheEngineBuilder.newBuilder().setProperty(EngineConfigurationKey.PRECOMPILE_ALL_TEMPLATES, true).setProperty(EngineConfigurationKey.SKIP_VALUE_ESCAPING, true).registerHelpers(HelpersBuilder.extra().add("format", new DateTimeFormatHelper()).build()).addTemplateLocator(ServletContextTemplateLocator.builder().setRootPath("/WEB-INF/templates").setSuffix("html").build()).setLocaleSupport(new RequestLocaleSupport()).addMustacheListener(Minify.htmlListener()).addMustacheListener(simpleStatsCollector).build();
}
Example 25
Project: uma-master  File: AppInitializer.java View source code
public void applicationInitialized(@Observes @Initialized(ApplicationScoped.class) Object init) {
    createConnectionProvider();
    configurationFactory.create();
    LdapEntryManager localLdapEntryManager = ldapEntryManagerInstance.get();
    List<GluuLdapConfiguration> ldapAuthConfigs = loadLdapAuthConfigs(localLdapEntryManager);
    createAuthConnectionProviders(ldapAuthConfigs);
    setDefaultAuthenticationMethod(localLdapEntryManager);
    // Initialize python interpreter
    pythonService.initPythonInterpreter(configurationFactory.getLdapConfiguration().getString("pythonModulesDir", null));
    // Initialize script manager
    List<CustomScriptType> supportedCustomScriptTypes = Arrays.asList(CustomScriptType.PERSON_AUTHENTICATION, CustomScriptType.CLIENT_REGISTRATION, CustomScriptType.ID_GENERATOR, CustomScriptType.UMA_AUTHORIZATION_POLICY, CustomScriptType.APPLICATION_SESSION, CustomScriptType.DYNAMIC_SCOPE);
    // Start timer
    quartzSchedulerManager.start();
    // Schedule timer tasks
    metricService.initTimer();
    configurationFactory.initTimer();
    ldapStatusTimer.initTimer();
    cleanerTimer.initTimer();
    customScriptManager.initTimer(supportedCustomScriptTypes);
    keyGeneratorTimer.initTimer();
    initTimer();
}
Example 26
Project: bullsfirst-server-java-master  File: DozerMapperFactory.java View source code
@Produces
@ApplicationScoped
public Mapper getMapper() {
    BeanMappingBuilder builder = new BeanMappingBuilder() {

        protected void configure() {
            mapping(org.archfirst.bfoms.domain.security.User.class, org.archfirst.bfoms.webservice.security.User.class).fields("person.firstName", "firstName").fields("person.lastName", "lastName");
            mapping(org.archfirst.bfoms.domain.security.User.class, org.archfirst.bfoms.restservice.user.User.class).fields("person.firstName", "firstName").fields("person.lastName", "lastName");
            mapping(org.archfirst.bfoms.domain.account.brokerage.order.Order.class, org.archfirst.bfoms.restservice.order.Order.class).fields("account.id", "accountId").fields("account.name", "accountName").fields("creationTime", "creationTime", copyByReference()).fields("quantity", "quantity", copyByReference()).fields("cumQty", "cumQty", copyByReference()).fields("limitPrice", "limitPrice", copyByReference());
            mapping(org.archfirst.bfoms.domain.account.brokerage.order.Execution.class, org.archfirst.bfoms.restservice.order.Execution.class).fields("creationTime", "creationTime", copyByReference()).fields("quantity", "quantity", copyByReference()).fields("price", "price", copyByReference());
        }
    };
    // Create mapper
    DozerBeanMapper mapper = new DozerBeanMapper();
    // Add mappings
    mapper.addMapping(builder);
    return mapper;
}
Example 27
Project: camel-master  File: Application.java View source code
void login(@Observes @Initialized(ApplicationScoped.class) Object event) {
    System.out.println("████████╗██╗  ██╗███████╗    ███╗   ███╗ █████╗ ████████╗██████╗ ██╗██╗  ██╗\n" + "╚��██╔���██║  ██║██╔�����    ████╗ ████║██╔��██╗╚��██╔���██╔��██╗██║╚██╗██╔�\n" + "   ██║   ███████║█████╗      ██╔████╔██║███████║   ██║   ██████╔�██║ ╚███╔� \n" + "   ██║   ██╔��██║██╔���      ██║╚██╔�██║██╔��██║   ██║   ██╔��██╗██║ ██╔██╗ \n" + "   ██║   ██║  ██║███████╗    ██║ ╚�� ██║██║  ██║   ██║   ██║  ██║██║██╔� ██╗\n" + "   ╚��   ╚��  ╚��╚�������    ╚��     ╚��╚��  ╚��   ╚��   ╚��  ╚��╚��╚��  ╚��");
}
Example 28
Project: cloudtm-data-platform-master  File: Config.java View source code
/**
    * Overrides the default embedded cache manager.
    */
@Produces
@ApplicationScoped
public EmbeddedCacheManager defaultCacheManager(@Resource("infinispan.xml") InputStream xml) throws IOException {
    EmbeddedCacheManager externalCacheContainerManager = new DefaultCacheManager(xml);
    externalCacheContainerManager.defineConfiguration("quick-very-large", new ConfigurationBuilder().read(externalCacheContainerManager.getDefaultCacheConfiguration()).expiration().wakeUpInterval(1l).build());
    return externalCacheContainerManager;
}
Example 29
Project: drools-master  File: KieCDIExtension.java View source code
private <T> Class<? extends Annotation> getScope(ProcessInjectionTarget<T> pit) {
    Set<Annotation> annotations = pit.getAnnotatedType().getAnnotations();
    for (Annotation annotation : annotations) {
        Class<? extends Annotation> scope = annotation.annotationType();
        if (scope.getAnnotation(NormalScope.class) != null || scope.getAnnotation(Scope.class) != null) {
            return scope;
        }
    }
    return ApplicationScoped.class;
}
Example 30
Project: jbosstools-javaee-master  File: ScopeDefinitionTest.java View source code
/**
	 * section 2.4.4 c)
	 * 
	 * @throws JavaModelException
	 */
public void testMultipleCompatibleScopeStereotypes() throws JavaModelException {
    Collection<IBean> beans = getBeans("org.jboss.jsr299.tck.tests.definition.scope.Grayling");
    assertEquals("Wrong number of beans.", 1, beans.size());
    IBean bean = beans.iterator().next();
    assertEquals("Wrong scope type", "javax.enterprise.context.ApplicationScoped", bean.getScope().getSourceType().getFullyQualifiedName());
}
Example 31
Project: liquibase-master  File: CDIBootstrap.java View source code
void afterBeanDiscovery(@Observes AfterBeanDiscovery abd, BeanManager bm) {
    AnnotatedType<CDILiquibase> at = bm.createAnnotatedType(CDILiquibase.class);
    final InjectionTarget<CDILiquibase> it = bm.createInjectionTarget(at);
    instance = new Bean<CDILiquibase>() {

        @Override
        public Set<Type> getTypes() {
            Set<Type> types = new HashSet<Type>();
            types.add(CDILiquibase.class);
            types.add(Object.class);
            return types;
        }

        @Override
        public Set<Annotation> getQualifiers() {
            Set<Annotation> qualifiers = new HashSet<Annotation>();
            qualifiers.add(new AnnotationLiteral<Default>() {
            });
            qualifiers.add(new AnnotationLiteral<Any>() {
            });
            return qualifiers;
        }

        @Override
        public Class<? extends Annotation> getScope() {
            return ApplicationScoped.class;
        }

        @Override
        public String getName() {
            return "cdiLiquibase";
        }

        @Override
        public Set<Class<? extends Annotation>> getStereotypes() {
            return Collections.emptySet();
        }

        @Override
        public Class<?> getBeanClass() {
            return CDILiquibase.class;
        }

        @Override
        public boolean isAlternative() {
            return false;
        }

        @Override
        public boolean isNullable() {
            return false;
        }

        @Override
        public Set<InjectionPoint> getInjectionPoints() {
            return it.getInjectionPoints();
        }

        @Override
        public CDILiquibase create(CreationalContext<CDILiquibase> ctx) {
            CDILiquibase instance = it.produce(ctx);
            it.inject(instance, ctx);
            it.postConstruct(instance);
            return instance;
        }

        @Override
        public void destroy(CDILiquibase instance, CreationalContext<CDILiquibase> ctx) {
            it.preDestroy(instance);
            it.dispose(instance);
            ctx.release();
        }
    };
    abd.addBean(instance);
}
Example 32
Project: org.ops4j.pax.exam2-master  File: PersistenceContextProvider.java View source code
@Produces
@ApplicationScoped
public EntityManagerFactory getEntityManagerFactory() {
    log.debug("producing EntityManagerFactory");
    Map<String, String> props = new HashMap<String, String>();
    props.put("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.EmbeddedDriver");
    props.put("javax.persistence.jdbc.url", "jdbc:derby:target/libraryDb;create=true");
    props.put("hibernate.hbm2ddl.auto", "create");
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("library", props);
    return emf;
}
Example 33
Project: searchisko-master  File: PersistenceBackendService.java View source code
@Produces
@Named("providerServiceBackend")
@ApplicationScoped
public EntityService produceProviderService() {
    JpaEntityService<Provider> serv = new JpaEntityService<>(em, new ProviderConverter(), Provider.class);
    if (appConfigurationService.getAppConfiguration().isProviderCreateInitData()) {
        final String initialProviderName = "jbossorg";
        Map<String, Object> initialProvider = serv.get(initialProviderName);
        if (initialProvider == null) {
            log.info("Provider entity doesn't exists. Creating initial entity for first authentication.");
            Map<String, Object> jbossorgEntity = new HashMap<>();
            jbossorgEntity.put(ProviderService.NAME, initialProviderName);
            // initial password: jbossorgjbossorg
            jbossorgEntity.put(ProviderService.PASSWORD_HASH, "47dc8a4d65fe0cd5b1236b7e8612634e604a0c2f");
            jbossorgEntity.put(ProviderService.SUPER_PROVIDER, true);
            serv.create(initialProviderName, jbossorgEntity);
        }
    }
    return serv;
}
Example 34
Project: camunda-bpm-camel-master  File: StartProcessFromRouteIT.java View source code
@Produces
@ApplicationScoped
public RouteBuilder createRoute() {
    return new RouteBuilder() {

        public void configure() {
            from("direct:start").routeId("start-process-from-route").to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true").to("camunda-bpm://start?processDefinitionKey=startProcessFromRoute©BodyAsVariable=var1").to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true").to(mockEndpoint);
            from("direct:processVariable").routeId("processVariableRoute").to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true").to(processVariableEndpoint);
        }
    };
}
Example 35
Project: capedwarf-green-master  File: EMF.java View source code
@Produces
@ApplicationScoped
public EntityManagerFactory produceFactory(EMFInfo info) {
    // let app know we're about to create EMF
    produceEvent.select(new BeforeImpl()).fire(new EMFNotification(null));
    EntityManagerFactory entityManagerFactory = getFactory(info);
    // let app know we created EMF
    produceEvent.select(new AfterImpl()).fire(new EMFNotification(entityManagerFactory));
    return entityManagerFactory;
}
Example 36
Project: cdi-unit-master  File: EjbExtension.java View source code
private static <T> void processClass(AnnotatedTypeBuilder<T> builder, String name) {
    builder.addToClass(new AnnotationLiteral<ApplicationScoped>() {

        private static final long serialVersionUID = 1L;
    });
    builder.addToClass(EJbQualifierLiteral.INSTANCE);
    if (!name.isEmpty()) {
        builder.addToClass(new EJbNameLiteral(name));
    } else {
        builder.addToClass(DefaultLiteral.INSTANCE);
    }
}
Example 37
Project: io.framework-master  File: IOComponentUtility.java View source code
/**
	 * 
	 * @param clazz
	 * @return
	 */
public static Annotation getCDIScope(Class<?> clazz) {
    if (clazz == null) {
        return null;
    } else if (clazz.isAnnotationPresent(RequestScoped.class)) {
        return clazz.getAnnotation(RequestScoped.class);
    } else if (clazz.isAnnotationPresent(ConversationScoped.class)) {
        return clazz.getAnnotation(ConversationScoped.class);
    } else if (clazz.isAnnotationPresent(SessionScoped.class)) {
        return clazz.getAnnotation(SessionScoped.class);
    } else if (clazz.isAnnotationPresent(ApplicationScoped.class)) {
        return clazz.getAnnotation(ApplicationScoped.class);
    }
    return null;
}
Example 38
Project: myfaces-ext-cdi-master  File: ConfigProducer.java View source code
@Produces
@ApplicationScoped
public ConfigResolver createSpecializedCodiConfig() {
    return new ConfigResolver() {

        private static final long serialVersionUID = -4410313406799415118L;

        public <T extends CodiConfig> T resolve(Class<T> targetType) {
            CodiConfig codiConfig = ApplicationCache.getConfig(targetType);
            if (codiConfig != null) {
                //noinspection unchecked
                return (T) codiConfig;
            }
            Set<CodiConfig> configs = createCodiConfig();
            for (CodiConfig config : configs) {
                if (targetType.isAssignableFrom(config.getClass())) {
                    if (!config.getClass().getName().startsWith("org.apache.myfaces.extensions.cdi.")) {
                        //noinspection unchecked
                        return (T) config;
                    } else {
                        codiConfig = config;
                    }
                }
            }
            ApplicationCache.setConfig(targetType, codiConfig);
            //noinspection unchecked
            return (T) codiConfig;
        }
    };
}
Example 39
Project: omnifaces-master  File: EagerExtension.java View source code
// Actions --------------------------------------------------------------------------------------------------------
public <T> void collect(@Observes ProcessBean<T> event, BeanManager beanManager) {
    Annotated annotated = event.getAnnotated();
    Eager eager = getAnnotation(beanManager, annotated, Eager.class);
    if (eager != null) {
        Bean<?> bean = event.getBean();
        if (getAnnotation(beanManager, annotated, ApplicationScoped.class) != null) {
            eagerBeans.addApplicationScoped(bean);
        } else if (getAnnotation(beanManager, annotated, SessionScoped.class) != null) {
            eagerBeans.addSessionScoped(bean);
        } else if (getAnnotation(beanManager, annotated, ViewScoped.class) != null || getAnnotation(beanManager, annotated, org.omnifaces.cdi.ViewScoped.class) != null) {
            eagerBeans.addByViewId(bean, eager.viewId());
        } else if (getAnnotation(beanManager, annotated, RequestScoped.class) != null) {
            eagerBeans.addByRequestURIOrViewId(bean, eager.requestURI(), eager.viewId());
        }
    }
}
Example 40
Project: spring-data-cassandra-master  File: CassandraOperationsProducer.java View source code
@Produces
@ApplicationScoped
public CassandraOperations createCassandraOperations(Cluster cluster) throws Exception {
    BasicCassandraMappingContext mappingContext = new BasicCassandraMappingContext();
    mappingContext.setUserTypeResolver(new SimpleUserTypeResolver(cluster, KEYSPACE_NAME));
    mappingContext.setInitialEntitySet(Collections.singleton(User.class));
    mappingContext.afterPropertiesSet();
    MappingCassandraConverter cassandraConverter = new MappingCassandraConverter(mappingContext);
    CassandraAdminTemplate cassandraTemplate = new CassandraAdminTemplate(cluster.connect(), cassandraConverter);
    CreateKeyspaceSpecification createKeyspaceSpecification = new CreateKeyspaceSpecification(KEYSPACE_NAME).ifNotExists();
    cassandraTemplate.getCqlOperations().execute(CreateKeyspaceCqlGenerator.toCql(createKeyspaceSpecification));
    cassandraTemplate.getCqlOperations().execute("USE " + KEYSPACE_NAME);
    CassandraPersistentEntitySchemaDropper schemaDropper = new CassandraPersistentEntitySchemaDropper(mappingContext, cassandraTemplate);
    schemaDropper.dropTables(false);
    schemaDropper.dropUserTypes(false);
    CassandraPersistentEntitySchemaCreator schemaCreator = new CassandraPersistentEntitySchemaCreator(mappingContext, cassandraTemplate);
    schemaCreator.createUserTypes(false);
    schemaCreator.createTables(false);
    for (CassandraPersistentEntity<?> entity : cassandraTemplate.getConverter().getMappingContext().getTableEntities()) {
        cassandraTemplate.truncate(entity.getType());
    }
    return cassandraTemplate;
}
Example 41
Project: Wink-master  File: WinkCdiExtension.java View source code
@SuppressWarnings("UnusedDeclaration")
public void validateJaxRsCdiBeans(@Observes AfterDeploymentValidation afterDeploymentValidation, BeanManager beanManager) {
    DefaultBeanManagerResolver.setBeanManager(beanManager);
    for (Class beanClass : beanClassesToCheck) {
        Bean<?> bean = CdiUtils.getBeanFor(beanClass, beanManager);
        if (bean == null) {
            //e.g. a vetoed bean
            continue;
        }
        if (ResourceMetadataCollector.isResource(beanClass) && Dependent.class.equals(bean.getScope())) {
            StringBuilder warning = new StringBuilder("{} gets processed as CDI bean, but uses {} ");
            if (CdiUtils.isBeanWithScope(beanClass.getAnnotations(), beanManager)) {
                warning.append("explicitly. ");
            } else {
                warning.append("implicitly. ");
            }
            warning.append("The suggested scope for this bean is {}. Alternatively use ");
            warning.append(OptionalScopeAutoUpgradeExtension.class.getName());
            Object[] parameters = new Object[] { beanClass.getName(), Dependent.class.getName(), RequestScoped.class.getName() };
            logger.warn(warning.toString(), parameters);
            continue;
        }
        //an extension can change the scope dynamically during bootstrapping -> check it at the end
        if (!bean.getScope().equals(Singleton.class) && !beanManager.isNormalScope(bean.getScope())) {
            StringBuilder warning = new StringBuilder();
            if (ApplicationMetadataCollector.isApplication(beanClass)) {
                warning.append("Implementations of ").append(Application.class.getName());
            } else {
                warning.append(Provider.class.getName()).append(" beans");
            }
            warning.append(" are only compatible with singletons. Please add ");
            warning.append(OptionalScopeAutoUpgradeExtension.class.getName());
            warning.append(" Or use ");
            warning.append(ApplicationScoped.class.getName());
            warning.append(" or ");
            warning.append(Singleton.class.getName());
            warning.append(" or a custom scope which keeps only one instance per class for the whole application.");
            logger.warn(warning.toString());
        }
    }
    beanClassesToCheck.clear();
}
Example 42
Project: aries-master  File: ServiceDeclaration.java View source code
@SuppressWarnings({ "unchecked" })
public Object getServiceInstance() {
    Class<?> scope = _bean.getScope();
    if (Singleton.class.isAssignableFrom(scope)) {
        return _bean.create(_creationalContext);
    } else if (ApplicationScoped.class.isAssignableFrom(scope)) {
        return new BundleScopeWrapper();
    }
    return new PrototypeScopeWrapper();
}
Example 43
Project: cdi-master  File: AnnotationLiteralTest.java View source code
@Test
public void testInitializedLiteral() {
    assertEquals(Initialized.Literal.of(RequestScoped.class).value(), RequestScoped.class);
    assertEquals(Initialized.Literal.REQUEST.value(), RequestScoped.class);
    assertEquals(Initialized.Literal.CONVERSATION.value(), ConversationScoped.class);
    assertEquals(Initialized.Literal.SESSION.value(), SessionScoped.class);
    assertEquals(Initialized.Literal.APPLICATION.value(), ApplicationScoped.class);
}
Example 44
Project: cdi-properties-master  File: DependentResolverMethodParametersVerifier.java View source code
/**
     * Checks if a custom resolver method injected parameter scope is {@link Dependent}
     * 
     * @param type
     *            The parameter type being checked
     * @return Returns true if the paraeter scope is {@link Dependent}
     */
private boolean checkDependentScope(Class<?> type) {
    for (Annotation annotation : type.getAnnotations()) {
        if (annotation.annotationType().equals(SessionScoped.class) || annotation.annotationType().equals(RequestScoped.class) || annotation.annotationType().equals(ApplicationScoped.class)) {
            return false;
        }
        Class<?> viewScopedClass = null;
        try {
            // Account for JEE 7 @ViewScoped scope
            viewScopedClass = Class.forName("javax.faces.view.ViewScoped");
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Class javax.faces.view.ViewScoped was not found: Running in a Java EE 6 environment.");
            }
        }
        if (viewScopedClass != null) {
            if (annotation.annotationType().equals(viewScopedClass)) {
                return false;
            }
        }
    }
    return true;
}
Example 45
Project: resin-master  File: Resource.java View source code
/**
   * Initialize the resource.
   */
@PostConstruct
public void init() throws Throwable {
    preInit();
    if (_type == null || _object == null)
        return;
    Config.init(_object);
    _object = Config.replaceObject(_object);
    if (_object instanceof ClassLoaderListener) {
        ClassLoaderListener listener = (ClassLoaderListener) _object;
        Environment.addClassLoaderListener(listener);
    }
    if (_object instanceof EnvironmentListener) {
        EnvironmentListener listener = (EnvironmentListener) _object;
        Environment.addEnvironmentListener(listener);
    }
    Object jndiObject = _object;
    boolean isStart = false;
    if (_object instanceof ResourceAdapter) {
        ResourceManagerImpl.addResource((ResourceAdapter) _object);
        isStart = true;
    }
    if (_object instanceof ManagedConnectionFactory) {
        ResourceManagerImpl rm = ResourceManagerImpl.createLocalManager();
        ManagedConnectionFactory mcf;
        mcf = (ManagedConnectionFactory) _object;
        ConnectionPool cm = rm.createConnectionPool();
        cm.setShareable(_shareable);
        cm.setLocalTransactionOptimization(_localTransactionOptimization);
        Object connectionFactory = cm.init(mcf);
        cm.start();
        jndiObject = connectionFactory;
        isStart = true;
    }
    Method start = null;
    try {
        start = _object.getClass().getMethod("start", new Class[0]);
    } catch (Throwable e) {
    }
    Method stop = null;
    try {
        stop = _object.getClass().getMethod("stop", new Class[0]);
    } catch (Throwable e) {
    }
    if (_jndiName != null)
        Jndi.bindDeepShort(_jndiName, jndiObject);
    if (isStart) {
    } else if (start != null || stop != null)
        Environment.addEnvironmentListener(new StartListener(_object));
    else if (CloseListener.getDestroyMethod(_object.getClass()) != null)
        Environment.addClassLoaderListener(new CloseListener(_object));
    String name = _name;
    if (_name == null)
        name = _var;
    if (_name == null)
        name = _jndiName;
    InjectManager beanManager = InjectManager.create();
    BeanBuilder factory = beanManager.createBeanFactory(_object.getClass());
    if (name != null) {
        factory.name(name);
        factory.qualifier(CurrentLiteral.CURRENT);
        factory.qualifier(Names.create(name));
    }
    // server/12dt
    // for backward compatibility <resource> is always ApplicationScoped
    // factory.scope(ApplicationScoped.class);
    factory.scope(Singleton.class);
    if (_object != null)
        beanManager.addBean(factory.singleton(_object));
    else
        beanManager.addBean(factory.bean());
    if (log.isLoggable(Level.CONFIG))
        logConfig();
}
Example 46
Project: visual-master  File: Resources.java View source code
@Produces
@Default
@ApplicationScoped
public PollerManager<CacheNameInfo> cacheNamesPoller(VisualizerRemoteCacheManager cacheManager) {
    JmxCacheNamesPollerManager manager = new JdgJmxCacheNamesPollerManager(cacheManager);
    manager.setJmxUsername(jmxUsername);
    manager.setJmxPassword(jmxPassword);
    manager.setJmxHotrodPortOffset(jmxHotrodPortOffset);
    manager.setRefreshRate(Long.valueOf(refreshRate));
    manager.init();
    return manager;
}
Example 47
Project: apiman-master  File: WarCdiFactory.java View source code
@Produces
@ApplicationScoped
public static INewUserBootstrapper provideNewUserBootstrapper(WarApiManagerConfig config, IPluginRegistry pluginRegistry) {
    String type = config.getNewUserBootstrapperType();
    if (type == null) {
        return new INewUserBootstrapper() {

            @Override
            public void bootstrapUser(UserBean user, IStorage storage) throws StorageException {
            // Do nothing special.
            }
        };
    } else {
        try {
            return createCustomComponent(INewUserBootstrapper.class, config.getNewUserBootstrapperType(), config.getNewUserBootstrapperProperties(), pluginRegistry);
        } catch (Throwable t) {
            throw new RuntimeException("Error or unknown user bootstrapper type: " + config.getNewUserBootstrapperType(), t);
        }
    }
}
Example 48
Project: gyrex-jaxrs-application-master  File: CDIComponentProviderFactory.java View source code
private Map<Class<? extends Annotation>, ComponentScope> createScopeMap() {
    Map<Class<? extends Annotation>, ComponentScope> m = new HashMap<Class<? extends Annotation>, ComponentScope>();
    m.put(ApplicationScoped.class, ComponentScope.Singleton);
    m.put(RequestScoped.class, ComponentScope.PerRequest);
    m.put(Dependent.class, ComponentScope.PerRequest);
    return Collections.unmodifiableMap(m);
}
Example 49
Project: jersey-1.x-old-master  File: CDIComponentProviderFactory.java View source code
private Map<Class<? extends Annotation>, ComponentScope> createScopeMap() {
    Map<Class<? extends Annotation>, ComponentScope> m = new HashMap<Class<? extends Annotation>, ComponentScope>();
    m.put(ApplicationScoped.class, ComponentScope.Singleton);
    m.put(RequestScoped.class, ComponentScope.PerRequest);
    m.put(Dependent.class, ComponentScope.PerRequest);
    return Collections.unmodifiableMap(m);
}
Example 50
Project: jersey-old-master  File: CDIComponentProviderFactory.java View source code
private Map<Class<? extends Annotation>, ComponentScope> createScopeMap() {
    Map<Class<? extends Annotation>, ComponentScope> m = new HashMap<Class<? extends Annotation>, ComponentScope>();
    m.put(ApplicationScoped.class, ComponentScope.Singleton);
    m.put(RequestScoped.class, ComponentScope.PerRequest);
    m.put(Dependent.class, ComponentScope.PerRequest);
    return Collections.unmodifiableMap(m);
}
Example 51
Project: quercus-master  File: BeanConfig.java View source code
/**
   * Sets the scope attribute.
   */
public void setScope(String scope) {
    if ("singleton".equals(scope)) {
        _scope = javax.inject.Singleton.class;
    //  addAnnotation(new AnnotationLiteral<Startup>() {});
    } else if ("dependent".equals(scope))
        _scope = Dependent.class;
    else if ("request".equals(scope))
        _scope = RequestScoped.class;
    else if ("session".equals(scope))
        _scope = SessionScoped.class;
    else if ("application".equals(scope))
        _scope = ApplicationScoped.class;
    else if ("conversation".equals(scope))
        _scope = ConversationScoped.class;
    else {
        Class cl = null;
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            cl = Class.forName(scope, false, loader);
        } catch (ClassNotFoundException e) {
        }
        setScopeType(cl);
    }
}
Example 52
Project: quickstart-master  File: Frontend.java View source code
public void init(@Observes @Initialized(ApplicationScoped.class) ServletContext servletContext) {
    if (servletContext == null) {
        log.severe(format("Failed to deploy frontend endpoint %s: %s", WEBSOCKET_PATH, "ServletContext not available"));
        return;
    }
    ServerContainer serverContainer = (ServerContainer) servletContext.getAttribute("javax.websocket.server.ServerContainer");
    if (serverContainer == null) {
        log.severe(format("Failed to deploy frontend endpoint %s: %s", WEBSOCKET_PATH, "javax.websocket.server.ServerContainer ServerContainer not available"));
        return;
    }
    // WebSocket does not honor CDI contexts in the default configuration; by default a new object is created for each new
    // websocket.
    // We can work around this by supplying a custom ServerEndpointConfig.Configurator that returns the same instance of the
    // endpoint for each new websocket. Unfortunately this precludes us from using annotations, and forces us to extend the
    // abstract class Endpoint, and forces us to add the server endpoint programmatically upon startup of the servlet
    // context.
    ServerEndpointConfig config = ServerEndpointConfig.Builder.create(Frontend.class, WEBSOCKET_PATH).configurator(new ServerEndpointConfig.Configurator() {

        @SuppressWarnings("unchecked")
        @Override
        public <T> T getEndpointInstance(final Class<T> endpointClass) throws InstantiationException {
            if (endpointClass.isAssignableFrom(Frontend.class)) {
                return (T) Frontend.this;
            }
            return super.getEndpointInstance(endpointClass);
        }
    }).build();
    try {
        serverContainer.addEndpoint(config);
    } catch (DeploymentException e) {
        log.log(Level.SEVERE, format("Failed to deploy frontend endpoint %s: %s", WEBSOCKET_PATH, e.getMessage()), e);
    }
}
Example 53
Project: sinkit-core-master  File: MyCacheManagerProvider.java View source code
public void init(@Observes @Initialized(ApplicationScoped.class) Object init) throws IOException {
    log.log(Level.INFO, "Constructing caches...");
    if (localCacheManager == null) {
        final GlobalConfiguration glob = new GlobalConfigurationBuilder().nonClusteredDefault().build();
        final Configuration loc = new ConfigurationBuilder().clustering().cacheMode(CacheMode.LOCAL).locking().isolationLevel(IsolationLevel.READ_UNCOMMITTED).eviction().strategy(EvictionStrategy.LRU).type(EvictionType.COUNT).size(SINKIT_LOCAL_CACHE_SIZE).expiration().lifespan(SINKIT_LOCAL_CACHE_LIFESPAN_MS, TimeUnit.MILLISECONDS).build();
        localCacheManager = new DefaultCacheManager(glob, loc, true);
        log.info("Local cache manager initialized.\n");
    }
    if (cacheManagerForIndexableCaches == null) {
        org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder();
        builder.addServer().host(SINKIT_HOTROD_HOST).port(SINKIT_HOTROD_PORT).marshaller(new ProtoStreamMarshaller());
        cacheManagerForIndexableCaches = new RemoteCacheManager(builder.build());
    }
    if (cacheManager == null) {
        org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder();
        builder.addServer().host(SINKIT_HOTROD_HOST).port(SINKIT_HOTROD_PORT);
        cacheManager = new RemoteCacheManager(builder.build());
    }
    final SerializationContext ctx = ProtoStreamMarshaller.getSerializationContext(cacheManagerForIndexableCaches);
    ctx.registerProtoFiles(FileDescriptorSource.fromResources(RULE_PROTOBUF_DEFINITION_RESOURCE));
    ctx.registerMarshaller(new RuleMarshaller());
    ctx.registerMarshaller(new ImmutablePairMarshaller());
    ctx.registerProtoFiles(FileDescriptorSource.fromResources(CUSTOM_LIST_PROTOBUF_DEFINITION_RESOURCE));
    ctx.registerMarshaller(new CustomListMarshaller());
    final RemoteCache<String, String> metadataCache = cacheManagerForIndexableCaches.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME);
    metadataCache.put(RULE_PROTOBUF_DEFINITION_RESOURCE, readResource(RULE_PROTOBUF_DEFINITION_RESOURCE));
    metadataCache.put(CUSTOM_LIST_PROTOBUF_DEFINITION_RESOURCE, readResource(CUSTOM_LIST_PROTOBUF_DEFINITION_RESOURCE));
    final String errors = metadataCache.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX);
    if (errors != null) {
        throw new IllegalStateException("Protobuffer files, either Rule or CustomLists contained errors:\n" + errors);
    }
    log.log(Level.INFO, "Managers started.");
}
Example 54
Project: validation-as-fork-master  File: ValidationExtension.java View source code
private void addValidatorFactoryIfRequired(AfterBeanDiscovery abd, final BeanManager beanManager) {
    // if a ValidatorFactory already exists, only inject it's ConstraintValidatorFactory if required
    if (!beanManager.getBeans(ValidatorFactory.class).isEmpty()) {
        ValidatorFactory validatorFactory = getReference(beanManager, ValidatorFactory.class);
        ConstraintValidatorFactory constraintValidatorFactory = validatorFactory.getConstraintValidatorFactory();
        if (constraintValidatorFactory instanceof InjectingConstraintValidatorFactory) {
            inject(beanManager, InjectingConstraintValidatorFactory.class, (InjectingConstraintValidatorFactory) constraintValidatorFactory);
        }
        return;
    }
    abd.addBean(new Bean<ValidatorFactory>() {

        @Override
        public Class<?> getBeanClass() {
            return ValidatorFactory.class;
        }

        @Override
        public Set<InjectionPoint> getInjectionPoints() {
            return Collections.emptySet();
        }

        @Override
        public String getName() {
            return "validatorFactory";
        }

        @SuppressWarnings("serial")
        @Override
        public Set<Annotation> getQualifiers() {
            Set<Annotation> qualifiers = new HashSet<Annotation>();
            qualifiers.add(new AnnotationLiteral<Default>() {
            });
            qualifiers.add(new AnnotationLiteral<Any>() {
            });
            return qualifiers;
        }

        @Override
        public Class<? extends Annotation> getScope() {
            return ApplicationScoped.class;
        }

        @Override
        public Set<Class<? extends Annotation>> getStereotypes() {
            return Collections.emptySet();
        }

        @Override
        public Set<Type> getTypes() {
            Set<Type> types = new HashSet<Type>();
            types.add(ValidatorFactory.class);
            types.add(Object.class);
            return types;
        }

        @Override
        public boolean isAlternative() {
            return false;
        }

        @Override
        public boolean isNullable() {
            return false;
        }

        @Override
        public ValidatorFactory create(CreationalContext<ValidatorFactory> ctx) {
            ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
            ConstraintValidatorFactory constraintValidatorFactory = validatorFactory.getConstraintValidatorFactory();
            if (constraintValidatorFactory instanceof InjectingConstraintValidatorFactory) {
                inject(beanManager, InjectingConstraintValidatorFactory.class, (InjectingConstraintValidatorFactory) constraintValidatorFactory);
            }
            return validatorFactory;
        }

        @Override
        public void destroy(ValidatorFactory instance, CreationalContext<ValidatorFactory> ctx) {
        }
    });
}
Example 55
Project: wildfly-swarm-master  File: ServiceClientProcessor.java View source code
static byte[] createImpl(String implName, ClassInfo classInfo) {
    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;
    AnnotationVisitor av0;
    cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER, implName.replace('.', '/'), null, "java/lang/Object", new String[] { classInfo.name().toString().replace('.', '/') });
    int lastDot = implName.lastIndexOf('.');
    String simpleName = implName.substring(lastDot + 1);
    cw.visitSource(simpleName + ".java", null);
    {
        av0 = cw.visitAnnotation("Ljavax/enterprise/context/ApplicationScoped;", true);
        av0.visitEnd();
    }
    cw.visitInnerClass("javax/ws/rs/client/Invocation$Builder", "javax/ws/rs/client/Invocation", "Builder", ACC_PUBLIC + ACC_STATIC + ACC_ABSTRACT + ACC_INTERFACE);
    {
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(14, l0);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLineNumber(15, l1);
        mv.visitInsn(RETURN);
        Label l2 = new Label();
        mv.visitLabel(l2);
        mv.visitLocalVariable("this", buildTypeDef(implName), null, l0, l2, 0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    List<AnnotationInstance> annotations = classInfo.annotations().get(DotName.createSimple("org.wildfly.swarm.client.jaxrs.Service"));
    String baseUrl = (String) annotations.get(0).value("baseUrl").value();
    int lineNum = 18;
    classInfo.asClass().methods().stream().forEachOrdered( method -> {
        createMethod(cw, implName, classInfo.name().toString(), method, lineNum, baseUrl);
    });
    cw.visitEnd();
    return cw.toByteArray();
}
Example 56
Project: errai-cdi-master  File: CDIExtensionPoints.java View source code
/**
     * Register managed beans as Errai services
     * @param event
     * @param <T>
     */
public <T> void observeResources(@Observes ProcessAnnotatedType<T> event) {
    final AnnotatedType<T> type = event.getAnnotatedType();
    // services
    if (type.isAnnotationPresent(Service.class)) {
        log.debug("Discovered Errai Annotation on type: " + type);
        boolean isRpc = false;
        Class<T> javaClass = type.getJavaClass();
        for (Class<?> intf : javaClass.getInterfaces()) {
            isRpc = intf.isAnnotationPresent(Remote.class);
            if (isRpc) {
                log.debug("Identified Errai RPC interface: " + intf + " on " + type);
                managedTypes.addRPCEndpoint(intf, type);
            }
        }
        if (!isRpc) {
            managedTypes.addServiceEndpoint(type);
        }
        // enforce application scope until we get the other scopes working
        ApplicationScoped scope = type.getAnnotation(ApplicationScoped.class);
        if (null == scope)
            log.warn("Service implementation not @ApplicationScoped: " + type.getJavaClass());
    }
/**
         * Mixing JSR-299 and Errai annotation causes bean valdation problems.
         * Therefore we need to provide additional meta data for the Provider implementations,
         * (the Produces annotation literal)
         * even though these classes are only client side implementations.
         */
/*else if(type.isAnnotationPresent(org.jboss.errai.ioc.client.api.Provider.class))
       {
         AnnotatedTypeBuilder<T> builder = AnnotatedTypeBuilder.newInstance(event.getAnnotatedType().getJavaClass());
         builder.readAnnotationsFromUnderlyingType();

         //builder.addToClass(new ApplicationScopedQualifier(){});
         for(AnnotatedMethod method : type.getMethods())
         {
           if("provide".equals(method.getJavaMember().getName()))
           {
             builder.addToMethod(method.getJavaMember(), new ProducesQualifier(){});
             break;
           }
         }
         AnnotatedType<T> replacement = builder.create();
         event.setAnnotatedType(replacement);
       } */
}
Example 57
Project: uberfire-master  File: SystemConfigProducer.java View source code
public <X> void processBean(@Observes final ProcessBean<X> event) {
    if (event.getBean().getName() != null && event.getBean().getName().equals("systemFS")) {
        systemFSNotExists = false;
    } else if (event.getBean().getName() != null && event.getBean().getName().equals("ioStrategy")) {
        ioStrategyBeanNotFound = false;
    }
    if (event.getAnnotated().isAnnotationPresent(Startup.class) && (event.getAnnotated().isAnnotationPresent(ApplicationScoped.class) || event.getAnnotated().isAnnotationPresent(Singleton.class))) {
        final Startup startupAnnotation = event.getAnnotated().getAnnotation(Startup.class);
        final StartupType type = startupAnnotation.value();
        final int priority = startupAnnotation.priority();
        final Bean<?> bean = event.getBean();
        switch(type) {
            case EAGER:
                startupEagerBeans.add(new OrderedBean(bean, priority));
                break;
            case BOOTSTRAP:
                startupBootstrapBeans.add(new OrderedBean(bean, priority));
                break;
        }
    } else if (event.getAnnotated().isAnnotationPresent(Named.class) && (event.getAnnotated().isAnnotationPresent(ApplicationScoped.class) || event.getAnnotated().isAnnotationPresent(Singleton.class))) {
        final Named namedAnnotation = event.getAnnotated().getAnnotation(Named.class);
        if (namedAnnotation.value().endsWith("-startable")) {
            final Bean<?> bean = event.getBean();
            startupBootstrapBeans.add(new OrderedBean(bean, 10));
        }
    }
}
Example 58
Project: ds-test-addon-master  File: CdiTestRunner.java View source code
public void applyBeforeClassConfig() {
    CdiContainer container = CdiContainerLoader.getCdiContainer();
    if (!isContainerStarted()) {
        container.boot();
        setContainerStarted();
    }
    List<Class<? extends Annotation>> restrictedScopes = new ArrayList<Class<? extends Annotation>>();
    //controlled by the container and not supported by weld:
    restrictedScopes.add(ApplicationScoped.class);
    restrictedScopes.add(Singleton.class);
    if (this.parent == null && this.testControl.getClass().equals(TestControlLiteral.class)) {
        //skip scope-handling if @TestControl isn't used explicitly on the test-class -> TODO re-visit it
        restrictedScopes.add(RequestScoped.class);
        restrictedScopes.add(SessionScoped.class);
    }
    startContexts(container, restrictedScopes.toArray(new Class[restrictedScopes.size()]));
}
Example 59
Project: kernel-master  File: TestExoContainer.java View source code
@Test
public void testScope() throws Exception {
    assertFalse(ContainerUtil.isSingleton(S1.class));
    assertFalse(ContainerUtil.isSingleton(S2.class));
    assertTrue(ContainerUtil.isSingleton(S3.class));
    assertTrue(ContainerUtil.isSingleton(S4.class));
    assertTrue(ContainerUtil.isSingleton(S5.class));
    assertFalse(ContainerUtil.isSingleton(S6.class));
    assertFalse(ContainerUtil.isSingleton(S7.class));
    assertTrue(ContainerUtil.isSingleton(S8.class));
    assertSame(RequestScoped.class, ContainerUtil.getScope(S1.class));
    assertSame(SessionScoped.class, ContainerUtil.getScope(S2.class));
    assertSame(ApplicationScoped.class, ContainerUtil.getScope(S3.class));
    assertSame(Singleton.class, ContainerUtil.getScope(S4.class));
    assertNull(ContainerUtil.getScope(S5.class));
    assertNull(ContainerUtil.getScope(S6.class));
    assertSame(Dependent.class, ContainerUtil.getScope(S7.class));
    assertSame(ApplicationScoped.class, ContainerUtil.getScope(S8.class));
    final RootContainer container = AbstractTestContainer.createRootContainer(getClass(), "test-exo-container.xml", "testScope");
    container.registerComponentImplementation(S1.class);
    container.registerComponentImplementation(S1_DEP1.class);
    container.registerComponentImplementation(S1_DEP2.class);
    container.registerComponentImplementation(S1_DEP3.class);
    container.registerComponentImplementation(S1_DEP4.class);
    container.registerComponentImplementation(S1_DEP5.class);
    container.registerComponentImplementation(S1_DEP6.class);
    container.registerComponentImplementation(S2.class);
    container.registerComponentImplementation(S20.class);
    container.registerComponentImplementation(S3.class);
    container.registerComponentImplementation(S4.class);
    container.registerComponentImplementation(S5.class);
    container.registerComponentImplementation(S6.class);
    container.registerComponentImplementation(S7.class);
    container.registerComponentImplementation(S8.class);
    container.registerComponentImplementation(Unproxyable1.class);
    container.registerComponentImplementation(Unproxyable2.class);
    container.registerComponentImplementation(Unproxyable3.class);
    container.registerComponentImplementation(Unproxyable4.class);
    container.registerComponentImplementation(Unproxyable5.class);
    container.registerComponentImplementation(Proxyable.class);
    container.registerComponentImplementation(Proxyable2.class);
    ContextManager manager = container.getComponentInstanceOfType(ContextManager.class);
    assertNotNull(manager);
    testScope(container, manager, true);
    testScope(container, manager, false);
    try {
        container.getComponentInstanceOfType(Unproxyable1.class);
        fail("An exception is expected as the class is unproxyable");
    } catch (Exception e) {
    }
    try {
        container.getComponentInstanceOfType(Unproxyable2.class);
        fail("An exception is expected as the class is unproxyable");
    } catch (Exception e) {
    }
    try {
        container.getComponentInstanceOfType(Unproxyable3.class);
        fail("An exception is expected as the class is unproxyable");
    } catch (Exception e) {
    }
    try {
        container.getComponentInstanceOfType(Unproxyable4.class);
        fail("An exception is expected as the class is unproxyable");
    } catch (Exception e) {
    }
    try {
        container.getComponentInstanceOfType(Unproxyable5.class);
        fail("An exception is expected as the class is unproxyable");
    } catch (Exception e) {
    }
    assertNotNull(container.getComponentInstanceOfType(Proxyable.class));
    assertNotNull(container.getComponentInstanceOfType(Proxyable2.class));
    try {
        container.getComponentInstanceOfType(S1.class).getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    S4 s4 = container.getComponentInstanceOfType(S4.class);
    assertSame(s4, container.getComponentInstanceOfType(S4.class));
    assertSame(Singleton.class, ((MX4JComponentAdapter<S4>) container.getComponentAdapterOfType(S4.class)).getScope());
    S5 s5 = container.getComponentInstanceOfType(S5.class);
    assertSame(s5, container.getComponentInstanceOfType(S5.class));
    assertSame(Singleton.class, ((MX4JComponentAdapter<S5>) container.getComponentAdapterOfType(S5.class)).getScope());
    S6 s6 = container.getComponentInstanceOfType(S6.class);
    assertNotSame(s6, container.getComponentInstanceOfType(S6.class));
    assertSame(Dependent.class, ((MX4JComponentAdapter<S6>) container.getComponentAdapterOfType(S6.class)).getScope());
    S7 s7 = container.getComponentInstanceOfType(S7.class);
    assertNotSame(s7, container.getComponentInstanceOfType(S7.class));
    assertSame(Dependent.class, ((MX4JComponentAdapter<S7>) container.getComponentAdapterOfType(S7.class)).getScope());
    S8 s8 = container.getComponentInstanceOfType(S8.class);
    assertSame(s8, container.getComponentInstanceOfType(S8.class));
    assertSame(ApplicationScoped.class, ((MX4JComponentAdapter<S8>) container.getComponentAdapterOfType(S8.class)).getScope());
    try {
        s4.s1.getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    try {
        s5.s1.getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    try {
        s6.s1.getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    try {
        s7.s1.getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    try {
        s8.s1.getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    // Request 1
    Map<Object, Object> mapReq1 = new HashMap<Object, Object>();
    ServletRequest req1 = createProxy(ServletRequest.class, mapReq1);
    manager.<ServletRequest>getContext(RequestScoped.class).activate(req1);
    S1 s1 = container.getComponentInstanceOfType(S1.class);
    int s1Id = s1.getId();
    assertEquals(1, mapReq1.size());
    assertNotNull(s1);
    assertSame(s1, container.getComponentInstanceOfType(S1.class));
    assertEquals(s1Id, container.getComponentInstanceOfType(S1.class).getId());
    assertEquals(s1Id, s1.getId());
    assertEquals(s1Id, s1.getId2());
    assertEquals(s1Id, s1.getId3());
    assertSame(s1, s4.s1);
    assertEquals(s1Id, s4.s1.getId());
    assertEquals(s1Id, s4.s1.getId2());
    assertEquals(s1Id, s4.s1.getId3());
    assertSame(s1, s5.s1);
    assertEquals(s1Id, s5.s1.getId());
    assertEquals(s1Id, s5.s1.getId2());
    assertEquals(s1Id, s5.s1.getId3());
    assertSame(s1, s6.s1);
    assertEquals(s1Id, s6.s1.getId());
    assertEquals(s1Id, s6.s1.getId2());
    assertEquals(s1Id, s6.s1.getId3());
    assertSame(s1, s7.s1);
    assertEquals(s1Id, s7.s1.getId());
    assertEquals(s1Id, s7.s1.getId2());
    assertEquals(s1Id, s7.s1.getId3());
    assertSame(s1, s8.s1);
    assertEquals(s1Id, s8.s1.getId());
    assertEquals(s1Id, s8.s1.getId2());
    assertEquals(s1Id, s8.s1.getId3());
    assertNotNull(s1.getDep1());
    assertNotNull(s1.getDep2());
    assertNotNull(s1.getDep3());
    assertNotNull(s1.getDep4());
    assertNotNull(s1.getDep5());
    assertSame(s1.getDep1(), container.getComponentInstanceOfType(S1_DEP1.class));
    int dep1Id;
    assertEquals(dep1Id = s1.getDep1().getId(), container.getComponentInstanceOfType(S1_DEP1.class).getId());
    assertEquals(s1.getDep1().getId(), s1.getDep1Id());
    assertSame(s1.getDep2(), container.getComponentInstanceOfType(S1_DEP2.class));
    try {
        s1.getDep2().getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    assertSame(s1.getDep3(), container.getComponentInstanceOfType(S1_DEP3.class));
    assertEquals(s1.getDep3().getId(), container.getComponentInstanceOfType(S1_DEP3.class).getId());
    assertSame(s1.getDep4(), container.getComponentInstanceOfType(S1_DEP4.class));
    assertEquals(s1.getDep4().getId(), container.getComponentInstanceOfType(S1_DEP4.class).getId());
    assertNotSame(s1.getDep5(), container.getComponentInstanceOfType(S1_DEP5.class));
    assertSame(s1.getDep6(), container.getComponentInstanceOfType(S1_DEP6.class));
    assertEquals(s1.getDep6().getId(), container.getComponentInstanceOfType(S1_DEP6.class).getId());
    assertSame(s1, s1.getDep6().getS1());
    assertEquals(s1.getId(), s1.getDep6().getS1().getId());
    assertSame(s1, container.getComponentInstanceOfType(S1_DEP6.class).getS1());
    assertEquals(s1.getId(), container.getComponentInstanceOfType(S1_DEP6.class).getS1().getId());
    manager.<ServletRequest>getContext(RequestScoped.class).deactivate(req1);
    assertTrue(mapReq1.isEmpty());
    s4 = container.getComponentInstanceOfType(S4.class);
    assertSame(s1, s4.s1);
    s5 = container.getComponentInstanceOfType(S5.class);
    assertSame(s1, s5.s1);
    s6 = container.getComponentInstanceOfType(S6.class);
    assertSame(s1, s6.s1);
    s7 = container.getComponentInstanceOfType(S7.class);
    assertSame(s1, s7.s1);
    s8 = container.getComponentInstanceOfType(S8.class);
    assertSame(s1, s8.s1);
    try {
        container.getComponentInstanceOfType(S1.class).getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    try {
        s4.s1.getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    try {
        s5.s1.getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    try {
        s6.s1.getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    try {
        s7.s1.getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    try {
        s8.s1.getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    // Request 2
    ServletRequest req2 = createProxy(ServletRequest.class, new HashMap<Object, Object>());
    manager.<ServletRequest>getContext(RequestScoped.class).activate(req2);
    S1 s1_2 = container.getComponentInstanceOfType(S1.class);
    assertNotNull(s1_2);
    assertSame(s1_2, container.getComponentInstanceOfType(S1.class));
    assertEquals(s1_2.getId(), container.getComponentInstanceOfType(S1.class).getId());
    assertFalse(s1_2.getId() == s1Id);
    assertSame(s1_2, s4.s1);
    assertEquals(s1_2.getId(), s4.s1.getId());
    assertEquals(s1_2.getId(), s4.s1.getId2());
    assertEquals(s1_2.getId(), s4.s1.getId3());
    assertSame(s1_2, s5.s1);
    assertEquals(s1_2.getId(), s5.s1.getId());
    assertEquals(s1_2.getId(), s5.s1.getId2());
    assertEquals(s1_2.getId(), s5.s1.getId3());
    assertSame(s1_2, s6.s1);
    assertEquals(s1_2.getId(), s6.s1.getId());
    assertEquals(s1_2.getId(), s6.s1.getId2());
    assertEquals(s1_2.getId(), s6.s1.getId3());
    assertSame(s1_2, s7.s1);
    assertEquals(s1_2.getId(), s7.s1.getId());
    assertEquals(s1_2.getId(), s7.s1.getId2());
    assertEquals(s1_2.getId(), s7.s1.getId3());
    assertSame(s1_2, s8.s1);
    assertEquals(s1_2.getId(), s8.s1.getId());
    assertEquals(s1_2.getId(), s8.s1.getId2());
    assertEquals(s1_2.getId(), s8.s1.getId3());
    assertNotNull(s1_2.getDep1());
    assertNotNull(s1_2.getDep2());
    assertNotNull(s1_2.getDep3());
    assertNotNull(s1_2.getDep4());
    assertNotNull(s1_2.getDep5());
    assertSame(s1_2.getDep1(), container.getComponentInstanceOfType(S1_DEP1.class));
    assertEquals(s1_2.getDep1().getId(), container.getComponentInstanceOfType(S1_DEP1.class).getId());
    assertEquals(s1_2.getDep1().getId(), s1_2.getDep1Id());
    assertTrue(s1_2.getDep1().getId() != dep1Id);
    assertSame(s1_2.getDep2(), container.getComponentInstanceOfType(S1_DEP2.class));
    try {
        s1_2.getDep2().getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    assertSame(s1_2.getDep3(), container.getComponentInstanceOfType(S1_DEP3.class));
    assertEquals(s1_2.getDep3().getId(), container.getComponentInstanceOfType(S1_DEP3.class).getId());
    assertSame(s1_2.getDep4(), container.getComponentInstanceOfType(S1_DEP4.class));
    assertEquals(s1_2.getDep4().getId(), container.getComponentInstanceOfType(S1_DEP4.class).getId());
    assertNotSame(s1_2.getDep5(), container.getComponentInstanceOfType(S1_DEP5.class));
    assertSame(s1_2.getDep6(), container.getComponentInstanceOfType(S1_DEP6.class));
    assertEquals(s1_2.getDep6().getId(), container.getComponentInstanceOfType(S1_DEP6.class).getId());
    assertSame(s1_2, s1_2.getDep6().getS1());
    assertEquals(s1_2.getId(), s1_2.getDep6().getS1().getId());
    assertSame(s1_2, container.getComponentInstanceOfType(S1_DEP6.class).getS1());
    assertEquals(s1_2.getId(), container.getComponentInstanceOfType(S1_DEP6.class).getS1().getId());
    manager.<ServletRequest>getContext(RequestScoped.class).deactivate(req2);
    try {
        container.getComponentInstanceOfType(S2.class).getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    // Request1 out of any session context
    manager.<HttpSession>getContext(SessionScoped.class).activate(null);
    try {
        container.getComponentInstanceOfType(S2.class).getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    manager.<HttpSession>getContext(SessionScoped.class).deactivate(null);
    // Register a session
    Map<Object, Object> mapSession1 = new HashMap<Object, Object>();
    HttpSession session1 = createProxy(HttpSession.class, mapSession1);
    manager.<HttpSession>getContext(SessionScoped.class).register(session1);
    // Request2 out of any session context
    manager.<HttpSession>getContext(SessionScoped.class).activate(null);
    try {
        container.getComponentInstanceOfType(S2.class).getId();
        fail("An exception is expected as the scope is not active");
    } catch (Exception e) {
    }
    assertTrue(mapSession1.isEmpty());
    manager.<HttpSession>getContext(SessionScoped.class).deactivate(null);
    // Request3 within the session context
    manager.<HttpSession>getContext(SessionScoped.class).activate(session1);
    try {
        container.getComponentInstanceOfType(S20.class);
        fail("An exception is expected as it is a passivating scope and S20 is not serializable");
    } catch (Exception e) {
    }
    S2 s2 = container.getComponentInstanceOfType(S2.class);
    assertNotNull(s2);
    int s2Id = s2.getId();
    assertSame(s2, container.getComponentInstanceOfType(S2.class));
    assertEquals(s2Id, container.getComponentInstanceOfType(S2.class).getId());
    manager.<HttpSession>getContext(SessionScoped.class).deactivate(session1);
    // Request4 within the session context
    manager.<HttpSession>getContext(SessionScoped.class).activate(session1);
    S2 s2_2 = container.getComponentInstanceOfType(S2.class);
    assertNotNull(s2_2);
    assertSame(s2_2, container.getComponentInstanceOfType(S2.class));
    assertSame(s2_2, s2);
    assertEquals(s2_2.getId(), s2Id);
    manager.<HttpSession>getContext(SessionScoped.class).deactivate(session1);
    // Register session 2
    Map<Object, Object> mapSession2 = new HashMap<Object, Object>();
    HttpSession session2 = createProxy(HttpSession.class, mapSession2);
    manager.<HttpSession>getContext(SessionScoped.class).register(session2);
    // Request5 within the session context of session#2
    manager.<HttpSession>getContext(SessionScoped.class).activate(session2);
    S2 s2_3 = container.getComponentInstanceOfType(S2.class);
    assertNotNull(s2_3);
    assertSame(s2_3, container.getComponentInstanceOfType(S2.class));
    assertFalse(s2_3.getId() == s2Id);
    assertEquals(1, mapSession2.size());
    manager.<HttpSession>getContext(SessionScoped.class).deactivate(session2);
    assertEquals(1, mapSession2.size());
    // Unregister session 2
    manager.<HttpSession>getContext(SessionScoped.class).unregister(session2);
    assertTrue(mapSession2.isEmpty());
    // Unregister session 1
    manager.<HttpSession>getContext(SessionScoped.class).unregister(session1);
    assertTrue(mapSession1.isEmpty());
    // Request6 out of any session context
    manager.<HttpSession>getContext(SessionScoped.class).activate(session1);
    container.getComponentInstanceOfType(S2.class).getId();
    assertEquals(1, mapSession1.size());
    manager.<HttpSession>getContext(SessionScoped.class).deactivate(session1);
    // Register session 3
    Map<Object, Object> mapSession3 = new HashMap<Object, Object>();
    HttpSession session3 = createProxy(HttpSession.class, mapSession2);
    manager.<HttpSession>getContext(SessionScoped.class).register(session3);
    checkConcurrentAccesses(container, S2.class, mapSession3, HttpSession.class, manager.<HttpSession>getContext(SessionScoped.class));
    // Unregister session 3
    manager.<HttpSession>getContext(SessionScoped.class).unregister(session3);
    // Request1 within the application context as it is always active
    S3 s3 = container.getComponentInstanceOfType(S3.class);
    assertNotNull(s3);
    assertSame(s3, container.getComponentInstanceOfType(S3.class));
    assertEquals(s3.getId(), container.getComponentInstanceOfType(S3.class).getId());
}
Example 60
Project: blaze-utils-master  File: DisposableProducer.java View source code
@Produces
@ApplicationScoped
@ExcludeIfExists(StringHolder.class)
public StringHolder getObject() {
    return new DisposableObject("Hello");
}
Example 61
Project: deltaspike-solder-master  File: OpenIdProviderInApplicationScopeProducer.java View source code
@Produces
@ApplicationScoped
public OpenIdProviderBean produce(@New OpenIdProviderBean op) {
    return op;
}
Example 62
Project: blog-cdidemo-master  File: EntityMangerFactoryProducer.java View source code
@Produces
@ApplicationScoped
public EntityManagerFactory create() {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("cdidemo");
    created.fire(new EntityManagerFactoryCreatedEvent(emf));
    return emf;
}
Example 63
Project: flags-master  File: ManagedFeatureManagerProvider.java View source code
@Produces
@ApplicationScoped
public FeatureManager produce() {
    return new FeatureManagerBuilder().featureEnum(Features.class).userProvider(new NoOpUserProvider()).stateRepository(new InMemoryStateRepository()).name("I'm managed by CDI").build();
}
Example 64
Project: furnace-cdi-master  File: ProxiedServiceFactory.java View source code
@Produces
@ApplicationScoped
public ProxiedService getProxiedService() {
    return new ProxiedServiceImpl();
}
Example 65
Project: optaconf-master  File: SolverFactoryProducer.java View source code
@Produces
@ApplicationScoped
public SolverFactory<Conference> createSolverFactory() {
    return SolverFactory.createFromXmlResource(OptaConfPlanner.SOLVER_CONFIG);
}
Example 66
Project: togglz-master  File: ManagedFeatureManagerProvider.java View source code
@Produces
@ApplicationScoped
public FeatureManager produce() {
    return new FeatureManagerBuilder().featureEnum(Features.class).userProvider(new NoOpUserProvider()).stateRepository(new InMemoryStateRepository()).name("I'm managed by CDI").build();
}
Example 67
Project: hazelcast-examples-master  File: DistributedMapProducer.java View source code
@ApplicationScoped
@Produces
public IMap<String, String> createSimpleDistributedMap() {
    return hazelcastInstance.getMap("default");
}
Example 68
Project: hibernate-search-master  File: CDIObserver.java View source code
public void onBeanManagerInitialized(@Observes @Initialized(ApplicationScoped.class) Object init) {
    CDIBeanManagerSynchronizer synchronizer = CDIBeanManagerSynchronizer.get(beanManager);
    if (synchronizer != null) {
        synchronizer.onBeanManagerInitialized();
    }
}
Example 69
Project: jbpm-examples-master  File: EnvironmentProducer.java View source code
@PersistenceUnit(unitName = "org.jbpm.sample")
@ApplicationScoped
@Produces
public EntityManagerFactory getEntityManagerFactory() {
    if (this.emf == null) {
        this.emf = Persistence.createEntityManagerFactory("org.jbpm.sample");
    }
    return this.emf;
}
Example 70
Project: jms-master  File: ActiveMQConnectionFactoryProducer.java View source code
@Override
@Specializes
@Produces
@ApplicationScoped
@JmsDefault("connectionFactory")
public ConnectionFactory produceConnectionFactory() {
    return connectionFactory;
}
Example 71
Project: justaddwater-master  File: EntityMangerFactoryProducer.java View source code
@Produces
@ApplicationScoped
public EntityManagerFactory create() {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("justaddwater");
    created.fire(new EntityManagerFactoryCreatedEvent(emf));
    return emf;
}
Example 72
Project: activemq-artemis-master  File: CDIProducers.java View source code
@Produces
@ApplicationScoped
public ArtemisClientConfiguration createConfig() {
    return new DefaultArtemisClientConfigurationImpl();
}
Example 73
Project: aerogear-unifiedpush-server-master  File: EntityFactory.java View source code
@Produces
@ApplicationScoped
private EntityManager entityManage() {
    return Persistence.createEntityManagerFactory("UnifiedPush").createEntityManager();
}
Example 74
Project: agorava-core-master  File: AgoravaExtensionTestProducers.java View source code
@ApplicationScoped
@Produces
@FakeService
public OAuthAppSettings produceFirstSetting() {
    PropertyOAuthAppSettingsBuilder builder = new PropertyOAuthAppSettingsBuilder();
    return builder.build();
}
Example 75
Project: cdi-jpa-jta-generic-dao-master  File: EntityManagerFactoryProducer.java View source code
@Produces
@ApplicationScoped
public EntityManagerFactory createEntityManagerFactory() {
    return Persistence.createEntityManagerFactory("cdi-presistence-unit");
}
Example 76
Project: metrics-cdi-master  File: MetricRegistryProducerMethodBean.java View source code
@Produces
@ApplicationScoped
MetricRegistry registry() {
    MetricRegistry registry = new MetricRegistry();
    registry.counter("counter");
    registry.timer("timer");
    return registry;
}
Example 77
Project: solder-old-master  File: ExpressionFactoryProducer.java View source code
@Produces
@ApplicationScoped
ExpressionFactory createExpressionFactory() {
    return ExpressionFactory.newInstance();
}
Example 78
Project: spring-data-jpa-master  File: EntityManagerFactoryProducer.java View source code
@Produces
@ApplicationScoped
public EntityManagerFactory createEntityManagerFactory() {
    String hibernateVersion = Version.getVersionString();
    return Persistence.createEntityManagerFactory(hibernateVersion.startsWith("5.2") ? "cdi-52" : "cdi");
}
Example 79
Project: wildfly-camel-master  File: JAXBDataFormatProducer.java View source code
@Produces
@ApplicationScoped
@Named("jaxb")
public JaxbDataFormat jaxbDataFormat() {
    JaxbDataFormat jaxbDataFormat = new JaxbDataFormat();
    jaxbDataFormat.setContextPath(Customer.class.getPackage().getName());
    return jaxbDataFormat;
}
Example 80
Project: droolsjbpm-knowledge-master  File: BootOnLoadExtension.java View source code
public <X> void processBean(@Observes final ProcessBean<X> event) {
    if (event.getAnnotated().isAnnotationPresent(BootOnLoad.class) && (event.getAnnotated().isAnnotationPresent(ApplicationScoped.class) || event.getAnnotated().isAnnotationPresent(Singleton.class))) {
        startupBootstrapBeans.add(event.getBean());
    }
}
Example 81
Project: Activiti-master  File: ActivitiServices.java View source code
@Produces
@Named
@ApplicationScoped
public ProcessEngine processEngine() {
    return processEngine;
}
Example 82
Project: arquillian-container-weld-master  File: ApplicationObserver.java View source code
public void observeAppScopeInit(@Observes @Initialized(ApplicationScoped.class) Object object) {
    this.payload = object;
    isAppScopeInitializationObserved.set(true);
}
Example 83
Project: arquillian-showcase-master  File: CacheProducer.java View source code
@Produces
@ApplicationScoped
public EmbeddedCacheManager createCacheManager() throws IOException {
    return new DefaultCacheManager(configName);
}
Example 84
Project: capedwarf-blue-master  File: AdminConsolePagesProducer.java View source code
@Produces
@ApplicationScoped
@Named
public static List<AdminConsolePage> getAdminConsolePages() {
    return ApplicationConfiguration.getInstance().getAppEngineWebXml().getAdminConsolePages();
}
Example 85
Project: cartographer-master  File: CartoUIConfig.java View source code
@Produces
@Default
@ApplicationScoped
public UIConfiguration getUiConfiguration() {
    if (config.getUIDir() == null) {
        config.setUIDir(DEFAULT_UI_DIR);
    }
    return config;
}
Example 86
Project: FiWare-Template-Handler-master  File: ActivitiServices.java View source code
@Produces
@Named
@ApplicationScoped
public ProcessEngine processEngine() {
    return processEngine;
}
Example 87
Project: graphity-core-master  File: Neo4jCdiProducer.java View source code
@Produces
@ApplicationScoped
Session createSession() {
    return null;
}
Example 88
Project: jbpm-master  File: ExecutorDatabaseProducer.java View source code
@PersistenceUnit(unitName = "org.jbpm.executor")
@ApplicationScoped
@Produces
public EntityManagerFactory getEntityManagerFactory() {
    if (this.emf == null) {
        // this needs to be here for non EE containers
        this.emf = Persistence.createEntityManagerFactory("org.jbpm.executor");
    }
    return this.emf;
}
Example 89
Project: jenkow-plugin-master  File: ActivitiServices.java View source code
@Produces
@Named
@ApplicationScoped
public ProcessEngine processEngine() {
    return processEngine;
}
Example 90
Project: keycloak-master  File: CDIResourcesProducer.java View source code
@Produces
@ApplicationScoped
public ServletOAuthClient produceOAuthClient() {
    return new ServletOAuthClient();
}
Example 91
Project: lettuce-master  File: AbstractCdiBean.java View source code
@Override
public Class<? extends Annotation> getScope() {
    return ApplicationScoped.class;
}
Example 92
Project: mapstruct-master  File: CdiComponentProcessor.java View source code
@Override
protected List<Annotation> getTypeAnnotations(Mapper mapper) {
    return Collections.singletonList(new Annotation(getTypeFactory().getType("javax.enterprise.context.ApplicationScoped")));
}
Example 93
Project: picketlink-extensions-master  File: IdentityManagerProducer.java View source code
@Produces
@ApplicationScoped
public IdentityManager produceIdentityManager() {
    return this.picketBoxManager.getIdentityManager();
}
Example 94
Project: rewrite-master  File: ExpressionFactoryProducer.java View source code
@Produces
@Composite
@ApplicationScoped
ExpressionFactory createExpressionFactory(BeanManager beanManager) {
    return beanManager.wrapExpressionFactory(ExpressionFactory.newInstance());
}
Example 95
Project: richfaces-master  File: TopicsContextProducer.java View source code
/**
     * Produces application scoped {@link TopicsContext} reference.
     *
     * @return application scoped {@link TopicsContext} reference.
     */
@Produces
@ApplicationScoped
public TopicsContext getTopicsContext() {
    return TopicsContext.lookup();
}
Example 96
Project: rtgov-master  File: StartupBeanExtension.java View source code
<X> void processBean(@Observes ProcessBean<X> event) {
    if (event.getAnnotated().isAnnotationPresent(Startup.class) && event.getAnnotated().isAnnotationPresent(ApplicationScoped.class)) {
        startupBeans.add(event.getBean());
    }
}
Example 97
Project: spring-data-mongodb-master  File: MongoTemplateProducer.java View source code
@Produces
@ApplicationScoped
public MongoOperations createMongoTemplate() {
    MongoDbFactory factory = new SimpleMongoDbFactory(new MongoClient(), "database");
    return new MongoTemplate(factory);
}
Example 98
Project: spring-data-neo4j-master  File: Neo4jCdiProducer.java View source code
@Produces
@ApplicationScoped
Session createSession() {
    return null;
}
Example 99
Project: vraptor-jpa-master  File: EntityManagerFactoryCreator.java View source code
@ApplicationScoped
@Produces
public EntityManagerFactory getEntityManagerFactory() {
    String persistenceUnit = environment.get("br.com.caelum.vraptor.jpa.persistenceunit", "default");
    return Persistence.createEntityManagerFactory(persistenceUnit);
}
Example 100
Project: vraptor4-master  File: ServletContextFactory.java View source code
public void observesContext(@Observes @Initialized(ApplicationScoped.class) ServletContext context) {
    this.context = context;
}
Example 101
Project: wildfly-master  File: Library.java View source code
public static void init(@Observes @Initialized(ApplicationScoped.class) Object event) {
    if (EVENT != null) {
        throw new IllegalStateException("Event already received: " + EVENT);
    }
    EVENT = event;
}