Java Code Examples for javax.enterprise.context.RequestScoped

The following examples show how to use javax.enterprise.context.RequestScoped. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Set some state on Request scoped bean and verify
 * the state is cleared on the thread where the other task runs.
 *
 * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDIMECtxClearsRequestScopedBean() throws Exception {
    // check if given context is active, if it isn't test ends successfully
    try {
        bm.getContext(RequestScoped.class);
    } catch (ContextNotActiveException e) {
        return;
    }

    ManagedExecutor propagatedNone = ManagedExecutor.builder()
            .propagated() // none
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Instance<RequestScopedBean> selectedInstance = instance.select(RequestScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    try {
        checkCDIPropagation(false, "testCDI_ME_Ctx_Clear-REQUEST", propagatedNone,
                selectedInstance.get());
    } 
    finally {
        propagatedNone.shutdown();
    }
}
 
Example 2
Source Project: quarkus   Source File: SpringDIProcessorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void springStereotypeScopes() {
    final Map<DotName, Set<DotName>> scopes = processor.getStereotypeScopes(index);

    final Map<DotName, Set<DotName>> expected = new HashMap<>();
    expected.put(SpringDIProcessor.SPRING_COMPONENT, Collections.emptySet());
    expected.put(SpringDIProcessor.SPRING_SERVICE, Collections.emptySet());
    expected.put(SpringDIProcessor.SPRING_REPOSITORY, Collections.emptySet());
    expected.put(DotName.createSimple(PrototypeService.class.getName()),
            Collections.singleton(DotName.createSimple(Dependent.class.getName())));
    expected.put(DotName.createSimple(RequestService.class.getName()),
            Collections.singleton(DotName.createSimple(RequestScoped.class.getName())));
    expected.put(DotName.createSimple(UndeclaredService.class.getName()), Collections.emptySet());
    expected.put(DotName.createSimple(ConflictService.class.getName()), setOf(
            DotName.createSimple(Dependent.class.getName()), DotName.createSimple(RequestScoped.class.getName())));
    assertEquals(expected, scopes);
}
 
Example 3
Source Project: quarkus   Source File: SpringDIProcessorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getAnnotationsToAddBeanMethodWithScope() {
    final Map<DotName, Set<DotName>> scopes = processor.getStereotypeScopes(index);
    final MethodInfo target = index.getClassByName(DotName.createSimple(BeanConfig.class.getName()))
            .method("requestBean");

    final Set<AnnotationInstance> ret = processor.getAnnotationsToAdd(target, scopes, null);

    final Set<AnnotationInstance> expected = setOf(
            AnnotationInstance.create(DotName.createSimple(RequestScoped.class.getName()), target,
                    Collections.emptyList()),
            AnnotationInstance.create(DotNames.PRODUCES, target, Collections.emptyList()),
            AnnotationInstance.create(DotName.createSimple(Named.class.getName()), target,
                    Collections.singletonList(AnnotationValue.createStringValue("value", "requestBean"))));
    assertEquals(expected, ret);
}
 
Example 4
public @Produces @RequestScoped TestSmellDetector createTestSmellDetector() {
  List<AbstractSmell> testSmells = new ArrayList<AbstractSmell>();
  testSmells.add(new AssertionRoulette());
  testSmells.add(new DuplicateAssert());
  testSmells.add(new RedundantAssertion());
  testSmells.add(new SensitiveEquality());
  testSmells.add(new UnknownTest());
  // Those two might require some love according to #426.
  // testSmells.add(new ExceptionCatchingThrowing());
  // Disabled as per #426, waiting for #500
  // testSmells.add(new MagicNumberTest());
  testSmells.add(new ConfigurableEagerTest(EAGER_TEST_THRESHOLD));
  /*
   * Those two are not mentioned on:
   * https://testsmells.github.io/pages/testsmells.html but might become
   * relevant later
   */
  // testSmells.add(new VerboseTest());
  // testSmells.add(new DependentTest());
  return new TestSmellDetector(testSmells);
}
 
Example 5
@Deployment
public static WebArchive createDeployment() {
    String url = SimpleGetApi.class.getName() + "/mp-rest/url=http://localhost:8080";
    String url2 = MyRequestScopedApi.class.getName() + "/mp-rest/url=http://localhost:8080";
    String scope = SimpleGetApi.class.getName() + "/mp-rest/scope=" + RequestScoped.class.getName();
    String configKeyScope = "myConfigKey/mp-rest/scope=" + RequestScoped.class.getName();
    String simpleName = HasRequestScopeTest.class.getSimpleName();
    JavaArchive jar = ShrinkWrap.create(JavaArchive.class, simpleName + ".jar")
        .addClasses(SimpleGetApi.class, MyRequestScopedApi.class, ConfigKeyClient.class)
        .addAsManifestResource(new StringAsset(url + "\n" + scope + "\n" + url2 + "\n" + configKeyScope),
                                               "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
    return ShrinkWrap.create(WebArchive.class, simpleName + ".war")
        .addAsLibrary(jar)
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
 
Example 6
Source Project: database-rider   Source File: CdiCucumberTestRunner.java    License: Apache License 2.0 6 votes vote down vote up
void applyBeforeFeatureConfig(Class testClass) {
    CdiContainer container = CdiContainerLoader.getCdiContainer();

    if (!isContainerStarted()) {
        container.boot(CdiTestSuiteRunner.getTestContainerConfig());
        containerStarted = true;
        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);
    }

    this.previousProjectStage = ProjectStageProducer.getInstance().getProjectStage();
    ProjectStageProducer.setProjectStage(this.projectStage);

    startScopes(container, testClass, null, restrictedScopes.toArray(new Class[restrictedScopes.size()]));
}
 
Example 7
Source Project: datawave   Source File: ServerSecurityProducer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Produces a {@link DatawavePrincipal} that is {@link RequestScoped}. This is the principal of the calling user--that is, the principal that is available
 * from the {@link javax.ejb.EJBContext} of an EJB.
 */
@Produces
@CallerPrincipal
@RequestScoped
public DatawavePrincipal produceCallerPrincipal() throws Exception {
    DatawavePrincipal dp = userOperationsBean.getCurrentPrincipal();
    return dp == null ? DatawavePrincipal.anonymousPrincipal() : dp;
}
 
Example 8
Source Project: datawave   Source File: ServerSecurityProducer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Produces a {@link DatawavePrincipal} that is {@link RequestScoped}. This is a principal that is filled in with the name and authorizations for the server
 * that is currently running DATAWAVE.
 */
@Produces
@ServerPrincipal
@RequestScoped
public DatawavePrincipal produceServerPrincipal() throws Exception {
    return new DatawavePrincipal(datawaveUserService.lookup(Collections.singleton(lookupServerDN())));
}
 
Example 9
public Object lookup(String beanName, String sessionID) {

		NGSessionScopeContext.setCurrentContext(sessionID);

		Set<Bean<?>> beans = beanManager.getBeans(beanName);

		Class beanClass = CommonUtils.beanNamesHolder.get(beanName);
		if (beans.isEmpty()) {
			beans = beanManager.getBeans(beanClass, new AnnotationLiteral<Any>() { //
			});
		}

		Bean bean = beanManager.resolve(beans);

		Class scopeAnnotationClass = bean.getScope();
		Context context;

		if (scopeAnnotationClass.equals(RequestScoped.class)) {
			context = beanManager.getContext(scopeAnnotationClass);
			if (context == null)
				return bean.create(beanManager.createCreationalContext(bean));

		} else {

			if (scopeAnnotationClass.equals(NGSessionScopeContext.class)) {
				context = NGSessionScopeContext.getINSTANCE();
			} else {
				context = beanManager.getContext(scopeAnnotationClass);
			}

		}
		CreationalContext creationalContext = beanManager.createCreationalContext(bean);
		Object reference = context.get(bean, creationalContext);

		// if(reference==null && scopeAnnotationClass.equals(RequestScoped.class)){
		// reference= bean.create(beanManager.createCreationalContext(bean));
		// }

		return reference;
	}
 
Example 10
@Override
public boolean activate() {
    if (Arc.container().getActiveContext(RequestScoped.class) != null) {
        return false;
    }
    requestContext.activate();
    isActivator.set(true);
    return true;
}
 
Example 11
@Override
public void deactivate() throws ContextNotActiveException {
    if (Arc.container().getActiveContext(RequestScoped.class) == null) {
        throw new ContextNotActiveException(RequestScoped.class.getName());
    }
    if (isActivator.compareAndSet(true, false)) {
        requestContext.terminate();
    }
}
 
Example 12
Source Project: quarkus   Source File: ScopeInheritanceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testScopeInheritanceIsTakenIntoAccount() {
    // we'll use BM to verify scopes
    BeanManager bm = Arc.container().beanManager();
    Set<Bean<?>> beans = bm.getBeans(RequestScopedSubBean.class);
    Assertions.assertTrue(beans.size() == 1);
    Assertions.assertEquals(RequestScoped.class.getSimpleName(), beans.iterator().next().getScope().getSimpleName());
    beans = bm.getBeans(InheritedScopeSubBean.class);
    Assertions.assertTrue(beans.size() == 1);
    Assertions.assertEquals(ApplicationScoped.class.getSimpleName(), beans.iterator().next().getScope().getSimpleName());
}
 
Example 13
Source Project: quarkus   Source File: RepeatingQualifierProducerTest.java    License: Apache License 2.0 5 votes vote down vote up
@RequestScoped
@Produces
@Location("home")
@NotAQualifier("ignored")
public SomePlace produceHome() {
    return new SomePlace() {
        @Override
        public String ping() {
            return "home";
        }
    };
}
 
Example 14
Source Project: quarkus   Source File: RepeatingQualifierProducerTest.java    License: Apache License 2.0 5 votes vote down vote up
@RequestScoped
@Produces
@Location("office")
@Location("work")
@NotAQualifier("ignored")
public SomePlace produceFarWork() {
    return new SomePlace() {
        @Override
        public String ping() {
            return "farAway";
        }
    };
}
 
Example 15
Source Project: quarkus   Source File: BeanManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIsScope() {
    BeanManager beanManager = Arc.container().beanManager();
    assertTrue(beanManager.isScope(Singleton.class));
    assertTrue(beanManager.isNormalScope(RequestScoped.class));
    assertFalse(beanManager.isNormalScope(Dependent.class));
}
 
Example 16
Source Project: quarkus   Source File: SecurityIdentityAssociation.java    License: Apache License 2.0 5 votes vote down vote up
@Produces
@RequestScoped
Principal principal() {
    //TODO: as this is request scoped we loose the type of the Principal
    //if this is important you can just inject the identity
    return new Principal() {
        @Override
        public String getName() {
            return getIdentity().getPrincipal().getName();
        }
    };
}
 
Example 17
Source Project: quarkus   Source File: OidcJsonWebTokenProducer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * The producer method for the current id token
 *
 * @return the id token
 */
@Produces
@IdToken
@RequestScoped
JsonWebToken currentIdToken() {
    return getTokenCredential(IdTokenCredential.class);
}
 
Example 18
Source Project: quarkus   Source File: SpringDIProcessorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getAnnotationsToAdd() {
    final Map<DotName, Set<DotName>> scopes = processor.getStereotypeScopes(index);
    final ClassInfo target = index.getClassByName(DotName.createSimple(RequestBean.class.getName()));

    final Set<AnnotationInstance> ret = processor.getAnnotationsToAdd(target, scopes, null);

    final Set<AnnotationInstance> expected = setOf(
            AnnotationInstance.create(DotName.createSimple(RequestScoped.class.getName()), target,
                    Collections.emptyList()));
    assertEquals(expected, ret);
}
 
Example 19
Source Project: scalable-coffee-shop   Source File: KafkaConfigurator.java    License: Apache License 2.0 5 votes vote down vote up
@Produces
@RequestScoped
public Properties exposeKafkaProperties() throws IOException {
    final Properties properties = new Properties();
    properties.putAll(kafkaProperties);
    return properties;
}
 
Example 20
Source Project: scalable-coffee-shop   Source File: KafkaConfigurator.java    License: Apache License 2.0 5 votes vote down vote up
@Produces
@RequestScoped
public Properties exposeKafkaProperties() throws IOException {
    final Properties properties = new Properties();
    properties.putAll(kafkaProperties);
    return properties;
}
 
Example 21
Source Project: scalable-coffee-shop   Source File: KafkaConfigurator.java    License: Apache License 2.0 5 votes vote down vote up
@Produces
@RequestScoped
public Properties exposeKafkaProperties() throws IOException {
    final Properties properties = new Properties();
    properties.putAll(kafkaProperties);
    return properties;
}
 
Example 22
@Produces
@RequestScoped
public IMutationTester getMutationTester() {
    if( enableParalleExecution ){
        return new ParallelMutationTester(backend, useMutantCoverage, testExecutorThreadPool);
    } else{
        return new MutationTester(backend, useMutantCoverage);
    }
}
 
Example 23
Source Project: library   Source File: AuthenticatedUserProducer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Produce the {@link CurrentUser} instance
 *
 * @return CurrentUser instance to be used
 */
@Produces
@RequestScoped
@AuthenticatedUser
CurrentUser produce() {

    if (this.authenticated.isEmpty()) {
        this.initialize();
    }

    return this.authenticated;
}
 
Example 24
Source Project: database-rider   Source File: CdiCucumberTestRunner.java    License: Apache License 2.0 5 votes vote down vote up
private void addScopesForDefaultBehavior(List<Class<? extends Annotation>> scopeClasses) {
    if (this.parent != null && !this.parent.isScopeStarted(RequestScoped.class)) {
        if (!scopeClasses.contains(RequestScoped.class)) {
            scopeClasses.add(RequestScoped.class);
        }
    }
    if (this.parent != null && !this.parent.isScopeStarted(SessionScoped.class)) {
        if (!scopeClasses.contains(SessionScoped.class)) {
            scopeClasses.add(SessionScoped.class);
        }
    }
}
 
Example 25
@Bean
@ConditionalOnProperty(value = "joinfaces.scope-configurer.cdi.enabled", havingValue = "true", matchIfMissing = true)
public static CustomScopeAnnotationConfigurer cdiScopeAnnotationsConfigurer(Environment environment) {
	CustomScopeAnnotationConfigurer scopeAnnotationConfigurer = new CustomScopeAnnotationConfigurer();

	scopeAnnotationConfigurer.setOrder(environment.getProperty("joinfaces.scope-configurer.cdi.order", Integer.class, Ordered.LOWEST_PRECEDENCE));

	scopeAnnotationConfigurer.addMapping(RequestScoped.class, WebApplicationContext.SCOPE_REQUEST);
	scopeAnnotationConfigurer.addMapping(SessionScoped.class, WebApplicationContext.SCOPE_SESSION);
	scopeAnnotationConfigurer.addMapping(ConversationScoped.class, WebApplicationContext.SCOPE_SESSION);
	scopeAnnotationConfigurer.addMapping(ApplicationScoped.class, WebApplicationContext.SCOPE_APPLICATION);

	return scopeAnnotationConfigurer;
}
 
Example 26
@Produces
@RequestScoped
public MyRestApi createMyApi() {
    return new MyRestApi() {
        @Override
        public String get() {
            return null;
        }

        @Override
        public void close() throws Exception {

        }
    };
}
 
Example 27
Source Project: smallrye-jwt   Source File: PrincipalProducer.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * The producer method for the current JsonWebToken
 *
 * @return JsonWebToken
 */
@Produces
@RequestScoped
JsonWebToken currentJWTPrincipalOrNull() {
    return token == null ? new NullJsonWebToken() : token;
}
 
Example 28
Source Project: krazo   Source File: BindingResultManager.java    License: Apache License 2.0 4 votes vote down vote up
@Produces
@RequestScoped
public BindingResultImpl createBindingResult() {
    return new BindingResultImpl();
}
 
Example 29
Source Project: krazo   Source File: JaxRsContextProducer.java    License: Apache License 2.0 4 votes vote down vote up
@Produces
@JaxRsContext
@RequestScoped
public Configuration produceConfiguration() {
    return Objects.requireNonNull(configuration, "Cannot produce Configuration");
}
 
Example 30
Source Project: krazo   Source File: JaxRsContextProducer.java    License: Apache License 2.0 4 votes vote down vote up
@Produces
@JaxRsContext
@RequestScoped
public HttpServletRequest produceHttpServletRequest() {
    return Objects.requireNonNull(request, "Cannot produce HttpServletRequest");
}