javax.enterprise.util.TypeLiteral Java Examples

The following examples show how to use javax.enterprise.util.TypeLiteral. 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: AddGloballyEnabledAlternativeTest.java    From weld-junit with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllBeansAreAddedAndCanBeSelected() {
    Bar bar = weld.select(Bar.class).get();
    Assert.assertNotNull(bar.getFoo());
    Assert.assertNotNull(bar.getSomeList());
    Assert.assertEquals("42", bar.getSomeList().get(0));

    // assert all of these are actually alternatives (enabled)
    Set<Bean<?>> beans = weld.getBeanManager().getBeans(Foo.class, Meaty.Literal.INSTANCE);
    Assert.assertEquals(1, beans.size());
    Assert.assertTrue(beans.iterator().next().isAlternative());

    beans = weld.getBeanManager().getBeans(new TypeLiteral<List<String>>() {
    }.getType());
    Assert.assertEquals(1, beans.size());
    Assert.assertTrue(beans.iterator().next().isAlternative());
}
 
Example #2
Source File: AsyncReferenceTest.java    From weld-vertx with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testAsyncReferenceNormalScoped(TestContext context) throws InterruptedException {
    NormalScopedBlockingFoo.reset();
    Async async = context.async();
    AtomicBoolean created = new AtomicBoolean(false);

    weld.select(new TypeLiteral<AsyncReference<NormalScopedBlockingFoo>>() {
    }).get().thenAccept((foo) -> {
        context.assertTrue(NormalScopedBlockingFoo.created.get());
        context.assertEquals("Foo", foo.getMessage());
        created.set(true);
        async.complete();
    });
    assertFalse(created.get());
    NormalScopedBlockingFoo.complete("Foo");
    Awaitility.await().atMost(Timeouts.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS).until(() -> created.get());
}
 
Example #3
Source File: AsyncReferenceTest.java    From weld-vertx with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testAsyncReferenceDynamicLookupSimple(TestContext context) throws InterruptedException {
    BlockingFoo.reset();
    Async async = context.async();
    AtomicBoolean created = new AtomicBoolean(false);

    weld.select(new TypeLiteral<AsyncReference<BlockingFoo>>() {
    }).get().thenAccept((foo) -> {
        context.assertEquals("Foo", foo.getMessage());
        created.set(true);
        async.complete();
    });

    assertFalse(created.get());
    BlockingFoo.complete("Foo");
}
 
Example #4
Source File: AddGloballyEnabledAlternativeTest.java    From weld-junit with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllBeansAreAddedAndCanBeSelected() {
    Bar bar = weld.select(Bar.class).get();
    Assertions.assertNotNull(bar.getFoo());
    Assertions.assertNotNull(bar.getSomeList());
    Assertions.assertEquals("42", bar.getSomeList().get(0));

    // assert all of these are actually alternatives (enabled)
    Set<Bean<?>> beans = weld.getBeanManager().getBeans(Foo.class, Meaty.Literal.INSTANCE);
    Assertions.assertEquals(1, beans.size());
    Assertions.assertTrue(beans.iterator().next().isAlternative());

    beans = weld.getBeanManager().getBeans(new TypeLiteral<List<String>>(){}.getType());
    Assertions.assertEquals(1, beans.size());
    Assertions.assertTrue(beans.iterator().next().isAlternative());
}
 
Example #5
Source File: DisposerTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testDisposers() {
    InstanceHandle<Long> longHandle = Arc.container().instance(Long.class);
    Long longValue = longHandle.get();
    longHandle.close();
    assertEquals(LongProducer.DISPOSED.get(), longValue);
    // String is only injected in Long disposer
    assertNotNull(StringProducer.DISPOSED.get());
    // Pong should be destroyed when the disposer invocation completes
    assertTrue(Pong.DESTROYED.get());

    // A new instance is created for produce and dispose
    assertEquals(2, StringProducer.DESTROYED.get());
    // Both producer and produced bean are application scoped
    @SuppressWarnings("serial")
    Comparable<BigDecimal> bigDecimal = Arc.container().instance(new TypeLiteral<Comparable<BigDecimal>>() {
    }).get();
    assertEquals(0, bigDecimal.compareTo(BigDecimal.ONE));
}
 
