org.jboss.weld.environment.se.WeldContainer Java Examples

The following examples show how to use org.jboss.weld.environment.se.WeldContainer. 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: JmsSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithDurableTopic() {
    Map<String, Object> map = new HashMap<>();
    map.put("mp.messaging.incoming.jms.connector", JmsConnector.CONNECTOR_NAME);
    map.put("mp.messaging.incoming.jms.destination", "my-topic");
    map.put("mp.messaging.incoming.jms.durable", "true");
    map.put("mp.messaging.incoming.jms.client-id", "me");
    map.put("mp.messaging.incoming.jms.destination-type", "topic");
    MapBasedConfig config = new MapBasedConfig(map);
    addConfig(config);
    WeldContainer container = deploy(RawMessageConsumerBean.class);
    RawMessageConsumerBean bean = container.select(RawMessageConsumerBean.class).get();
    assertThat(bean.messages()).isEmpty();

    Topic q = jms.createTopic("my-topic");
    JMSProducer producer = jms.createProducer();
    String uuid = UUID.randomUUID().toString();
    producer.send(q, uuid);

    await().until(() -> bean.messages().size() == 1);
    IncomingJmsMessage<?> incomingJmsMessage = bean.messages().get(0);
    assertThat(incomingJmsMessage.getPayload()).isEqualTo(uuid);
}
 
Example #2
Source File: JmsSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Test
public void testReceptionOfMultipleMessages() {
    WeldContainer container = prepare();

    RawMessageConsumerBean bean = container.select(RawMessageConsumerBean.class).get();
    assertThat(bean.messages()).isEmpty();

    Queue q = jms.createQueue("queue-one");
    JMSProducer producer = jms.createProducer();

    new Thread(() -> {
        for (int i = 0; i < 50; i++) {
            TextMessage message = jms.createTextMessage(Integer.toString(i));
            producer.send(q, message);
        }
    }).start();

    await().until(() -> bean.messages().size() == 50);
}
 
Example #3
Source File: NoKafkaTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Test
public void testIncomingWithoutKafkaCluster() throws IOException, InterruptedException {
    KafkaUsage usage = new KafkaUsage();
    container = KafkaTestBase.baseWeld();
    KafkaTestBase.addConfig(myKafkaSourceConfig());
    container.addBeanClasses(MyIncomingBean.class);
    WeldContainer weld = container.initialize();

    nap();

    MyIncomingBean bean = weld.select(MyIncomingBean.class).get();
    assertThat(bean.received()).hasSize(0);

    KafkaTestBase.startKafkaBroker();

    nap();

    AtomicInteger counter = new AtomicInteger();
    usage.produceIntegers(5, null, () -> new ProducerRecord<>("output", "1", counter.getAndIncrement()));

    await().until(() -> bean.received().size() == 5);

}
 
Example #4
Source File: AbstractWeldInitiator.java    From weld-junit with Apache License 2.0 6 votes vote down vote up
protected WeldContainer initWeldContainer(Weld weld) {
    // Register mock injection services if needed
    if (!resources.isEmpty()) {
        weld.addServices(new MockResourceInjectionServices(resources));
    }
    if (ejbFactory != null) {
        weld.addServices(new MockEjbInjectionServices(ejbFactory));
    }
    if (persistenceContextFactory != null || persistenceUnitFactory != null) {
        weld.addServices(new MockJpaInjectionServices(persistenceUnitFactory, persistenceContextFactory));
    }
    // Init the container
    container = weld.initialize();
    if (extension != null) {
        extension.activateContexts();
    }
    injectInstances();
    return container;
}
 
Example #5
Source File: JmsConnectorTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithStringAndSessionModel() {
    Map<String, Object> map = new HashMap<>();
    map.put("mp.messaging.outgoing.queue-one.connector", JmsConnector.CONNECTOR_NAME);
    map.put("mp.messaging.incoming.jms.connector", JmsConnector.CONNECTOR_NAME);
    map.put("mp.messaging.incoming.jms.destination", "queue-one");
    map.put("mp.messaging.incoming.jms.session-mode", "DUPS_OK_ACKNOWLEDGE");
    MapBasedConfig config = new MapBasedConfig(map);
    addConfig(config);
    WeldContainer container = deploy(PayloadConsumerBean.class, ProducerBean.class);

    PayloadConsumerBean bean = container.select(PayloadConsumerBean.class).get();
    await().until(() -> bean.list().size() > 3);
    assertThat(bean.list()).hasSizeGreaterThan(3);
}
 
