repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/observability/micrometer/MicrometerSetupTask.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.observability.micrometer; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STATISTICS_ENABLED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.jboss.dmr.ModelNode; import org.testcontainers.utility.MountableFile; import java.io.File; import java.io.IOException; public class MicrometerSetupTask implements ServerSetupTask { static OpenTelemetryCollectorContainer otelCollector; private final ModelNode micrometerExtension = Operations.createAddress("extension", "org.wildfly.extension.micrometer"); private final ModelNode micrometerSubsystem = Operations.createAddress("subsystem", "micrometer"); private boolean extensionAdded = false; private boolean subsystemAdded = false; private boolean containerStarted = false; @Override public void setup(final ManagementClient managementClient, String containerId) throws Exception { try { startOpenTelemetryCollector(); } catch (Exception e) { System.err.println("OpenTelemetry Container failed to start."); } executeOp(managementClient, enableStatistics(true)); ModelNode outcome = executeRead(managementClient, micrometerExtension); if (!Operations.isSuccessfulOutcome(outcome)) { executeOp(managementClient, Operations.createAddOperation(micrometerExtension)); extensionAdded = true; } outcome = executeRead(managementClient, micrometerSubsystem); if (!Operations.isSuccessfulOutcome(outcome)) { ModelNode addOp = Operations.createAddOperation(micrometerSubsystem); addOp.get("endpoint").set("http://localhost:4318/v1/metrics"); // Default endpoint executeOp(managementClient, addOp); subsystemAdded = true; } if (containerStarted) { executeOp(managementClient, writeAttribute("micrometer", "endpoint", otelCollector.getOtlpEndpoint())); } executeOp(managementClient, writeAttribute("micrometer", "step", "1")); ServerReload.executeReloadAndWaitForCompletion(managementClient); } @Override public void tearDown(final ManagementClient managementClient, String containerId) throws Exception { if (containerStarted) { otelCollector.stop(); otelCollector = null; containerStarted = false; } executeOp(managementClient, enableStatistics(false)); if (subsystemAdded) { executeOp(managementClient, Operations.createRemoveOperation(micrometerSubsystem)); } if (extensionAdded) { executeOp(managementClient, Operations.createRemoveOperation(micrometerExtension)); } ServerReload.reloadIfRequired(managementClient); } private void startOpenTelemetryCollector() { if ( AssumeTestGroupUtil.isDockerAvailable()) { String otelCollectorConfigFile = getClass().getPackage().getName().replaceAll("\\.", File.separator) + File.separator + "otel-collector-config.yaml"; otelCollector = new OpenTelemetryCollectorContainer() .withCopyFileToContainer(MountableFile.forClasspathResource(otelCollectorConfigFile), OpenTelemetryCollectorContainer.OTEL_COLLECTOR_CONFIG_YAML) .withCommand("--config " + OpenTelemetryCollectorContainer.OTEL_COLLECTOR_CONFIG_YAML) ; otelCollector.start(); containerStarted = true; } } private ModelNode enableStatistics(boolean enabled) { return writeAttribute("undertow", STATISTICS_ENABLED, String.valueOf(enabled)); } private ModelNode writeAttribute(String subsystem, String name, String value) { return Operations.createWriteAttributeOperation(Operations.createAddress(SUBSYSTEM, subsystem), name, value); } private void executeOp(final ManagementClient client, final ModelNode op) throws IOException { executeOp(client.getControllerClient(), Operation.Factory.create(op)); } private void executeOp(final ModelControllerClient client, final Operation op) throws IOException { final ModelNode result = client.execute(op); if (!Operations.isSuccessfulOutcome(result)) { throw new RuntimeException("Failed to execute operation: " + Operations.getFailureDescription(result) .asString()); } } private ModelNode executeRead(final ManagementClient managementClient, ModelNode address) throws IOException { return managementClient.getControllerClient().execute(Operations.createReadResourceOperation(address)); } }
5,774
42.421053
124
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/observability/micrometer/MetricResource.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.observability.micrometer; import io.micrometer.core.instrument.Tags; import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.RequestScoped; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Timer; /** * @author <a href="mailto:[email protected]">Jason Lee</a> */ @RequestScoped @Path("/") public class MetricResource { @Inject private MeterRegistry meterRegistry; private Counter counter; @PostConstruct public void setupMeters() { counter = meterRegistry.counter("demo_counter"); } @GET @Path("/") public double getCount() { Timer timer = meterRegistry.timer("demo_timer", Tags.of("ts", "" + System.currentTimeMillis())); timer.record(() -> { try { Thread.sleep((long) (Math.random() * 1000L)); } catch (InterruptedException e) { throw new RuntimeException(e); } counter.increment(); }); return counter.count(); } }
1,809
28.193548
104
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/observability/micrometer/MicrometerOtelIntegrationTestCase.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.observability.micrometer; import jakarta.inject.Inject; import jakarta.ws.rs.client.Client; import jakarta.ws.rs.client.ClientBuilder; import jakarta.ws.rs.client.WebTarget; import com.fasterxml.jackson.core.util.JacksonFeature; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.test.shared.CdiUtils; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import java.net.URISyntaxException; import java.net.URL; import java.util.Arrays; @RunWith(Arquillian.class) @ServerSetup(MicrometerSetupTask.class) public class MicrometerOtelIntegrationTestCase { public static final int REQUEST_COUNT = 5; @ArquillianResource private URL url; @Inject private MeterRegistry meterRegistry; private final Client client = ClientBuilder.newClient().register(JacksonFeature.class); static final String WEB_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" + " xmlns=\"http://xmlns.jcp.org/xml/ns/javaee\"\n" + " xsi:schemaLocation=\"http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd\" \n" + " version=\"4.0\">\n" + " <servlet-mapping>\n" + " <servlet-name>jakarta.ws.rs.core.Application</servlet-name>\n" + " <url-pattern>/*</url-pattern>\n" + " </servlet-mapping>" + "</web-app>\n"; @Deployment public static Archive<?> deploy() { return ShrinkWrap.create(WebArchive.class, "micrometer-test.war") .addClasses(ServerSetupTask.class, MetricResource.class) .addAsWebInfResource(new StringAsset(WEB_XML), "web.xml") .addAsWebInfResource(CdiUtils.createBeansXml(), "beans.xml"); } @BeforeClass public static void checkForDocker() { AssumeTestGroupUtil.assumeDockerAvailable(); } @Test @InSequence(1) public void testInjection() { Assert.assertNotNull(meterRegistry); } @Test @RunAsClient @InSequence(2) public void makeRequests() throws URISyntaxException { WebTarget target = client.target(url.toURI()); for (int i = 0; i < REQUEST_COUNT; i++) { target.request().get(); } } @Test @InSequence(3) public void checkCounter() { Counter counter = meterRegistry.get("demo_counter").counter(); Assert.assertEquals(counter.count(), REQUEST_COUNT, 0.0); } // Request the published metrics from the OpenTelemetry Collector via the configured Prometheus exporter and check // a few metrics to verify there existence @Test @RunAsClient @InSequence(Integer.MAX_VALUE) public void getMetrics() throws InterruptedException { WebTarget target = client.target(MicrometerSetupTask.otelCollector.getPrometheusUrl()); int attemptCount = 0; boolean found = false; String body = ""; // Request counts can vary. Setting high to help ensure test stability while (!found && attemptCount < 30) { // Wait to give Micrometer time to export Thread.sleep(1000); body = target.request().get().readEntity(String.class); found = body.contains("demo_counter"); attemptCount++; } final String finalBody = body; Arrays.asList( "demo_counter", "memory_used_heap", "cpu_available_processors", "classloader_loaded_classes_count", "cpu_system_load_average", "gc_time", "thread_count", "undertow_bytes_received" ).forEach(n -> Assert.assertTrue("Missing metric: " + n, finalBody.contains(n))); } }
5,301
36.076923
144
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/observability/opentelemetry/OpenTelemetryIntegrationTestCase.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.observability.opentelemetry; import java.net.URISyntaxException; import io.opentelemetry.api.common.AttributeKey; import jakarta.ws.rs.client.Client; import jakarta.ws.rs.client.ClientBuilder; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.shrinkwrap.api.Archive; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @ServerSetup(OpenTelemetrySetupTask.class) @Ignore public class OpenTelemetryIntegrationTestCase extends BaseOpenTelemetryTest { @Deployment public static Archive getDeployment() { return buildBaseArchive(OpenTelemetryIntegrationTestCase.class.getSimpleName()); } @Test public void testServiceNameOverride() throws URISyntaxException { try (Client client = ClientBuilder.newClient()) { client.target(url.toURI()) .request().get(); } AttributeKey<String> key = AttributeKey.stringKey("service.name"); spanExporter.getFinishedSpanItems(3).forEach(spanData -> { Assert.assertEquals(SERVICE_NAME, spanData.getResource().getAttribute(key)); }); } }
2,033
34.068966
88
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/observability/opentelemetry/ContextPropagationTestCase.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.observability.opentelemetry; import io.opentelemetry.sdk.trace.data.SpanData; import jakarta.ws.rs.client.Client; import jakarta.ws.rs.client.ClientBuilder; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.shrinkwrap.api.Archive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import java.net.URI; import java.util.List; /** * This test exercises the context propagation functionality. Two services are deployed, with the first calling the * second. The second service attempts to retrieve the trace propagation header and return it. The first returns a JSON * object containing the traceparent header value and the traceId. We then query the Jaeger collector, started using the * ClassRule, to verify that the trace was successfully exported. */ @RunWith(Arquillian.class) @ServerSetup(OpenTelemetrySetupTask.class) public class ContextPropagationTestCase extends BaseOpenTelemetryTest { @Deployment public static Archive getDeployment() { return buildBaseArchive(ContextPropagationTestCase.class.getSimpleName()); } @Test public void testContextPropagation() throws Exception { String contextPropUrl = url.toString() + "/contextProp1"; try (Client client = ClientBuilder.newClient()) { client .target(URI.create(contextPropUrl)) .request() .get(); } // 6 Expected spans named: // Recording traceparent // /ContextPropagationTestCase/contextProp2 // HTTP GET // Making second request // /ContextPropagationTestCase/contextProp1 // HTTP GET List<SpanData> finishedSpans = spanExporter.getFinishedSpanItems(6); SpanData lastSpan = finishedSpans.get(finishedSpans.size()-1); String traceId = lastSpan.getSpanContext().getTraceId(); finishedSpans.forEach(s -> { Assert.assertEquals("The traceId of the span did not match the first span's. Context propagation failed.", traceId, s.getSpanContext().getTraceId()); }); } }
2,990
36.3875
120
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/observability/opentelemetry/OpenTelemetrySetupTask.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.observability.opentelemetry; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; public class OpenTelemetrySetupTask implements ServerSetupTask { private final ModelNode subsystemAddress = Operations.createAddress("subsystem", "opentelemetry"); @Override public void setup(final ManagementClient managementClient, final String containerId) throws Exception { execute(managementClient, Operations.createWriteAttributeOperation(subsystemAddress, "batch-delay", "1")); ServerReload.reloadIfRequired(managementClient); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { execute(managementClient, Operations.createWriteAttributeOperation(subsystemAddress, "batch-delay", new ModelNode())); ServerReload.reloadIfRequired(managementClient); } private void execute(final ManagementClient managementClient, final ModelNode op) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); assertEquals(response.toString(), "success", outcome); } }
2,214
40.018519
126
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/observability/opentelemetry/BaseOpenTelemetryTest.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.observability.opentelemetry; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import jakarta.inject.Inject; import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider; import io.smallrye.opentelemetry.api.OpenTelemetryConfig; import org.apache.commons.lang3.RandomStringUtils; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.wildfly.test.integration.observability.opentelemetry.application.OtelApplication; import org.wildfly.test.integration.observability.opentelemetry.application.OtelService; import org.wildfly.test.integration.observability.opentelemetry.application.TestOpenTelemetryConfig; import org.wildfly.test.integration.observability.opentelemetry.exporter.InMemorySpanExporter; import org.wildfly.test.integration.observability.opentelemetry.exporter.InMemorySpanExporterProvider; import java.lang.reflect.ReflectPermission; import java.net.NetPermission; import java.net.URL; import java.util.PropertyPermission; public abstract class BaseOpenTelemetryTest { public static final String SERVICE_NAME = RandomStringUtils.random(15); private static final String WEB_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://java.sun.com/xml/ns/javaee\"\n" + " xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n" + " metadata-complete=\"false\" version=\"3.0\">\n" + " <servlet-mapping>\n" + " <servlet-name>jakarta.ws.rs.core.Application</servlet-name>\n" + " <url-pattern>/*</url-pattern>\n" + " </servlet-mapping>" + "</web-app>"; @ArquillianResource URL url; @Inject InMemorySpanExporter spanExporter; static WebArchive buildBaseArchive(String name) { String beansXml = "<beans bean-discovery-mode=\"all\">" + " <alternatives>\n" + " <class>" + TestOpenTelemetryConfig.class.getCanonicalName() + "</class>\n" + " </alternatives>" + "</beans>"; return ShrinkWrap .create(WebArchive.class, name + ".war") .addClasses(BaseOpenTelemetryTest.class, OtelApplication.class, OtelService.class, OpenTelemetryConfig.class, TestOpenTelemetryConfig.class, InMemorySpanExporter.class, RandomStringUtils.class, InMemorySpanExporterProvider.class) .addAsServiceProvider(ConfigurableSpanExporterProvider.class, InMemorySpanExporterProvider.class) .addAsLibrary(ShrinkWrap.create(JavaArchive.class, "awaitility.jar") .addPackages(true, "org.awaitility", "org.hamcrest") ) .addAsWebInfResource(new StringAsset(WEB_XML), "web.xml") .addAsWebInfResource(new StringAsset(beansXml), "beans.xml") // Some of the classes used in testing do things that break when the Security Manager is installed .addAsManifestResource(createPermissionsXmlAsset( new RuntimePermission("getClassLoader"), new RuntimePermission("getProtectionDomain"), new RuntimePermission("getenv.*"), new RuntimePermission("setDefaultUncaughtExceptionHandler"), new RuntimePermission("modifyThread"), new ReflectPermission("suppressAccessChecks"), new NetPermission("getProxySelector"), new PropertyPermission("*", "read, write")), "permissions.xml"); } }
5,036
50.927835
133
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/observability/opentelemetry/BasicOpenTelemetryTestCase.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.observability.opentelemetry; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.baggage.Baggage; import io.opentelemetry.api.trace.Tracer; import jakarta.inject.Inject; import jakarta.ws.rs.client.Client; import jakarta.ws.rs.client.ClientBuilder; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.shrinkwrap.api.Archive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @ServerSetup(OpenTelemetrySetupTask.class) public class BasicOpenTelemetryTestCase extends BaseOpenTelemetryTest { @Inject private Tracer tracer; @Inject private OpenTelemetry openTelemetry; @Inject private Baggage baggage; @Deployment public static Archive getDeployment() { return buildBaseArchive(BasicOpenTelemetryTestCase.class.getSimpleName()); } @Test public void openTelemetryInjection() { Assert.assertNotNull(openTelemetry); } @Test public void traceInjection() { Assert.assertNotNull(tracer); } @Test public void baggageInjection() { Assert.assertNotNull(baggage); } @Test public void restClientHasFilterAdded() throws ClassNotFoundException { try (Client client = ClientBuilder.newClient()) { Assert.assertTrue( client.getConfiguration().isRegistered( Class.forName("io.smallrye.opentelemetry.implementation.rest.OpenTelemetryClientFilter")) ); } } }
2,394
29.705128
117
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/observability/opentelemetry/application/OtelService.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.observability.opentelemetry.application; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.client.Client; import jakarta.ws.rs.client.ClientBuilder; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriInfo; @Path("/") @Produces(MediaType.APPLICATION_JSON) public class OtelService { @Inject private Tracer tracer; @Context UriInfo uriInfo; @GET public Response endpoint() { final Span span = tracer.spanBuilder("Custom span").startSpan(); span.makeCurrent(); span.addEvent("Custom event"); span.end(); return Response.noContent().build(); } @Context private HttpHeaders headers; @GET @Path("contextProp1") public Response contextProp1() { final Span span = tracer.spanBuilder("Making second request").startSpan(); span.makeCurrent(); try (Client client = ClientBuilder.newClient()) { client.target(uriInfo.getBaseUriBuilder().path("contextProp2")) .request() .get(); } span.end(); return Response.noContent().build(); } @GET @Path("contextProp2") public Response contextProp2() { final Span span = tracer.spanBuilder("Recording traceparent").startSpan(); span.makeCurrent(); String traceParent = headers.getHeaderString("traceparent"); if (traceParent == null || traceParent.isEmpty()) { throw new WebApplicationException("Missing traceparent header"); } span.addEvent("Test event", Attributes.builder() .put("traceparent", traceParent) .build()); span.end(); return Response.noContent().build(); } }
2,893
29.463158
82
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/observability/opentelemetry/application/TestOpenTelemetryConfig.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.observability.opentelemetry.application; import java.util.HashMap; import java.util.Map; import io.smallrye.opentelemetry.api.OpenTelemetryConfig; import jakarta.annotation.Priority; import jakarta.enterprise.inject.Alternative; import jakarta.inject.Singleton; @Alternative @Singleton @Priority(Integer.MAX_VALUE) public class TestOpenTelemetryConfig implements OpenTelemetryConfig { private Map<String, String> properties = new HashMap<>(); @Override public Map<String, String> properties() { // properties.put("otel.service.name", BaseOpenTelemetryTest.SERVICE_NAME); properties.put("otel.traces.exporter", "in-memory"); return properties; } }
1,438
32.465116
82
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/observability/opentelemetry/application/OtelApplication.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.observability.opentelemetry.application; import jakarta.ws.rs.core.Application; public class OtelApplication extends Application { }
884
31.777778
77
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/observability/opentelemetry/exporter/InMemorySpanExporterProvider.java
/* * Copyright (c) 2016-2022 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.wildfly.test.integration.observability.opentelemetry.exporter; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider; import io.opentelemetry.sdk.trace.export.SpanExporter; import jakarta.enterprise.inject.spi.CDI; public class InMemorySpanExporterProvider implements ConfigurableSpanExporterProvider { @Override public SpanExporter createExporter(final ConfigProperties config) { return CDI.current().select(InMemorySpanExporter.class).get(); } @Override public String getName() { return "in-memory"; } }
1,413
36.210526
87
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/observability/opentelemetry/exporter/InMemorySpanExporter.java
/* * Copyright (c) 2016-2022 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.wildfly.test.integration.observability.opentelemetry.exporter; import static java.util.Comparator.comparingLong; import static java.util.concurrent.TimeUnit.SECONDS; import java.util.Collection; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.export.SpanExporter; import jakarta.enterprise.context.ApplicationScoped; import org.awaitility.Awaitility; import org.junit.Assert; @ApplicationScoped public class InMemorySpanExporter implements SpanExporter { private boolean isStopped = false; private final List<SpanData> finishedSpanItems = new CopyOnWriteArrayList<>(); /** * Careful when retrieving the list of finished spans. There is a chance when the response is already sent to the * client and the server still writing the end of the spans. This means that a response is available to assert from * the test side but not all spans may be available yet. For this reason, this method requires the number of * expected spans. */ public List<SpanData> getFinishedSpanItems(int spanCount) { assertSpanCount(spanCount); return finishedSpanItems.stream().sorted(comparingLong(SpanData::getStartEpochNanos).reversed()) .collect(Collectors.toList()); } public void assertSpanCount(int spanCount) { try { Awaitility.await().pollDelay(3, SECONDS).atMost(30, SECONDS) .untilAsserted(() -> Assert.assertEquals(spanCount, finishedSpanItems.size())); } catch (RuntimeException e) { String spanNames = finishedSpanItems.stream().map(SpanData::getName).collect(Collectors.joining("\n")); throw new AssertionError("Failed to get expected spans. Got:\n" + spanNames, e); } } public void reset() { finishedSpanItems.clear(); } @Override public CompletableResultCode export(Collection<SpanData> spans) { if (isStopped) { return CompletableResultCode.ofFailure(); } finishedSpanItems.addAll(spans); return CompletableResultCode.ofSuccess(); } @Override public CompletableResultCode flush() { return CompletableResultCode.ofSuccess(); } @Override public CompletableResultCode shutdown() { finishedSpanItems.clear(); isStopped = true; return CompletableResultCode.ofSuccess(); } }
3,335
36.066667
119
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/lra/EnableLRAExtensionsSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.lra; import org.jboss.as.test.shared.ManagementServerSetupTask; public class EnableLRAExtensionsSetupTask extends ManagementServerSetupTask { private static final String MODULE_LRA_PARTICIPANT = "org.wildfly.extension.microprofile.lra-participant"; private static final String MODULE_LRA_COORDINATOR = "org.wildfly.extension.microprofile.lra-coordinator"; private static final String SUBSYSTEM_LRA_PARTICIPANT = "microprofile-lra-participant"; private static final String SUBSYSTEM_LRA_COORDINATOR = "microprofile-lra-coordinator"; public EnableLRAExtensionsSetupTask() { super(createContainerConfigurationBuilder() .setupScript(createScriptBuilder() .startBatch() .add("/extension=" + MODULE_LRA_COORDINATOR + ":add") .add("/subsystem=" + SUBSYSTEM_LRA_COORDINATOR + ":add") .add("/extension=" + MODULE_LRA_PARTICIPANT + ":add") .add("/subsystem=" + SUBSYSTEM_LRA_PARTICIPANT + ":add") .endBatch() .build() ) .tearDownScript(createScriptBuilder() .startBatch() .add("/subsystem=" + SUBSYSTEM_LRA_PARTICIPANT + ":remove") .add("/extension=" + MODULE_LRA_PARTICIPANT + ":remove") .add("/subsystem=" + SUBSYSTEM_LRA_COORDINATOR + ":remove") .add("/extension=" + MODULE_LRA_COORDINATOR + ":remove") .endBatch() .build()) .build()); } }
2,613
47.407407
110
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/lra/participant/smoke/LRAParticipantSmokeTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.lra.participant.smoke; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.lra.EnableLRAExtensionsSetupTask; import org.wildfly.test.integration.microprofile.lra.participant.smoke.hotel.HotelParticipant; import org.wildfly.test.integration.microprofile.lra.participant.smoke.model.Booking; import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.Arrays; import java.util.regex.Pattern; @RunAsClient @RunWith(Arquillian.class) @ServerSetup(EnableLRAExtensionsSetupTask.class) public class LRAParticipantSmokeTestCase { private static final String LRA_COORDINATOR_URL_KEY = "lra.coordinator.url"; private static final String CLOSE_PATH = "/close"; private static final String CANCEL_PATH = "/cancel"; @ArquillianResource public URL baseURL; public CloseableHttpClient client; @Before public void before() { System.setProperty(LRA_COORDINATOR_URL_KEY, "http://localhost:8080/lra-coordinator/lra-coordinator"); client = HttpClientBuilder.create().build(); } @After public void after() throws IOException { try { if (client != null) { client.close(); } } finally { System.clearProperty(LRA_COORDINATOR_URL_KEY); } } @Deployment public static WebArchive getDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "lra-participant-test.war") .addPackages(true, "org.wildfly.test.integration.microprofile.lra.participant.smoke.hotel", "org.wildfly.test.integration.microprofile.lra.participant.smoke.model") .addClasses(LRAParticipantSmokeTestCase.class, EnableLRAExtensionsSetupTask.class, CLIServerSetupTask.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); return webArchive; } @Test public void hotelParticipantCompleteBookingTest() throws Exception { final URI lraId = startBooking(); String id = getLRAUid(lraId.toString()); closeLRA(id); validateBooking(true); } @Test public void hotelParticipantCompensateBookingTest() throws Exception { final URI lraId = startBooking(); String id = getLRAUid(lraId.toString()); cancelLRA(id); validateBooking(false); } private URI startBooking() throws Exception { Booking b = bookHotel("Paris-hotel"); return new URI(b.getId()); } private static final Pattern UID_REGEXP_EXTRACT_MATCHER = Pattern.compile(".*/([^/?]+).*"); public String getLRAUid(String lraId) { return lraId == null ? null : UID_REGEXP_EXTRACT_MATCHER.matcher(lraId).replaceFirst("$1"); } private void validateBooking(boolean isEntryPresent) throws Exception { try (CloseableHttpResponse response = client.execute(new HttpGet( uriFrom(baseURL.toURI(), HotelParticipant.HOTEL_PARTICIPANT_PATH)))) { String result = EntityUtils.toString(response.getEntity()); if (isEntryPresent) { Assert.assertTrue( "Booking confirmed", result.contains("CONFIRMED")); } else { Assert.assertTrue( "Booking cancelled", result.contains("CANCELLED")); } } } private Booking bookHotel(String name) throws Exception { try (CloseableHttpResponse response = client.execute(new HttpPost( new URIBuilder(uriFrom(baseURL.toURI(), HotelParticipant.HOTEL_PARTICIPANT_PATH)) .addParameter("hotelName", name) .build()))) { if (response.getStatusLine().getStatusCode() != 200) { throw new Exception("hotel booking problem; response status = " + response.getStatusLine().getStatusCode()); } else if (response.getEntity() != null) { String result = EntityUtils.toString(response.getEntity()); ObjectMapper obj = new ObjectMapper(); return obj.readValue(result, Booking.class); } else { throw new Exception("hotel booking problem; no entity"); } } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } } private void closeLRA(String lraId) throws Exception { endLRA(lraId, true); } private void cancelLRA(String lraId) throws Exception { endLRA(lraId, false); } private void endLRA(String lraId, boolean close) throws Exception { try { URI coordinatorURI = new URI(System.getProperty(LRA_COORDINATOR_URL_KEY)); HttpPut request = new HttpPut(uriFrom(coordinatorURI, close ? lraId.concat(CLOSE_PATH) : lraId.concat(CANCEL_PATH))); request.setHeader("Narayana-LRA-API-version", "1.0"); request.setEntity(new StringEntity("")); client.execute(request); } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } } private static URI uriFrom(URI baseURI, String... paths) { StringBuilder sb = new StringBuilder(baseURI.toString()); Arrays.stream(paths).forEach(s -> sb.append(s.startsWith("/") ? s : "/" + s)); return URI.create(sb.toString()); } }
7,560
37.974227
129
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/lra/participant/smoke/hotel/HotelParticipant.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.lra.participant.smoke.hotel; import com.fasterxml.jackson.core.JsonProcessingException; import jakarta.inject.Inject; import jakarta.inject.Singleton; import jakarta.ws.rs.DefaultValue; import jakarta.ws.rs.GET; import jakarta.ws.rs.HeaderParam; import jakarta.ws.rs.NotFoundException; import jakarta.ws.rs.POST; import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.lra.annotation.Compensate; import org.eclipse.microprofile.lra.annotation.Complete; import org.eclipse.microprofile.lra.annotation.ws.rs.LRA; import org.wildfly.test.integration.microprofile.lra.participant.smoke.model.Booking; import java.util.Collection; import static org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_CONTEXT_HEADER; @Singleton @Path(HotelParticipant.HOTEL_PARTICIPANT_PATH) @LRA(LRA.Type.SUPPORTS) public class HotelParticipant { public static final String HOTEL_PARTICIPANT_PATH = "/hotel-participant"; public static final String TRANSACTION_COMPLETE = "/complete"; public static final String TRANSACTION_COMPENSATE = "/compensate"; @Inject private HotelService service; @POST @Produces(MediaType.APPLICATION_JSON) @LRA(value = LRA.Type.REQUIRED, end = false) public Booking bookRoom(@HeaderParam(LRA_HTTP_CONTEXT_HEADER) String lraId, @QueryParam("hotelName") @DefaultValue("Default") String hotelName) { return service.book(lraId, hotelName); } @PUT @Path(TRANSACTION_COMPLETE) @Produces(MediaType.APPLICATION_JSON) @Complete public Response completeWork(@HeaderParam(LRA_HTTP_CONTEXT_HEADER) String lraId) throws NotFoundException, JsonProcessingException { service.get(lraId).setStatus(Booking.BookingStatus.CONFIRMED); return Response.ok(service.get(lraId).toJson()).build(); } @PUT @Path(TRANSACTION_COMPENSATE) @Produces(MediaType.APPLICATION_JSON) @Compensate public Response compensateWork(@HeaderParam(LRA_HTTP_CONTEXT_HEADER) String lraId) throws NotFoundException, JsonProcessingException { service.get(lraId).setStatus(Booking.BookingStatus.CANCELLED); return Response.ok(service.get(lraId).toJson()).build(); } @GET @Path("/{bookingId}") @Produces(MediaType.APPLICATION_JSON) @LRA(LRA.Type.NOT_SUPPORTED) public Booking getBooking(@PathParam("bookingId") String bookingId) throws JsonProcessingException { return service.get(bookingId); } @GET @Produces(MediaType.APPLICATION_JSON) public Collection<Booking> getAll() { return service.getAll(); } }
3,857
37.58
138
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/lra/participant/smoke/hotel/HotelService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.lra.participant.smoke.hotel; import jakarta.enterprise.context.ApplicationScoped; import jakarta.ws.rs.NotFoundException; import jakarta.ws.rs.core.Response; import org.wildfly.test.integration.microprofile.lra.participant.smoke.model.Booking; import java.util.Collection; import java.util.HashMap; import java.util.Map; @ApplicationScoped public class HotelService { private Map<String, Booking> bookings = new HashMap<>(); public Booking book(String bid, String hotel) { Booking booking = new Booking(bid, hotel, "Hotel"); Booking earlierBooking = bookings.putIfAbsent(booking.getId(), booking); return earlierBooking == null ? booking : earlierBooking; } public Booking get(String bookingId) throws NotFoundException { if (!bookings.containsKey(bookingId)) throw new NotFoundException(Response.status(404).entity("Invalid bookingId id: " + bookingId).build()); return bookings.get(bookingId); } public Collection<Booking> getAll() { return bookings.values(); } }
2,134
38.537037
115
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/lra/participant/smoke/hotel/JaxRsActivator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.lra.participant.smoke.hotel; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.core.Application; @ApplicationPath("/") public class JaxRsActivator extends Application { }
1,254
42.275862
78
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/lra/participant/smoke/model/Booking.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.lra.participant.smoke.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.Array; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.IntStream; public class Booking { @JsonProperty("id") private String id; @JsonProperty("name") private String name; @JsonProperty("status") private BookingStatus status; @JsonProperty("type") private String type; @JsonProperty("details") private Booking[] details; private IOException decodingException; public Booking(String id, String type, Booking... bookings) { this(id, "Aggregate Booking", type, BookingStatus.PROVISIONAL, bookings); } public Booking(String id, String name, String type) { this(id, name, type, BookingStatus.PROVISIONAL, null); } @JsonCreator public Booking(@JsonProperty("id") String id, @JsonProperty("name") String name, @JsonProperty("type") String type, @JsonProperty("status") BookingStatus status, @JsonProperty("details") Booking[] details) { init(id, name, type, status, details); } public Booking(IOException decodingException) { this.decodingException = decodingException; } public Booking(Booking booking) { this.init(booking.getId(), booking.getName(), booking.getType(), booking.getStatus(), null); details = new Booking[booking.getDetails().length]; IntStream.range(0, details.length).forEach(i -> details[i] = new Booking(booking.getDetails()[i])); } public static Booking fromJson(String json) { try { return new ObjectMapper().readValue(json, Booking.class); } catch (IOException e) { return new Booking(e); } } public static List<Booking> listFromJson(String json) throws IOException { ObjectMapper mapper = new ObjectMapper(); return Arrays.asList(mapper.readValue(json, Booking[].class)); } private void init(String id, String name, String type, BookingStatus status, Booking[] details) { this.id = id; this.name = name == null ? "" : name; this.type = type == null ? "" : type; this.status = status; this.details = details == null ? new Booking[0] : removeNullEnElements(details); } @SuppressWarnings("unchecked") private <T> T[] removeNullEnElements(T[] a) { List<T> list = new ArrayList<T>(Arrays.asList(a)); list.removeAll(Collections.singleton(null)); return list.toArray((T[]) Array.newInstance(a.getClass().getComponentType(), list.size())); } public String getId() { return id; } public String getName() { return name; } public String getType() { return type; } public Booking[] getDetails() { return details; } public BookingStatus getStatus() { return status; } public void setStatus(BookingStatus status) { this.status = status; } public void requestCancel() { status = BookingStatus.CANCEL_REQUESTED; } @JsonIgnore public boolean isCancelPending() { return status == BookingStatus.CANCEL_REQUESTED; } public String toString() { return String.format("{\"id\":\"%s\",\"name\":\"%s\",\"type\":\"%s\",\"status\":\"%s\"}", id, name, type, status); } public boolean merge(Booking booking) { if (!id.equals(booking.getId())) return false; // or throw an exception name = booking.getName(); status = booking.getStatus(); return true; } @JsonIgnore public String getEncodedId() { try { return URLEncoder.encode(id, "UTF-8"); } catch (UnsupportedEncodingException e) { return id; // TODD do it in the constructor } } public String toJson() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writeValueAsString(this); } @JsonIgnore public IOException getDecodingException() { return decodingException; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Booking booking = (Booking) o; if (!getId().equals(booking.getId())) return false; if (!getName().equals(booking.getName())) return false; if (!getType().equals(booking.getType())) return false; return true; } @Override public int hashCode() { int result = getId().hashCode(); result = 31 * result + getName().hashCode(); result = 31 * result + getType().hashCode(); return result; } public enum BookingStatus { CONFIRMED, CANCELLED, PROVISIONAL, CONFIRMING, CANCEL_REQUESTED } }
6,411
30.126214
107
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/AssertUtils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ public class AssertUtils { public static void assertTextContainsProperty(String text, String propName, Object propValue) { assertTextContainsProperty(text, propName, propValue, true); } public static void assertTextContainsProperty(String text, String propName, Object propValue, boolean exactMatch) { if (exactMatch) { // Include also newline at the end of the line to assure that whole value is checked. assertTrue("String '" + propName + " = " + propValue + "' not found in the following output:\n" + text, text.contains(propName + " = " + propValue + "\n")); } else { // Find the line starting with "${propName} =" List<String> matchingLines = Arrays.stream(text.split("\n")) .filter(line -> line.startsWith(propName + " =")) .collect(Collectors.toList()); assertEquals(1, matchingLines.size()); assertTrue("Text " + propValue + "not found for property " + propName + " in " + text, matchingLines.get(0).contains(propValue.toString())); } } }
2,503
42.172414
119
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/AbstractMicroProfileConfigTestCase.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.microprofile.config.smallrye; import java.security.Permission; import java.util.ArrayList; import java.util.Collection; import java.util.Locale; import java.util.PropertyPermission; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public abstract class AbstractMicroProfileConfigTestCase { /** * Creates the following permissions for config tests: * <ul> * <li>A read {@link PropertyPermission} for each name</li> * <li>A {@code getenv} permission for each name</li> * <li>A {@code getenv} permission for each name replacing any dots {@code .} with an underscore {@code _}</li> * <li>A {@code getenv} permission for each name converted to upper case</li> * <li>A {@code getenv} permission for each name converted to upper case replacing any dots {@code .} * with an underscore {@code _} * </li> * </ul> * * @param names the names to create the permissions for * * @return the set of permissions */ protected static Permission[] createPermissions(final String... names) { final Collection<Permission> permissions = new ArrayList<>(names.length * 2); for (String name : names) { permissions.add(new PropertyPermission(name, "read")); permissions.add(new RuntimePermission("getenv." + name)); permissions.add(new RuntimePermission("getenv." + name.replace('.', '_'))); permissions.add(new RuntimePermission("getenv." + name.toUpperCase(Locale.ROOT))); permissions.add(new RuntimePermission("getenv." + name.replace('.', '_').toUpperCase(Locale.ROOT))); } return permissions.toArray(new Permission[0]); } }
2,346
39.465517
115
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/SubsystemConfigSourceTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROPERTIES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import java.io.File; import java.io.IOException; import java.util.LinkedList; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; import org.wildfly.test.integration.microprofile.config.smallrye.app.MicroProfileConfigTestCase; /** * Add a config-source with a property class in the microprofile-config-smallrye subsystem. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ public class SubsystemConfigSourceTask implements ServerSetupTask { public static final String MY_PROP_FROM_SUBSYSTEM_PROP_NAME = "my.prop.from.subsystem"; public static final String MY_PROP_FROM_SUBSYSTEM_PROP_VALUE = "I'm configured in the subsystem"; public static final String BOOL_OVERRIDDEN_PROP_NAME = "boolOverridden"; public static final String BOOLEAN_OVERRIDDEN_PROP_NAME = "booleanOverridden"; public static final String BOOLEAN_OVERRIDDEN_PROP_VALUE = "yes"; public static final String INT_OVERRIDDEN_PROP_NAME = "intOverridden"; public static final String INTEGER_OVERRIDDEN_PROP_NAME = "integerOverridden"; public static final String INTEGER_OVERRIDDEN_PROP_VALUE = String.valueOf(Integer.MAX_VALUE); public static final String LONG_OVERRIDDEN_PROP_NAME = "longOverridden"; public static final String LONG_CLASS_OVERRIDDEN_PROP_NAME = "longClassOverridden"; public static final String LONG_OVERRIDDEN_PROP_VALUE = String.valueOf(Long.MAX_VALUE); public static final String FLOAT_OVERRIDDEN_PROP_NAME = "floatOverridden"; public static final String FLOAT_CLASS_OVERRIDDEN_PROP_NAME = "floatClassOverridden"; public static final String FLOAT_OVERRIDDEN_PROP_VALUE = String.valueOf(Float.MAX_VALUE); public static final String DOUBLE_OVERRIDDEN_PROP_NAME = "doubleOverridden"; public static final String DOUBLE_CLASS_OVERRIDDEN_PROP_NAME = "doubleClassOverridden"; public static final String DOUBLE_OVERRIDDEN_PROP_VALUE = String.valueOf(Double.MAX_VALUE); public static final String PROPERTIES_PROP_NAME0 = "priority.prop.0"; public static final String PROPERTIES_PROP_NAME1 = "priority.prop.1"; public static final String PROPERTIES_PROP_NAME2 = "priority.prop.2"; public static final String PROPERTIES_PROP_NAME3 = "priority.prop.3"; public static final String PROPERTIES_PROP_NAME4 = "priority.prop.4"; public static final String PROPERTIES_PROP_NAME5 = "priority.prop.5"; public static final String PROP1_VALUE = "priority.prop.1 value loaded via properties config-source"; public static final String PROP2_VALUE = "priority.prop.2 value loaded via properties config-source"; public static final String PROP3_VALUE = "priority.prop.3 value loaded via properties config-source"; public static final String PROP4_VALUE = "priority.prop.4 value loaded via properties config-source"; // public static final String CUSTOM_FILE_PROPERTY_NAME = "custom.file.property"; public static final String MICROPROFILE_SUBSYSTEM_NAME = "microprofile-config-smallrye"; public static final String CONFIG_SOURCE = "config-source"; // Contains list of created config sources --- this is used during tearDown private final LinkedList<String> registeredConfigSources = new LinkedList<>(); /* Default ordinal values, https://github.com/eclipse/microprofile-config#design - System.getProperties() (ordinal=400) - System.getenv() (ordinal=300) - all META-INF/microprofile-config.properties files on the ClassPath. (default ordinal=100, separately configurable via a config_ordinal property inside each file) */ @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { ModelControllerClient mgmtCli = managementClient.getControllerClient(); // TODO system properties and env properites should be added here... // ===== PROPERTIES TYPE config sources (ordinal default is 100) ===== addPropertiesConfigSource(mgmtCli, BOOL_OVERRIDDEN_PROP_NAME, BOOL_OVERRIDDEN_PROP_NAME, BOOLEAN_OVERRIDDEN_PROP_VALUE); addPropertiesConfigSource(mgmtCli, BOOLEAN_OVERRIDDEN_PROP_NAME, BOOLEAN_OVERRIDDEN_PROP_NAME, BOOLEAN_OVERRIDDEN_PROP_VALUE); addPropertiesConfigSource(mgmtCli, INT_OVERRIDDEN_PROP_NAME, INT_OVERRIDDEN_PROP_NAME, INTEGER_OVERRIDDEN_PROP_VALUE); addPropertiesConfigSource(mgmtCli, INTEGER_OVERRIDDEN_PROP_NAME, INTEGER_OVERRIDDEN_PROP_NAME, INTEGER_OVERRIDDEN_PROP_VALUE); addPropertiesConfigSource(mgmtCli, LONG_OVERRIDDEN_PROP_NAME, LONG_OVERRIDDEN_PROP_NAME, LONG_OVERRIDDEN_PROP_VALUE); addPropertiesConfigSource(mgmtCli, LONG_CLASS_OVERRIDDEN_PROP_NAME, LONG_CLASS_OVERRIDDEN_PROP_NAME, LONG_OVERRIDDEN_PROP_VALUE); addPropertiesConfigSource(mgmtCli, FLOAT_OVERRIDDEN_PROP_NAME, FLOAT_OVERRIDDEN_PROP_NAME, FLOAT_OVERRIDDEN_PROP_VALUE); addPropertiesConfigSource(mgmtCli, FLOAT_CLASS_OVERRIDDEN_PROP_NAME, FLOAT_CLASS_OVERRIDDEN_PROP_NAME, FLOAT_OVERRIDDEN_PROP_VALUE); addPropertiesConfigSource(mgmtCli, DOUBLE_OVERRIDDEN_PROP_NAME, DOUBLE_OVERRIDDEN_PROP_NAME, DOUBLE_OVERRIDDEN_PROP_VALUE); addPropertiesConfigSource(mgmtCli, DOUBLE_CLASS_OVERRIDDEN_PROP_NAME, DOUBLE_CLASS_OVERRIDDEN_PROP_NAME, DOUBLE_OVERRIDDEN_PROP_VALUE); addPropertiesConfigSource(mgmtCli, "petsProperty", "myPetsOverridden", "donkey,shrek\\,fiona"); addPropertiesConfigSource(mgmtCli, "propertiesProp", MY_PROP_FROM_SUBSYSTEM_PROP_NAME, MY_PROP_FROM_SUBSYSTEM_PROP_VALUE); addPropertiesConfigSource(mgmtCli, "propertiesProp1", PROPERTIES_PROP_NAME1, PROP1_VALUE); addPropertiesConfigSource(mgmtCli, "propertiesProp2", PROPERTIES_PROP_NAME2, PROP2_VALUE, 200); addPropertiesConfigSource(mgmtCli, "propertiesProp3", PROPERTIES_PROP_NAME3, PROP3_VALUE, 350); // ===== DIR TYPE config sources (ordinal default is 100) ===== // File propertiesDir = new File(MicroProfileConfigTestCase.class.getResource(CUSTOM_FILE_PROPERTY_NAME).toURI()).getParentFile(); // TODO workaround due to the https://issues.jboss.org/browse/WFWIP-57 File propertiesDir = new File(MicroProfileConfigTestCase.class.getResource("microprofile-config.properties").toURI()).getParentFile(); // Prefix these so that they get alphabetically sorted after the 'propertiesProp*' ones. This is because SM Config // 2.x changed the sorting order of sources with the same ordinal to take into account the order they are added // (previously they were sorted according to the underlying implementation name). IterableRegistry in the // MP Config subsystem has been updated to order config sources by name. addDirConfigSource(mgmtCli, "zDirProp1", propertiesDir.getAbsolutePath() + File.separator + "fileProperty1"); addDirConfigSource(mgmtCli, "zDirProp2", propertiesDir.getAbsolutePath() + File.separator + "fileProperty2", 200); addDirConfigSource(mgmtCli, "zDirProp3", propertiesDir.getAbsolutePath() + File.separator + "fileProperty3", 350); addDirConfigSource(mgmtCli, "zDirProp4", propertiesDir.getAbsolutePath() + File.separator + "fileProperty4", 450); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { ModelControllerClient mgmtCli = managementClient.getControllerClient(); removeConfigSource(mgmtCli, registeredConfigSources); ServerReload.reloadIfRequired(managementClient); } /** * Adds config-source of type 'properties' with given value and priority ordinal value set to default. * * @param client model controller client * @param configSourceName name of the added config-source resource * @param propName name of the property to be created * @param propValue value of the property which shall be created * @throws IOException */ private void addPropertiesConfigSource(ModelControllerClient client, String configSourceName, String propName, String propValue) throws IOException { addPropertiesConfigSource(client, configSourceName, propName, propValue, -1); } /** * Adds config-source of type 'properties' with given value and priority ordinal value. * * @param client model controller client * @param configSourceName name of the added config-source resource * @param propName name of the property to be created * @param propValue value of the property which shall be created * @param ordinal ordinal value of the priority of the added config-source; if less than zero, default is * set * @throws IOException */ private void addPropertiesConfigSource(ModelControllerClient client, String configSourceName, String propName, String propValue, int ordinal) throws IOException { ModelNode op; op = new ModelNode(); op.get(OP_ADDR).add(SUBSYSTEM, MICROPROFILE_SUBSYSTEM_NAME); op.get(OP_ADDR).add(CONFIG_SOURCE, configSourceName); op.get(OP).set(ADD); op.get(PROPERTIES).add(propName, propValue); if (ordinal >= 0) { op.get("ordinal").set(ordinal); } client.execute(op); registeredConfigSources.add(configSourceName); } /** * Adds config-source of type 'dir' with given value and priority ordinal value set to default. * * @param client model controller client * @param configSourceName name of the added config-source resource * @param dirPath value of the config-source - path to the directory from where the properties should be * loaded * @throws IOException */ private void addDirConfigSource(ModelControllerClient client, String configSourceName, String dirPath) throws IOException { addDirConfigSource(client, configSourceName, dirPath, -1); } /** * Adds config-source of type 'dir' with given value and priority ordinal value. * * @param client model controller client * @param configSourceName name of the added config-source resource * @param dirPath value of the config-source - path to the directory from where the properties should be * loaded * @param ordinal ordinal value of the priority of the added config-source; if less than zero, default is * set * @throws IOException */ private void addDirConfigSource(ModelControllerClient client, String configSourceName, String dirPath, int ordinal) throws IOException { ModelNode op; op = new ModelNode(); op.get(OP_ADDR).add(SUBSYSTEM, MICROPROFILE_SUBSYSTEM_NAME); op.get(OP_ADDR).add(CONFIG_SOURCE, configSourceName); op.get(OP).set(ADD); ModelNode dir = new ModelNode(); dir.get("path").set(dirPath); op.get("dir").set(dir); if (ordinal >= 0) { op.get("ordinal").set(ordinal); } client.execute(op); registeredConfigSources.add(configSourceName); } /** * Removes defined list of config-sources. * * @param client model controller client * @param names list of strings containing names of the config-sources to be removed * @throws IOException */ private void removeConfigSource(ModelControllerClient client, LinkedList<String> names) throws IOException { for (String name : names) { removeConfigSource(client, name); } } /** * Removes defined config-source. * * @param client model controller client * @param name string containing name of the config-source to be removed * @throws IOException */ private void removeConfigSource(ModelControllerClient client, String name) throws IOException { ModelNode op; op = new ModelNode(); op.get(OP_ADDR).add(SUBSYSTEM, MICROPROFILE_SUBSYSTEM_NAME); op.get(OP_ADDR).add(CONFIG_SOURCE, name); op.get(OP).set(REMOVE); client.execute(op); } }
14,050
51.234201
143
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_dir/TestApplication.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir; import jakarta.inject.Inject; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Application; import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.config.inject.ConfigProperty; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ @ApplicationPath("/custom-config-source") public class TestApplication extends Application { static final String FROM_A = "from-a"; static final String FROM_B = "from-b"; static final String B_OVERRIDES_A = "b-overrides-a"; static final String NOT_AVAILABLE_NESTED_DIR_UNDER_A = "not-available-a"; static final String NOT_AVAILABLE_NESTED_DIR_UNDER_B = "not-available-b"; static final String DEFAULT = "default"; @Path("/test") public static class Resource { @Inject @ConfigProperty(name = FROM_A) String fromA; @Inject @ConfigProperty(name = FROM_B) String fromB; @Inject @ConfigProperty(name = B_OVERRIDES_A) String bOverridesA; @Inject @ConfigProperty(name = NOT_AVAILABLE_NESTED_DIR_UNDER_A, defaultValue = DEFAULT) String notAvailableA; @Inject @ConfigProperty(name = NOT_AVAILABLE_NESTED_DIR_UNDER_B, defaultValue = DEFAULT) String notAvailableB; @GET @Produces("text/plain") public Response doGet() { StringBuilder text = new StringBuilder(); text.append(FROM_A + " = " + fromA + "\n"); text.append(FROM_B + " = " + fromB + "\n"); text.append(B_OVERRIDES_A + " = " + bOverridesA + "\n"); text.append(NOT_AVAILABLE_NESTED_DIR_UNDER_A + " = " + notAvailableA + "\n"); text.append(NOT_AVAILABLE_NESTED_DIR_UNDER_B + " = " + notAvailableB + "\n"); return Response.ok(text).build(); } } }
3,078
34.390805
100
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_dir/ConfigSourceFromDirTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir.SetupTask.A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir.SetupTask.B; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir.TestApplication.B_OVERRIDES_A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir.TestApplication.DEFAULT; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir.TestApplication.FROM_A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir.TestApplication.FROM_B; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir.TestApplication.NOT_AVAILABLE_NESTED_DIR_UNDER_A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir.TestApplication.NOT_AVAILABLE_NESTED_DIR_UNDER_B; import java.net.URL; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.config.smallrye.AbstractMicroProfileConfigTestCase; import org.wildfly.test.integration.microprofile.config.smallrye.AssertUtils; /** * Load a ConfigSource from a class (in a module). * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(SetupTask.class) public class ConfigSourceFromDirTestCase extends AbstractMicroProfileConfigTestCase { @Deployment public static Archive<?> deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, "ConfigSourceFromDirTestCase.war") .addClasses(TestApplication.class, TestApplication.Resource.class, AbstractMicroProfileConfigTestCase.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); return war; } @ArquillianResource private URL url; @Test public void testGetWithConfigProperties() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + "custom-config-source/test")); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); AssertUtils.assertTextContainsProperty(text, FROM_A, A); AssertUtils.assertTextContainsProperty(text, FROM_B, B); AssertUtils.assertTextContainsProperty(text, B_OVERRIDES_A, SetupTask.OVERRIDDEN_B); AssertUtils.assertTextContainsProperty(text, NOT_AVAILABLE_NESTED_DIR_UNDER_A, DEFAULT); AssertUtils.assertTextContainsProperty(text, NOT_AVAILABLE_NESTED_DIR_UNDER_B, DEFAULT); } } }
4,757
51.285714
155
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_dir/SetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir.TestApplication.B_OVERRIDES_A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir.TestApplication.FROM_A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir.TestApplication.FROM_B; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir.TestApplication.NOT_AVAILABLE_NESTED_DIR_UNDER_A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_dir.TestApplication.NOT_AVAILABLE_NESTED_DIR_UNDER_B; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.shared.CLIServerSetupTask; import org.junit.Assert; /** * Add a config-source with a custom class in the microprofile-config subsystem. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ public class SetupTask extends CLIServerSetupTask { private static final String PROPS_A = "propsA"; private static final String PROPS_B = "propsB"; private static final String ADDR_A = "/subsystem=microprofile-config-smallrye/config-source=propsA"; private static final String ADDR_B = "/subsystem=microprofile-config-smallrye/config-source=propsB"; private static final String ADDR_NON_EXISTENT = "/subsystem=microprofile-config-smallrye/config-source=not-there"; static final String A = "val-a"; static final String B = "val-b"; // In propsA this will be 'overridden-a', in propsB 'overridden-b'. Due to the relative ordinals of the config sources, propsB should win private static final String OVERRIDDEN_A = "overridden-a"; static final String OVERRIDDEN_B = "overridden-b"; private volatile Path rootDir; private volatile Path nonExistent; @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { Path target = Paths.get("target").toAbsolutePath().normalize(); rootDir = Files.createTempDirectory(target, "test"); Assert.assertTrue(Files.exists(rootDir)); nonExistent = Files.createTempDirectory(target, "duff"); deleteDirectory(nonExistent); Assert.assertFalse(Files.exists(nonExistent)); Path dirA = createPropsDir(rootDir, PROPS_A, FROM_A, A, B_OVERRIDES_A, OVERRIDDEN_A); Path dirB = createPropsDir(rootDir, PROPS_B, FROM_B, B, B_OVERRIDES_A, OVERRIDDEN_B); // Add some files which will be ignored (since the config sources we are adding here are not roots) // in child directories of the config source directories createPropsDir(dirA, PROPS_A, NOT_AVAILABLE_NESTED_DIR_UNDER_A, "Hello"); createPropsDir(dirB, PROPS_B, NOT_AVAILABLE_NESTED_DIR_UNDER_B, "Hello"); NodeBuilder nb = builder.node(containerId); nb.setup(String.format("%s:add(dir={path=\"%s\"})", ADDR_A, escapePath(dirA))); nb.setup(String.format("/path=mp-config-test:add(path=\"%s\")", escapePath(dirB.getParent()))); // Make this one explicitly set root=false for test coverage nb.setup(String.format("%s:add(dir={relative-to=mp-config-test, path=\"%s\", root=false}, ordinal=300)", ADDR_B, dirB.getFileName())); nb.setup(String.format("%s:add(dir={path=\"%s\"})", ADDR_NON_EXISTENT, escapePath(nonExistent))); nb.teardown(String.format("%s:remove", ADDR_A)); nb.teardown(String.format("%s:remove", ADDR_B)); nb.teardown(String.format("%s:remove", ADDR_NON_EXISTENT)); nb.teardown("/path=mp-config-test:remove"); super.setup(managementClient, containerId); } private String escapePath(Path path) { String s = path.toString(); //Avoid problems with paths on Windows s = s.replace('\\', '/'); return s; } private Path createPropsDir(Path rootDir, String sourceName, String... props) throws IOException { Path sourceDir = rootDir.resolve(sourceName); Files.createDirectory(sourceDir); Assert.assertTrue(Files.exists(sourceDir)); for (int i = 0 ; i < props.length ; i += 2) { Path file = sourceDir.resolve(props[i]); Files.createFile(file); Assert.assertTrue(Files.exists(file)); Files.write(file, Collections.singletonList(props[i + 1])); } return sourceDir.toAbsolutePath().normalize(); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { super.tearDown(managementClient, containerId); deleteDirectory(); } private void deleteDirectory() throws IOException { deleteDirectory(rootDir); } private void deleteDirectory(Path rootDir) throws IOException { if (rootDir != null && Files.exists(rootDir)) { Files.walkFileTree(rootDir, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return super.visitFile(file, attrs); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return super.postVisitDirectory(dir, exc); } }); } } }
6,959
45.092715
155
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_class/TestApplication.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_class; import jakarta.inject.Inject; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Application; import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.config.inject.ConfigProperty; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ @ApplicationPath("/custom-config-source") public class TestApplication extends Application { @Path("/test") public static class Resource { @Inject @ConfigProperty(name = CustomConfigSource.PROP_NAME) String prop; @Inject @ConfigProperty(name = CustomConfigSourceServiceLoader.PROP_NAME) String propFromServiceLoader; @Inject @ConfigProperty(name = CustomConfigSource.PROP_NAME_OVERRIDEN_BY_SERVICE_LOADER) String propOverridenByServiceLoader; @Inject @ConfigProperty(name = CustomConfigSourceAServiceLoader.PROP_NAME_SAME_ORDINALITY_OVERRIDE) String propSameOrdinalityOverridenByFqcn; @GET @Produces("text/plain") public Response doGet() { StringBuilder text = new StringBuilder(); text.append(CustomConfigSource.PROP_NAME + " = " + prop + "\n"); text.append(CustomConfigSourceServiceLoader.PROP_NAME + " = " + propFromServiceLoader + "\n"); text.append(CustomConfigSource.PROP_NAME_OVERRIDEN_BY_SERVICE_LOADER + " = " + propOverridenByServiceLoader + "\n"); text.append(CustomConfigSourceAServiceLoader.PROP_NAME_SAME_ORDINALITY_OVERRIDE + " = " + propSameOrdinalityOverridenByFqcn + "\n"); return Response.ok(text).build(); } } }
2,876
38.410959
128
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_class/CustomConfigSourceServiceLoader.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_class; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.eclipse.microprofile.config.spi.ConfigSource; /** * @author <a href="mailto:[email protected]">Michal Jurc</a> (c) 2018 Red Hat, Inc. */ public class CustomConfigSourceServiceLoader implements ConfigSource { public static final String PROP_NAME = "my.prop.from.service.loader.class"; public static final String PROP_VALUE = "I'm from a custom config source provided by service loader mechanism!"; public static final String PROP_NAME_OVERRIDEN_BY_SERVICE_LOADER = "my.prop.from.class.overriden.service.loader"; public static final String PROP_VALUE_OVERRIDEN_BY_SERVICE_LOADER = "I'm from a custom config source provided by service" + " loader mechanism! My ordinality is higher, so I override property from custom config source without service loader."; public static final String PROP_NAME_SAME_ORDINALITY_OVERRIDE = "my.prop.from.class.overriden.same.ordinality"; public static final String PROP_VALUE_SAME_ORDINALITY_OVERRIDE = "I'm from a custom config source provided by service " + "loader! However I should be overriden by property from ConfigSource with same ordinality based on FQCN " + "lexicographic ordering."; final Map<String, String> props; public CustomConfigSourceServiceLoader() { props = new HashMap<>(); props.put(PROP_NAME, PROP_VALUE); props.put(PROP_NAME_OVERRIDEN_BY_SERVICE_LOADER, PROP_VALUE_OVERRIDEN_BY_SERVICE_LOADER); props.put(PROP_NAME_SAME_ORDINALITY_OVERRIDE, PROP_VALUE_SAME_ORDINALITY_OVERRIDE); } @Override public int getOrdinal() { return 101; } @Override public Map<String, String> getProperties() { return Collections.unmodifiableMap(props); } @Override public String getValue(String s) { return props.get(s); } @Override public String getName() { return this.getClass().getName(); } @Override public Set<String> getPropertyNames() { return props.keySet(); } }
3,255
39.7
131
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_class/CustomConfigSource.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_class; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.eclipse.microprofile.config.spi.ConfigSource; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ public class CustomConfigSource implements ConfigSource{ public static final String PROP_NAME = "my.prop.from.class"; public static final String PROP_VALUE = "I'm from a custom config source!"; public static final String PROP_NAME_OVERRIDEN_BY_SERVICE_LOADER = "my.prop.from.class.overriden.service.loader"; public static final String PROP_VALUE_OVERRIDEN_BY_SERVICE_LOADER = "I'm from a custom config source! However I should be " + "overriden by property from ConfigSource provided by service loader."; final Map<String, String> props; public CustomConfigSource() { props = new HashMap<>(); props.put(PROP_NAME, PROP_VALUE); props.put(PROP_NAME_OVERRIDEN_BY_SERVICE_LOADER, PROP_VALUE_OVERRIDEN_BY_SERVICE_LOADER); } @Override public Map<String, String> getProperties() { return Collections.unmodifiableMap(props); } @Override public String getValue(String s) { return props.get(s); } @Override public String getName() { return this.getClass().getName(); } @Override public Set<String> getPropertyNames() { return props.keySet(); } }
2,560
35.585714
129
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_class/ConfigSourceFromClassTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_class; import java.net.URL; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.config.smallrye.AbstractMicroProfileConfigTestCase; import org.wildfly.test.integration.microprofile.config.smallrye.AssertUtils; /** * Load a ConfigSource from a class (in a module). * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(SetupTask.class) public class ConfigSourceFromClassTestCase extends AbstractMicroProfileConfigTestCase { @Deployment public static Archive<?> deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, "ConfigSourceFromClassTestCase.war") .addClasses(TestApplication.class, TestApplication.Resource.class, AbstractMicroProfileConfigTestCase.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addAsWebInfResource(ConfigSourceFromClassTestCase.class.getPackage(), "jboss-deployment-structure.xml", "jboss-deployment-structure.xml"); return war; } @ArquillianResource private URL url; @Test public void testGetWithConfigProperties() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + "custom-config-source/test")); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); AssertUtils.assertTextContainsProperty(text, CustomConfigSource.PROP_NAME, CustomConfigSource.PROP_VALUE); AssertUtils.assertTextContainsProperty(text, CustomConfigSource.PROP_NAME_OVERRIDEN_BY_SERVICE_LOADER, CustomConfigSourceServiceLoader.PROP_VALUE_OVERRIDEN_BY_SERVICE_LOADER); AssertUtils.assertTextContainsProperty(text, CustomConfigSourceServiceLoader.PROP_NAME, CustomConfigSourceServiceLoader.PROP_VALUE); // TODO - enable this when https://issues.jboss.org/browse/WFWIP-60 is resolved //AssertUtils.assertTextContainsProperty(text, CustomConfigSourceAServiceLoader.PROP_NAME_SAME_ORDINALITY_OVERRIDE, // CustomConfigSourceAServiceLoader.PROP_VALUE_SAME_ORDINALITY_OVERRIDE); } } }
4,231
47.643678
127
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_class/SetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_class; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.util.HashSet; import java.util.Set; import org.eclipse.microprofile.config.spi.ConfigSource; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.module.util.TestModule; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; /** * Add a config-source with a custom class in the microprofile-config subsystem. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ public class SetupTask implements ServerSetupTask { private static final String TEST_MODULE_NAME = "test.custom-config-source"; private static final String TEST_MODULE_NAME_SERVICE_LOADER = TEST_MODULE_NAME + "-service-loader"; private static Set<TestModule> testModules = new HashSet<>(); @Override public void setup(ManagementClient managementClient, String s) throws Exception { URL url = ConfigSourceFromClassTestCase.class.getResource("module.xml"); File moduleXmlFile = new File(url.toURI()); TestModule testModule = new TestModule(TEST_MODULE_NAME, moduleXmlFile); testModule.addResource("config-source.jar") .addClass(CustomConfigSource.class); testModule.create(); addConfigSource(managementClient.getControllerClient()); testModules.add(testModule); final File archiveDir = new File("target/archives"); archiveDir.mkdirs(); File moduleFile = new File(archiveDir, "config-source-service-loader.jar"); JavaArchive configSourceServiceLoad = ShrinkWrap.create(JavaArchive.class, "config-source-service-loader.jar") .addClass(CustomConfigSourceServiceLoader.class) .addClass(CustomConfigSourceAServiceLoader.class) .addAsServiceProvider(ConfigSource.class, CustomConfigSourceAServiceLoader.class, CustomConfigSourceServiceLoader.class); try(FileOutputStream target = new FileOutputStream(moduleFile)) { configSourceServiceLoad.as(ZipExporter.class).exportTo(target); } url = ConfigSourceFromClassTestCase.class.getResource("module_service_loader.xml"); moduleXmlFile = new File(url.toURI()); testModule = new TestModule(TEST_MODULE_NAME_SERVICE_LOADER, moduleXmlFile); testModule.addJavaArchive(moduleFile); testModule.create(); testModules.add(testModule); ServerReload.reloadIfRequired(managementClient); } @Override public void tearDown(ManagementClient managementClient, String s) throws Exception { removeConfigSource(managementClient.getControllerClient()); for (TestModule testModule : testModules) { testModule.remove(); } final File archiveDir = new File("target/archives"); cleanFile(archiveDir); ServerReload.reloadIfRequired(managementClient); } private void addConfigSource(ModelControllerClient client) throws IOException { ModelNode op; op = new ModelNode(); op.get(OP_ADDR).add(SUBSYSTEM, "microprofile-config-smallrye"); op.get(OP_ADDR).add("config-source", "cs-from-class"); op.get(OP).set(ADD); op.get("class").get("module").set(TEST_MODULE_NAME); op.get("class").get("name").set(CustomConfigSource.class.getName()); client.execute(op); } private void removeConfigSource(ModelControllerClient client) throws IOException { ModelNode op; op = new ModelNode(); op.get(OP_ADDR).add(SUBSYSTEM, "microprofile-config-smallrye"); op.get(OP_ADDR).add("config-source", "cs-from-class"); op.get(OP).set(REMOVE); client.execute(op); } private static void cleanFile(File toClean) { if (toClean.exists()) { if (toClean.isDirectory()) { for (File child : toClean.listFiles()) { cleanFile(child); } } toClean.delete(); } } }
6,940
43.49359
118
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_class/CustomConfigSourceAServiceLoader.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_class; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.eclipse.microprofile.config.spi.ConfigSource; /** * @author <a href="mailto:[email protected]">Michal Jurc</a> (c) 2018 Red Hat, Inc. */ public class CustomConfigSourceAServiceLoader implements ConfigSource { public static final String PROP_NAME_SAME_ORDINALITY_OVERRIDE = "my.prop.from.class.overriden.same.ordinality"; public static final String PROP_VALUE_SAME_ORDINALITY_OVERRIDE = "I'm from a custom config source provided by service " + "loader overriding ConfigSource with same ordinality since my FQCN is ranked higher lexicographically."; final Map<String, String> props; public CustomConfigSourceAServiceLoader() { props = new HashMap<>(); props.put(PROP_NAME_SAME_ORDINALITY_OVERRIDE, PROP_VALUE_SAME_ORDINALITY_OVERRIDE); } @Override public int getOrdinal() { return 101; } @Override public Map<String, String> getProperties() { return Collections.unmodifiableMap(props); } @Override public String getValue(String s) { return props.get(s); } @Override public String getName() { return this.getClass().getName(); } @Override public Set<String> getPropertyNames() { return props.keySet(); } }
2,501
33.273973
125
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_properties/TestApplication.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_properties; import jakarta.inject.Inject; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Application; import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.config.inject.ConfigProperty; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ @ApplicationPath("/custom-config-source") public class TestApplication extends Application { static final String FROM_A = "from-a"; static final String FROM_B = "from-b"; static final String B_OVERRIDES_A = "b-overrides-a"; @Path("/test") public static class Resource { @Inject @ConfigProperty(name = FROM_A) String fromA; @Inject @ConfigProperty(name = FROM_B) String fromB; @Inject @ConfigProperty(name = B_OVERRIDES_A) String bOverridesA; @GET @Produces("text/plain") public Response doGet() { StringBuilder text = new StringBuilder(); text.append(FROM_A + " = " + fromA + "\n"); text.append(FROM_B + " = " + fromB + "\n"); text.append(B_OVERRIDES_A + " = " + bOverridesA + "\n"); return Response.ok(text).build(); } } }
2,431
33.742857
107
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_properties/ConfigSourceFromPropertiesTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_properties; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_properties.SetupTask.A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_properties.SetupTask.B; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_properties.TestApplication.B_OVERRIDES_A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_properties.TestApplication.FROM_A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_properties.TestApplication.FROM_B; import java.net.URL; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.config.smallrye.AbstractMicroProfileConfigTestCase; import org.wildfly.test.integration.microprofile.config.smallrye.AssertUtils; /** * Load a ConfigSource from a class (in a module). * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(SetupTask.class) public class ConfigSourceFromPropertiesTestCase extends AbstractMicroProfileConfigTestCase { @Deployment public static Archive<?> deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, "ConfigSourceFromPropertiesTestCase.war") .addClasses(TestApplication.class, TestApplication.Resource.class, AbstractMicroProfileConfigTestCase.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); return war; } @ArquillianResource private URL url; @Test public void testGetWithConfigProperties() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + "custom-config-source/test")); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); AssertUtils.assertTextContainsProperty(text, FROM_A, A); AssertUtils.assertTextContainsProperty(text, FROM_B, B); AssertUtils.assertTextContainsProperty(text, B_OVERRIDES_A, SetupTask.OVERRIDDEN_B); } } }
4,168
47.476744
143
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_properties/SetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_properties; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_properties.TestApplication.B_OVERRIDES_A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_properties.TestApplication.FROM_A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_properties.TestApplication.FROM_B; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.shared.CLIServerSetupTask; /** * Add a config-source with a custom class in the microprofile-config subsystem. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ public class SetupTask extends CLIServerSetupTask { private static final String ADDR_A = "/subsystem=microprofile-config-smallrye/config-source=propsA"; private static final String ADDR_B = "/subsystem=microprofile-config-smallrye/config-source=propsB"; static final String A = "val-a"; static final String B = "val-b"; // In propsA this will be 'overridden-a', in propsB 'overridden-b'. Due to the relative ordinals of the config sources, propsB should win private static final String OVERRIDDEN_A = "overridden-a"; static final String OVERRIDDEN_B = "overridden-b"; @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { NodeBuilder nb = builder.node(containerId); String propsA = String.format("{%s=%s, %s=%s}", FROM_A, A, B_OVERRIDES_A, OVERRIDDEN_A); String propsB = String.format("{%s=%s, %s=%s}", FROM_B, B, B_OVERRIDES_A, OVERRIDDEN_B); nb.setup(String.format("%s:add(properties=%s)", ADDR_A, propsA)); nb.setup(String.format("%s:add(properties=%s, ordinal=300)", ADDR_B, propsB)); nb.teardown(String.format("%s:remove", ADDR_A)); nb.teardown(String.format("%s:remove", ADDR_B)); super.setup(managementClient, containerId); } }
3,128
48.666667
143
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_root_dir/ConfigSourceRootTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.DEFAULT; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.NOT_AVAILABLE_NESTED_DIR_UNDER_A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.NOT_AVAILABLE_ROOT_FILE; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.X_D_OVERRIDES_A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.FROM_A1; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.FROM_A2; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.FROM_B; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.Y_A_OVERRIDES_B; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.Z_C_OVERRIDES_A; import java.net.URL; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.config.smallrye.AbstractMicroProfileConfigTestCase; import org.wildfly.test.integration.microprofile.config.smallrye.AssertUtils; /** * Tests Root directory config sources * * @author Kabir Khan */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(SetupTask.class) public class ConfigSourceRootTestCase extends AbstractMicroProfileConfigTestCase { @Deployment public static Archive<?> deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, "ConfigSourceFromDirTestCase.war") .addClasses(TestApplication.class, TestApplication.Resource.class, AbstractMicroProfileConfigTestCase.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); return war; } @ArquillianResource private URL url; @Test public void testGetWithConfigProperties() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + "custom-config-source/test")); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); AssertUtils.assertTextContainsProperty(text, FROM_A1, SetupTask.A1); AssertUtils.assertTextContainsProperty(text, FROM_A2, SetupTask.A2); AssertUtils.assertTextContainsProperty(text, FROM_B, SetupTask.B); AssertUtils.assertTextContainsProperty(text, X_D_OVERRIDES_A, SetupTask.X_FROM_D); AssertUtils.assertTextContainsProperty(text, Y_A_OVERRIDES_B, SetupTask.Y_FROM_A); AssertUtils.assertTextContainsProperty(text, Z_C_OVERRIDES_A, SetupTask.Z_FROM_C); AssertUtils.assertTextContainsProperty(text, NOT_AVAILABLE_NESTED_DIR_UNDER_A, DEFAULT); AssertUtils.assertTextContainsProperty(text, NOT_AVAILABLE_ROOT_FILE, DEFAULT); } } }
5,182
53.557895
160
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_root_dir/TestApplication.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir; import jakarta.inject.Inject; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Application; import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.config.inject.ConfigProperty; /** * @author Kabir Khan */ @ApplicationPath("/custom-config-source") public class TestApplication extends Application { static final String FROM_A1 = "from-a1"; static final String FROM_A2 = "from-a2"; static final String FROM_B = "from-b"; static final String X_D_OVERRIDES_A = "x-d-overrides-a"; static final String Y_A_OVERRIDES_B = "y-a-overrides-b"; static final String Z_C_OVERRIDES_A = "y-c-overrides-a"; static final String NOT_AVAILABLE_NESTED_DIR_UNDER_A = "not-available-a"; static final String NOT_AVAILABLE_ROOT_FILE = "not-available-root-file"; static final String DEFAULT = "default"; @Path("/test") public static class Resource { @Inject @ConfigProperty(name = FROM_A1) String fromA1; @Inject @ConfigProperty(name = FROM_A2) String fromA2; @Inject @ConfigProperty(name = FROM_B) String fromB; @Inject @ConfigProperty(name = X_D_OVERRIDES_A) String xDOverridesA; @Inject @ConfigProperty(name = Y_A_OVERRIDES_B) String yAOverridesB; @Inject @ConfigProperty(name = Z_C_OVERRIDES_A) String zCOverridesA; @Inject @ConfigProperty(name = NOT_AVAILABLE_NESTED_DIR_UNDER_A, defaultValue = DEFAULT) String notAvailableA; @Inject @ConfigProperty(name = NOT_AVAILABLE_ROOT_FILE, defaultValue = DEFAULT) String notAvailableRootFile; @GET @Produces("text/plain") public Response doGet() { StringBuilder text = new StringBuilder(); text.append(FROM_A1 + " = " + fromA1 + "\n"); text.append(FROM_A2 + " = " + fromA2 + "\n"); text.append(FROM_B + " = " + fromB + "\n"); text.append(X_D_OVERRIDES_A + " = " + xDOverridesA + "\n"); text.append(Y_A_OVERRIDES_B + " = " + yAOverridesB + "\n"); text.append(Z_C_OVERRIDES_A + " = " + zCOverridesA + "\n"); text.append(NOT_AVAILABLE_NESTED_DIR_UNDER_A + " = " + notAvailableA + "\n"); text.append(NOT_AVAILABLE_ROOT_FILE + " = " + notAvailableRootFile + "\n"); return Response.ok(text).build(); } } }
3,675
33.679245
105
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source/from_root_dir/SetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.NOT_AVAILABLE_NESTED_DIR_UNDER_A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.NOT_AVAILABLE_ROOT_FILE; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.Y_A_OVERRIDES_B; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.X_D_OVERRIDES_A; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.FROM_A1; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.FROM_A2; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.FROM_B; import static org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_root_dir.TestApplication.Z_C_OVERRIDES_A; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.shared.CLIServerSetupTask; import org.junit.Assert; /** * Adds config-source-roots in the microprofile-config subsystem. * * @author Kabir Khan */ public class SetupTask extends CLIServerSetupTask { private static final String PROPS_A = "propsA"; private static final String PROPS_B = "propsB"; private static final String PROPS_C = "propsC"; private static final String PROPS_D = "propsD"; private static final String ROOT_A = "/subsystem=microprofile-config-smallrye/config-source=rootA"; private static final String ROOT_B = "/subsystem=microprofile-config-smallrye/config-source=rootB"; private static final String ROOT_NON_EXISTENT = "/subsystem=microprofile-config-smallrye/config-source=bad-root"; static final String A1 = "val-a1"; static final String A2 = "val-a2"; static final String B = "val-b"; static final String X_FROM_A = "x-from-a"; static final String X_FROM_D = "x-from-d"; static final String Y_FROM_A = "y-from-a"; static final String Y_FROM_B = "y-from-b"; static final String Z_FROM_A = "z-from-a"; static final String Z_FROM_C = "z-from-c"; private volatile Path rootDir1; private volatile Path rootDir2; private volatile Path nonExistent; @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { Path target = Paths.get("target").toAbsolutePath().normalize(); rootDir1 = Files.createTempDirectory(target, "test1"); rootDir2 = Files.createTempDirectory(target, "test2"); Assert.assertTrue(Files.exists(rootDir1)); Assert.assertTrue(Files.exists(rootDir2)); nonExistent = Files.createTempDirectory(target, "duff"); deleteDirectory(nonExistent); Assert.assertFalse(Files.exists(nonExistent)); // Since PROPS_A is alphabetically lower than PROPS_B, Y will come from PROPS_A Path dirA = createPropsDir(rootDir1, PROPS_A, FROM_A1, A1, FROM_A2, A2, X_D_OVERRIDES_A, X_FROM_A, Y_A_OVERRIDES_B, Y_FROM_A, Z_C_OVERRIDES_A, Z_FROM_A); createPropsDir(rootDir1, PROPS_B, FROM_B, B, Y_A_OVERRIDES_B, Y_FROM_B); // Since PROPS_C has a higher ordinal, Z will come from PROPS_A createPropsDir(rootDir1, PROPS_C, "config_ordinal", "500", Z_C_OVERRIDES_A, Z_FROM_C); // Since this config-source-root has a higher ordinal than rootDir1, X will be used from here createPropsDir(rootDir2, PROPS_D, X_D_OVERRIDES_A, X_FROM_D); NodeBuilder nb = builder.node(containerId); //Create some files in locations that should not be considered as properties for a config source root director // 1) in the root directory itself Files.write(rootDir1.resolve(NOT_AVAILABLE_ROOT_FILE), Collections.singletonList("Hello")); // 2) in a nested folder under one of the folders under the root dirctory createPropsDir(dirA, PROPS_A, NOT_AVAILABLE_NESTED_DIR_UNDER_A, "Hello"); nb.setup(String.format("%s:add(dir={root=true, path=\"%s\"})", ROOT_A, escapePath(rootDir1))); nb.setup(String.format("/path=mp-config-test:add(path=\"%s\")", escapePath(rootDir2.getParent()))); nb.setup(String.format("%s:add(dir={root=true, relative-to=mp-config-test, path=\"%s\"}, ordinal=300)", ROOT_B, rootDir2.getFileName())); nb.setup(String.format("%s:add(dir={root=true, path=\"%s\"})", ROOT_NON_EXISTENT, escapePath(nonExistent))); nb.teardown(String.format("%s:remove", ROOT_A)); nb.teardown(String.format("%s:remove", ROOT_B)); nb.teardown(String.format("%s:remove", ROOT_NON_EXISTENT)); nb.teardown("/path=mp-config-test:remove"); super.setup(managementClient, containerId); } private String escapePath(Path path) { String s = path.toString(); //Avoid problems with paths on Windows s = s.replace('\\', '/'); return s; } private Path createPropsDir(Path rootDir, String sourceName, String... props) throws IOException { Path sourceDir = rootDir.resolve(sourceName); Files.createDirectory(sourceDir); Assert.assertTrue(Files.exists(sourceDir)); for (int i = 0 ; i < props.length ; i += 2) { Path file = sourceDir.resolve(props[i]); Files.createFile(file); Assert.assertTrue(Files.exists(file)); Files.write(file, Collections.singletonList(props[i + 1])); } return sourceDir.toAbsolutePath().normalize(); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { super.tearDown(managementClient, containerId); deleteDirectory(rootDir1); deleteDirectory(rootDir2); } private void deleteDirectory(Path dir) throws IOException { if (dir != null && Files.exists(dir)) { Files.walkFileTree(dir, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return super.visitFile(file, attrs); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return super.postVisitDirectory(dir, exc); } }); } } }
8,119
47.915663
161
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source_provider/TestApplication.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source_provider; import jakarta.inject.Inject; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Application; import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_class.CustomConfigSource; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ @ApplicationPath("/custom-config-source-provider") public class TestApplication extends Application { @Path("/test") public static class Resource { @Inject @ConfigProperty(name = CustomConfigSource.PROP_NAME) String prop; @GET @Produces("text/plain") public Response doGet() { StringBuilder text = new StringBuilder(); text.append(CustomConfigSource.PROP_NAME + " = " + prop + "\n"); return Response.ok(text).build(); } } }
2,155
36.824561
120
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source_provider/ConfigSourceProviderFromClassTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source_provider; import java.net.URL; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.config.smallrye.AbstractMicroProfileConfigTestCase; import org.wildfly.test.integration.microprofile.config.smallrye.AssertUtils; import org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_class.CustomConfigSource; /** * Load a ConfigSource from a class (in a module). * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(SetupTask.class) public class ConfigSourceProviderFromClassTestCase extends AbstractMicroProfileConfigTestCase { @Deployment public static Archive<?> deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, "ConfigSourceProviderFromClassTestCase.war") .addClasses(TestApplication.class, TestApplication.Resource.class, AbstractMicroProfileConfigTestCase.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); return war; } @ArquillianResource private URL url; @Test public void testGetWithConfigProperties() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + "custom-config-source-provider/test")); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); AssertUtils.assertTextContainsProperty(text, CustomConfigSource.PROP_NAME, CustomConfigSource.PROP_VALUE); } } }
3,510
43.443038
124
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source_provider/CustomConfigSourceProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source_provider; import java.util.Arrays; import org.eclipse.microprofile.config.spi.ConfigSource; import org.eclipse.microprofile.config.spi.ConfigSourceProvider; import org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_class.CustomConfigSource; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ public class CustomConfigSourceProvider implements ConfigSourceProvider{ @Override public Iterable<ConfigSource> getConfigSources(ClassLoader classLoader) { return Arrays.asList(new CustomConfigSource()); } }
1,712
41.825
120
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/management/config_source_provider/SetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.management.config_source_provider; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import java.io.File; import java.io.IOException; import java.net.URL; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.module.util.TestModule; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; import org.wildfly.test.integration.microprofile.config.smallrye.management.config_source.from_class.CustomConfigSource; /** * Add a config-source-provider with a custom class in the microprofile-config subsystem. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ public class SetupTask implements ServerSetupTask { private static final String MODULE_NAME = "test.custom-config-source-provider"; private static TestModule testModule; @Override public void setup(ManagementClient managementClient, String s) throws Exception { URL url = ConfigSourceProviderFromClassTestCase.class.getResource("module.xml"); File moduleXmlFile = new File(url.toURI()); testModule = new TestModule(MODULE_NAME, moduleXmlFile); testModule.addResource("config-source-provider.jar") .addClass(CustomConfigSourceProvider.class) .addClass(CustomConfigSource.class); testModule.create(); addConfigSourceProvider(managementClient.getControllerClient()); } @Override public void tearDown(ManagementClient managementClient, String s) throws Exception { removeConfigSourceProvider(managementClient.getControllerClient()); testModule.remove(); ServerReload.reloadIfRequired(managementClient); } private void addConfigSourceProvider(ModelControllerClient client) throws IOException { ModelNode op; op = new ModelNode(); op.get(OP_ADDR).add(SUBSYSTEM, "microprofile-config-smallrye"); op.get(OP_ADDR).add("config-source-provider", "my-config-source-config_source_provider"); op.get(OP).set(ADD); op.get("class").get("module").set(MODULE_NAME); op.get("class").get("name").set(CustomConfigSourceProvider.class.getName()); client.execute(op); } private void removeConfigSourceProvider(ModelControllerClient client) throws IOException { ModelNode op; op = new ModelNode(); op.get(OP_ADDR).add(SUBSYSTEM, "microprofile-config-smallrye"); op.get(OP_ADDR).add("config-source-provider", "my-config-source-config_source_provider"); op.get(OP).set(REMOVE); client.execute(op); } }
4,168
43.351064
120
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/app/MicroProfileConfigTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.app; import static org.wildfly.test.integration.microprofile.config.smallrye.AssertUtils.assertTextContainsProperty; import java.net.URL; import java.util.Arrays; import java.util.LinkedList; import java.util.Optional; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.PermissionUtils; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.config.smallrye.AbstractMicroProfileConfigTestCase; import org.wildfly.test.integration.microprofile.config.smallrye.SubsystemConfigSourceTask; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. * @author Jan Stourac <[email protected]> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(SubsystemConfigSourceTask.class) public class MicroProfileConfigTestCase extends AbstractMicroProfileConfigTestCase { @Deployment public static Archive<?> deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, "MicroProfileConfigTestCase.war") .addClasses(TestApplication.class, AbstractMicroProfileConfigTestCase.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource(MicroProfileConfigTestCase.class.getPackage(), "microprofile-config.properties", "microprofile-config.properties") .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(createPermissions( "my.prop", "my.other.prop", SubsystemConfigSourceTask.MY_PROP_FROM_SUBSYSTEM_PROP_NAME, "optional.injected.prop.that.is.not.configured", "my.prop.from.meta", "node0", "MPCONFIG_TEST_ENV_VAR", "boolTrue", "bool1", "boolYes", "boolY", "boolOn", "boolDefault", SubsystemConfigSourceTask.BOOL_OVERRIDDEN_PROP_NAME, "booleanDefault", SubsystemConfigSourceTask.BOOLEAN_OVERRIDDEN_PROP_NAME, "intDefault", SubsystemConfigSourceTask.INT_OVERRIDDEN_PROP_NAME, "integerDefault", SubsystemConfigSourceTask.INTEGER_OVERRIDDEN_PROP_NAME, "intBadValue", "integerBadValue", "longDefault", SubsystemConfigSourceTask.LONG_OVERRIDDEN_PROP_NAME, "longClassDefault", SubsystemConfigSourceTask.LONG_CLASS_OVERRIDDEN_PROP_NAME, "longBadValue", "longClassBadValue", "floatDefault", SubsystemConfigSourceTask.FLOAT_OVERRIDDEN_PROP_NAME, "floatClassDefault", SubsystemConfigSourceTask.FLOAT_CLASS_OVERRIDDEN_PROP_NAME, "floatBadValue", "floatClassBadValue", "doubleDefault", SubsystemConfigSourceTask.DOUBLE_OVERRIDDEN_PROP_NAME, "doubleClassDefault", SubsystemConfigSourceTask.DOUBLE_CLASS_OVERRIDDEN_PROP_NAME, "doubleBadValue", "doubleClassBadValue", SubsystemConfigSourceTask.PROPERTIES_PROP_NAME0, SubsystemConfigSourceTask.PROPERTIES_PROP_NAME1, SubsystemConfigSourceTask.PROPERTIES_PROP_NAME2, SubsystemConfigSourceTask.PROPERTIES_PROP_NAME3, SubsystemConfigSourceTask.PROPERTIES_PROP_NAME4, SubsystemConfigSourceTask.PROPERTIES_PROP_NAME5, "myPets", "my.prop.never.defined", "my_prop_never_defined", "myPetsOverridden" )), "permissions.xml"); return war; } @ArquillianResource private URL url; private final String appContext = "microprofile"; /** * Check that we get default values for properties except for one, which should have value loaded from the * subsystem. There is also checked that property form META-INF file and also some System Property is loaded. * * @throws Exception */ @Test public void testGetWithConfigProperties() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + appContext + TestApplication.APP_PATH)); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); assertTextContainsProperty(text, "my.prop.never.defined", Optional.empty().toString()); assertTextContainsProperty(text, "my.prop", "BAR"); assertTextContainsProperty(text, "my.other.prop", false); assertTextContainsProperty(text, "optional.injected.prop.that.is.not.configured", Optional.empty().toString()); assertTextContainsProperty(text, SubsystemConfigSourceTask.MY_PROP_FROM_SUBSYSTEM_PROP_NAME, SubsystemConfigSourceTask.MY_PROP_FROM_SUBSYSTEM_PROP_VALUE); assertTextContainsProperty(text, "node0", System.getProperty("node0")); assertTextContainsProperty(text, "MPCONFIG_TEST_ENV_VAR", System.getenv("MPCONFIG_TEST_ENV_VAR")); } } /** * Check boolean/Boolean type is correctly handled in regards of the default values, no default values and if it is * overridden. * * @throws Exception */ @Test public void testGetBooleanProperties() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + appContext + TestApplication.BOOLEAN_APP_PATH)); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); assertTextContainsProperty(text, "boolTrue", true); assertTextContainsProperty(text, "bool1", true); assertTextContainsProperty(text, "boolYes", true); assertTextContainsProperty(text, "boolY", true); assertTextContainsProperty(text, "boolOn", true); assertTextContainsProperty(text, "boolDefault", true); assertTextContainsProperty(text, SubsystemConfigSourceTask.BOOL_OVERRIDDEN_PROP_NAME, true); assertTextContainsProperty(text, "booleanDefault", true); assertTextContainsProperty(text, SubsystemConfigSourceTask.BOOLEAN_OVERRIDDEN_PROP_NAME, true); } } /** * Check int/Integer type is correctly handled in regards of the default values, no default values and if it is * overridden. * * @throws Exception */ @Test public void testGetIntegerProperties() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + appContext + TestApplication.INTEGER_APP_PATH)); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); assertTextContainsProperty(text, "intDefault", -42); assertTextContainsProperty(text, SubsystemConfigSourceTask.INT_OVERRIDDEN_PROP_NAME, SubsystemConfigSourceTask.INTEGER_OVERRIDDEN_PROP_VALUE); assertTextContainsProperty(text, "integerDefault", -42); assertTextContainsProperty(text, SubsystemConfigSourceTask.INTEGER_OVERRIDDEN_PROP_NAME, SubsystemConfigSourceTask.INTEGER_OVERRIDDEN_PROP_VALUE); } } /** * Check long/Long type is correctly handled in regards of the default values, no default values and if it is * overridden. * * @throws Exception */ @Test public void testGetLongProperties() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + appContext + TestApplication.LONG_APP_PATH)); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); assertTextContainsProperty(text, "longDefault", -42); assertTextContainsProperty(text, SubsystemConfigSourceTask.LONG_OVERRIDDEN_PROP_NAME, SubsystemConfigSourceTask.LONG_OVERRIDDEN_PROP_VALUE); assertTextContainsProperty(text, "longClassDefault", -42); assertTextContainsProperty(text, SubsystemConfigSourceTask.LONG_CLASS_OVERRIDDEN_PROP_NAME, SubsystemConfigSourceTask.LONG_OVERRIDDEN_PROP_VALUE); } } /** * Check float/Float type is correctly handled in regards of the default values, no default values and if it is * overridden. * * @throws Exception */ @Test public void testGetFloatProperties() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + appContext + TestApplication.FLOAT_APP_PATH)); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); assertTextContainsProperty(text, "floatDefault", -3.14); assertTextContainsProperty(text, SubsystemConfigSourceTask.FLOAT_OVERRIDDEN_PROP_NAME, SubsystemConfigSourceTask.FLOAT_OVERRIDDEN_PROP_VALUE); assertTextContainsProperty(text, "floatClassDefault", Float.valueOf("-3.14e10")); assertTextContainsProperty(text, SubsystemConfigSourceTask.FLOAT_CLASS_OVERRIDDEN_PROP_NAME, SubsystemConfigSourceTask.FLOAT_OVERRIDDEN_PROP_VALUE); } } /** * Check double/Double type is correctly handled in regards of the default values, no default values and if it is * overridden. * * @throws Exception */ @Test public void testGetDoubleProperties() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + appContext + TestApplication.DOUBLE_APP_PATH)); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); assertTextContainsProperty(text, "doubleDefault", -3.14); assertTextContainsProperty(text, SubsystemConfigSourceTask.DOUBLE_OVERRIDDEN_PROP_NAME, SubsystemConfigSourceTask.DOUBLE_OVERRIDDEN_PROP_VALUE); assertTextContainsProperty(text, "doubleClassDefault", Double.valueOf("-3.14e10")); assertTextContainsProperty(text, SubsystemConfigSourceTask.DOUBLE_CLASS_OVERRIDDEN_PROP_NAME, SubsystemConfigSourceTask.DOUBLE_OVERRIDDEN_PROP_VALUE); } } /** * Check String array, List and Set properties are correctly handled in regards of the default values. * * @throws Exception */ @Test public void testGetWithArraySetListDefaultProperties() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + appContext + TestApplication.ARRAY_SET_LIST_DEFAULT_APP_PATH)); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); LinkedList<String> petsList = new LinkedList<>(); petsList.add("cat"); petsList.add("lama,yokohama"); assertTextContainsProperty(text, "myPets as String array", Arrays.toString(new String[]{"horse","monkey,donkey"})); assertTextContainsProperty(text, "myPets as String list", petsList); // order is not guaranteed for set so we test each set item individually assertTextContainsProperty(text, "myPets as String set", "dog", false); assertTextContainsProperty(text, "myPets as String set", "mouse,house", false); } } /** * Check String array, List and Set properties are correctly handled if their default values are overridden. * * @throws Exception */ @Test public void testGetWithArraySetListOverriddenProperties() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + appContext + TestApplication.ARRAY_SET_LIST_OVERRIDE_APP_PATH)); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); LinkedList<String> petsList = new LinkedList<>(); petsList.add("donkey"); petsList.add("shrek,fiona"); assertTextContainsProperty(text, "myPetsOverridden as String array", Arrays.toString(new String[] {"donkey", "shrek,fiona"})); assertTextContainsProperty(text, "myPetsOverridden as String list", petsList); // order is not guaranteed for set so we test each set item individually assertTextContainsProperty(text, "myPetsOverridden as String set", "donkey", false); assertTextContainsProperty(text, "myPetsOverridden as String set", "shrek,fiona", false); } } /** * Checks that properties with same names are loaded based on their priorities defined by their sources. * * @throws Exception */ @Test public void testPriorityOrderingProperties() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + appContext + TestApplication.PRIORITY_APP_PATH)); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); // Values from META-INF assertTextContainsProperty(text, SubsystemConfigSourceTask.PROPERTIES_PROP_NAME0, "Value prop0 from META-INF/microprofile-config.properties"); // TODO - enable this when https://issues.jboss.org/browse/WFWIP-60 is resolved //assertTextContainsProperty(text, SubsystemConfigSourceTask.PROPERTIES_PROP_NAME1, SubsystemConfigSourceTask.PROP1_VALUE); // Value from defined system property in subsystem overrided meta-inf assertTextContainsProperty(text, SubsystemConfigSourceTask.PROPERTIES_PROP_NAME2, SubsystemConfigSourceTask.PROP2_VALUE); // fileProperty has ordinal value 100, same as default for META-INF properties, thus system property should override this assertTextContainsProperty(text, SubsystemConfigSourceTask.PROPERTIES_PROP_NAME3, SubsystemConfigSourceTask.PROP3_VALUE); // dir property should override all in this case assertTextContainsProperty(text, SubsystemConfigSourceTask.PROPERTIES_PROP_NAME4, "priority.prop.4 value loaded via directory config-source fileProperty4"); // not defined anywhere... assertTextContainsProperty(text, SubsystemConfigSourceTask.PROPERTIES_PROP_NAME5, "Custom file property not defined!"); } } }
17,657
49.887608
168
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/app/TestApplication.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.app; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.Set; import jakarta.inject.Inject; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Application; import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.wildfly.test.integration.microprofile.config.smallrye.SubsystemConfigSourceTask; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. * @author Jan Stourac <[email protected]> */ @ApplicationPath("/microprofile") public class TestApplication extends Application { public static final String APP_PATH = "/simpleTest"; public static final String BOOLEAN_APP_PATH = "/booleanTest"; public static final String INTEGER_APP_PATH = "/integerTest"; public static final String LONG_APP_PATH = "/longTest"; public static final String FLOAT_APP_PATH = "/floatTest"; public static final String DOUBLE_APP_PATH = "/doubleTest"; public static final String ARRAY_SET_LIST_DEFAULT_APP_PATH = "/arraySetListDefaultTest"; public static final String ARRAY_SET_LIST_OVERRIDE_APP_PATH = "/arraySetListOverriddenTest"; public static final String ARRAY_SET_LIST_NO_DEF_APP_PATH = "/arraySetListNoDefTest"; public static final String PRIORITY_APP_PATH = "/priorityTest"; @Path(APP_PATH) public static class ResourceSimple { @Inject Config config; @Inject @ConfigProperty(name = "my.prop", defaultValue = "BAR") String prop1; @Inject @ConfigProperty(name = "my.other.prop", defaultValue = "no") boolean prop2; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.MY_PROP_FROM_SUBSYSTEM_PROP_NAME) String prop3; @Inject @ConfigProperty(name = "optional.injected.prop.that.is.not.configured") Optional<String> optionalProp; @Inject @ConfigProperty(name = "my.prop.from.meta", defaultValue = "Meta property not defined!") String metaProp; @Inject @ConfigProperty(name = "node0", defaultValue = "System property not defined!") String systemProperty; @Inject @ConfigProperty(name = "MPCONFIG_TEST_ENV_VAR", defaultValue = "Environment variable not defined!") String envVariable; @GET @Produces("text/plain") public Response doGet() { Optional<String> foo = config.getOptionalValue("my.prop.never.defined", String.class); StringBuilder text = new StringBuilder(); text.append("my.prop.never.defined = " + foo + "\n"); text.append("my.prop = " + prop1 + "\n"); text.append("my.other.prop = " + prop2 + "\n"); text.append("optional.injected.prop.that.is.not.configured = " + optionalProp + "\n"); text.append(SubsystemConfigSourceTask.MY_PROP_FROM_SUBSYSTEM_PROP_NAME + " = " + prop3 + "\n"); text.append("my.prop.from.meta = " + metaProp + "\n"); text.append("node0 = " + systemProperty + "\n"); text.append("MPCONFIG_TEST_ENV_VAR = " + envVariable + "\n"); return Response.ok(text).build(); } } @Path(BOOLEAN_APP_PATH) public static class ResourceBoolean { @Inject Config config; @Inject @ConfigProperty(name = "boolTrue", defaultValue = "true") private boolean boolTrue; @Inject @ConfigProperty(name = "bool1", defaultValue = "1") private boolean bool1; @Inject @ConfigProperty(name = "boolYes", defaultValue = "YES") private boolean boolYes; @Inject @ConfigProperty(name = "boolY", defaultValue = "Y") private boolean boolY; @Inject @ConfigProperty(name = "boolOn", defaultValue = "on") private boolean boolOn; @Inject @ConfigProperty(name = "boolDefault", defaultValue = "yes") private boolean boolDefault; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.BOOL_OVERRIDDEN_PROP_NAME, defaultValue = "badValue") private boolean boolOverridden; @Inject @ConfigProperty(name = "booleanDefault", defaultValue = "yes") private boolean booleanDefault; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.BOOLEAN_OVERRIDDEN_PROP_NAME, defaultValue = "badValue") private boolean booleanOverridden; @GET @Produces("text/plain") public Response doGet() { StringBuilder text = new StringBuilder(); text.append("boolTrue = " + boolTrue + "\n"); text.append("bool1 = " + bool1 + "\n"); text.append("boolYes = " + boolYes + "\n"); text.append("boolY = " + boolY + "\n"); text.append("boolOn = " + boolOn + "\n"); text.append("boolDefault = " + boolDefault + "\n"); text.append(SubsystemConfigSourceTask.BOOL_OVERRIDDEN_PROP_NAME + " = " + boolOverridden + "\n"); text.append("booleanDefault = " + booleanDefault + "\n"); text.append(SubsystemConfigSourceTask.BOOLEAN_OVERRIDDEN_PROP_NAME + " = " + booleanOverridden + "\n"); return Response.ok(text).build(); } } @Path(INTEGER_APP_PATH) public static class ResourceInteger { @Inject Config config; @Inject @ConfigProperty(name = "intDefault", defaultValue = "-42") private int intDefault; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.INT_OVERRIDDEN_PROP_NAME, defaultValue = "123") private int intOverridden; @Inject @ConfigProperty(name = "integerDefault", defaultValue = "-42") private Integer integerDefault; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.INTEGER_OVERRIDDEN_PROP_NAME, defaultValue = "123") private Integer integerOverridden; @GET @Produces("text/plain") public Response doGet() { StringBuilder text = new StringBuilder(); text.append("intDefault = " + intDefault + "\n"); text.append(SubsystemConfigSourceTask.INT_OVERRIDDEN_PROP_NAME + " = " + intOverridden + "\n"); text.append("integerDefault = " + integerDefault + "\n"); text.append(SubsystemConfigSourceTask.INTEGER_OVERRIDDEN_PROP_NAME + " = " + integerOverridden + "\n"); return Response.ok(text).build(); } } @Path(LONG_APP_PATH) public static class ResourceLong { @Inject Config config; @Inject @ConfigProperty(name = "longDefault", defaultValue = "-42") private long longDefault; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.LONG_OVERRIDDEN_PROP_NAME, defaultValue = "123") private long longOverridden; @Inject @ConfigProperty(name = "longClassDefault", defaultValue = "-42") private Long longClassDefault; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.LONG_CLASS_OVERRIDDEN_PROP_NAME, defaultValue = "123") private Long longClassOverridden; @GET @Produces("text/plain") public Response doGet() { StringBuilder text = new StringBuilder(); text.append("longDefault = " + longDefault + "\n"); text.append(SubsystemConfigSourceTask.LONG_OVERRIDDEN_PROP_NAME + " = " + longOverridden + "\n"); text.append("longClassDefault = " + longClassDefault + "\n"); text.append(SubsystemConfigSourceTask.LONG_CLASS_OVERRIDDEN_PROP_NAME + " = " + longClassOverridden + "\n"); return Response.ok(text).build(); } } @Path(FLOAT_APP_PATH) public static class ResourceFloat { @Inject Config config; @Inject @ConfigProperty(name = "floatDefault", defaultValue = "-3.14") private float floatDefault; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.FLOAT_OVERRIDDEN_PROP_NAME, defaultValue = "1.618") private float floatOverridden; @Inject @ConfigProperty(name = "floatClassDefault", defaultValue = "-3.14e10") private Float floatClassDefault; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.FLOAT_CLASS_OVERRIDDEN_PROP_NAME, defaultValue = "1.618") private Float floatClassOverridden; @GET @Produces("text/plain") public Response doGet() { StringBuilder text = new StringBuilder(); text.append("floatDefault = " + floatDefault + "\n"); text.append(SubsystemConfigSourceTask.FLOAT_OVERRIDDEN_PROP_NAME + " = " + floatOverridden + "\n"); text.append("floatClassDefault = " + floatClassDefault + "\n"); text.append(SubsystemConfigSourceTask.FLOAT_CLASS_OVERRIDDEN_PROP_NAME + " = " + floatClassOverridden + "\n"); return Response.ok(text).build(); } } @Path(DOUBLE_APP_PATH) public static class ResourceDouble { @Inject Config config; @Inject @ConfigProperty(name = "doubleDefault", defaultValue = "-3.14") private double doubleDefault; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.DOUBLE_OVERRIDDEN_PROP_NAME, defaultValue = "1.618") private double doubleOverridden; @Inject @ConfigProperty(name = "doubleClassDefault", defaultValue = "-3.14e10") private Double doubleClassDefault; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.DOUBLE_CLASS_OVERRIDDEN_PROP_NAME, defaultValue = "1.618") private Double doubleClassOverridden; @GET @Produces("text/plain") public Response doGet() { StringBuilder text = new StringBuilder(); text.append("doubleDefault = " + doubleDefault + "\n"); text.append(SubsystemConfigSourceTask.DOUBLE_OVERRIDDEN_PROP_NAME + " = " + doubleOverridden + "\n"); text.append("doubleClassDefault = " + doubleClassDefault + "\n"); text.append(SubsystemConfigSourceTask.DOUBLE_CLASS_OVERRIDDEN_PROP_NAME + " = " + doubleClassOverridden + "\n"); return Response.ok(text).build(); } } @Path(PRIORITY_APP_PATH) public static class ResourcePriority { @Inject Config config; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.PROPERTIES_PROP_NAME0, defaultValue = "Custom file property not defined!") String customFileProp0; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.PROPERTIES_PROP_NAME1, defaultValue = "Custom file property not defined!") String customFileProp1; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.PROPERTIES_PROP_NAME2, defaultValue = "Custom file property not defined!") String customFileProp2; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.PROPERTIES_PROP_NAME3, defaultValue = "Custom file property not defined!") String customFileProp3; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.PROPERTIES_PROP_NAME4, defaultValue = "Custom file property not defined!") String customFileProp4; @Inject @ConfigProperty(name = SubsystemConfigSourceTask.PROPERTIES_PROP_NAME5, defaultValue = "Custom file property not defined!") String customFileProp5; @GET @Produces("text/plain") public Response doGet() { StringBuilder text = new StringBuilder(); text.append(SubsystemConfigSourceTask.PROPERTIES_PROP_NAME0 + " = " + customFileProp0 + "\n"); text.append(SubsystemConfigSourceTask.PROPERTIES_PROP_NAME1 + " = " + customFileProp1 + "\n"); text.append(SubsystemConfigSourceTask.PROPERTIES_PROP_NAME2 + " = " + customFileProp2 + "\n"); text.append(SubsystemConfigSourceTask.PROPERTIES_PROP_NAME3 + " = " + customFileProp3 + "\n"); text.append(SubsystemConfigSourceTask.PROPERTIES_PROP_NAME4 + " = " + customFileProp4 + "\n"); text.append(SubsystemConfigSourceTask.PROPERTIES_PROP_NAME5 + " = " + customFileProp5 + "\n"); return Response.ok(text).build(); } } @Path(ARRAY_SET_LIST_DEFAULT_APP_PATH) public static class ResourceArraySetListDefaultProps { @Inject Config config; @Inject @ConfigProperty(name = "myPets", defaultValue = "horse,monkey\\,donkey") private String[] myArrayPets; @Inject @ConfigProperty(name = "myPets", defaultValue = "cat,lama\\,yokohama") private List<String> myListPets; @Inject @ConfigProperty(name = "myPets", defaultValue = "dog,mouse\\,house") private Set<String> mySetPets; @GET @Produces("text/plain") public Response doGet() { StringBuilder text = new StringBuilder(); text.append("myPets as String array = " + Arrays.toString(myArrayPets) + "\n"); text.append("myPets as String list = " + myListPets + "\n"); text.append("myPets as String set = " + mySetPets + "\n"); return Response.ok(text).build(); } } @Path(ARRAY_SET_LIST_OVERRIDE_APP_PATH) public static class ResourceArraySetListOverriddenProps { @Inject Config config; @Inject @ConfigProperty(name = "myPetsOverridden", defaultValue = "horse,monkey\\,donkey") private String[] myArrayPetsOverridden; @Inject @ConfigProperty(name = "myPetsOverridden", defaultValue = "cat,lama\\,yokohama") private List<String> myListPetsOverridden; @Inject @ConfigProperty(name = "myPetsOverridden", defaultValue = "dog,mouse\\,house") private Set<String> mySetPetsOverridden; @GET @Produces("text/plain") public Response doGet() { StringBuilder text = new StringBuilder(); text.append("myPetsOverridden as String array = " + Arrays.toString(myArrayPetsOverridden) + "\n"); text.append("myPetsOverridden as String list = " + myListPetsOverridden + "\n"); text.append("myPetsOverridden as String set = " + mySetPetsOverridden + "\n"); return Response.ok(text).build(); } } }
15,763
35.406467
131
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/converter/Return102Converter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.converter; import jakarta.annotation.Priority; import org.eclipse.microprofile.config.spi.Converter; /** * @author <a href="mailto:[email protected]">Michal Jurc</a> (c) 2018 Red Hat, Inc. */ @Priority(102) public class Return102Converter implements Converter<Integer> { @Override public Integer convert(String value) { return 102; } }
1,450
36.205128
83
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/converter/MicroProfileConfigConvertersTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.converter; import java.net.URL; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.PermissionUtils; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.config.smallrye.AbstractMicroProfileConfigTestCase; import org.wildfly.test.integration.microprofile.config.smallrye.AssertUtils; /** * @author <a href="mailto:[email protected]">Michal Jurc</a> (c) 2018 Red Hat, Inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(SetupTask.class) public class MicroProfileConfigConvertersTestCase extends AbstractMicroProfileConfigTestCase { @Deployment public static Archive<?> deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, "MicroProfileConfigConvertersTestCase.war") .addClasses(TestApplication.class, TestApplication.Resource.class, AbstractMicroProfileConfigTestCase.class, MyString.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addAsWebInfResource(TestApplication.class.getPackage(), "jboss-deployment-structure.xml", "jboss-deployment-structure.xml") .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(createPermissions( "int_converted_to_102_by_priority_of_custom_converter")), "permissions.xml"); return war; } @ArquillianResource private URL url; @Test public void testConverterPriority() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(url + "custom-converter/test")); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String text = EntityUtils.toString(response.getEntity()); AssertUtils.assertTextContainsProperty(text, "int_converted_to_102_by_priority_of_custom_converter", "102"); // TODO - enable this when https://issues.jboss.org/browse/WFWIP-60 is resolved //AssertUtils.assertTextContainsProperty(text, "string_converted_by_priority_of_custom_converter", "Property converted by HighPriorityStringConverter1"); } } }
4,005
47.26506
165
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/converter/MyString.java
package org.wildfly.test.integration.microprofile.config.smallrye.converter; /** * Simple String wrapper to avoid converting all Strings */ public class MyString { public String value; public static MyString from(String value) { MyString myString = new MyString(); myString.value = value; return myString; } }
351
21
76
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/converter/TestApplication.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.converter; import jakarta.inject.Inject; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Application; import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.config.inject.ConfigProperty; /** * @author <a href="mailto:[email protected]">Michal Jurc</a> (c) 2018 Red Hat, Inc. */ @ApplicationPath("/custom-converter") public class TestApplication extends Application { @Path("/test") public static class Resource { @Inject @ConfigProperty(name = "int_converted_to_102_by_priority_of_custom_converter", defaultValue = "42") int convertedTo102; @Inject @ConfigProperty(name = "string_converted_by_priority_of_custom_converter", defaultValue = "I should not be here") MyString convertedString; @GET @Produces("text/plain") public Response doGet() { StringBuilder sb = new StringBuilder(); sb.append("int_converted_to_102_by_priority_of_custom_converter = " + convertedTo102 + "\n"); sb.append("string_converted_by_priority_of_custom_converter = " + convertedString.value + "\n"); return Response.ok(sb).build(); } } }
2,364
37.145161
121
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/converter/HighPriorityMyStringConverter2.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.converter; import jakarta.annotation.Priority; import org.eclipse.microprofile.config.spi.Converter; /** * @author <a href="mailto:[email protected]">Michal Jurc</a> (c) 2018 Red Hat, Inc. */ @Priority(101) public class HighPriorityMyStringConverter2 implements Converter<MyString> { @Override public MyString convert(String value) { return !value.isEmpty() ? MyString.from("Property converted by HighPriorityStringConverter2") : null; } }
1,554
38.871795
109
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/converter/HighPriorityMyStringConverter1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.converter; import jakarta.annotation.Priority; import org.eclipse.microprofile.config.spi.Converter; /** * @author <a href="mailto:[email protected]">Michal Jurc</a> (c) 2018 Red Hat, Inc. */ @Priority(101) public class HighPriorityMyStringConverter1 implements Converter<MyString> { @Override public MyString convert(String value) { return !value.isEmpty() ? MyString.from("Property converted by HighPriorityStringConverter1") : null; } }
1,555
37.9
109
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/converter/Return101Converter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.converter; import jakarta.annotation.Priority; import org.eclipse.microprofile.config.spi.Converter; /** * @author <a href="mailto:[email protected]">Michal Jurc</a> (c) 2018 Red Hat, Inc. */ @Priority(101) public class Return101Converter implements Converter<Integer> { @Override public Integer convert(String value) { return 101; } }
1,450
36.205128
83
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/config/smallrye/converter/SetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.config.smallrye.converter; import java.io.File; import java.io.FileOutputStream; import java.net.URL; import org.eclipse.microprofile.config.spi.Converter; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.module.util.TestModule; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; /** * Add a config-source with a custom class in the microprofile-config subsystem. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ public class SetupTask implements ServerSetupTask { private static final String TEST_MODULE_NAME = "test.custom-config-converters"; private static TestModule testModule; @Override public void setup(ManagementClient managementClient, String s) throws Exception { final File archiveDir = new File("target/archives"); archiveDir.mkdirs(); File moduleFile = new File(archiveDir, "config-converters.jar"); JavaArchive configSourceServiceLoad = ShrinkWrap.create(JavaArchive.class, "config-converters.jar") .addClasses(Return101Converter.class, Return102Converter.class, HighPriorityMyStringConverter1.class, HighPriorityMyStringConverter2.class, MyString.class) .addAsServiceProvider(Converter.class, Return101Converter.class, Return102Converter.class, HighPriorityMyStringConverter1.class, HighPriorityMyStringConverter2.class); URL url = MicroProfileConfigConvertersTestCase.class.getResource("module.xml"); File moduleXmlFile = new File(url.toURI()); try (FileOutputStream target = new FileOutputStream(moduleFile)) { configSourceServiceLoad.as(ZipExporter.class).exportTo(target); } testModule = new TestModule(TEST_MODULE_NAME, moduleXmlFile); testModule.addJavaArchive(moduleFile); testModule.create(); } @Override public void tearDown(ManagementClient managementClient, String s) throws Exception { testModule.remove(); final File archiveDir = new File("target/archives"); cleanFile(archiveDir); } private static void cleanFile(File toClean) { if (toClean.exists()) { if (toClean.isDirectory()) { for (File child : toClean.listFiles()) { cleanFile(child); } } toClean.delete(); } } }
3,652
40.988506
117
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/EnableReactiveExtensionsSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive; import java.util.List; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.dmr.ModelNode; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class EnableReactiveExtensionsSetupTask extends CLIServerSetupTask { private static final String MODULE_REACTIVE_MESSAGING = "org.wildfly.extension.microprofile.reactive-messaging-smallrye"; private static final String MODULE_REACTIVE_STREAMS_OPERATORS = "org.wildfly.extension.microprofile.reactive-streams-operators-smallrye"; private static final String SUBSYSTEM_REACTIVE_MESSAGING = "microprofile-reactive-messaging-smallrye"; private static final String SUBSYSTEM_REACTIVE_STREAMS_OPERATORS = "microprofile-reactive-streams-operators-smallrye"; public EnableReactiveExtensionsSetupTask() { } @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { boolean rsoExt = !containsChild(managementClient, "extension", MODULE_REACTIVE_STREAMS_OPERATORS); boolean rsoSs = !containsChild(managementClient, "extension", SUBSYSTEM_REACTIVE_STREAMS_OPERATORS); boolean rmExt = !containsChild(managementClient, "extension", MODULE_REACTIVE_MESSAGING); boolean rmSs = !containsChild(managementClient, "extension", SUBSYSTEM_REACTIVE_MESSAGING); NodeBuilder nb = this.builder.node(containerId); if (rsoExt) { nb.setup("/extension=%s:add", MODULE_REACTIVE_STREAMS_OPERATORS); } if (rmExt) { nb.setup("/extension=%s:add", MODULE_REACTIVE_MESSAGING); } if (rsoSs) { nb.setup("/subsystem=%s:add", SUBSYSTEM_REACTIVE_STREAMS_OPERATORS); } if (rmSs) { nb.setup("/subsystem=%s:add", SUBSYSTEM_REACTIVE_MESSAGING); } if (rmSs) { nb.teardown("/subsystem=%s:remove", SUBSYSTEM_REACTIVE_MESSAGING); } if (rsoSs) { nb.teardown("/subsystem=%s:remove", SUBSYSTEM_REACTIVE_STREAMS_OPERATORS); } if (rmExt) { nb.teardown("/extension=%s:remove", MODULE_REACTIVE_MESSAGING); } if (rsoSs) { nb.teardown("/extension=%s:remove", MODULE_REACTIVE_STREAMS_OPERATORS); } super.setup(managementClient, containerId); } private boolean containsChild(ManagementClient managementClient, String childType, String childName) throws Exception { ModelNode op = new ModelNode(); op.get("operation").set("read-children-names"); op.get("child-type").set(childType); ModelNode result = managementClient.getControllerClient().execute(op); if (!result.get("outcome").asString().equals("success")) { throw new IllegalStateException(result.asString()); } List<ModelNode> names = result.get("result").asList(); for (ModelNode name : names) { if (name.asString().equals(childName)) { return true; } } return false; } }
4,195
43.168421
141
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/RunKafkaSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive; import io.smallrye.reactive.messaging.kafka.companion.KafkaCompanion; import io.smallrye.reactive.messaging.kafka.companion.test.EmbeddedKafkaBroker; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.wildfly.security.manager.WildFlySecurityManager; import java.security.PrivilegedAction; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.Map; import java.util.Properties; import java.util.logging.Logger; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class RunKafkaSetupTask implements ServerSetupTask { volatile EmbeddedKafkaBroker broker; volatile KafkaCompanion companion; final boolean ipv6 = WildFlySecurityManager.doChecked( (PrivilegedAction<Boolean>) () -> System.getProperties().containsKey("ipv6")); protected final String LOOPBACK = ipv6 ? "[::1]" : "127.0.0.1"; private final Logger logger = Logger.getLogger("RunKafkaSetupTask"); @Override public void setup(ManagementClient managementClient, String s) throws Exception { try { broker = new EmbeddedKafkaBroker() .withNodeId(0) .withKafkaPort(9092) .withDeleteLogDirsOnClose(true); broker.withAdditionalProperties(props -> addBrokerProperties(props)); broker = augmentKafkaBroker(broker); broker.start(); companion = new KafkaCompanion(broker.getAdvertisedListeners()); for (Map.Entry<String, Integer> topicAndPartition : getTopicsAndPartitions().entrySet()) { companion.topics().createAndWait(topicAndPartition.getKey(), topicAndPartition.getValue(), Duration.of(10, ChronoUnit.SECONDS)); } } catch (Exception e) { try { if (companion != null) { companion.close(); } if (broker != null) { broker.close(); } } finally { throw e; } } } protected EmbeddedKafkaBroker augmentKafkaBroker(EmbeddedKafkaBroker broker) { return broker; } protected void addBrokerProperties(Properties brokerProperties) { } protected Map<String, Integer> getTopicsAndPartitions() { return Collections.singletonMap("testing", 1); } // protected String[] getTopics() { // return new String[]{"testing"}; // } // // protected int getPartitions() { // return 1; // } @Override public void tearDown(ManagementClient managementClient, String s) throws Exception { if (companion != null) { companion.close(); } if (broker != null) { broker.close(); } } }
3,971
33.842105
144
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/streams/operators/ReactiveStreamsOperatorsNoReactiveEngineProviderSanityTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.streams.operators; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.io.FilePermission; import java.util.List; import java.util.concurrent.CompletionStage; import java.util.stream.Collectors; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @RunWith(Arquillian.class) @ServerSetup(EnableReactiveExtensionsSetupTask.class) public class ReactiveStreamsOperatorsNoReactiveEngineProviderSanityTestCase { @Deployment public static WebArchive getDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "rx-stream-ops.war") .addClass(ReactiveStreamsOperatorsNoReactiveEngineProviderSanityTestCase.class) .addClasses(EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class) .addAsManifestResource(createPermissionsXmlAsset( new FilePermission("<<ALL FILES>>", "read") ), "permissions.xml"); return webArchive; } @Test public void testReactiveApi() throws Exception { CompletionStage<List<String>> cs = ReactiveStreams.of("this", "is", "only", "a", "test") .map(String::toUpperCase) // Transform the words .filter(s -> s.length() > 3) // Filter items .collect(Collectors.toList()) .run(); List<String> result = cs.toCompletableFuture().get(); Assert.assertEquals(3, result.size()); Assert.assertEquals("THIS", result.get(0)); Assert.assertEquals("ONLY", result.get(1)); Assert.assertEquals("TEST", result.get(2)); } }
3,317
41
106
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/streams/operators/ReactiveStreamsOperatorsInjectedReactiveEngineProviderSanityTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.streams.operators; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.io.FilePermission; import java.util.List; import java.util.concurrent.CompletionStage; import java.util.stream.Collectors; import jakarta.inject.Inject; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.eclipse.microprofile.reactive.streams.operators.spi.ReactiveStreamsEngine; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @RunWith(Arquillian.class) @ServerSetup(EnableReactiveExtensionsSetupTask.class) public class ReactiveStreamsOperatorsInjectedReactiveEngineProviderSanityTestCase { @Inject ReactiveStreamsEngine engine; @Deployment public static WebArchive getDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "rx-stream-ops.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClass(ReactiveStreamsOperatorsInjectedReactiveEngineProviderSanityTestCase.class) .addClasses(EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class) .addAsManifestResource(createPermissionsXmlAsset( new FilePermission("<<ALL FILES>>", "read") ), "permissions.xml"); return webArchive; } @Test public void testReactiveApiWithInjectedEngine() throws Exception { Assert.assertNotNull(engine); CompletionStage<List<String>> cs = ReactiveStreams.of("this", "is", "only", "a", "test") .map(String::toUpperCase) // Transform the words .filter(s -> s.length() > 3) // Filter items .collect(Collectors.toList()) .run(engine); List<String> result = cs.toCompletableFuture().get(); Assert.assertEquals(3, result.size()); Assert.assertEquals("THIS", result.get(0)); Assert.assertEquals("ONLY", result.get(1)); Assert.assertEquals("TEST", result.get(2)); } }
3,677
40.325843
106
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/api/InDepthMetadataBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.api; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.CountDownLatch; import jakarta.enterprise.context.ApplicationScoped; import org.apache.kafka.common.header.internals.RecordHeader; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.reactivestreams.Publisher; import io.smallrye.reactive.messaging.kafka.api.IncomingKafkaRecordMetadata; import io.smallrye.reactive.messaging.kafka.api.KafkaMetadataUtil; import io.smallrye.reactive.messaging.kafka.api.OutgoingKafkaRecordMetadata; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ApplicationScoped public class InDepthMetadataBean { private final CountDownLatch latch = new CountDownLatch(6); private final Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> metadatas = Collections.synchronizedMap(new HashMap<>()); private final Instant timestampEntry5Topic1 = Instant.now().minus(Duration.ofSeconds(10)).truncatedTo(ChronoUnit.SECONDS); public CountDownLatch getLatch() { return latch; } public Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> getMetadatas() { return metadatas; } public Instant getTimestampEntry5Topic1() { return timestampEntry5Topic1; } @Outgoing("invm1") public Publisher<Integer> source() { return ReactiveStreams.of(1, 2, 3, 4, 5, 6).buildRs(); } @Incoming("invm1") @Outgoing("to-kafka1") public Message<Integer> sendToKafka(Integer i) { Message<Integer> msg = Message.of(i); if (i <= 5) { // For 6 we don't want any metadata. If we want to tweak what is set in the metadata use another entry OutgoingKafkaRecordMetadata.OutgoingKafkaRecordMetadataBuilder<String> mb = OutgoingKafkaRecordMetadata.<String>builder() .withKey("KEY-" + i); if (i == 5) { mb.withHeaders(Collections.singletonList(new RecordHeader("simple", new byte[]{0, 1, 2}))); mb.withTimestamp(timestampEntry5Topic1); } msg = KafkaMetadataUtil.writeOutgoingKafkaMetadata(msg, mb.build()); return msg; } return msg; } @Incoming("from-kafka1") public CompletionStage<Void> receiveFromKafka(Message<Integer> msg) { IncomingKafkaRecordMetadata<String, Integer> metadata = KafkaMetadataUtil.readIncomingKafkaMetadata(msg).get(); metadatas.put(msg.getPayload(), metadata); latch.countDown(); return msg.ack(); } }
4,013
38.742574
134
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/api/ReactiveMessagingKafkaUserApiTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.api; import io.smallrye.reactive.messaging.kafka.api.IncomingKafkaRecordMetadata; import jakarta.inject.Inject; import kafka.server.KafkaConfig; import org.apache.kafka.common.header.Header; import org.apache.kafka.common.header.Headers; import org.apache.kafka.common.record.TimestampType; import org.eclipse.microprofile.reactive.messaging.Message; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; import org.wildfly.test.integration.microprofile.reactive.RunKafkaSetupTask; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import java.util.PropertyPermission; import java.util.Set; import java.util.concurrent.TimeUnit; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @RunWith(Arquillian.class) @ServerSetup({ReactiveMessagingKafkaUserApiTestCase.CustomRunKafkaSetupTask.class, EnableReactiveExtensionsSetupTask.class}) public class ReactiveMessagingKafkaUserApiTestCase { private static final long TIMEOUT = TimeoutUtil.adjust(15000); @Inject InDepthMetadataBean inDepthMetadataBean; @Inject ConfiguredToSendToTopicAndOverrideTopicForSomeMessagesBean configuredToSendToTopicAndOverrideTopicForSomeMessagesBean; @Inject NoTopicSetupOverrideForAllMessagesBean noTopicSetupOverrideForAllMessagesBean; @Inject SpecifyPartitionBean specifyPartitionBean; @Deployment public static WebArchive getDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "reactive-messaging-kafka-user-api.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addPackage(ReactiveMessagingKafkaUserApiTestCase.class.getPackage()) .addClasses(RunKafkaSetupTask.class, EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class) .addAsWebInfResource(ReactiveMessagingKafkaUserApiTestCase.class.getPackage(), "microprofile-config.properties", "classes/META-INF/microprofile-config.properties") .addClass(TimeoutUtil.class) .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read") ), "permissions.xml"); return webArchive; } /* * This tests that: * - incoming Metadata is set (also for entry 6 which did not set any metadata) and contains the topic * - the key is propagated from what was set in the outgoing metadata, and that it may be null when not set * - Headers are propagated, if set in the outgoing metadata * - offsets are unique per partition * - the timestamp and type are set, and that the timestamp matches if we set it ourselves in the outgoing metadata */ @Test public void testOutgoingAndIncomingMetadataExtensively() throws InterruptedException { inDepthMetadataBean.getLatch().await(TIMEOUT, TimeUnit.MILLISECONDS); Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> map = inDepthMetadataBean.getMetadatas(); Assert.assertEquals(6, map.size()); Map<Integer, Set<Long>> offsetsByPartition = new HashMap<>(); for (int i = 1; i <= 6; i++) { IncomingKafkaRecordMetadata metadata = map.get(i); Assert.assertNotNull(metadata); if (i != 6) { Assert.assertEquals("KEY-" + i, metadata.getKey()); } else { Assert.assertNull(metadata.getKey()); } Assert.assertEquals("testing1", metadata.getTopic()); Set<Long> offsets = offsetsByPartition.get(metadata.getPartition()); if (offsets == null) { offsets = new HashSet<>(); offsetsByPartition.put(metadata.getPartition(), offsets); } offsets.add(metadata.getOffset()); Assert.assertNotNull(metadata.getTimestamp()); if (i == 5) { Assert.assertEquals(inDepthMetadataBean.getTimestampEntry5Topic1(), metadata.getTimestamp()); } Assert.assertEquals(TimestampType.CREATE_TIME, metadata.getTimestampType()); Assert.assertNotNull(metadata.getRecord()); Headers headers = metadata.getHeaders(); if (i != 5) { Assert.assertEquals(0, headers.toArray().length); } else { Assert.assertEquals(1, headers.toArray().length); Header header = headers.toArray()[0]; Assert.assertEquals("simple", header.key()); Assert.assertArrayEquals(new byte[]{0, 1, 2}, header.value()); } } Assert.assertEquals(6, checkOffsetsByPartitionAndCalculateTotalEntries(offsetsByPartition)); } private int checkOffsetsByPartitionAndCalculateTotalEntries(Map<Integer, Set<Long>> offsetsByPartition) { int total = 0; for (Iterator<Set<Long>> it = offsetsByPartition.values().iterator(); it.hasNext() ; ) { Set<Long> offsets = it.next(); long size = offsets.size(); total += size; for (long l = 0; l < size; l++) { Assert.assertTrue(offsets.contains(l)); } } return total; } /* * The outgoing method is configured to send to a given topic. We test that we can successfully set this topic via metadata */ @Test public void testOverrideDefaultTopicWhenOneIsSetInTheConfig() throws InterruptedException { configuredToSendToTopicAndOverrideTopicForSomeMessagesBean.getLatch().await(TIMEOUT, TimeUnit.MILLISECONDS); Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> map2 = configuredToSendToTopicAndOverrideTopicForSomeMessagesBean.getTesting2Metadatas(); Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> map3 = configuredToSendToTopicAndOverrideTopicForSomeMessagesBean.getTesting3Metadatas(); Assert.assertEquals(2, map2.size()); Assert.assertEquals(2, map3.size()); // Do some less in-depth checks here, than in the testIncomingMetadata() method, focussing on what we have set for (int i = 1; i <= 2; i++) { IncomingKafkaRecordMetadata metadata = map2.get(i); Assert.assertNotNull(metadata); Assert.assertEquals("testing2", metadata.getTopic()); } for (int i = 3; i <= 4; i++) { IncomingKafkaRecordMetadata metadata = map3.get(i); Assert.assertNotNull(metadata); Assert.assertEquals("testing3", metadata.getTopic()); } } /* * The outgoing method doesn't have any topic configured. We test that we can successfully set this topic via metadata */ @Test public void testNoTopicConfiguredOverrideForAllMessages() throws InterruptedException { noTopicSetupOverrideForAllMessagesBean.getLatch().await(TIMEOUT, TimeUnit.MILLISECONDS); Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> map4 = noTopicSetupOverrideForAllMessagesBean.getTesting4Metadatas(); Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> map5 = noTopicSetupOverrideForAllMessagesBean.getTesting5Metadatas(); Assert.assertEquals(3, map4.size()); Assert.assertEquals(3, map5.size()); // Do some less in-depth checks here, than in the testIncomingMetadata() method, focussing on what we have set for (int i = 1; i <= 6; i += 2) { IncomingKafkaRecordMetadata metadata = map4.get(i); Assert.assertNotNull(metadata); Assert.assertEquals("testing4", metadata.getTopic()); } for (int i = 2; i <= 5; i += 2) { IncomingKafkaRecordMetadata metadata = map5.get(i); Assert.assertNotNull(metadata); Assert.assertEquals("testing5", metadata.getTopic()); } } /* * The first 10 messages are assigned the partition by the partitioner - the last 10 specify it in the metadata. * There are two sets of each - the first specifies 1 as the partition for the specified ones, the second does 2. */ @Test public void testSpecifyPartition() throws InterruptedException { specifyPartitionBean.getLatch().await(TIMEOUT, TimeUnit.MILLISECONDS); checkSpecifiedPartitionMetadatas( specifyPartitionBean.getNoPartitionSpecifiedMetadatas6(), specifyPartitionBean.getPartitionSpecifiedMetadatas6(), 1); checkSpecifiedPartitionMetadatas( specifyPartitionBean.getNoPartitionSpecifiedMetadatas7(), specifyPartitionBean.getPartitionSpecifiedMetadatas7(), 0); } private void checkSpecifiedPartitionMetadatas( Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> unspecifiedPartitions, Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> specifiedPartitions, int expectedSpecifiedPartition) { Assert.assertEquals(10, unspecifiedPartitions.size()); Assert.assertEquals(10, specifiedPartitions.size()); Set<Integer> partitionsSeen6 = new HashSet<>(); for (int i = 1; i <= 10; i++) { IncomingKafkaRecordMetadata metadata = unspecifiedPartitions.get(i); Assert.assertNotNull(metadata); partitionsSeen6.add(metadata.getPartition()); } // The partitioner spreads these records over the two partitions that seem to be created // I am missing the magic to be able to control how many partitions are set up by the embedded server, // currently there are two. If this check becomes problematic it can be removed Assert.assertTrue(partitionsSeen6.toString(), partitionsSeen6.size() > 1); for (int i = 11; i <= 20; i++) { IncomingKafkaRecordMetadata metadata = specifiedPartitions.get(i); Assert.assertNotNull(metadata); Assert.assertEquals(expectedSpecifiedPartition, metadata.getPartition()); } } // For debugging only, as and when needed static String metadataToString(IncomingKafkaRecordMetadata metadata, Message<?> msg) { return "=====> \n" + "Key: " + metadata.getKey() + "\n" + "Topic: " + metadata.getTopic() + "\n" + "Offset: " + metadata.getOffset() + "\n" + "Partition: " + metadata.getPartition() + "\n" + "Timestamp: " + metadata.getTimestamp() + "\n" + "TimestampType" + metadata.getTimestampType() + "\n" + "Payload: " + msg.getPayload(); } public static class CustomRunKafkaSetupTask extends RunKafkaSetupTask { @Override protected void addBrokerProperties(Properties brokerProperties) { brokerProperties.put(KafkaConfig.NumPartitionsProp(), String.valueOf(getPartitions())); } @Override protected Map<String, Integer> getTopicsAndPartitions() { Map<String, Integer> map = new LinkedHashMap<>(); map.put("testing1", 2); map.put("testing2", 2); map.put("testing3", 2); map.put("testing4", 2); map.put("testing5", 2); map.put("testing6", 2); return map; } //@Override protected int getPartitions() { // Doesn't seem to have any effect. Perhaps that will change in the future return 12; } } }
13,371
44.638225
179
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/api/ConfiguredToSendToTopicAndOverrideTopicForSomeMessagesBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.api; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.CountDownLatch; import jakarta.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.reactivestreams.Publisher; import io.smallrye.reactive.messaging.kafka.api.IncomingKafkaRecordMetadata; import io.smallrye.reactive.messaging.kafka.api.KafkaMetadataUtil; import io.smallrye.reactive.messaging.kafka.api.OutgoingKafkaRecordMetadata; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ApplicationScoped public class ConfiguredToSendToTopicAndOverrideTopicForSomeMessagesBean { private final CountDownLatch latch = new CountDownLatch(4); private final Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> testing2Metadatas = Collections.synchronizedMap(new HashMap<>()); private final Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> testing3Metadatas = Collections.synchronizedMap(new HashMap<>()); public CountDownLatch getLatch() { return latch; } public Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> getTesting2Metadatas() { return testing2Metadatas; } public Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> getTesting3Metadatas() { return testing3Metadatas; } @Outgoing("invm2") public Publisher<Integer> source() { return ReactiveStreams.of(1, 2, 3, 4).buildRs(); } @Incoming("invm2") @Outgoing("to-kafka2or3-default-to-2") public Message<Integer> sendToKafka2or3(Integer i) { Message<Integer> msg = Message.of(i); OutgoingKafkaRecordMetadata.OutgoingKafkaRecordMetadataBuilder<String> mb = OutgoingKafkaRecordMetadata.<String>builder(); if (i % 2 == 0) { // Only set the key for half the messages mb.withKey("KEY-" + i); } if (i >= 3) { mb.withTopic("testing3"); } msg = KafkaMetadataUtil.writeOutgoingKafkaMetadata(msg, mb.build()); return msg; } // Messages which did not have the topic set in the metadata should end up here // (as this is the topic set up in the MP Config) @Incoming("from-kafka2") public CompletionStage<Void> receiveFromKafka2(Message<Integer> msg) { IncomingKafkaRecordMetadata<String, Integer> metadata = KafkaMetadataUtil.readIncomingKafkaMetadata(msg).get(); testing2Metadatas.put(msg.getPayload(), metadata); latch.countDown(); return msg.ack(); } // Messages which had the topic set in the metadata should end up here @Incoming("from-kafka3") public CompletionStage<Void> receiveFromKafka3(Message<Integer> msg) { IncomingKafkaRecordMetadata<String, Integer> metadata = KafkaMetadataUtil.readIncomingKafkaMetadata(msg).get(); testing3Metadatas.put(msg.getPayload(), metadata); latch.countDown(); return msg.ack(); } }
4,334
39.138889
142
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/api/NoTopicSetupOverrideForAllMessagesBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.api; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.CountDownLatch; import jakarta.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.reactivestreams.Publisher; import io.smallrye.reactive.messaging.kafka.api.IncomingKafkaRecordMetadata; import io.smallrye.reactive.messaging.kafka.api.KafkaMetadataUtil; import io.smallrye.reactive.messaging.kafka.api.OutgoingKafkaRecordMetadata; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ApplicationScoped public class NoTopicSetupOverrideForAllMessagesBean { private final CountDownLatch latch = new CountDownLatch(6); private final Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> testing4Metadatas = Collections.synchronizedMap(new HashMap<>()); private final Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> testing5Metadatas = Collections.synchronizedMap(new HashMap<>()); public CountDownLatch getLatch() { return latch; } public Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> getTesting4Metadatas() { return testing4Metadatas; } public Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> getTesting5Metadatas() { return testing5Metadatas; } @Outgoing("invm4") public Publisher<Integer> source1() { return ReactiveStreams.of(1, 2, 3, 4, 5, 6).buildRs(); } @Incoming("invm4") @Outgoing("to-kafka4or5") public Message<Integer> sendToKafka4or5(Integer i) { Message<Integer> msg = Message.of(i); String topic = "testing" + ((i % 2 == 0) ? "5" : "4"); System.out.println("-----> Sending to " + topic); OutgoingKafkaRecordMetadata.OutgoingKafkaRecordMetadataBuilder<String> mb = OutgoingKafkaRecordMetadata.<String>builder() .withKey("KEY-" + i) .withTopic(topic); msg = KafkaMetadataUtil.writeOutgoingKafkaMetadata(msg, mb.build()); return msg; } @Incoming("from-kafka4") public CompletionStage<Void> receiveFromKafka4(Message<Integer> msg) { IncomingKafkaRecordMetadata<String, Integer> metadata = KafkaMetadataUtil.readIncomingKafkaMetadata(msg).get(); testing4Metadatas.put(msg.getPayload(), metadata); latch.countDown(); return msg.ack(); } @Incoming("from-kafka5") public CompletionStage<Void> receiveFromKafka5(Message<Integer> msg) { IncomingKafkaRecordMetadata<String, Integer> metadata = KafkaMetadataUtil.readIncomingKafkaMetadata(msg).get(); testing5Metadatas.put(msg.getPayload(), metadata); latch.countDown(); return msg.ack(); } }
4,093
38.365385
142
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/api/SpecifyPartitionBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.api; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.CountDownLatch; import jakarta.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.reactivestreams.Publisher; import io.smallrye.reactive.messaging.kafka.api.IncomingKafkaRecordMetadata; import io.smallrye.reactive.messaging.kafka.api.KafkaMetadataUtil; import io.smallrye.reactive.messaging.kafka.api.OutgoingKafkaRecordMetadata; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ApplicationScoped public class SpecifyPartitionBean { private final CountDownLatch latch = new CountDownLatch(40); private final Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> noPartitionSpecifiedMetadatas6 = Collections.synchronizedMap(new HashMap<>()); private final Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> partitionSpecifiedMetadatas6 = Collections.synchronizedMap(new HashMap<>()); private final Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> noPartitionSpecifiedMetadatas7 = Collections.synchronizedMap(new HashMap<>()); private final Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> partitionSpecifiedMetadatas7 = Collections.synchronizedMap(new HashMap<>()); public CountDownLatch getLatch() { return latch; } public Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> getNoPartitionSpecifiedMetadatas6() { return noPartitionSpecifiedMetadatas6; } public Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> getPartitionSpecifiedMetadatas6() { return partitionSpecifiedMetadatas6; } public Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> getNoPartitionSpecifiedMetadatas7() { return noPartitionSpecifiedMetadatas7; } public Map<Integer, IncomingKafkaRecordMetadata<String, Integer>> getPartitionSpecifiedMetadatas7() { return partitionSpecifiedMetadatas7; } @Outgoing("invm6") public Publisher<Integer> source6() { return ReactiveStreams.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20).buildRs(); } @Incoming("invm6") @Outgoing("to-kafka6") public Message<Integer> sendToKafka6(Integer i) { Message<Integer> msg = Message.of(i); OutgoingKafkaRecordMetadata.OutgoingKafkaRecordMetadataBuilder<String> mb = OutgoingKafkaRecordMetadata.<String>builder() .withKey("KEY-" + i); if (i > 10) { mb.withPartition(1); } msg = KafkaMetadataUtil.writeOutgoingKafkaMetadata(msg, mb.build()); return msg; } @Incoming("from-kafka6") public CompletionStage<Void> receiveFromKafka6(Message<Integer> msg) { IncomingKafkaRecordMetadata<String, Integer> metadata = KafkaMetadataUtil.readIncomingKafkaMetadata(msg).get(); if (msg.getPayload() <= 10) { noPartitionSpecifiedMetadatas6.put(msg.getPayload(), metadata); } else { partitionSpecifiedMetadatas6.put(msg.getPayload(), metadata); } latch.countDown(); return msg.ack(); } @Outgoing("invm7") public Publisher<Integer> source7() { return ReactiveStreams.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20).buildRs(); } @Incoming("invm7") @Outgoing("to-kafka7") public Message<Integer> sendToKafka7(Integer i) { Message<Integer> msg = Message.of(i); OutgoingKafkaRecordMetadata.OutgoingKafkaRecordMetadataBuilder<String> mb = OutgoingKafkaRecordMetadata.<String>builder() .withKey("KEY-" + i); if (i > 10) { mb.withPartition(0); } msg = KafkaMetadataUtil.writeOutgoingKafkaMetadata(msg, mb.build()); return msg; } @Incoming("from-kafka7") public CompletionStage<Void> receiveFromKafka7(Message<Integer> msg) { IncomingKafkaRecordMetadata<String, Integer> metadata = KafkaMetadataUtil.readIncomingKafkaMetadata(msg).get(); if (msg.getPayload() <= 10) { noPartitionSpecifiedMetadatas7.put(msg.getPayload(), metadata); } else { partitionSpecifiedMetadatas7.put(msg.getPayload(), metadata); } latch.countDown(); return msg.ack(); } }
5,725
39.041958
155
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/tx/TransactionalBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.tx; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import jakarta.enterprise.context.ApplicationScoped; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.persistence.TypedQuery; import jakarta.transaction.Transactional; @ApplicationScoped public class TransactionalBean { @PersistenceContext(unitName = "test") EntityManager em; @Transactional public void storeValue(String name) { ContextEntity entity = new ContextEntity(); entity.setName(name); em.persist(entity); } @Transactional public void checkValues(Set<String> names) { checkCount(names.size()); TypedQuery<ContextEntity> query = em.createQuery("SELECT c from ContextEntity c", ContextEntity.class); Set<String> values = query.getResultList().stream().map(v -> v.getName()).collect(Collectors.toSet()); if (!values.containsAll(names) || !names.containsAll(values)) { throw new IllegalStateException("Mismatch of expected names. Expected: " + names + "; actual: " + values); } } @Transactional private int checkCount(int expected) { TypedQuery<Long> query = em.createQuery("SELECT count(c) from ContextEntity c", Long.class); List<Long> result = query.getResultList(); int count = result.get(0).intValue(); if (count != expected) { throw new IllegalStateException("Expected " + expected + "; got " + count); } return count; } }
2,664
36.013889
118
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/tx/ReactiveMessagingKafkaTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.tx; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.PropertyPermission; import java.util.Set; import java.util.concurrent.TimeUnit; import jakarta.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; import org.wildfly.test.integration.microprofile.reactive.RunKafkaSetupTask; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @RunWith(Arquillian.class) @ServerSetup({RunKafkaSetupTask.class, EnableReactiveExtensionsSetupTask.class}) public class ReactiveMessagingKafkaTestCase { private static final long TIMEOUT = TimeoutUtil.adjust(25000); @Inject Bean bean; @Inject TransactionalBean txBean; @Deployment public static WebArchive getDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "reactive-messaging-kafka-tx.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addPackage(ReactiveMessagingKafkaTestCase.class.getPackage()) .addClasses(RunKafkaSetupTask.class, EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class) .addAsWebInfResource(ReactiveMessagingKafkaTestCase.class.getPackage(), "persistence.xml", "classes/META-INF/persistence.xml") .addAsWebInfResource(ReactiveMessagingKafkaTestCase.class.getPackage(), "microprofile-config.properties", "classes/META-INF/microprofile-config.properties") .addClass(TimeoutUtil.class) .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read") ), "permissions.xml"); return webArchive; } @Test public void test() throws InterruptedException { boolean wait = bean.getLatch().await(TIMEOUT, TimeUnit.MILLISECONDS); Assert.assertTrue("Timed out", wait); // KK: Initially I thought we could do something similar here to in ReactiveMessagingKafkaSerializerTestCase // to check that messages are received in order on a partition but it is a bit complicated due to the // asynchronous storing of entries to a database Set<String> expected = new HashSet<>(Arrays.asList("hello", "reactive", "messaging")); Assert.assertEquals(expected.size(), bean.getWords().size()); Assert.assertTrue("Expected " + bean.getWords() + " to contain all of " + expected, bean.getWords().containsAll(expected)); // Check the data was stored txBean.checkValues(Collections.singleton("reactive")); } }
4,337
44.1875
172
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/tx/Bean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.tx; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ApplicationScoped public class Bean { private final CountDownLatch latch = new CountDownLatch(3); private List<String> words = new ArrayList<>(); @Inject TransactionalBean txBean; private ExecutorService executorService = Executors.newSingleThreadExecutor(); @PreDestroy public void stop() { executorService.shutdown(); } public CountDownLatch getLatch() { return latch; } @Outgoing("to-kafka") public PublisherBuilder<String> source() { // We need to set the following in microprofile-config.properties for this approach to work // mp.messaging.incoming.from-kafka.auto.offset.reset=earliest return ReactiveStreams.of("hello", "reactive", "messaging"); } @Incoming("from-kafka") @Outgoing("sink") public CompletionStage<String> store(String payload) { // Make sure it is on a separate thread. If Context Propagation was enabled, I'd use // a ManagedExecutor return CompletableFuture.supplyAsync(() -> { if (payload.equals("reactive")) { // Add a sleep here to make sure the calling method has returned try { Thread.sleep(3000); } catch (InterruptedException e){ throw new RuntimeException(e); } txBean.storeValue(payload); } return payload; }, executorService); } @Incoming("sink") public void sink(String word) { words.add(word); latch.countDown(); } public List<String> getWords() { return words; } }
3,501
33.673267
99
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/tx/ContextEntity.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.tx; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @Entity public class ContextEntity { private Long id; private String name; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
1,643
28.890909
78
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/serializer/ReactiveMessagingKafkaSerializerTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.serializer; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PropertyPermission; import java.util.concurrent.TimeUnit; import jakarta.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; import org.wildfly.test.integration.microprofile.reactive.RunKafkaSetupTask; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @RunWith(Arquillian.class) @ServerSetup({RunKafkaSetupTask.class, EnableReactiveExtensionsSetupTask.class}) public class ReactiveMessagingKafkaSerializerTestCase { private static final long TIMEOUT = TimeoutUtil.adjust(15000); @Inject Bean bean; @Deployment public static WebArchive getDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "reactive-messaging-kafka-tx.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addPackage(ReactiveMessagingKafkaSerializerTestCase.class.getPackage()) .addClasses(RunKafkaSetupTask.class, EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class) .addAsWebInfResource(ReactiveMessagingKafkaSerializerTestCase.class.getPackage(), "microprofile-config.properties", "classes/META-INF/microprofile-config.properties") .addClass(TimeoutUtil.class) .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read") ), "permissions.xml"); return webArchive; } @Test public void test() throws InterruptedException { boolean wait = bean.getLatch().await(TIMEOUT, TimeUnit.MILLISECONDS); Assert.assertTrue("Timed out", wait); List<Person> list = bean.getReceived(); Assert.assertEquals(3, list.size()); // Kafka messages only have order per partition, so do some massaging of the data Map<Integer, List<Person>> map = new HashMap<>(); for (int i = 0; i < list.size(); i++) { List<Person> persons = map.computeIfAbsent(bean.getPartitionReceived().get(i), ind -> new ArrayList<>()); persons.add(list.get(i)); } Person kabir = assertPersonNextOnAPartition(map, "Kabir"); Person bob = assertPersonNextOnAPartition(map, "Bob"); Person roger = assertPersonNextOnAPartition(map, "Roger"); Assert.assertEquals(101, kabir.getAge()); Assert.assertEquals(18, bob.getAge()); Assert.assertEquals(21, roger.getAge()); } private Person assertPersonNextOnAPartition(Map<Integer, List<Person>> map, String name) { Person found = null; int remove = -1; for (Map.Entry<Integer, List<Person>> entry : map.entrySet()) { List<Person> persons = entry.getValue(); Person p = persons.get(0); if (p.getName().equals(name)) { found = p; persons.remove(0); if (persons.size() == 0) { remove = entry.getKey(); } } } map.remove(remove); Assert.assertNotNull("Could not find " + name, found); return found; } }
4,977
39.471545
182
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/serializer/Bean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.serializer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletionStage; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import io.smallrye.reactive.messaging.kafka.api.KafkaMetadataUtil; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ApplicationScoped public class Bean { private final CountDownLatch latch = new CountDownLatch(3); private List<Person> received = new ArrayList<>(); private List<Integer> partitionReceived = new ArrayList<>(); private ExecutorService executorService = Executors.newSingleThreadExecutor(); @PreDestroy public void stop() { executorService.shutdown(); } public CountDownLatch getLatch() { return latch; } @Outgoing("to-kafka") public PublisherBuilder<Person> source() { // We need to set the following in microprofile-config.properties for this approach to work // mp.messaging.incoming.from-kafka.auto.offset.reset=earliest return ReactiveStreams.of( new Person("Kabir", 101), new Person("Bob", 18), new Person("Roger", 21)); } @Incoming("from-kafka") public CompletionStage<Void> sink(Message<Person> msg) { received.add(msg.getPayload()); partitionReceived.add(KafkaMetadataUtil.readIncomingKafkaMetadata(msg).get().getPartition()); latch.countDown(); return msg.ack(); } public List<Person> getReceived() { return received; } public List<Integer> getPartitionReceived() { return partitionReceived; } }
3,231
34.911111
101
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/serializer/PersonSerializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.serializer; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import org.apache.kafka.common.serialization.Serializer; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class PersonSerializer implements Serializer<Person> { @Override public byte[] serialize(String topic, Person data) { if (data == null) { return null; } try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout); out.writeUTF(data.getName()); out.writeInt(data.getAge()); out.close(); return bout.toByteArray(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } }
1,968
34.8
86
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/serializer/Person.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.serializer; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class Person { private final String name; private final int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
1,650
30.150943
86
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/serializer/PersonDeserializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.serializer; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import org.apache.kafka.common.serialization.Deserializer; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class PersonDeserializer implements Deserializer<Person> { @Override public Person deserialize(String topic, byte[] data) { if (data == null) { return null; } try { ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data)); String name = in.readUTF(); int age = in.readInt(); in.close(); return new Person(name, age); } catch (IOException e){ e.printStackTrace(); throw new RuntimeException(e); } } }
1,919
35.923077
89
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/ssl/Bean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.ssl; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ApplicationScoped public class Bean { private final CountDownLatch latch = new CountDownLatch(4); private List<String> words = new ArrayList<>(); private ExecutorService executorService = Executors.newSingleThreadExecutor(); @PreDestroy public void stop() { executorService.shutdown(); } public CountDownLatch getLatch() { return latch; } @Outgoing("to-kafka") public PublisherBuilder<String> source() { // We need to set the following in microprofile-config.properties for this approach to work // mp.messaging.incoming.from-kafka.auto.offset.reset=earliest return ReactiveStreams.of("hello", "reactive", "messaging", "ssl"); } @Incoming("from-kafka") public void sink(String word) { words.add(word); latch.countDown(); } public List<String> getWords() { return words; } }
2,635
34.146667
99
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/ssl/ReactiveMessagingKafkaSslTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.ssl; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.util.Arrays; import java.util.HashSet; import java.util.PropertyPermission; import java.util.Set; import java.util.concurrent.TimeUnit; import jakarta.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; import org.wildfly.test.integration.microprofile.reactive.RunKafkaSetupTask; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @RunWith(Arquillian.class) @ServerSetup({RunKafkaWithSslSetupTask.class, EnableReactiveExtensionsSetupTask.class, ConfigureElytronSslContextSetupTask.class}) public class ReactiveMessagingKafkaSslTestCase { private static final long TIMEOUT = TimeoutUtil.adjust(15000); @Inject Bean bean; @Deployment public static WebArchive getDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "reactive-messaging-kafka-tx.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addPackage(ReactiveMessagingKafkaSslTestCase.class.getPackage()) .addClasses(RunKafkaSetupTask.class, RunKafkaWithSslSetupTask.class, EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class) .addAsWebInfResource(ReactiveMessagingKafkaSslTestCase.class.getPackage(), "microprofile-config.properties", "classes/META-INF/microprofile-config.properties") .addClass(TimeoutUtil.class) .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read") ), "permissions.xml"); return webArchive; } @Test public void test() throws InterruptedException { boolean wait = bean.getLatch().await(TIMEOUT, TimeUnit.MILLISECONDS); Assert.assertTrue("Timed out", wait); Set<String> expected = new HashSet<>(Arrays.asList("hello", "reactive", "messaging", "ssl")); Assert.assertEquals(expected.size(), bean.getWords().size()); Assert.assertTrue("Expected " + bean.getWords() + " to contain all of " + expected, bean.getWords().containsAll(expected)); } }
3,835
44.129412
175
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/ssl/ConfigureElytronSslContextSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.ssl; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.shared.CLIServerSetupTask; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class ConfigureElytronSslContextSetupTask extends CLIServerSetupTask { @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { Path path = Paths.get(RunKafkaWithSslSetupTask.CLIENT_TRUSTSTORE) .toAbsolutePath() .normalize(); if (!Files.exists(path)) { throw new IllegalStateException(path.toString()); } NodeBuilder nb = this.builder.node(containerId); nb.setup("/subsystem=elytron/key-store=kafka-ssl-test:add(credential-reference={clear-text=%s}, path=%s, type=PKCS12)", RunKafkaWithSslSetupTask.CLIENT_TRUESTSTORE_PWD, RunKafkaWithSslSetupTask.CLIENT_TRUSTSTORE); nb.setup("/subsystem=elytron/trust-manager=kafka-ssl-test:add(key-store=kafka-ssl-test)"); nb.setup("/subsystem=elytron/client-ssl-context=kafka-ssl-test:add(trust-manager=kafka-ssl-test)"); nb.teardown("/subsystem=elytron/client-ssl-context=kafka-ssl-test:remove"); nb.teardown("/subsystem=elytron/trust-manager=kafka-ssl-test:remove"); nb.teardown("/subsystem=elytron/key-store=kafka-ssl-test:remove"); super.setup(managementClient, containerId); } }
2,594
43.741379
221
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/kafka/ssl/RunKafkaWithSslSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.kafka.ssl; import io.smallrye.reactive.messaging.kafka.companion.KafkaCompanion; import io.smallrye.reactive.messaging.kafka.companion.test.EmbeddedKafkaBroker; import org.apache.kafka.common.Endpoint; import org.apache.kafka.common.config.SslConfigs; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.logging.Logger; import java.io.File; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Paths; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import static io.smallrye.reactive.messaging.kafka.companion.test.EmbeddedKafkaBroker.endpoint; import static org.apache.kafka.common.security.auth.SecurityProtocol.PLAINTEXT; import static org.apache.kafka.common.security.auth.SecurityProtocol.SSL; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class RunKafkaWithSslSetupTask implements ServerSetupTask { private static final String SERVER_KEYSTORE = "target/reactive-messaging-kafka/server.keystore.p12"; private static final String SERVER_CER = "target/reactive-messaging-kafka/server.cer"; private static final String SERVER_TRUSTSTORE = "target/reactive-messaging-kafka/server.truststore.p12"; public static final String CLIENT_TRUSTSTORE = "target/reactive-messaging-kafka/client.truststore.p12"; private static final String KEYSTORE_PWD = "serverks"; private static final String SERVER_TRUESTSTORE_PWD = "serverts"; public static final String CLIENT_TRUESTSTORE_PWD = "clientts"; volatile EmbeddedKafkaBroker broker; volatile KafkaCompanion companion; private static final Logger log = Logger.getLogger(RunKafkaWithSslSetupTask.class); private File configDir; @Override public void setup(ManagementClient managementClient, String s) throws Exception { try { configDir = new File("target", "reactive-messaging-kafka"); configDir.mkdir(); //keytool -genkeypair -alias localhost -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore server.keystore.p12 -validity 3650 -ext SAN=DNS:localhost,IP:127.0.0.1 final List<String> createKeyStoreWithCertificateCommand = new ArrayList<>(List.of("keytool", "-genkeypair")); createKeyStoreWithCertificateCommand.addAll(List.of("-alias", "localhost")); createKeyStoreWithCertificateCommand.addAll(List.of("-keyalg", "RSA")); createKeyStoreWithCertificateCommand.addAll(List.of("-keysize", "2048")); createKeyStoreWithCertificateCommand.addAll(List.of("-storetype", "PKCS12")); createKeyStoreWithCertificateCommand.addAll(List.of("-keystore", SERVER_KEYSTORE)); createKeyStoreWithCertificateCommand.addAll(List.of("-storepass", KEYSTORE_PWD)); createKeyStoreWithCertificateCommand.addAll(List.of("-keypass", KEYSTORE_PWD)); createKeyStoreWithCertificateCommand.addAll( List.of("-dname", "CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")); createKeyStoreWithCertificateCommand.addAll(List.of("-validity", "3650")); createKeyStoreWithCertificateCommand.addAll(List.of("-ext", "SAN=DNS:localhost,IP:127.0.0.1")); runKeytoolCommand(createKeyStoreWithCertificateCommand); //keytool -exportcert -alias localhost -keystore server.keystore.p12 -file server.cer -storetype pkcs12 -noprompt -storepass serverks final List<String> exportCertificateCommand = new ArrayList<>(List.of("keytool", "-exportcert")); exportCertificateCommand.addAll(List.of("-alias", "localhost")); exportCertificateCommand.addAll(List.of("-keystore", SERVER_KEYSTORE)); exportCertificateCommand.addAll(List.of("-file", SERVER_CER)); exportCertificateCommand.addAll(List.of("-storetype", "PKCS12")); exportCertificateCommand.addAll(List.of("-noprompt")); exportCertificateCommand.addAll(List.of("-storepass", KEYSTORE_PWD)); runKeytoolCommand(exportCertificateCommand); //keytool -keystore server.truststore.p12 -alias localhost -importcert -file server.cer -storetype pkcs12 final List<String> importServerTrustStoreCommand = new ArrayList<>(List.of("keytool")); importServerTrustStoreCommand.addAll(List.of("-keystore", SERVER_TRUSTSTORE)); importServerTrustStoreCommand.addAll(List.of("-alias", "localhost")); importServerTrustStoreCommand.addAll(List.of("-importcert")); importServerTrustStoreCommand.addAll(List.of("-file", SERVER_CER)); importServerTrustStoreCommand.addAll(List.of("-storetype", "PKCS12")); importServerTrustStoreCommand.addAll(List.of("-storepass", SERVER_TRUESTSTORE_PWD)); importServerTrustStoreCommand.addAll(List.of("-keypass", SERVER_TRUESTSTORE_PWD)); importServerTrustStoreCommand.addAll(List.of("-noprompt")); runKeytoolCommand(importServerTrustStoreCommand); //keytool -keystore client.truststore.p12 -alias localhost -importcert -file server.cer -storetype pkcs12 final List<String> importClientTrustStoreCommand = new ArrayList<>(List.of("keytool")); importClientTrustStoreCommand.addAll(List.of("-keystore", CLIENT_TRUSTSTORE)); importClientTrustStoreCommand.addAll(List.of("-alias", "localhost")); importClientTrustStoreCommand.addAll(List.of("-importcert")); importClientTrustStoreCommand.addAll(List.of("-file", SERVER_CER)); importClientTrustStoreCommand.addAll(List.of("-storetype", "PKCS12")); importClientTrustStoreCommand.addAll(List.of("-storepass", CLIENT_TRUESTSTORE_PWD)); importClientTrustStoreCommand.addAll(List.of("-keypass", CLIENT_TRUESTSTORE_PWD)); importClientTrustStoreCommand.addAll(List.of("-noprompt")); runKeytoolCommand(importClientTrustStoreCommand); Endpoint external = endpoint("EXTERNAL", SSL, "localhost", 9092); Endpoint internal = endpoint("INTERNAL", PLAINTEXT, "localhost", 19002); broker = new EmbeddedKafkaBroker() .withAdvertisedListeners(external, internal) .withAdditionalProperties(properties -> { properties.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, SERVER_KEYSTORE); properties.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, KEYSTORE_PWD); properties.put(SslConfigs.SSL_KEY_PASSWORD_CONFIG, KEYSTORE_PWD); properties.put(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PKCS12"); properties.put(SslConfigs.SSL_SECURE_RANDOM_IMPLEMENTATION_CONFIG, "SHA1PRNG"); }) .withDeleteLogDirsOnClose(true); broker.start(); companion = new KafkaCompanion(EmbeddedKafkaBroker.toListenerString(internal)); companion.topics().createAndWait("testing", 1, Duration.of(10, ChronoUnit.SECONDS)); } catch (Exception e) { try { if (companion != null) { companion.close(); } if (broker != null) { broker.close(); } } finally { throw e; } } } private void runKeytoolCommand(List<String> commandParameters) throws IOException { ProcessBuilder keytool = new ProcessBuilder().command(commandParameters); final Process process = keytool.start(); try { process.waitFor(); } catch (InterruptedException e) { log.errorf(e, "Keytool execution error"); } log.debugf("Generating certificate using `keytool` using command: %s, parameters: %s", process.info(), commandParameters); if (process.exitValue() > 0) { final String processError = (new BufferedReader(new InputStreamReader(process.getErrorStream()))).lines() .collect(Collectors.joining(" \\ ")); final String processOutput = (new BufferedReader(new InputStreamReader(process.getInputStream()))).lines() .collect(Collectors.joining(" \\ ")); log.errorf("Error generating certificate, error output: %s, normal output: %s, commandline parameters: %s", processError, processOutput, commandParameters); } } private boolean deleteDirectory(File directoryToBeDeleted) { File[] allContents = directoryToBeDeleted.listFiles(); if (allContents != null) { for (File file : allContents) { deleteDirectory(file); } } return directoryToBeDeleted.delete(); } @Override public void tearDown(ManagementClient managementClient, String s) throws Exception { if (companion != null) { companion.close(); } if (broker != null) { broker.close(); } if (configDir != null && Files.exists(Paths.get(configDir.getPath()))) { boolean deleted = deleteDirectory(configDir); if (!deleted) { log.warnf("Deleting config directory %s was not successful", configDir.toString()); } } } }
10,654
53.362245
176
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/sanity/Bean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.sanity; import java.util.concurrent.CountDownLatch; import jakarta.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ApplicationScoped public class Bean { private final CountDownLatch latch = new CountDownLatch(4); private StringBuilder phrase = new StringBuilder(); public CountDownLatch getLatch() { return latch; } @Outgoing("source") public PublisherBuilder<String> source() { return ReactiveStreams.of("hello", "with", "SmallRye", "reactive", "message"); } @Incoming("source") @Outgoing("processed-a") public String toUpperCase(String payload) { return payload.toUpperCase(); } @Incoming("processed-a") @Outgoing("processed-b") public PublisherBuilder<String> filter(PublisherBuilder<String> input) { return input.filter(item -> item.length() > 4); } @Incoming("processed-b") public void sink(String word) { if (phrase.length() > 0) { phrase.append(" "); } this.phrase.append(word); latch.countDown(); } public String getPhrase() { return phrase.toString(); } }
2,570
32.828947
86
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/sanity/ReactiveMessagingSanityTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.sanity; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.util.PropertyPermission; import java.util.concurrent.TimeUnit; import jakarta.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @RunWith(Arquillian.class) @ServerSetup(EnableReactiveExtensionsSetupTask.class) public class ReactiveMessagingSanityTestCase { private static final long TIMEOUT = TimeoutUtil.adjust(5000); @Inject Bean bean; @Deployment public static WebArchive getDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "rx-messaging.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addPackage(ReactiveMessagingSanityTestCase.class.getPackage()) .addClasses(TimeoutUtil.class, EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class) .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read") ), "permissions.xml"); return webArchive; } @Test public void test() throws InterruptedException { boolean wait = bean.getLatch().await(TIMEOUT, TimeUnit.MILLISECONDS); Assert.assertTrue("Timed out", wait); Assert.assertEquals("HELLO SMALLRYE REACTIVE MESSAGE", bean.getPhrase()); } }
3,103
39.842105
113
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/ported/ReactiveMessagingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.ported; import java.util.List; import jakarta.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; import org.wildfly.test.integration.microprofile.reactive.messaging.ported.channels.ChannelConsumer; import org.wildfly.test.integration.microprofile.reactive.messaging.ported.channels.EmitterExample; /** * Ported from Quarkus and adjusted * * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ServerSetup(EnableReactiveExtensionsSetupTask.class) @RunWith(Arquillian.class) public class ReactiveMessagingTestCase { @Inject ChannelConsumer channelConsumer; @Inject EmitterExample emitterExample; @Deployment public static WebArchive createDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "rx-messaging-ported.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(ReactiveMessagingTestCase.class, SimpleBean.class, ChannelConsumer.class, EmitterExample.class) .addClasses(EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class); return webArchive; } @Test public void testSimpleBean() { Assert.assertEquals(4, SimpleBean.RESULT.size()); Assert.assertTrue(SimpleBean.RESULT.contains("HELLO")); Assert.assertTrue(SimpleBean.RESULT.contains("SMALLRYE")); Assert.assertTrue(SimpleBean.RESULT.contains("REACTIVE")); Assert.assertTrue(SimpleBean.RESULT.contains("MESSAGE")); } @Test public void testChannelInjection() throws Exception { List<String> consumed = channelConsumer.consume(); Assert.assertEquals(5, consumed.size()); Assert.assertEquals("hello", consumed.get(0)); Assert.assertEquals("with", consumed.get(1)); Assert.assertEquals("SmallRye", consumed.get(2)); Assert.assertEquals("reactive", consumed.get(3)); Assert.assertEquals("message", consumed.get(4)); } @Test public void testEmitter() { emitterExample.run(); List<String> list = emitterExample.list(); Assert.assertEquals(3, list.size()); Assert.assertEquals("a", list.get(0)); Assert.assertEquals("b", list.get(1)); Assert.assertEquals("c", list.get(2)); } }
3,861
38.814433
123
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/ported/SimpleBean.java
package org.wildfly.test.integration.microprofile.reactive.messaging.ported; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import jakarta.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; /** * Ported from Quarkus and adjusted * * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ApplicationScoped public class SimpleBean { static final List<String> RESULT = new CopyOnWriteArrayList<>(); @Outgoing("source") public PublisherBuilder<String> source() { return ReactiveStreams.of("hello", "with", "SmallRye", "reactive", "message"); } @Incoming("source") @Outgoing("processed-a") public String toUpperCase(String payload) { return payload.toUpperCase(); } @Incoming("processed-a") @Outgoing("processed-b") public PublisherBuilder<String> filter(PublisherBuilder<String> input) { return input.filter(item -> item.length() > 4); } @Incoming("processed-b") public void sink(String word) { RESULT.add(word); } }
1,318
27.673913
86
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/ported/config/ConnectorConfigTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.ported.config; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils.await; import static org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils.checkList; import java.util.List; import java.util.PropertyPermission; import java.util.concurrent.CopyOnWriteArrayList; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; import org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils; /** * Copied from Quarkus and adjusted */ @ServerSetup({EnableReactiveExtensionsSetupTask.class, ConnectorConfigTestCase.SetConfigPropertiesSetupTask.class}) @RunWith(Arquillian.class) public class ConnectorConfigTestCase { @Deployment public static WebArchive enableExtensions() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "rx-messaging-connector-cfg.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(DumbConnector.class, BeanUsingDummyConnector.class) .addClasses(ReactiveMessagingTestUtils.class, TimeoutUtil.class, EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class, SetConfigPropertiesSetupTask.class) // Rather than using Quarkus's overrideConfigKey() method which we don't have, we set the config // properties via the SetConfigPropertiesSetupTask .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read") ), "permissions.xml"); return webArchive; } @Inject BeanUsingDummyConnector bean; @Test public void test() { await(() -> bean.getList().size() == 2); checkList(bean.getList(), "bonjour", "BONJOUR"); } @ApplicationScoped public static class BeanUsingDummyConnector { private List<String> list = new CopyOnWriteArrayList<>(); @Incoming("a") public void consume(String s) { list.add(s); } public List<String> getList() { return list; } } public static class SetConfigPropertiesSetupTask extends CLIServerSetupTask { @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { NodeBuilder nb = this.builder.node(containerId); nb.setup("/system-property=mp.messaging.incoming.a.values:add(value=bonjour)"); nb.setup("/system-property=mp.messaging.incoming.a.connector:add(value=dummy)"); super.setup(managementClient, containerId); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { NodeBuilder nb = this.builder.node(containerId); nb.teardown("/system-property=mp.messaging.incoming.a.values:remove"); nb.teardown("/system-property=mp.messaging.incoming.a.connector:remove"); super.tearDown(managementClient, containerId); } } }
5,053
42.947826
126
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/ported/config/DumbConnector.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.ported.config; import jakarta.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.messaging.spi.Connector; import org.eclipse.microprofile.reactive.messaging.spi.IncomingConnectorFactory; import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; /** * Copied from Quarkus and adjusted */ @ApplicationScoped @Connector("dummy") public class DumbConnector implements IncomingConnectorFactory { @Override public PublisherBuilder<? extends Message<?>> getPublisherBuilder(Config config) { String values = config.getValue("values", String.class); return ReactiveStreams.of(values, values.toUpperCase()) .map(Message::of); } }
1,992
41.404255
86
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/ported/config/ConnectorProfileConfigTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.ported.config; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils.await; import java.util.List; import java.util.PropertyPermission; import java.util.concurrent.CopyOnWriteArrayList; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; import org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils; /** * Copied from Quarkus and adjusted */ @ServerSetup(EnableReactiveExtensionsSetupTask.class) @RunWith(Arquillian.class) public class ConnectorProfileConfigTestCase { @Deployment public static WebArchive createArchive() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "rx-messaging-connector-profile-cfg.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(DumbConnector.class, BeanUsingDummyConnector.class) .addClasses(ReactiveMessagingTestUtils.class, TimeoutUtil.class, EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class) .addAsWebInfResource(ConnectorProfileConfigTestCase.class.getPackage(), "dummy-connector-with-profile.properties", "classes/META-INF/microprofile-config.properties") .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read") ), "permissions.xml"); return webArchive; } @Inject BeanUsingDummyConnector bean; @Test public void testThatTestProfileValuesAreUsed() { await(() -> bean.getList().size() == 2); ReactiveMessagingTestUtils.checkList(bean.getList(), "ola", "OLA"); } @ApplicationScoped public static class BeanUsingDummyConnector { private List<String> list = new CopyOnWriteArrayList<>(); @Incoming("a") public void consume(String s) { list.add(s); } public List<String> getList() { return list; } } }
3,892
39.978947
147
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/ported/signatures/PublisherSignatureTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.ported.signatures; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils.await; import static org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils.checkList; import java.io.FilePermission; import java.util.List; import java.util.PropertyPermission; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; import org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils; /** * Ported from Quarkus and adjusted * * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ServerSetup(EnableReactiveExtensionsSetupTask.class) @RunWith(Arquillian.class) public class PublisherSignatureTestCase { @Deployment public static WebArchive enableExtensions() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "rx-messaging-publisher-signature.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(PublisherSignatureTestCase.class, BeanProducingAPublisherOfMessage.class, BeanProducingAPublisherOfPayload.class, BeanProducingAPublisherBuilderOfMessage.class, BeanProducingAPublisherBuilderOfPayload.class, BeanProducingPayloads.class, BeanProducingMessages.class, BeanProducingPayloadsAsynchronously.class, BeanProducingMessagesAsynchronously.class, Spy.class) .addClasses(ReactiveMessagingTestUtils.class, TimeoutUtil.class, EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class) .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read"), // It complains about files in the local maven repo, which may vary across environments new FilePermission("<<ALL FILES>>", "read"), new RuntimePermission("modifyThread") ), "permissions.xml"); return webArchive; } @Inject BeanProducingAPublisherOfMessage beanProducingAPublisherOfMessage; @Inject BeanProducingAPublisherOfPayload beanProducingAPublisherOfPayload; @Inject BeanProducingAPublisherBuilderOfMessage beanProducingAPublisherBuilderOfMessage; @Inject BeanProducingAPublisherBuilderOfPayload beanProducingAPublisherBuilderOfPayload; @Inject BeanProducingPayloads beanProducingPayloads; @Inject BeanProducingMessages beanProducingMessages; @Inject BeanProducingPayloadsAsynchronously beanProducingPayloadsAsynchronously; @Inject BeanProducingMessagesAsynchronously beanProducingMessagesAsynchronously; @After public void closing() { beanProducingAPublisherOfMessage.close(); beanProducingAPublisherOfPayload.close(); beanProducingAPublisherBuilderOfMessage.close(); beanProducingAPublisherBuilderOfPayload.close(); beanProducingPayloads.close(); beanProducingMessages.close(); beanProducingPayloadsAsynchronously.close(); beanProducingMessagesAsynchronously.close(); } @Test public void test() { check(beanProducingAPublisherBuilderOfMessage); check(beanProducingAPublisherOfPayload); check(beanProducingAPublisherBuilderOfMessage); check(beanProducingAPublisherBuilderOfPayload); check(beanProducingPayloads); check(beanProducingMessages); check(beanProducingPayloadsAsynchronously); check(beanProducingMessagesAsynchronously); } private void check(Spy spy) { await(() -> spy.getItems().size() == 10); checkList(spy.getItems(), 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); } @ApplicationScoped public static class BeanProducingAPublisherOfMessage extends Spy { @Outgoing("A") public Publisher<Message<Integer>> produce() { return ReactiveStreams.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) .map(Message::of) .buildRs(); } @Incoming("A") public void consume(Integer item) { items.add(item); } } @ApplicationScoped public static class BeanProducingAPublisherOfPayload extends Spy { @Outgoing("B") public Publisher<Integer> produce() { return ReactiveStreams.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) .buildRs(); } @Incoming("B") public void consume(Integer item) { items.add(item); } } @ApplicationScoped public static class BeanProducingAPublisherBuilderOfMessage extends Spy { @Outgoing("C") public PublisherBuilder<Message<Integer>> produce() { return ReactiveStreams.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) .map(Message::of); } @Incoming("C") public void consume(Integer item) { items.add(item); } } @ApplicationScoped public static class BeanProducingAPublisherBuilderOfPayload extends Spy { @Outgoing("D") public PublisherBuilder<Integer> produce() { return ReactiveStreams.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); } @Incoming("D") public void consume(Integer item) { items.add(item); } } @ApplicationScoped public static class BeanProducingPayloads extends Spy { AtomicInteger count = new AtomicInteger(); @Outgoing("E") public int produce() { return count.getAndIncrement(); } @SuppressWarnings("SubscriberImplementation") @Incoming("E") public Subscriber<Integer> consume() { return new Subscriber<Integer>() { @Override public void onSubscribe(Subscription subscription) { subscription.request(10); } @Override public void onNext(Integer integer) { getItems().add(integer); } @Override public void onError(Throwable throwable) { // Ignored } @Override public void onComplete() { // Ignored } }; } } @ApplicationScoped public static class BeanProducingMessages extends Spy { AtomicInteger count = new AtomicInteger(); @Outgoing("F") public Message<Integer> produce() { return Message.of(count.getAndIncrement()); } @SuppressWarnings("SubscriberImplementation") @Incoming("F") public Subscriber<Integer> consume() { return new Subscriber<Integer>() { @Override public void onSubscribe(Subscription subscription) { subscription.request(10); } @Override public void onNext(Integer integer) { getItems().add(integer); } @Override public void onError(Throwable throwable) { // Ignored } @Override public void onComplete() { // Ignored } }; } } @ApplicationScoped public static class BeanProducingPayloadsAsynchronously extends Spy { AtomicInteger count = new AtomicInteger(); @Outgoing("G") public CompletionStage<Integer> produce() { return CompletableFuture.supplyAsync(() -> count.getAndIncrement(), executor); } @SuppressWarnings("SubscriberImplementation") @Incoming("G") public Subscriber<Integer> consume() { return new Subscriber<Integer>() { @Override public void onSubscribe(Subscription subscription) { subscription.request(10); } @Override public void onNext(Integer integer) { getItems().add(integer); } @Override public void onError(Throwable throwable) { // Ignored } @Override public void onComplete() { // Ignored } }; } } @ApplicationScoped public static class BeanProducingMessagesAsynchronously extends Spy { AtomicInteger count = new AtomicInteger(); @Outgoing("H") public CompletionStage<Message<Integer>> produce() { return CompletableFuture.supplyAsync(() -> count.getAndIncrement(), executor).thenApply(Message::of); } @SuppressWarnings("SubscriberImplementation") @Incoming("H") public Subscriber<Integer> consume() { return new Subscriber<Integer>() { @Override public void onSubscribe(Subscription subscription) { subscription.request(10); } @Override public void onNext(Integer integer) { getItems().add(integer); } @Override public void onError(Throwable throwable) { // Ignored } @Override public void onComplete() { // Ignored } }; } } public static class Spy { List<Integer> items = new CopyOnWriteArrayList<>(); ExecutorService executor = Executors.newSingleThreadExecutor(); public List<Integer> getItems() { return items; } public void close() { executor.shutdown(); } } }
12,629
34.181058
147
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/ported/signatures/TransformerSignatureTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.ported.signatures; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils.await; import static org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils.checkList; import java.util.List; import java.util.PropertyPermission; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.AfterClass; import org.junit.Test; import org.junit.runner.RunWith; import org.reactivestreams.Publisher; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; import org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils; /** * Ported from Quarkus and adjusted * * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ServerSetup(EnableReactiveExtensionsSetupTask.class) @RunWith(Arquillian.class) public class TransformerSignatureTestCase { @Deployment public static WebArchive enableExtensions() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "rx-messaging-transformer-signature.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(TransformerSignatureTestCase.class, BeanWithPublisherOfMessages.class, BeanWithPublisherBuilderOfMessages.class, BeanWithPublisherOfPayloads.class, BeanWithPublisherBuilderOfPayloads.class, Spy.class) .addClasses(ReactiveMessagingTestUtils.class, TimeoutUtil.class, EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class) .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read") ), "permissions.xml"); return webArchive; } @Inject BeanWithPublisherOfMessages beanWithPublisherOfMessages; @Inject BeanWithPublisherOfPayloads beanWithPublisherOfPayloads; @Inject BeanWithPublisherBuilderOfMessages beanWithPublisherBuilderOfMessages; @Inject BeanWithPublisherBuilderOfPayloads beanWithPublisherBuilderOfPayloads; @AfterClass public static void close() { Spy.executor.shutdown(); } @Test public void test() { check(beanWithPublisherOfMessages); check(beanWithPublisherOfPayloads); check(beanWithPublisherBuilderOfMessages); check(beanWithPublisherBuilderOfPayloads); } private void check(Spy spy) { new Thread(() -> { for (int i = 0; i < 10; i++) { spy.getEmitter().send(i); } spy.getEmitter().complete(); }).start(); await(() -> spy.items().size() == 10); checkList(spy.items(), "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); } @ApplicationScoped public static class BeanWithPublisherOfMessages extends Spy { @Inject @Channel("A") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("A") @Outgoing("AA") public Publisher<Message<String>> process(Publisher<Message<Integer>> publisher) { return ReactiveStreams.fromPublisher(publisher) .flatMapCompletionStage(m -> CompletableFuture .supplyAsync(() -> Message.of(Integer.toString(m.getPayload())), executor)) .buildRs(); } @Incoming("AA") public void consume(String item) { items().add(item); } } @ApplicationScoped public static class BeanWithPublisherOfPayloads extends Spy { @Inject @Channel("B") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("B") @Outgoing("BB") public Publisher<String> process(Publisher<Integer> publisher) { return ReactiveStreams.fromPublisher(publisher) .flatMapCompletionStage(i -> CompletableFuture.supplyAsync(() -> Integer.toString(i), executor)) .buildRs(); } @Incoming("BB") public void consume(String item) { items().add(item); } } @ApplicationScoped public static class BeanWithPublisherBuilderOfMessages extends Spy { @Inject @Channel("C") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("C") @Outgoing("CC") public PublisherBuilder<Message<String>> process(PublisherBuilder<Message<Integer>> publisher) { return publisher .flatMapCompletionStage(m -> CompletableFuture .supplyAsync(() -> Message.of(Integer.toString(m.getPayload())), executor)); } @Incoming("CC") public void consume(String item) { items().add(item); } } @ApplicationScoped public static class BeanWithPublisherBuilderOfPayloads extends Spy { @Inject @Channel("D") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("D") @Outgoing("DD") public PublisherBuilder<String> process(PublisherBuilder<Integer> publisher) { return publisher .flatMapCompletionStage(i -> CompletableFuture.supplyAsync(() -> Integer.toString(i), executor)); } @Incoming("DD") public void consume(String item) { items().add(item); } } public abstract static class Spy { List<String> items = new CopyOnWriteArrayList<>(); static ExecutorService executor = Executors.newSingleThreadExecutor(); public List<String> items() { return items; } public void close() { executor.shutdown(); } abstract Emitter<Integer> getEmitter(); } }
8,445
34.045643
147
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/ported/signatures/SubscriberSignatureTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.ported.signatures; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils.await; import static org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils.checkList; import java.util.List; import java.util.PropertyPermission; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Message; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; import org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils; /** * Ported from Quarkus and adjusted * * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ServerSetup(EnableReactiveExtensionsSetupTask.class) @RunWith(Arquillian.class) public class SubscriberSignatureTestCase { @Deployment public static WebArchive enableExtensions() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "rx-messaging-subscriber-signature.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(SubscriberSignatureTestCase.class, BeanUsingSubscriberOfPayload.class, BeanUsingSubscriberOfMessage.class, BeanUsingConsumerMethod.class, BeanConsumingMessages.class, BeanConsumingPayloads.class, Spy.class) .addClasses(ReactiveMessagingTestUtils.class, TimeoutUtil.class, EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class) .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read") ), "permissions.xml"); return webArchive; } @Inject BeanUsingSubscriberOfPayload beanUsingSubscriberOfPayload; @Inject BeanUsingSubscriberOfMessage beanUsingSubscriberOfMessage; @Inject BeanUsingConsumerMethod beanUsingConsumerMethod; @Inject BeanConsumingMessages beanConsumingMessages; @Inject BeanConsumingPayloads beanConsumingPayloads; @Test public void testMethodReturningASubscriberOfPayload() { Emitter<Integer> emitter = beanUsingSubscriberOfPayload.emitter(); List<Integer> items = beanUsingSubscriberOfPayload.getItems(); emit(emitter); await(() -> items.size() == 10); checkList(items, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); Assert.assertTrue(beanUsingSubscriberOfPayload.hasCompleted()); } private void emit(Emitter<Integer> emitter) { CountDownLatch completedLatch = new CountDownLatch(1); new Thread(() -> { for (int i = 0; i < 10; i++) { emitter.send(i); } emitter.complete(); completedLatch.countDown(); }).start(); try { completedLatch.await(3, TimeUnit.SECONDS); } catch (InterruptedException e) { // Rethrow as an unchecked exception to keep this test as similar as possible to the original Quarkus // code (I don't want to declare every method to throw Exception) throw new RuntimeException(e); } } @Test public void testMethodReturningASubscriberOfMessage() { Emitter<Integer> emitter = beanUsingSubscriberOfMessage.emitter(); List<Integer> items = beanUsingSubscriberOfMessage.getItems(); emit(emitter); await(() -> items.size() == 10); checkList(items, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); Assert.assertEquals(10, beanUsingSubscriberOfMessage.getMessages().size()); Assert.assertTrue(beanUsingSubscriberOfPayload.hasCompleted()); } @Test public void testMethodConsumingPayloadSynchronously() { Emitter<Integer> emitter = beanUsingConsumerMethod.emitter(); List<Integer> items = beanUsingConsumerMethod.getItems(); emit(emitter); await(() -> items.size() == 10); checkList(items, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); } @Test public void testMethodConsumingPayloadAsynchronously() { Emitter<Integer> emitter = beanConsumingPayloads.emitter(); List<Integer> items = beanConsumingPayloads.getItems(); emit(emitter); await(() -> items.size() == 10); checkList(items, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); } @Test public void testMethodConsumingMessages() { Emitter<Integer> emitter = beanConsumingMessages.emitter(); List<Integer> items = beanConsumingMessages.getItems(); emit(emitter); await(() -> items.size() == 10); checkList(items, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); Assert.assertEquals(10, beanConsumingMessages.getMessages().size()); } @ApplicationScoped public static class BeanUsingSubscriberOfPayload extends Spy { @Inject @Channel("A") Emitter<Integer> emitter; public Emitter<Integer> emitter() { return emitter; } @SuppressWarnings("SubscriberImplementation") @Incoming("A") public Subscriber<Integer> consume() { return new Subscriber<Integer>() { @Override public void onSubscribe(Subscription subscription) { subscription.request(10); } @Override public void onNext(Integer o) { items.add(o); } @Override public void onError(Throwable throwable) { failure.set(throwable); } @Override public void onComplete() { completed.set(true); } }; } } @ApplicationScoped public static class BeanUsingSubscriberOfMessage extends Spy { @Inject @Channel("B") Emitter<Integer> emitter; public Emitter<Integer> emitter() { return emitter; } @SuppressWarnings("SubscriberImplementation") @Incoming("B") public Subscriber<Message<Integer>> consume() { return new Subscriber<Message<Integer>>() { @Override public void onSubscribe(Subscription subscription) { subscription.request(10); } @Override public void onNext(Message<Integer> o) { messages.add(o); items.add(o.getPayload()); } @Override public void onError(Throwable throwable) { failure.set(throwable); } @Override public void onComplete() { completed.set(true); } }; } } @ApplicationScoped public static class BeanUsingConsumerMethod extends Spy { @Inject @Channel("C") Emitter<Integer> emitter; public Emitter<Integer> emitter() { return emitter; } @Incoming("C") public void consume(Integer i) { items.add(i); } } @ApplicationScoped public static class BeanConsumingMessages extends Spy { @Inject @Channel("D") Emitter<Integer> emitter; public Emitter<Integer> emitter() { return emitter; } @Incoming("D") public CompletionStage<Void> consume(Message<Integer> message) { getItems().add(message.getPayload()); getMessages().add(message); return message.ack(); } } @ApplicationScoped public static class BeanConsumingPayloads extends Spy { @Inject @Channel("E") Emitter<Integer> emitter; public Emitter<Integer> emitter() { return emitter; } @Incoming("E") public CompletionStage<Void> consume(Integer item) { getItems().add(item); return CompletableFuture.completedFuture(null); } } public static class Spy { AtomicBoolean completed = new AtomicBoolean(); AtomicReference<Throwable> failure = new AtomicReference<>(); List<Integer> items = new CopyOnWriteArrayList<>(); List<Message<Integer>> messages = new CopyOnWriteArrayList<>(); public boolean hasCompleted() { return completed.get(); } public List<Integer> getItems() { return items; } public List<Message<Integer>> getMessages() { return messages; } } }
11,105
32.451807
147
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/ported/signatures/ProcessorSignatureTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.ported.signatures; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils.await; import static org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils.checkList; import java.util.List; import java.util.PropertyPermission; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.ProcessorBuilder; import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.AfterClass; import org.junit.Test; import org.junit.runner.RunWith; import org.reactivestreams.Processor; import org.reactivestreams.Publisher; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; import org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils.ReactiveMessagingTestUtils; /** * Ported from Quarkus and adjusted * * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ServerSetup(EnableReactiveExtensionsSetupTask.class) @RunWith(Arquillian.class) public class ProcessorSignatureTestCase { @Deployment public static WebArchive enableExtensions() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "rx-messaging-processor-signature.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(ProcessorSignatureTestCase.class, BeanProducingAProcessorOfMessage.class, BeanProducingAProcessorOfPayload.class, BeanProducingAProcessorBuilderOfMessage.class, BeanProducingAProcessorBuilderOfPayload.class, BeanProducingAPublisherOfPayload.class, BeanProducingAPublisherOfMessage.class, BeanProducingAPublisherBuilderOfPayload.class, BeanProducingAPublisherBuilderOfMessage.class, BeanConsumingMessages.class, BeanConsumingPayloads.class, BeanConsumingMessagesAsynchronously.class, BeanConsumingPayloadsAsynchronously.class, Spy.class) .addClasses(ReactiveMessagingTestUtils.class, TimeoutUtil.class, EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class) .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read") ), "permissions.xml"); return webArchive; } @Inject BeanProducingAProcessorOfMessage beanProducingAProcessorOfMessage; @Inject BeanProducingAProcessorOfPayload beanProducingAProcessorOfPayload; @Inject BeanProducingAProcessorBuilderOfMessage beanProducingAPublisherBuilderOfMessage; @Inject BeanProducingAProcessorBuilderOfPayload beanProducingAProcessorBuilderOfPayload; @Inject BeanProducingAPublisherOfPayload beanProducingAPublisherOfPayload; @Inject BeanProducingAPublisherOfMessage beanProducingAPublisherOfMessage; @Inject BeanProducingAPublisherBuilderOfPayload beanProducingAPublisherBuilderOfPayloads; @Inject BeanProducingAPublisherBuilderOfMessage beanProducingAPublisherBuilderOfMessages; @Inject BeanConsumingMessages beanConsumingMessages; @Inject BeanConsumingPayloads beanConsumingPayloads; @Inject BeanConsumingMessagesAsynchronously beanConsumingMessagesAsynchronously; @Inject BeanConsumingPayloadsAsynchronously beanConsumingPayloadsAsynchronously; @AfterClass public static void close() { Spy.executor.shutdown(); } @Test public void test() { check(beanProducingAProcessorOfMessage); check(beanProducingAPublisherBuilderOfMessage); check(beanProducingAProcessorOfPayload); check(beanProducingAProcessorBuilderOfPayload); checkDouble(beanProducingAPublisherOfPayload); checkDouble(beanProducingAPublisherOfMessage); checkDouble(beanProducingAPublisherBuilderOfMessages); checkDouble(beanProducingAPublisherBuilderOfPayloads); check(beanConsumingMessages); check(beanConsumingPayloads); check(beanConsumingPayloadsAsynchronously); check(beanConsumingMessagesAsynchronously); } private void check(Spy spy) { new Thread(() -> { for (int i = 0; i < 10; i++) { spy.getEmitter().send(i); } spy.getEmitter().complete(); }).start(); await(() -> spy.getItems().size() == 10); checkList(spy.getItems(), "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); } private void checkDouble(Spy spy) { new Thread(() -> { for (int i = 0; i < 10; i++) { spy.getEmitter().send(i); } spy.getEmitter().complete(); }).start(); await(() -> spy.getItems().size() == 20); checkList(spy.getItems(), "0", "0", "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", "6", "6", "7", "7", "8", "8", "9", "9"); } @ApplicationScoped public static class BeanProducingAProcessorOfMessage extends Spy { @Inject @Channel("A") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("A") @Outgoing("AA") public Processor<Message<Integer>, Message<String>> process() { return ReactiveStreams.<Message<Integer>> builder() .map(m -> Message.of(Integer.toString(m.getPayload()))) .buildRs(); } @Incoming("AA") public void consume(String item) { getItems().add(item); } } @ApplicationScoped public static class BeanProducingAProcessorBuilderOfMessage extends Spy { @Inject @Channel("B") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("B") @Outgoing("BB") public ProcessorBuilder<Message<Integer>, Message<String>> process() { return ReactiveStreams.<Message<Integer>> builder() .map(m -> Message.of(Integer.toString(m.getPayload()))); } @Incoming("BB") public void consume(String item) { getItems().add(item); } } @ApplicationScoped public static class BeanProducingAProcessorOfPayload extends Spy { @Inject @Channel("C") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("C") @Outgoing("CC") public Processor<Integer, String> process() { return ReactiveStreams.<Integer> builder() .map(m -> Integer.toString(m)) .buildRs(); } @Incoming("CC") public void consume(String item) { getItems().add(item); } } @ApplicationScoped public static class BeanProducingAProcessorBuilderOfPayload extends Spy { @Inject @Channel("D") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("D") @Outgoing("DD") public ProcessorBuilder<Integer, String> process() { return ReactiveStreams.<Integer> builder() .map(m -> Integer.toString(m)); } @Incoming("DD") public void consume(String item) { getItems().add(item); } } @ApplicationScoped public static class BeanProducingAPublisherOfPayload extends Spy { @Inject @Channel("E") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("E") @Outgoing("EE") public Publisher<String> process(int item) { return ReactiveStreams.of(item, item).map(i -> Integer.toString(i)).buildRs(); } @Incoming("EE") public void consume(String item) { getItems().add(item); } } @ApplicationScoped public static class BeanProducingAPublisherOfMessage extends Spy { @Inject @Channel("F") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("F") @Outgoing("FF") public Publisher<Message<String>> process(Message<Integer> item) { return ReactiveStreams.of(item.getPayload(), item.getPayload()).map(i -> Integer.toString(i)) .map(Message::of) .buildRs(); } @Incoming("FF") public void consume(String item) { getItems().add(item); } } @ApplicationScoped public static class BeanProducingAPublisherBuilderOfMessage extends Spy { @Inject @Channel("G") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("G") @Outgoing("GG") public PublisherBuilder<Message<String>> process(Message<Integer> item) { return ReactiveStreams.of(item.getPayload(), item.getPayload()).map(i -> Integer.toString(i)) .map(Message::of); } @Incoming("GG") public void consume(String item) { getItems().add(item); } } @ApplicationScoped public static class BeanProducingAPublisherBuilderOfPayload extends Spy { @Inject @Channel("H") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("H") @Outgoing("HH") public PublisherBuilder<String> process(int item) { return ReactiveStreams.of(item, item).map(i -> Integer.toString(i)); } @Incoming("HH") public void consume(String item) { getItems().add(item); } } @ApplicationScoped public static class BeanConsumingMessages extends Spy { @Inject @Channel("I") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("I") @Outgoing("II") public Message<String> process(Message<Integer> item) { return Message.of(Integer.toString(item.getPayload())); } @Incoming("II") public void consume(String item) { getItems().add(item); } } @ApplicationScoped public static class BeanConsumingPayloads extends Spy { @Inject @Channel("J") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("J") @Outgoing("JJ") public String process(Integer item) { return Integer.toString(item); } @Incoming("JJ") public void consume(String item) { getItems().add(item); } } @ApplicationScoped public static class BeanConsumingMessagesAsynchronously extends Spy { @Inject @Channel("K") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("K") @Outgoing("KK") public CompletionStage<Message<String>> process(Message<Integer> item) { return CompletableFuture.supplyAsync(() -> Message.of(Integer.toString(item.getPayload())), executor); } @Incoming("KK") public void consume(String item) { getItems().add(item); } } @ApplicationScoped public static class BeanConsumingPayloadsAsynchronously extends Spy { @Inject @Channel("L") Emitter<Integer> emitter; public Emitter<Integer> getEmitter() { return emitter; } @Incoming("L") @Outgoing("LL") public CompletableFuture<String> process(Integer item) { return CompletableFuture.supplyAsync(() -> Integer.toString(item), executor); } @Incoming("LL") public void consume(String item) { getItems().add(item); } } public abstract static class Spy { List<String> items = new CopyOnWriteArrayList<>(); static ExecutorService executor = Executors.newSingleThreadExecutor(); public List<String> getItems() { return items; } abstract Emitter<Integer> getEmitter(); } }
15,099
30.589958
147
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/ported/channels/EmitterExample.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.ported.channels; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; import org.eclipse.microprofile.reactive.messaging.Incoming; /** * Copied from Quarkus and adjusted * * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ApplicationScoped public class EmitterExample { @Inject @Channel("sink") Emitter<String> emitter; private final List<String> list = new CopyOnWriteArrayList<>(); public void run() { emitter.send("a"); emitter.send("b"); emitter.send("c"); emitter.complete(); } @Incoming("sink") public void consume(String s) { list.add(s); } public List<String> list() { return list; } }
2,032
30.276923
85
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/ported/channels/EmitterWithOverflowTest.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.ported.channels; import java.util.List; import jakarta.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; /** * Ported from Quarkus and adjusted * * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ServerSetup(EnableReactiveExtensionsSetupTask.class) @RunWith(Arquillian.class) public class EmitterWithOverflowTest { @Deployment public static WebArchive createDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "rx-messaging-emitter-with-overflow.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(ChannelEmitterWithOverflow.class) .addClasses(EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class); return webArchive; } @Inject ChannelEmitterWithOverflow bean; @Test public void testEmitter() { bean.run(); List<String> list = bean.list(); Assert.assertEquals(3, list.size()); Assert.assertEquals("a", list.get(0)); Assert.assertEquals("b", list.get(1)); Assert.assertEquals("c", list.get(2)); List<String> sink1 = bean.sink1(); Assert.assertEquals(3, sink1.size()); Assert.assertEquals("a1", sink1.get(0)); Assert.assertEquals("b1", sink1.get(1)); Assert.assertEquals("c1", sink1.get(2)); List<String> sink2 = bean.sink2(); Assert.assertEquals(3, sink2.size()); Assert.assertEquals("a2", sink2.get(0)); Assert.assertEquals("b2", sink2.get(1)); Assert.assertEquals("c2", sink2.get(2)); } }
3,189
36.093023
115
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/ported/channels/ChannelEmitterWithOverflow.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.ported.channels; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.OnOverflow; @ApplicationScoped public class ChannelEmitterWithOverflow { @Inject @Channel("sink") @OnOverflow(value = OnOverflow.Strategy.BUFFER) Emitter<String> emitter; private Emitter<String> emitterForSink2; private Emitter<String> emitterForSink1; @Inject public void setEmitter(@Channel("sink-1") Emitter<String> sink1, @Channel("sink-2") @OnOverflow(value = OnOverflow.Strategy.BUFFER, bufferSize = 4) Emitter<String> sink2) { this.emitterForSink1 = sink1; this.emitterForSink2 = sink2; } private final List<String> list = new CopyOnWriteArrayList<>(); private final List<String> sink1 = new CopyOnWriteArrayList<>(); private final List<String> sink2 = new CopyOnWriteArrayList<>(); public void run() { emitter.send("a"); emitter.send("b"); emitter.send("c").toCompletableFuture().join(); emitter.complete(); emitterForSink1.send("a1"); emitterForSink1.send("b1").toCompletableFuture().join(); emitterForSink1.send("c1"); emitterForSink1.complete(); emitterForSink2.send("a2").toCompletableFuture().join(); emitterForSink2.send("b2"); emitterForSink2.send("c2"); emitterForSink2.complete(); } @Incoming("sink") public void consume(String s) { list.add(s); } @Incoming("sink-1") public void consume1(String s) { sink1.add(s); } @Incoming("sink-2") public void consume2(String s) { sink2.add(s); } public List<String> list() { return list; } public List<String> sink1() { return sink1; } public List<String> sink2() { return sink2; } }
3,243
31.118812
119
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/ported/channels/ChannelConsumer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.ported.channels; import java.util.List; import java.util.concurrent.CompletionStage; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; /** * Ported from Quarkus and adjusted * * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ApplicationScoped public class ChannelConsumer { @Inject @Channel("source-channel") PublisherBuilder<Message<String>> sourceStream; public List<String> consume() throws Exception { CompletionStage<List<String>> cs = sourceStream .map(Message::getPayload) .toList() .run(); return cs.toCompletableFuture().get(); } @Outgoing("source-channel") public PublisherBuilder<String> source() { return ReactiveStreams.of("hello", "with", "SmallRye", "reactive", "message"); } }
2,286
35.887097
86
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/ported/utils/ReactiveMessagingTestUtils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.ported.utils; import java.util.Arrays; import java.util.List; import java.util.function.Supplier; import org.jboss.as.test.shared.TimeoutUtil; import org.junit.Assert; /** * Add some utils to make porting of tests from Quarkus easier * * @author <a href="mailto:[email protected]">Kabir Khan</a> */ public class ReactiveMessagingTestUtils { public static void await(Supplier<Boolean> condition) { long end = System.currentTimeMillis() + TimeoutUtil.adjust(5000); while (!condition.get()) { try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } if (System.currentTimeMillis() > end) { throw new IllegalStateException("Timeout"); } } } public static <T> void checkList(List<T> list, T... expected) { List<T> expectedList = Arrays.asList(expected); Assert.assertEquals(expectedList, list); } }
2,100
34.610169
82
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/rest/channels/PublisherToChannelPublisherEndpoint.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.microprofile.reactive.messaging.rest.channels; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.jboss.resteasy.annotations.Stream; import org.reactivestreams.Publisher; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @Path("/publisher-to-channel-publisher") @Produces(MediaType.TEXT_PLAIN) @ApplicationScoped public class PublisherToChannelPublisherEndpoint { @Outgoing("generator") public PublisherBuilder<String> generate() { return ReactiveStreams.of("One", "Zwei", "Tres"); } @Inject @Channel("generator") Publisher<String> publisher; @GET @Path("/poll") @Produces("text/plain") @Stream public Publisher<String> poll() { return publisher; } }
1,814
30.293103
83
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/rest/channels/EmitterToSubscribedChannelPublisherBuilderEndpoint.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.microprofile.reactive.messaging.rest.channels; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletionStage; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.FormParam; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.jboss.resteasy.annotations.Stream; import org.reactivestreams.Publisher; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @Path("/emitter-to-subscribed-channel-publisher-builder") @Produces(MediaType.TEXT_PLAIN) @ApplicationScoped public class EmitterToSubscribedChannelPublisherBuilderEndpoint { List<String> list = new ArrayList<>(); @Inject @Channel("emitter-2") Emitter<String> emitter; CompletionStage<List<String>> completionStage; public EmitterToSubscribedChannelPublisherBuilderEndpoint() { //Needed for weld proxy } @Inject public EmitterToSubscribedChannelPublisherBuilderEndpoint(@Channel("emitter-2") PublisherBuilder<String> publisher) { // We need a subscription or the emitter.send() will fail completionStage = publisher.toList().run(); } @POST @Path("/publish") @Produces("text/plain") public Response publish(@FormParam("value") String value) { if (value.equals("-end-")) { // We have to complete the emitter to end the 'stream' so the completion stage finishes emitter.complete(); } else { emitter.send(value); } return Response.ok().build(); } @GET @Path("/poll") @Produces("text/plain") @Stream public Publisher<String> poll() { PublisherBuilder<List<String>> listBuilder = ReactiveStreams.fromCompletionStage(completionStage); return listBuilder //Flat map to extract the list entries, and convert to // PublishBuilder<String> with the individual list entries .flatMap(list -> ReactiveStreams.of(list.toArray(new String[0]))) .buildRs(); } }
3,115
32.505376
121
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/rest/channels/EmitterToSubscriberEndpoint.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.microprofile.reactive.messaging.rest.channels; import java.util.ArrayList; import java.util.List; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.FormParam; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.jboss.resteasy.annotations.Stream; import org.reactivestreams.Publisher; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @Path("/emitter-to-subscriber") @Produces(MediaType.TEXT_PLAIN) @ApplicationScoped public class EmitterToSubscriberEndpoint { List<String> list = new ArrayList<>(); @Inject @Channel("emitter-1") Emitter<String> emitter; @Incoming("emitter-1") public void dest(String s) { list.add(s); } @POST @Path("/publish") @Produces("text/plain") public Response publish(@FormParam("value") String value) { emitter.send(value); return Response.ok().build(); } @GET @Path("/poll") @Produces("text/plain") @Stream public Publisher<String> poll() { return ReactiveStreams.fromIterable(list).buildRs(); } }
2,148
27.653333
83
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/rest/channels/ReactiveMessagingChannelsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.rest.channels; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.junit.Assert.assertEquals; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.SocketPermission; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; import org.wildfly.test.integration.microprofile.reactive.RunKafkaSetupTask; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({RunKafkaSetupTask.class, EnableReactiveExtensionsSetupTask.class}) public class ReactiveMessagingChannelsTestCase { @ArquillianResource URL url; @Deployment public static WebArchive getDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "rm-channels-client.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .setWebXML(ReactiveMessagingChannelsTestCase.class.getPackage(), "web.xml") .addAsWebInfResource(ReactiveMessagingChannelsTestCase.class.getPackage(), "microprofile-config.properties", "classes/META-INF/microprofile-config.properties") .addClasses(EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class, RunKafkaSetupTask.class) .addClasses( PublisherToChannelPublisherEndpoint.class, EmitterToSubscriberEndpoint.class, EmitterToSubscribedChannelPublisherBuilderEndpoint.class, EmitterToChannelPublisherViaKafkaEndpoint.class) .addAsManifestResource(createPermissionsXmlAsset( new SocketPermission("*", "connect, resolve") ), "permissions.xml"); return webArchive; } @Test public void testPublisherToChannelPublisher() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()){ checkData(client, "publisher-to-channel-publisher/poll", "One", "Zwei", "Tres"); } } @Test public void testEmitterToSubscriber() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()){ postData(client,"emitter-to-subscriber/publish", "Hello"); postData(client,"emitter-to-subscriber/publish", "world"); checkData(client, "emitter-to-subscriber/poll", "Hello", "world"); } } @Test public void testEmitterToSubscribedPublisherBuilder() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()){ postData(client,"emitter-to-subscribed-channel-publisher-builder/publish", "Hola"); postData(client,"emitter-to-subscribed-channel-publisher-builder/publish", "mundo"); postData(client,"emitter-to-subscribed-channel-publisher-builder/publish", "-end-"); checkData(client, "emitter-to-subscribed-channel-publisher-builder/poll", "Hola", "mundo"); } } @Test public void testEmitterToChannelPublisherViaKafka() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()){ postData(client,"emitter-to-subscribed-channel-publisher-via-kafka/publish", "Welcome"); postData(client,"emitter-to-subscribed-channel-publisher-via-kafka/publish", "to"); postData(client,"emitter-to-subscribed-channel-publisher-via-kafka/publish", "Kafka"); // Kafka is slower than the other in-memory examples, so do some retrying here long end = System.currentTimeMillis() + TimeoutUtil.adjust(5000); AssertionError error = null; List<String> expected = Arrays.asList("Welcome", "to", "Kafka"); List<String> list = null; while (System.currentTimeMillis() < end) { Thread.sleep(200); error = null; try { list = getData(client, "emitter-to-subscribed-channel-publisher-via-kafka/poll"); Assert.assertEquals(expected.size(), list.size()); break; } catch (AssertionError e) { error = e; } } if (error != null) { throw error; } List<Integer> partitions = getPartitions(client); // The data may come on different Kafka partitions and ordering is only per partition so do some extra // massaging of the data Assert.assertEquals(expected.size(), list.size()); // Kafka messages only have order per partition, so do some massaging of the data Map<Integer, List<String>> map = new HashMap<>(); for (int i = 0; i < list.size(); i++) { List<String> values = map.computeIfAbsent(partitions.get(i), ind -> new ArrayList<>()); values.add(list.get(i)); } for (String s : expected) { assertValueNextOnAPartition(map, s); } } } private void assertValueNextOnAPartition(Map<Integer, List<String>> map, String value) { String found = null; int remove = -1; for (Map.Entry<Integer, List<String>> entry : map.entrySet()) { List<String> persons = entry.getValue(); String s = persons.get(0); if (s.equals("data: " + value)) { found = s; persons.remove(0); if (persons.size() == 0) { remove = entry.getKey(); } } } map.remove(remove); Assert.assertNotNull("Could not find " + value, found); } private List<Integer> getPartitions(CloseableHttpClient client) throws Exception { List<String> data = getData(client, "emitter-to-subscribed-channel-publisher-via-kafka/partitions"); String value = data.get(0); // The list will be of the format '[0,0,1]' value = value.substring(1, value.length() - 1); List<Integer> list = new ArrayList<>(); String[] values = value.split(","); for (int i = 0; i < values.length; i++) { list.add(Integer.valueOf( values[i].trim())); } return list; } private void postData(CloseableHttpClient client, String path, String value) throws Exception { HttpPost post = new HttpPost(url + path); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("value", value)); post.setEntity(new UrlEncodedFormEntity(nvps)); try (CloseableHttpResponse response = client.execute(post);){ assertEquals(200, response.getStatusLine().getStatusCode()); } } private void checkData(CloseableHttpClient client, String path, String... expected) throws Exception { List<String> lines = getData(client, path); Assert.assertEquals(expected.length, lines.size()); for (int i = 0; i < expected.length; i++) { Assert.assertTrue(lines.get(i).contains(expected[i])); } } private List<String> getData(CloseableHttpClient client, String path) throws Exception { HttpGet get = new HttpGet(url + path); List<String> lines = new ArrayList<>(); try (CloseableHttpResponse response = client.execute(get)){ assertEquals(200, response.getStatusLine().getStatusCode()); try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { while (true) { String line = reader.readLine(); if (line == null) { break; } if (line.length() > 0) { lines.add(line); } } } } return lines; } }
10,292
42.614407
175
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/rest/channels/EmitterToChannelPublisherViaKafkaEndpoint.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.microprofile.reactive.messaging.rest.channels; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.FormParam; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.jboss.resteasy.annotations.Stream; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import io.smallrye.reactive.messaging.kafka.api.KafkaMetadataUtil; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @Path("/emitter-to-subscribed-channel-publisher-via-kafka") @Produces(MediaType.TEXT_PLAIN) @ApplicationScoped public class EmitterToChannelPublisherViaKafkaEndpoint { @Inject @Channel("to-kafka") Emitter<String> emitter; List<String> values = new ArrayList<>(); List<Integer> partitions = new ArrayList(); public EmitterToChannelPublisherViaKafkaEndpoint() { } @Inject public EmitterToChannelPublisherViaKafkaEndpoint(@Channel("from-kafka") Publisher<Message<String>> publisher) { AtomicReference<Subscription> ref = new AtomicReference<>(); publisher.subscribe(new Subscriber<Message<String>>() { @Override public void onSubscribe(Subscription subscription) { subscription.request(1); ref.set(subscription); } @Override public void onNext(Message<String> msg) { values.add(msg.getPayload()); partitions.add(KafkaMetadataUtil.readIncomingKafkaMetadata(msg).get().getPartition()); ref.get().request(1); } @Override public void onError(Throwable throwable) { ref.get().cancel(); } @Override public void onComplete() { ref.get().cancel(); } }); } @POST @Path("/publish") @Produces("text/plain") public Response publish(@FormParam("value") String value) { emitter.send(value); return Response.ok().build(); } @GET @Path("/poll") @Produces("text/plain") @Stream public Publisher<String> poll() { return ReactiveStreams.of(values.toArray(new String[values.size()])).buildRs(); } @GET @Path("/partitions") @Produces("text/plain") public List<Integer> getPartitions() { return partitions; } }
3,558
30.219298
115
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/tx/TransactionalBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.tx; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import jakarta.enterprise.context.ApplicationScoped; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.persistence.TypedQuery; import jakarta.transaction.Transactional; @ApplicationScoped public class TransactionalBean { @PersistenceContext(unitName = "test") EntityManager em; @Transactional public void storeValue(String name) { ContextEntity entity = new ContextEntity(); entity.setName(name); em.persist(entity); } @Transactional public void checkValues(Set<String> names) { checkCount(names.size()); TypedQuery<ContextEntity> query = em.createQuery("SELECT c from ContextEntity c", ContextEntity.class); Set<String> values = query.getResultList().stream().map(v -> v.getName()).collect(Collectors.toSet()); if (!values.containsAll(names) || !names.containsAll(values)) { throw new IllegalStateException("Mismatch of expected names. Expected: " + names + "; actual: " + values); } } @Transactional private int checkCount(int expected) { TypedQuery<Long> query = em.createQuery("SELECT count(c) from ContextEntity c", Long.class); List<Long> result = query.getResultList(); int count = result.get(0).intValue(); if (count != expected) { throw new IllegalStateException("Expected " + expected + "; got " + count); } return count; } }
2,658
35.930556
118
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/tx/ReactiveMessagingTransactionTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.tx; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.util.Collections; import java.util.PropertyPermission; import java.util.concurrent.TimeUnit; import jakarta.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.microprofile.reactive.EnableReactiveExtensionsSetupTask; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @RunWith(Arquillian.class) @ServerSetup(EnableReactiveExtensionsSetupTask.class) public class ReactiveMessagingTransactionTestCase { private static final long TIMEOUT = TimeoutUtil.adjust(15000); @Inject Bean bean; @Inject TransactionalBean txBean; @Deployment public static WebArchive getDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "rx-messaging-tx.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addPackage(ReactiveMessagingTransactionTestCase.class.getPackage()) .addAsWebInfResource(ReactiveMessagingTransactionTestCase.class.getPackage(), "persistence.xml", "classes/META-INF/persistence.xml") .addClasses(TimeoutUtil.class, EnableReactiveExtensionsSetupTask.class, CLIServerSetupTask.class) .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read") ), "permissions.xml"); return webArchive; } @Test public void test() throws InterruptedException { boolean wait = bean.getLatch().await(TIMEOUT, TimeUnit.MILLISECONDS); Assert.assertTrue("Timed out", wait); Assert.assertEquals("hello reactive messaging", bean.getPhrase()); // Check the data was stored txBean.checkValues(Collections.singleton("reactive")); } }
3,429
39.833333
148
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/tx/Bean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.tx; import java.util.Collections; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @ApplicationScoped public class Bean { private final CountDownLatch latch = new CountDownLatch(3); private StringBuilder phrase = new StringBuilder(); @Inject TransactionalBean txBean; private ExecutorService executorService = Executors.newSingleThreadExecutor(); @PreDestroy public void stop() { executorService.shutdown(); } public CountDownLatch getLatch() { return latch; } @Outgoing("source") public PublisherBuilder<String> source() { txBean.checkValues(Collections.emptySet()); return ReactiveStreams.of("hello", "reactive", "messaging"); } @Incoming("source") @Outgoing("sink") public CompletionStage<String> store(String payload) { // Make sure it is on a separate thread. If Context Propagation was enabled, I'd use // a ManagedExecutor return CompletableFuture.supplyAsync(() -> { if (payload.equals("reactive")) { // Add a sleep here to make sure the calling method has returned try { Thread.sleep(3000); } catch (InterruptedException e){ throw new RuntimeException(e); } txBean.storeValue(payload); } return payload; }, executorService); } @Incoming("sink") public void sink(String word) { if (phrase.length() > 0) { phrase.append(" "); } this.phrase.append(word); latch.countDown(); } public String getPhrase() { return phrase.toString(); } }
3,444
33.108911
92
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/reactive/messaging/tx/ContextEntity.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.reactive.messaging.tx; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; /** * @author <a href="mailto:[email protected]">Kabir Khan</a> */ @Entity public class ContextEntity { private Long id; private String name; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
1,637
28.781818
72
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/health/MicroProfileHealthApplicationWithoutReadinessTestBase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.health; import java.io.IOException; import java.net.URL; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Test that an application without any readiness probe got one setup by WildFly so that the application * is considered ready when it is deployed */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({MicroProfileHealthApplicationReadySetupTask.class}) public abstract class MicroProfileHealthApplicationWithoutReadinessTestBase { abstract void checkGlobalOutcome(ManagementClient managementClient, String operation, boolean mustBeUP, String probeName) throws IOException; @Deployment(name = "MicroProfileHealthApplicationWithoutReadinessTestBaseSetup") public static Archive<?> deploySetup() { WebArchive war = ShrinkWrap.create(WebArchive.class, "MicroProfileHealthApplicationWithoutReadinessTestBaseSetup.war") .addClass(MicroProfileHealthApplicationReadySetupTask.class); return war; } // deployment does not define any readiness probe @Deployment(name = "MicroProfileHealthApplicationWithoutReadinessTestBase", managed = false) public static Archive<?> deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, "MicroProfileHealthApplicationWithoutReadinessTestBase.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); return war; } @ContainerResource ManagementClient managementClient; @ArquillianResource private Deployer deployer; @Test @InSequence(1) public void testApplicationReadinessBeforeDeployment() throws Exception { checkGlobalOutcome(managementClient, "check-ready", false, null); // deploy the archive deployer.deploy("MicroProfileHealthApplicationWithoutReadinessTestBase"); } @Test @InSequence(2) @OperateOnDeployment("MicroProfileHealthApplicationWithoutReadinessTestBase") public void testApplicationReadinessAfterDeployment(@ArquillianResource URL url) throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { checkGlobalOutcome(managementClient, "check-ready", true, "ready-deployment.MicroProfileHealthApplicationWithoutReadinessTestBase.war"); } } @Test @InSequence(3) public void testHealthCheckAfterUndeployment() throws Exception { deployer.undeploy("MicroProfileHealthApplicationWithoutReadinessTestBase"); checkGlobalOutcome(managementClient, "check-ready", false, null); } }
4,451
40.222222
148
java
null
wildfly-main/testsuite/integration/microprofile/src/test/java/org/wildfly/test/integration/microprofile/health/MicroProfileHealthApplicationStartupOperationTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.microprofile.health; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.dmr.ModelNode; import java.io.IOException; import static org.jboss.as.controller.operations.common.Util.getEmptyOperation; import static org.wildfly.test.integration.microprofile.health.MicroProfileHealthUtils.testManagementOperation; /** * @author <a href="http://xstefank.io/">Martin Stefanko</a> (c) 2021 Red Hat inc. */ public class MicroProfileHealthApplicationStartupOperationTestCase extends MicroProfileHealthApplicationStartupTestBase { void checkGlobalOutcome(ManagementClient managementClient, String operation, boolean mustBeUP, String probeName) throws IOException { final ModelNode address = new ModelNode(); address.add("subsystem", "microprofile-health-smallrye"); ModelNode checkOp = getEmptyOperation(operation, address); ModelNode response = managementClient.getControllerClient().execute(checkOp); testManagementOperation(response, mustBeUP, probeName); } }
2,093
42.625
137
java