Example #6
Source File: CdiServiceDiscovery.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> List<T> getInstancesByType(Class<T> clazz) {
	BeanManager beanManager = getBeanManager();
	List<T> list = new ArrayList<>();
	if (beanManager != null) {
		Type type = clazz;
		if (clazz == ExceptionMapper.class) {
			TypeLiteral<ExceptionMapper<?>> typeLiteral = new TypeLiteral<ExceptionMapper<?>>() {
			};
			type = typeLiteral.getType();
		}

		Set<Bean<?>> beans = beanManager.getBeans(type);
		for (Bean<?> bean : beans) {
			CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
			T object = (T) beanManager.getReference(bean, type, creationalContext);
			list.add(object);
		}
	}
	return list;
}
 
Example #7
Source File: InjectionPointMetadataTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "serial" })
@Test
public void testObserverInjectionPointMetadata() {
    AtomicReference<InjectionPoint> ip = new AtomicReference<>();
    Arc.container().beanManager().getEvent().select(new TypeLiteral<AtomicReference<InjectionPoint>>() {
    }).fire(ip);
    InjectionPoint injectionPoint = ip.get();
    assertNotNull(injectionPoint);
    assertEquals(Controlled.class, injectionPoint.getType());
    Set<Annotation> qualifiers = injectionPoint.getQualifiers();
    assertEquals(1, qualifiers.size());
    assertEquals(Default.class, qualifiers.iterator().next().annotationType());
    Assertions.assertNull(injectionPoint.getBean());
    assertNotNull(injectionPoint.getAnnotated());
    assertTrue(injectionPoint.getAnnotated() instanceof AnnotatedParameter);
    AnnotatedParameter<Controller> annotatedParam = (AnnotatedParameter<Controller>) injectionPoint.getAnnotated();
    assertEquals(Controlled.class, annotatedParam.getBaseType());
    assertEquals(1, annotatedParam.getAnnotations().size());
    assertFalse(annotatedParam.isAnnotationPresent(Inject.class));
    assertTrue(annotatedParam.isAnnotationPresent(FooAnnotation.class));
    assertTrue(annotatedParam.getAnnotation(Singleton.class) == null);
    assertTrue(annotatedParam.getAnnotations(Singleton.class).isEmpty());
}
 
Example #8
Source File: ArcContainerSelectTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testSelect() {
    assertTrue(Arc.container().select(BeanManager.class).isResolvable());
    InjectableInstance<Supplier<String>> instance = Arc.container().select(new TypeLiteral<Supplier<String>>() {
    });
    Set<String> strings = new HashSet<>();
    for (InstanceHandle<Supplier<String>> handle : instance.handles()) {
        strings.add(handle.get().get());
        handle.close();
    }
    assertEquals(2, strings.size());
    assertTrue(strings.contains("alpha"));
    assertTrue(strings.contains("washcloth"));
    assertTrue(Washcloth.INIT.get());
    assertTrue(Washcloth.DESTROYED.get());
}
 
Example #9
Source File: BuiltInBeansAreResolvableTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "serial", "unchecked", "rawtypes" })
@Test
public void testEventBean() {
    // use dynamic resolution to test it
    Instance<Object> instance = Arc.container().beanManager().createInstance();
    // event with no qualifier and raw type
    Instance<Event> rawNoQualifier = instance.select(Event.class);
    assertTrue(rawNoQualifier.isResolvable());
    DummyBean.resetCounters();
    rawNoQualifier.get().fire(new Payload());
    assertEquals(1, DummyBean.noQualifiers);
    assertEquals(0, DummyBean.qualifierTimesTriggered);
    assertEquals(1, DummyBean.timesTriggered);

    // event with type and no qualifier
    Instance<Event<Payload>> typedEventNoQualifier = instance.select(new TypeLiteral<Event<Payload>>() {
    });
    assertTrue(typedEventNoQualifier.isResolvable());
    DummyBean.resetCounters();
    typedEventNoQualifier.get().fire(new Payload());
    assertEquals(1, DummyBean.noQualifiers);
    assertEquals(0, DummyBean.qualifierTimesTriggered);
    assertEquals(1, DummyBean.timesTriggered);

    // event with type and qualifier
    Instance<Event<Payload>> typedEventWithQualifier = instance.select(new TypeLiteral<Event<Payload>>() {
    }, new DummyQualifier.Literal());
    assertTrue(typedEventWithQualifier.isResolvable());
    DummyBean.resetCounters();
    typedEventWithQualifier.get().fire(new Payload());
    assertEquals(1, DummyBean.noQualifiers);
    assertEquals(1, DummyBean.qualifierTimesTriggered);
    assertEquals(1, DummyBean.timesTriggered);

}
 
