下面列出了io.reactivex.exceptions.MissingBackpressureException#org.jboss.weld.environment.se.WeldContainer 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
@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);
}
@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);
}
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;
}
@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);
}
@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);
}
@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();
}
@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);
}
@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);
}
@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);
}
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);
}
@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);
}
WeldContainer initWeld(Object testInstance) {
Weld weld = WeldInitiator.this.weld;
if (weld == null) {
weld = createWeld().addPackage(false, testInstance.getClass());
}
return initWeldContainer(weld);
}
@Test
public void first() {
if (containerId == null) {
containerId = WeldContainer.current().getId();
} else {
Assertions.assertEquals(containerId, WeldContainer.current().getId());
}
}
@Test
public void second() {
if (containerId == null) {
containerId = WeldContainer.current().getId();
} else {
Assertions.assertEquals(containerId, WeldContainer.current().getId());
}
}
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();
}
@Test
public void bootstrapWeldContainer() {
Weld weld = new Weld();
try (WeldContainer container = weld.initialize()) {
Greeter greeter = container.select(Greeter.class).get();
assertTrue(greeter != null);
}
}
@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);
}
}
@Override
public void shutdown() throws Exception {
WeldContainer internalContainer = WeldContainer.instance(ServerBootstrap.WELD_INSTANCE_ID);
if (internalContainer != null) {
internalContainer.shutdown();
}
}
@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();
}
}
}
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();
}
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();
}
/**
* 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
}
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();
}
@BeforeClass
public static void setImageProcessorInstance() {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
imageFileProcessor = container.select(ImageFileProcessor.class)
.get();
container.shutdown();
}
protected WeldContainer deploy(Class<?>... beanClass) {
weld.addBeanClasses(beanClass);
return weld.initialize();
}
/**
* Store {@link WeldContainer} to {@link ExtensionContext.Store}
*/
public static void setContainerToStore(ExtensionContext context, WeldContainer container) {
getTestStore(context).put(CONTAINER, container);
}
@Test
public void testSuperclassPrivateWeldInit() {
final Foo foo = WeldContainer.current().select(Foo.class).get();
assertNotNull(foo);
}
@Test
public void testRunningContainers() {
// we assert that there is only one container running at this point
assertEquals(1, WeldContainer.getRunningContainerIds().size());
}
@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());
}
}