Example #6
Source File: ImageProcessorUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@BeforeClass
public static void setImageProcessorInstance() {
    Weld weld = new Weld();
    WeldContainer container = weld.initialize();
    imageFileProcessor = container.select(ImageFileProcessor.class)
        .get();
    container.shutdown();
}
 
Example #7
Source File: FileApplication.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    Weld weld = new Weld();
    WeldContainer container = weld.initialize();
    ImageFileProcessor imageFileProcessor = container.select(ImageFileProcessor.class).get();
    System.out.println(imageFileProcessor.openFile("file1.png"));
    System.out.println(imageFileProcessor.writeFile("file1.png"));
    System.out.println(imageFileProcessor.saveFile("file1.png"));
    container.shutdown();
}
 
Example #8
Source File: Installer.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Sets up the {@link InitialContext} for a given configuration.
 * <p>
 * Also adds the database {@link DataSource} to the initial context.
 *
 * @param configurations the configuration used to set the initial context.
 * @throws NamingException when setting the initial context fails.
 */
private static void setupInitialContext(Properties configurations) throws NamingException {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");

    InitialContext ic = new InitialContext();

    ic.createSubcontext("java:");
    ic.createSubcontext("java:comp");
    ic.createSubcontext("java:comp/env");
    ic.createSubcontext("java:comp/env/codedefenders");

    // Alessio: Maybe there a better way to do it...
    for (String propName : configurations.stringPropertyNames()) {
        logger.info("Setting java:comp/env/codedefenders/" + propName + " = " + configurations.get(propName));
        ic.bind("java:comp/env/codedefenders/" + propName, configurations.get(propName));
    }

    ic.createSubcontext("java:comp/env/jdbc");

    MysqlDataSource dataSource = new MysqlDataSource();
    dataSource.setURL(configurations.getProperty("db.url"));
    dataSource.setUser(configurations.getProperty("db.username"));
    dataSource.setPassword(configurations.getProperty("db.password"));

    ic.bind("java:comp/env/jdbc/codedefenders", dataSource);

    // Maybe there's a way to provide the beans definition directly here...
    Weld weld = new Weld();
    WeldContainer container = weld.initialize();
    // Manually load the dependencies and set the backend in the context, this is only because I cannot inject BeanManager
    BackendExecutorService backend = container.instance().select(BackendExecutorService.class).get();
    ic.bind("java:comp/env/codedefenders/backend", backend);
    // Weld will be automatically closed at system.exit
}
 
Example #9
Source File: App.java    From drools-workshop with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    //Boostrap the CDI container, in this case WELD
    Weld w = new Weld();

    WeldContainer wc = w.initialize();
    App app = wc.instance().select(App.class).get();
    app.bootstrapDrools();

    w.shutdown();
}
 
Example #10
Source File: App.java    From drools-workshop with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    //Boostrap the CDI container, in this case WELD
    Weld w = new Weld();

    WeldContainer wc = w.initialize();
    App app = wc.instance().select(App.class).get();
    app.bootstrapDrools();

    w.shutdown();
}
 
Example #11
Source File: RegisterConsumersAfterBootstrapTest.java    From weld-vertx with Apache License 2.0 5 votes vote down vote up
@Test
public void testConsumers() throws InterruptedException {
    try (WeldContainer weld = new Weld().disableDiscovery().addExtension(new VertxExtension()).addPackage(false, RegisterConsumersAfterBootstrapTest.class)
            .initialize()) {
        Vertx vertx = Vertx.vertx();
        try {
            weld.select(VertxExtension.class).get().registerConsumers(vertx, weld.event());
            vertx.eventBus().send(HelloObserver.HELLO_ADDRESS, "hello");
            assertEquals("hello", SYNCHRONIZER.poll(Timeouts.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS));
        } finally {
            vertx.close();
        }
    }
}
 
Example #12
Source File: WeldShutdownImpl.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
public void shutdown() throws Exception {
    WeldContainer internalContainer = WeldContainer.instance(ServerBootstrap.WELD_INSTANCE_ID);
    if (internalContainer != null) {
        internalContainer.shutdown();
    }
}
 