Example #10
Source File: AddPassivatingBeanTest.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
static Bean<?> createListBean() {
    return MockBean.builder()
            .types(new TypeLiteral<List<String>>() {}.getType())
            .scope(SessionScoped.class)
            .creating(
                    // Mock object provided by Mockito
                    when(mock(List.class).get(0)).thenReturn("42").getMock())
            .build();
}
 
Example #11
Source File: AddBeanTest.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
static Bean<?> createListBean() {
    return MockBean.builder()
            .types(new TypeLiteral<List<String>>() {}.getType())
            .qualifiers(Meaty.Literal.INSTANCE)
            .creating(
                    // Mock object provided by Mockito
                    when(mock(List.class).get(0)).thenReturn("42").getMock())
            .build();
}
 
Example #12
Source File: AddGloballyEnabledAlternativeTest.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
static Bean<?> createListBean() {
    return MockBean.builder()
            .types(new TypeLiteral<List<String>>() {
            }.getType())
            .globallySelectedAlternative(2)
            .creating(
                    // Mock object provided by Mockito
                    Mockito.when(Mockito.mock(List.class).get(0)).thenReturn("42").getMock())
            .build();
}
 
Example #13
Source File: AddPassivatingBeanTest.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
static Bean<?> createListBean() {
    return MockBean.builder()
        .types(new TypeLiteral<List<String>>() {
        }.getType())
        .scope(SessionScoped.class)
        .creating(
            // Mock object provided by Mockito
            when(mock(List.class).get(0)).thenReturn("42").getMock())
        .build();
}
 
Example #14
Source File: AddBeanTest.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
static Bean<?> createListBean() {
    return MockBean.builder()
        .types(new TypeLiteral<List<String>>() {
        }.getType())
        .qualifiers(Meaty.Literal.INSTANCE)
        .creating(
            // Mock object provided by Mockito
            Mockito.when(Mockito.mock(List.class).get(0)).thenReturn("42").getMock())
        .build();
}
 
Example #15
Source File: AddGloballyEnabledAlternativeTest.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
static Bean<?> createListBean() {
    return MockBean.builder()
            .types(new TypeLiteral<List<String>>() {
            }.getType())
            .globallySelectedAlternative(2)
            .creating(
                    // Mock object provided by Mockito
                    Mockito.when(Mockito.mock(List.class).get(0)).thenReturn("42").getMock())
            .build();
}
 
Example #16
Source File: AlternativesPriorityTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testAlternativePriority() {
    assertEquals(Charlie.class.getName(), Arc.container().instance(new TypeLiteral<Supplier<String>>() {
    }).get().get());

    assertEquals(Charlie.class.getName(), Arc.container().instance(Consumer.class).get().consume());
}
 
Example #17
Source File: AssignabilityWithGenericsTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testRequiredTypeIsActualTypeAndBeanHasObject() {
    InstanceHandle<FooTyped<Object>> fooTypedInstance = Arc.container().instance(new TypeLiteral<FooTyped<Object>>() {
    });
    assertTrue(fooTypedInstance.isAvailable());
    InstanceHandle<BeanInjectingActualType> beanInjectingActualTypeInstance = Arc.container()
            .instance(BeanInjectingActualType.class);
    assertTrue(beanInjectingActualTypeInstance.isAvailable());
}
 
Example #18
Source File: DeclaringBeanTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testDependendDestroyedProducerMethod() {
    TypeLiteral<List<String>> literal = new TypeLiteral<List<String>>() {
    };
    assertFalse(ListProducer.DESTROYED.get());
    List<String> list1 = Arc.container().instance(literal).get();
    // @Dependent contextual instance created to receive a producer method is destroyed when the invocation completes
    assertTrue(ListProducer.DESTROYED.get());
    assertNotEquals(list1, Arc.container().instance(literal).get());
}
 
