javax.enterprise.context.RequestScoped Java Examples

The following examples show how to use javax.enterprise.context.RequestScoped. 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
Source File: CDIContextTest.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
/**
 * 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 File: CdiCucumberTestRunner.java    From database-rider with 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 #3
Source File: HasRequestScopeTest.java    From microprofile-rest-client with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: TestSmellDetectorProducer.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
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
Source File: SpringDIProcessorTest.java    From quarkus with 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 #6
Source File: SpringDIProcessorTest.java    From quarkus with 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 #7
Source File: ContextInProxiedInstancesTest.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Produces
@RequestScoped
public MyRestApi createMyApi() {
    return new MyRestApi() {
        @Override
        public String get() {
            return null;
        }

        @Override
        public void close() throws Exception {

        }
    };
}
 
Example #8
Source File: ServerSecurityProducer.java    From datawave with 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
Source File: RepeatingQualifierProducerTest.java    From quarkus with 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 #10
Source File: BeanLocator.java    From AngularBeans with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #11
Source File: RepeatingQualifierProducerTest.java    From quarkus with 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 #12
Source File: InjectableRequestContextController.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@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 #13
Source File: ScopeInheritanceTest.java    From quarkus with 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 #14
Source File: InjectableRequestContextController.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public boolean activate() {
    if (Arc.container().getActiveContext(RequestScoped.class) != null) {
        return false;
    }
    requestContext.activate();
    isActivator.set(true);
    return true;
}
 
Example #15
Source File: BeanManagerTest.java    From quarkus with 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 File: SecurityIdentityAssociation.java    From quarkus with 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 File: OidcJsonWebTokenProducer.java    From quarkus with 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 File: SpringDIProcessorTest.java    From quarkus with 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 File: KafkaConfigurator.java    From scalable-coffee-shop with 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 File: KafkaConfigurator.java    From scalable-coffee-shop with 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 File: KafkaConfigurator.java    From scalable-coffee-shop with 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
Source File: MutationTesterProducer.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Produces
@RequestScoped
public IMutationTester getMutationTester() {
    if( enableParalleExecution ){
        return new ParallelMutationTester(backend, useMutantCoverage, testExecutorThreadPool);
    } else{
        return new MutationTester(backend, useMutantCoverage);
    }
}
 
Example #23
Source File: AuthenticatedUserProducer.java    From library with 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 File: CdiCucumberTestRunner.java    From database-rider with 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
Source File: CdiScopeAnnotationsAutoConfiguration.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@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
Source File: ServerSecurityProducer.java    From datawave with 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 #27
Source File: HasRequestScopeTest.java    From microprofile-rest-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testHasRequestScoped() {
    Set<Bean<?>> beans = beanManager.getBeans(SimpleGetApi.class, RestClient.LITERAL);
    Bean<?> resolved = beanManager.resolve(beans);
    assertEquals(resolved.getScope(), RequestScoped.class);
}
 
Example #28
Source File: HasRequestScopeTest.java    From microprofile-rest-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testHasRequestScopedWhenAnnotated() {
    Set<Bean<?>> beans = beanManager.getBeans(MyRequestScopedApi.class, RestClient.LITERAL);
    Bean<?> resolved = beanManager.resolve(beans);
    assertEquals(resolved.getScope(), RequestScoped.class);
}
 
Example #29
Source File: WebResources.java    From ipst with Mozilla Public License 2.0 4 votes vote down vote up
@Produces
@RequestScoped
public FacesContext produceFacesContext() {
    return FacesContext.getCurrentInstance();
}
 
Example #30
Source File: BindingResultManager.java    From krazo with Apache License 2.0 4 votes vote down vote up
@Produces
@RequestScoped
public BindingResultImpl createBindingResult() {
    return new BindingResultImpl();
}