Example #13
Source File: GreeterTest.java    From ee8-sandbox with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnsatisfiedResolutionException.class)
public void bootWeldSeContainer() {
    Extension testExtension = ContainerLifecycleObserver.extensionBuilder()
        .add(afterBeanDiscovery((e) -> System.out.println("Bean discovery completed!")))
        .add(processAnnotatedType().notify((e) -> {
            if (e.getAnnotatedType().getJavaClass().getName().startsWith("com.hantsylab")) {
                e.veto();
            }
        })).build();
    try (WeldContainer container = new Weld().addExtension(testExtension).initialize()) {
        Greeter greeter = container.select(Greeter.class).get();
        //assertTrue(greeter == null);
    }

}
 
Example #14
Source File: GreeterTest.java    From ee8-sandbox with Apache License 2.0 5 votes vote down vote up
@Test
public void bootstrapWeldContainer() {
    Weld weld = new Weld();

    try (WeldContainer container = weld.initialize()) {
        Greeter greeter = container.select(Greeter.class).get();
        assertTrue(greeter != null);
    }
}
 
Example #15
Source File: Main.java    From hacep with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Weld weld = new Weld();
    WeldContainer container = weld.initialize();

    TextUI textUI = container.instance().select(TextUI.class).get();
    printBanner();
    textUI.start();
}
 
Example #16
Source File: PerClassLifecycleTest.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
@Test
public void second() {
    if (containerId == null) {
        containerId = WeldContainer.current().getId();
    } else {
        Assertions.assertEquals(containerId, WeldContainer.current().getId());
    }
}
 
Example #17
Source File: JmsConnectorTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithString() {
    Map<String, Object> map = new HashMap<>();
    map.put("mp.messaging.outgoing.queue-one.connector", JmsConnector.CONNECTOR_NAME);
    map.put("mp.messaging.incoming.jms.connector", JmsConnector.CONNECTOR_NAME);
    map.put("mp.messaging.incoming.jms.destination", "queue-one");
    MapBasedConfig config = new MapBasedConfig(map);
    addConfig(config);
    WeldContainer container = deploy(PayloadConsumerBean.class, ProducerBean.class);

    PayloadConsumerBean bean = container.select(PayloadConsumerBean.class).get();
    await().until(() -> bean.list().size() > 3);
    assertThat(bean.list()).hasSizeGreaterThan(3);
}
 
Example #18
Source File: JmsConnectorTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithPerson() {
    Map<String, Object> map = new HashMap<>();
    map.put("mp.messaging.outgoing.queue-one.connector", JmsConnector.CONNECTOR_NAME);
    map.put("mp.messaging.incoming.jms.connector", JmsConnector.CONNECTOR_NAME);
    map.put("mp.messaging.incoming.jms.destination", "queue-one");
    MapBasedConfig config = new MapBasedConfig(map);
    addConfig(config);
    WeldContainer container = deploy(PersonConsumerBean.class, PersonProducerBean.class);

    PersonConsumerBean bean = container.select(PersonConsumerBean.class).get();
    await().until(() -> bean.list().size() > 1);
    assertThat(bean.list()).isNotEmpty();
}
 
Example #19
Source File: WeldInitiator.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
WeldContainer initWeld(Object testInstance) {
    Weld weld = WeldInitiator.this.weld;
    if (weld == null) {
        weld = createWeld().addPackage(false, testInstance.getClass());
    }

    return initWeldContainer(weld);
}
 
Example #20
Source File: NamedFactoryTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
public void testNamedConnectionFactory() {
    initWithoutConnectionFactory().addBeanClasses(BarConnectionFactoryBean.class, FooConnectionFactoryBean.class);
    Map<String, Object> map = new HashMap<>();
    map.put("mp.messaging.connector." + JmsConnector.CONNECTOR_NAME + ".connection-factory-name", "foo");
    map.put("mp.messaging.outgoing.queue-one.connector", JmsConnector.CONNECTOR_NAME);
    map.put("mp.messaging.incoming.jms.connector", JmsConnector.CONNECTOR_NAME);
    map.put("mp.messaging.incoming.jms.destination", "queue-one");
    MapBasedConfig config = new MapBasedConfig(map);
    addConfig(config);
    WeldContainer container = deploy(PayloadConsumerBean.class, ProducerBean.class);

    PayloadConsumerBean bean = container.select(PayloadConsumerBean.class).get();
    await().until(() -> bean.list().size() > 3);
}
 