Example #19
Source File: RuntimeResolutionTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testResolution() throws IOException {
    ArcContainer arc = Arc.container();
    // MyList bean types: MyList, AbstractList<Integer>, List<Integer>, AbstractCollection<Integer>, Iterable<Integer>, Object
    InstanceHandle<List<? extends Number>> list = arc.instance(new TypeLiteral<List<? extends Number>>() {
    });
    assertTrue(list.isAvailable());
    assertEquals(Integer.valueOf(7), list.get().get(1));
}
 
Example #20
Source File: AsyncReferenceTest.java    From weld-vertx with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testAsyncReferenceDynamicLookup() throws InterruptedException, ExecutionException {
    BlockingFoo.reset();
    BlockingBarProducer.reset();
    Boss.DESTROYED.set(false);
    List<Boolean> stageResults = new CopyOnWriteArrayList<>();

    AsyncReference<Boss> ref = weld.select(new TypeLiteral<AsyncReference<Boss>>() {
    }).get();
    ref.thenAccept((boss) -> stageResults.add(true));
    assertEquals(0, stageResults.size());

    Awaitility.await().atMost(Timeouts.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS).until(() -> ref.isDone());

    BlockingFoo.complete("Foo");
    BlockingBarProducer.complete(152);

    Awaitility.await().atMost(Timeouts.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS).until(() -> ref.get().isReadyToTest());

    assertEquals(1, stageResults.size());

    ref.whenComplete((r, t) -> {
        if (r != null)
            stageResults.add(true);
    });

    assertEquals(2, stageResults.size());
    assertEquals(152, ref.get().juicyBar.get().code);
    weld.destroy(ref);
    assertTrue(Boss.DESTROYED.get());
}
 
Example #21
Source File: MockInstanceImpl.java    From vraptor4 with Apache License 2.0 4 votes vote down vote up
@Override
public <U extends T> Instance<U> select(TypeLiteral<U> subtype, Annotation... qualifiers) {
	return null;
}
 
Example #22
Source File: AbstractWeldInitiator.java    From weld-junit with Apache License 2.0 4 votes vote down vote up
@Override
public <U> WeldInstance<U> select(TypeLiteral<U> subtype, Annotation... qualifiers) {
    checkContainer();
    return container.select(subtype, qualifiers);
}
 
Example #23
Source File: MockInstance.java    From thorntail with Apache License 2.0 4 votes vote down vote up
@Override
public <U extends T> Instance<U> select(TypeLiteral<U> typeLiteral, Annotation... annotations) {
    throw new RuntimeException("operation not supported by mock");
}
 
Example #24
Source File: TestEvent.java    From development with Apache License 2.0 4 votes vote down vote up
@Override
public Event select(TypeLiteral arg0, Annotation... arg1) {
    return null;
}
 
Example #25
Source File: TestClassProducerTest.java    From weld-junit with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testBean() {
    assertEquals("42", weld.select(new TypeLiteral<List<String>>() {
    }).get().get(0));
}
 
Example #26
Source File: AddPassivatingBeanTest.java    From weld-junit with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testPassivatingBeanAdded() {
    assertEquals("42", weld.select(new TypeLiteral<List<String>>() {}).get().get(0));
}
 
Example #27
Source File: TestInstance.java    From pnc with Apache License 2.0 4 votes vote down vote up
@Override
public <U extends T> Instance<U> select(TypeLiteral<U> subtype, Annotation... qualifiers) {
    throw new UnsupportedOperationException("not implemented");
}
 
Example #28
Source File: CancelledBuildByBpmTest.java    From pnc with Apache License 2.0 4 votes vote down vote up
@Override
public <U extends BuildStatusChangedEvent> Event<U> select(TypeLiteral<U> subtype, Annotation... qualifiers) {
    return null;
}
 
Example #29
Source File: CDIAccessor.java    From javamoney-lib with Apache License 2.0 4 votes vote down vote up
@Override
public <U extends T> Instance<U> select(TypeLiteral<U> uTypeLiteral, Annotation... annotations) {
    return new EmptyInstance<>();
}
 
Example #30
Source File: ClaimValueProducerIT.java    From smallrye-jwt with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "serial" })
<T> ClaimValue<Optional<T>> selectOptionalClaimValue(String name) {
    return weld.select(new TypeLiteral<ClaimValue<Optional<T>>>() {
    },
            new ClaimQualifier(name, null)).get();
}