Example #21
Source File: NoKafkaTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
public void testOutgoingWithoutKafkaClusterWithoutBackPressure() throws InterruptedException {
    container = KafkaTestBase.baseWeld();
    KafkaTestBase.addConfig(myKafkaSinkConfig());
    container.addBeanClasses(MyOutgoingBeanWithoutBackPressure.class);
    WeldContainer weld = this.container.initialize();

    nap();

    MyOutgoingBeanWithoutBackPressure bean = weld
            .select(MyOutgoingBeanWithoutBackPressure.class).get();
    Throwable throwable = bean.error();
    assertThat(throwable).isNotNull();
    assertThat(throwable).isInstanceOf(MissingBackpressureException.class);
}
 
Example #22
Source File: JmsSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
private WeldContainer prepare() {
    Map<String, Object> map = new HashMap<>();
    map.put("mp.messaging.incoming.jms.connector", JmsConnector.CONNECTOR_NAME);
    map.put("mp.messaging.incoming.jms.destination", "queue-one");
    MapBasedConfig config = new MapBasedConfig(map);
    addConfig(config);
    return deploy(RawMessageConsumerBean.class);
}
 
Example #23
Source File: PerClassLifecycleTest.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
@Test
public void first() {
    if (containerId == null) {
        containerId = WeldContainer.current().getId();
    } else {
        Assertions.assertEquals(containerId, WeldContainer.current().getId());
    }
}
 
Example #24
Source File: JmsSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithString() throws JMSException {
    WeldContainer container = prepare();

    RawMessageConsumerBean bean = container.select(RawMessageConsumerBean.class).get();
    assertThat(bean.messages()).isEmpty();

    Queue q = jms.createQueue("queue-one");
    JMSProducer producer = jms.createProducer();
    TextMessage message = jms.createTextMessage("hello");
    message.setStringProperty("string", "value");
    message.setBooleanProperty("bool", true);
    message.setLongProperty("long", 100L);
    message.setByteProperty("byte", (byte) 5);
    message.setFloatProperty("float", 5.5f);
    message.setDoubleProperty("double", 10.3);
    message.setIntProperty("int", 23);
    message.setObjectProperty("object", "yop");
    message.setShortProperty("short", (short) 3);
    producer.send(q, message);

    await().until(() -> bean.messages().size() == 1);
    IncomingJmsMessage<?> incomingJmsMessage = bean.messages().get(0);
    IncomingJmsMessageMetadata metadata = incomingJmsMessage.getMetadata(IncomingJmsMessageMetadata.class)
            .orElseThrow(() -> new AssertionError("Metadata expected"));
    assertThat(incomingJmsMessage.getPayload()).isEqualTo("hello");
    assertThat(metadata.getBody(String.class)).isEqualTo("hello");
    assertThat(metadata.propertyExists("string")).isTrue();
    assertThat(metadata.propertyExists("missing")).isFalse();
    assertThat(metadata.getStringProperty("string")).isEqualTo("value");
    assertThat(metadata.getBooleanProperty("bool")).isTrue();
    assertThat(metadata.getLongProperty("long")).isEqualTo(100L);
    assertThat(metadata.getByteProperty("byte")).isEqualTo((byte) 5);
    assertThat(metadata.getFloatProperty("float")).isEqualTo(5.5f);
    assertThat(metadata.getDoubleProperty("double")).isEqualTo(10.3);
    assertThat(metadata.getIntProperty("int")).isEqualTo(23);
    assertThat(metadata.getObjectProperty("object")).isInstanceOf(String.class);
    assertThat(((String) message.getObjectProperty("object"))).isEqualTo("yop");
    assertThat(message.getShortProperty("short")).isEqualTo((short) 3);
}
 
Example #25
Source File: JmsSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithLong() {
    WeldContainer container = prepare();

    RawMessageConsumerBean bean = container.select(RawMessageConsumerBean.class).get();
    assertThat(bean.messages()).isEmpty();

    Queue q = jms.createQueue("queue-one");
    JMSProducer producer = jms.createProducer();
    producer.send(q, 10000L);

    await().until(() -> bean.messages().size() == 1);
    IncomingJmsMessage<?> incomingJmsMessage = bean.messages().get(0);
    assertThat(incomingJmsMessage.getPayload()).isEqualTo(10000L);
}
 
Example #26
Source File: ServerBootstrapImpl.java    From thorntail with Apache License 2.0 4 votes vote down vote up
@Override
public Server bootstrap() throws Exception {
    try (AutoCloseable bootstrap = Performance.time("Bootstrap")) {
        Module module = Module.getBootModuleLoader().loadModule("swarm.container");
        return ClassLoading.withTCCL(new ExtensionPreventionClassLoaderWrapper(module.getClassLoader()), () -> {
            //Thread.currentThread().setContextClassLoader(new ExtensionPreventionClassLoaderWrapper(module.getClassLoader()));

            try (AutoCloseable logFractionHandle = Performance.time("Log fractions")) {
                logFractions();
            }

            RuntimeServer outerServer = LogSilencer.silently("org.jboss.weld", "ServiceLoader").execute(() -> {
                Weld weld = new Weld(WELD_INSTANCE_ID);
                weld.setClassLoader(module.getClassLoader());

                ConfigViewProducingExtension configViewProducingExtension = new ConfigViewProducingExtension(this.configView);
                DeploymentContext deploymentContext = new DeploymentContextImpl();
                ConfigurableManager configurableManager = new ConfigurableManager(this.configView, deploymentContext);

                // Add Extension that adds User custom bits into configurator
                weld.addExtension(new FractionProducingExtension(explicitlyInstalledFractions, configurableManager));
                weld.addExtension(new ConfigurableExtension(configurableManager));
                weld.addExtension(new CommandLineArgsExtension(args));
                weld.addExtension(configViewProducingExtension);
                weld.addExtension(new XMLConfigProducingExtension(this.xmlConfigURL));
                weld.addExtension(new InterfaceExtension(this.configView));
                weld.addExtension(new OutboundSocketBindingExtension(this.outboundSocketBindings));
                weld.addExtension(new SocketBindingExtension(this.socketBindings));
                weld.addExtension(new DeploymentScopedExtension(deploymentContext));
                weld.addExtension(new ImplicitArchiveExtension());

                for (Class<?> each : this.userComponents) {
                    weld.addBeanClass(each);
                }

                weld.property("org.jboss.weld.se.shutdownHook", false);
                WeldContainer weldContainer = null;
                RuntimeServer server = null;
                try (AutoCloseable weldRelated = Performance.time("Weld-related")) {
                    try (AutoCloseable weldInitHandle = Performance.time("Weld initialize")) {
                        weldContainer = weld.initialize();
                    }
                    try (AutoCloseable serverSelectHandle = Performance.time("Server construction")) {
                        server = weldContainer.select(RuntimeServer.class).get();
                    }
                }
                return server;
            });

            try (AutoCloseable weldInitHandle = Performance.time("Server start")) {
                outerServer.start(true);
            }
            return outerServer;
        });
    } finally {
        SwarmMetricsMessages.MESSAGES.bootPerformance(Performance.dump());
    }
}
 
Example #27
Source File: WeldControllerFactory.java    From pippo with Apache License 2.0 4 votes vote down vote up
public WeldControllerFactory(WeldContainer weldContainer){
    this.weldContainer = weldContainer;
}
 
Example #28
Source File: JmsTestBase.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
protected WeldContainer deploy(Class<?>... beanClass) {
    weld.addBeanClasses(beanClass);
    return weld.initialize();
}
 
Example #29
Source File: ExtensionContextUtils.java    From weld-junit with Apache License 2.0 4 votes vote down vote up
/**
 * Store {@link WeldContainer} to {@link ExtensionContext.Store}
 */
public static void setContainerToStore(ExtensionContext context, WeldContainer container) {
    getTestStore(context).put(CONTAINER, container);
}
 
Example #30
Source File: DisabledMethodsTest.java    From weld-junit with Apache License 2.0 4 votes vote down vote up
@Test
public void testRunningContainers() {
    // we assert that there is only one container running at this point
    assertEquals(1, WeldContainer.getRunningContainerIds().size());
}