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/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/AddressControlManagementTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.jboss.as.test.integration.messaging.mgmt; import static org.jboss.as.controller.operations.common.Util.getEmptyOperation; import java.io.IOException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.Property; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests the management API for HornetQ core addresss. * * @author Brian Stansberry (c) 2011 Red Hat Inc. */ @RunAsClient() @RunWith(Arquillian.class) public class AddressControlManagementTestCase { private static long count = System.currentTimeMillis(); @ContainerResource private static ManagementClient managementClient; private JMSOperations jmsOperations; @Before public void setup() throws Exception { jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); count++; jmsOperations.addCoreQueue(getQueueName(), getAddress(), false, "anycast"); jmsOperations.addCoreQueue(getOtherQueueName(), getAddress(), false, "anycast"); } @After public void cleanup() throws Exception { jmsOperations.removeCoreQueue(getQueueName()); jmsOperations.removeCoreQueue(getOtherQueueName()); } @Test public void testSubsystemRootOperations() throws Exception { ModelNode op = getSubsystemOperation("read-children-types"); op.get("child-type").set("core-address"); ModelNode result = execute(op, true); Assert.assertTrue(result.isDefined()); boolean found = false; for (ModelNode type : result.asList()) { if ("core-address".equals(type.asString())) { found = true; break; } } Assert.assertTrue(found); op = getSubsystemOperation("read-children-names"); op.get("child-type").set("core-address"); result = execute(op, true); Assert.assertTrue(result.isDefined()); found = false; for (ModelNode address : result.asList()) { if (getAddress().equals(address.asString())) { found = true; break; } } Assert.assertTrue(found); op = getSubsystemOperation("read-children-resources"); op.get("child-type").set("core-address"); result = execute(op, true); Assert.assertTrue(result.isDefined()); found = false; for (Property address : result.asPropertyList()) { if (getAddress().equals(address.getName())) { found = true; break; } } Assert.assertTrue(found); } @Test public void testAddressGlobalOperations() throws Exception { ModelNode op = getAddressOperation("read-children-types"); op.get("child-type").set("core-address"); ModelNode result = execute(op, true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(1, result.asInt()); op = getAddressOperation("read-children-names"); op.get("child-type").set("role"); result = execute(op, true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(1, result.asInt()); op = getAddressOperation("read-children-resources"); op.get("child-type").set("role"); result = execute(op, true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(1, result.asInt()); } @Test public void testReadResource() throws Exception { ModelNode op = getAddressOperation("read-resource"); op.get("include-runtime").set(true); op.get("recursive").set(true); ModelNode result = execute(op, true); Assert.assertEquals(ModelType.OBJECT, result.getType()); Assert.assertEquals(ModelType.OBJECT, result.get("role").getType()); Assert.assertEquals(ModelType.LONG, result.get("number-of-pages").getType()); Assert.assertEquals(ModelType.LONG, result.get("number-of-bytes-per-page").getType()); Assert.assertEquals(ModelType.LIST, result.get("binding-names").getType()); boolean foundMain = false; boolean foundOther = false; for (ModelNode node : result.get("binding-names").asList()) { if (getQueueName().equals(node.asString())) { Assert.assertFalse(foundMain); foundMain = true; } else if (getOtherQueueName().equals(node.asString())) { Assert.assertFalse(foundOther); foundOther = true; } } Assert.assertTrue(foundMain); Assert.assertTrue(foundOther); } private ModelNode getSubsystemOperation(String operationName) { return getEmptyOperation(operationName, jmsOperations.getServerAddress().clone()); } private ModelNode getAddressOperation(String operationName) { final ModelNode address = jmsOperations.getServerAddress().clone(); address.add("core-address", getAddress()); return getEmptyOperation(operationName, address); } private ModelNode execute(final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { /*if (!"success".equals(outcome)) { System.out.println(response); }*/ Assert.assertEquals("success", outcome); return response.get("result"); } else { /*if ("success".equals(outcome)) { System.out.println(response); }*/ Assert.assertEquals("failed", outcome); return response.get("failure-description"); } } private static String getAddress() { return AddressControlManagementTestCase.class.getSimpleName() + count; } private static String getQueueName() { return getAddress(); } private static String getOtherQueueName() { return getAddress() + "other"; } }
7,590
34.806604
99
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/ExternalJMSDestinationManagementTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.jboss.as.test.integration.messaging.mgmt; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import jakarta.jms.Destination; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSException; import jakarta.jms.TextMessage; import javax.naming.Context; import org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests the management API for Jakarta Messaging queues. * * @author Brian Stansberry (c) 2011 Red Hat Inc. */ @RunAsClient() @RunWith(Arquillian.class) public class ExternalJMSDestinationManagementTestCase { private static final Logger LOGGER = Logger.getLogger(ExternalJMSDestinationManagementTestCase.class); public static final String LEGACY_QUEUE_NAME = "myExternalLegacyQueue"; public static final String LEGACY_TOPIC_NAME = "myExternalLegacyTopic"; public static final String QUEUE_NAME = "myExternalQueue"; public static final String TOPIC_NAME = "myExternalTopic"; private static final String CONNECTION_FACTORY_JNDI_NAME = "java:jboss/exported/jms/TestConnectionFactory"; private static Set<String> initialQueues = Collections.emptySet(); @ContainerResource private ManagementClient managementClient; @ContainerResource private Context remoteContext; @Before public void prepareDestinations() throws Exception { if (initialQueues == null || initialQueues.isEmpty()) { initialQueues = listRuntimeQueues(managementClient); } JMSOperations adminSupport = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); adminSupport.addCoreQueue(QUEUE_NAME, QUEUE_NAME, true, "ANYCAST"); adminSupport.addCoreQueue("jms.queue." + LEGACY_QUEUE_NAME, "jms.queue." + LEGACY_QUEUE_NAME, true, "ANYCAST"); adminSupport.addCoreQueue(TOPIC_NAME, TOPIC_NAME, true, "MULTICAST"); adminSupport.addCoreQueue("jms.topic." + LEGACY_TOPIC_NAME, "jms.topic." + LEGACY_TOPIC_NAME, true, "MULTICAST"); ModelNode op = Operations.createAddOperation(adminSupport.getSubsystemAddress().add("external-jms-topic", TOPIC_NAME)); op.get("enable-amq1-prefix").set("false"); op.get("entries").add("java:jboss/exported/jms/topic/" + TOPIC_NAME); managementClient.getControllerClient().execute(op); op = Operations.createAddOperation(adminSupport.getSubsystemAddress().add("external-jms-topic", LEGACY_TOPIC_NAME)); op.get("enable-amq1-prefix").set("true"); op.get("entries").add("java:jboss/exported/jms/topic/" + LEGACY_TOPIC_NAME); managementClient.getControllerClient().execute(op); op = Operations.createAddOperation(adminSupport.getSubsystemAddress().add("external-jms-queue", QUEUE_NAME)); op.get("enable-amq1-prefix").set("false"); op.get("entries").add("java:jboss/exported/jms/queue/" + QUEUE_NAME); managementClient.getControllerClient().execute(op); op = Operations.createAddOperation(adminSupport.getSubsystemAddress().add("external-jms-queue", LEGACY_QUEUE_NAME)); op.get("enable-amq1-prefix").set("true"); op.get("entries").add("java:jboss/exported/jms/queue/" + LEGACY_QUEUE_NAME); managementClient.getControllerClient().execute(op); ModelNode attr = new ModelNode(); if (adminSupport.isRemoteBroker()) { adminSupport.addExternalRemoteConnector("remote-broker-connector", "messaging-activemq"); attr.get("connectors").add("remote-broker-connector"); } else { adminSupport.addExternalHttpConnector("http-test-connector", "http", "http-acceptor"); attr.get("connectors").add("http-test-connector"); } adminSupport.addJmsExternalConnectionFactory("TestConnectionFactory", CONNECTION_FACTORY_JNDI_NAME, attr); adminSupport.close(); } Set<String> listRuntimeQueues(org.jboss.as.arquillian.container.ManagementClient managementClient) throws IOException { JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); ModelNode op = Operations.createOperation("read-children-names", ops.getServerAddress()); op.get("child-type").set("runtime-queue"); ModelNode result = Operations.readResult(managementClient.getControllerClient().execute(op)); List<ModelNode> runtimeQueues = result.asList(); return runtimeQueues.stream().map(ModelNode::asString).collect(Collectors.toSet()); } @Test public void testCreatedDestinations() throws Exception { ActiveMQJMSConnectionFactory cf = (ActiveMQJMSConnectionFactory) remoteContext.lookup("jms/TestConnectionFactory"); Assert.assertNotNull(cf); Destination myExternalQueue = (Destination) remoteContext.lookup("jms/queue/" + QUEUE_NAME); Assert.assertNotNull(myExternalQueue); Destination myLegacyExternalQueue = (Destination) remoteContext.lookup("jms/queue/" + LEGACY_QUEUE_NAME); Assert.assertNotNull(myLegacyExternalQueue); Destination myExternalTopic = (Destination) remoteContext.lookup("jms/topic/" + TOPIC_NAME); Assert.assertNotNull(myExternalTopic); Destination myLegacyExternalTopic = (Destination) remoteContext.lookup("jms/topic/" + LEGACY_TOPIC_NAME); Assert.assertNotNull(myLegacyExternalTopic); try (JMSContext jmsContext = cf.createContext("guest", "guest", JMSContext.AUTO_ACKNOWLEDGE)) { checkJMSDestination(jmsContext, myLegacyExternalQueue); checkJMSDestination(jmsContext, myLegacyExternalTopic); } cf = (ActiveMQJMSConnectionFactory) remoteContext.lookup("jms/TestConnectionFactory"); cf.setEnable1xPrefixes(false); try (JMSContext jmsContext = cf.createContext("guest", "guest", JMSContext.AUTO_ACKNOWLEDGE)) { checkJMSDestination(jmsContext, myExternalQueue); checkJMSDestination(jmsContext, myExternalTopic); } JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); if (!ops.isRemoteBroker()) { ModelNode op = Operations.createOperation("read-children-names", ops.getServerAddress()); op.get("child-type").set("runtime-queue"); List<ModelNode> runtimeQueues = Operations.readResult(managementClient.getControllerClient().execute(op)).asList(); Set<String> queues = runtimeQueues.stream().map(ModelNode::asString).collect(Collectors.toSet()); Assert.assertEquals(initialQueues.size() + 4, queues.size()); Assert.assertTrue("We should have myExternalQueue queue", queues.contains(QUEUE_NAME)); Assert.assertTrue("We should have myExternalQueue queue", queues.contains("jms.queue." + LEGACY_QUEUE_NAME)); queues.removeAll(initialQueues); queues.remove(QUEUE_NAME); queues.remove("jms.queue." + LEGACY_QUEUE_NAME); checkRuntimeQueue(ops, QUEUE_NAME, "ANYCAST", QUEUE_NAME); checkRuntimeQueue(ops, "jms.queue." + LEGACY_QUEUE_NAME, "ANYCAST", "jms.queue." + LEGACY_QUEUE_NAME); for (String topicId : queues) { checkRuntimeTopic(ops, topicId); } } } private void checkJMSDestination(JMSContext jmsContext, Destination destination) throws JMSException { String message = "Sending message to " + destination.toString(); try (JMSConsumer consumer = jmsContext.createConsumer(destination)) { jmsContext.createProducer().send(destination, jmsContext.createTextMessage(message)); TextMessage msg = (TextMessage) consumer.receive(TimeoutUtil.adjust(5000)); Assert.assertNotNull(msg); Assert.assertEquals(message, msg.getText()); } } private void checkRuntimeQueue(JMSOperations ops, String name, String expectedRoutingType, String expectedQueueAddress) throws IOException { ModelNode op = Operations.createReadResourceOperation(ops.getServerAddress().add("runtime-queue", name), false); op.get("include-runtime").set(true); op.get("include-defaults").set(true); ModelNode result = Operations.readResult(managementClient.getControllerClient().execute(op)); Assert.assertEquals("ANYCAST", result.require("routing-type").asString()); Assert.assertEquals(expectedQueueAddress, result.require("queue-address").asString()); } private void checkRuntimeTopic(JMSOperations ops, String topicId) throws IOException { ModelNode op = Operations.createReadResourceOperation(ops.getServerAddress().add("runtime-queue", topicId), false); op.get("include-runtime").set(true); op.get("include-defaults").set(true); ModelNode result = Operations.readResult(managementClient.getControllerClient().execute(op)); String address = result.require("queue-address").asString(); Assert.assertTrue(address.equals("jms.topic." + LEGACY_TOPIC_NAME) || address.equals(TOPIC_NAME)); Assert.assertEquals("MULTICAST", result.require("routing-type").asString()); } @After public void removeQueues() throws Exception { JMSOperations adminSupport = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); adminSupport.removeCoreQueue(QUEUE_NAME); adminSupport.removeCoreQueue("jms.queue." + LEGACY_QUEUE_NAME); adminSupport.removeCoreQueue(TOPIC_NAME); adminSupport.removeCoreQueue("jms.topic." + LEGACY_TOPIC_NAME); ModelNode op = Operations.createRemoveOperation(adminSupport.getSubsystemAddress().add("external-jms-topic", TOPIC_NAME)); managementClient.getControllerClient().execute(op); op = Operations.createRemoveOperation(adminSupport.getSubsystemAddress().add("external-jms-topic", LEGACY_TOPIC_NAME)); managementClient.getControllerClient().execute(op); op = Operations.createRemoveOperation(adminSupport.getSubsystemAddress().add("external-jms-queue", QUEUE_NAME)); managementClient.getControllerClient().execute(op); op = Operations.createRemoveOperation(adminSupport.getSubsystemAddress().add("external-jms-queue", LEGACY_QUEUE_NAME)); managementClient.getControllerClient().execute(op); adminSupport.removeJmsExternalConnectionFactory("TestConnectionFactory"); if (adminSupport.isRemoteBroker()) { adminSupport.removeExternalRemoteConnector("remote-broker-connector"); } else { adminSupport.removeExternalHttpConnector("http-test-connector"); } adminSupport.close(); } }
12,426
55.486364
144
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/GenericJmsResourceAdpterTestCase.java
/* * Copyright 2022 JBoss by Red Hat. * * 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.jboss.as.test.integration.messaging.mgmt; import java.io.IOException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Simple test trying to deploy the Generic JMS Resource Adapter * * @author Emmanuel Hugonnet (c) 2022 Red Hat, Inc. */ @RunAsClient() @RunWith(Arquillian.class) public class GenericJmsResourceAdpterTestCase { private static final Logger LOGGER = Logger.getLogger(GenericJmsResourceAdpterTestCase.class); @ContainerResource private ManagementClient managementClient; @Test public void testAddResourceAdapter() throws Exception { ModelNode op = new ModelNode(); op.get(ClientConstants.OP_ADDR).add("subsystem", "resource-adapters"); op.get(ClientConstants.OP_ADDR).add("resource-adapter", "MyResourceAdapter"); op.get(ClientConstants.OP).set(ClientConstants.ADD); op.get("module").set("org.jboss.genericjms"); execute(op, true); op = new ModelNode(); op.get(ClientConstants.OP_ADDR).add("subsystem", "resource-adapters"); op.get(ClientConstants.OP_ADDR).add("resource-adapter", "MyResourceAdapter"); op.get(ClientConstants.OP).set(ClientConstants.REMOVE_OPERATION); execute(op, true); } private ModelNode execute(final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { if (!"success".equals(outcome)) { LOGGER.trace(response); } Assert.assertEquals("success", outcome); return response.get("result"); } else { if ("success".equals(outcome)) { LOGGER.trace(response); } Assert.assertEquals("failed", outcome); return response.get("failure-description"); } } }
2,938
37.671053
99
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/metrics/JMSThreadPoolMetricsUtil.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, 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.jboss.as.test.integration.messaging.mgmt.metrics; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.junit.Assert; import jakarta.jms.Destination; import jakarta.jms.JMSException; import jakarta.jms.Message; import jakarta.jms.MessageConsumer; import jakarta.jms.MessageProducer; import jakarta.jms.Session; import jakarta.jms.TextMessage; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Ivan Straka */ public class JMSThreadPoolMetricsUtil { public static final String SCHEDULED_ACTIVE_COUNT = "global-client-scheduled-thread-pool-active-count"; public static final String SCHEDULED_COMPLETED_COUNT = "global-client-scheduled-thread-pool-completed-task-count"; public static final String SCHEDULED_CURRENT_COUNT = "global-client-scheduled-thread-pool-current-thread-count"; public static final String SCHEDULED_KEEPALIVE_TIME = "global-client-scheduled-thread-pool-keepalive-time"; public static final String SCHEDULED_LARGEST_COUNT = "global-client-scheduled-thread-pool-largest-thread-count"; public static final String SCHEDULED_TASK_COUNT = "global-client-scheduled-thread-pool-task-count"; public static final String ACTIVE_COUNT = "global-client-thread-pool-active-count"; public static final String COMPLETED_COUNT = "global-client-thread-pool-completed-task-count"; public static final String CURRENT_COUNT = "global-client-thread-pool-current-thread-count"; public static final String KEEPALIVE_TIME = "global-client-thread-pool-keepalive-time"; public static final String LARGEST_COUNT = "global-client-thread-pool-largest-thread-count"; public static final String TASK_COUNT = "global-client-thread-pool-task-count"; public static final int MESSAGES_COUNT = 10; private static final ModelNode READ_MESSAGING_SUBSYSTEM_OPERATION = new ModelNode(); static { ModelNode serverAddress = new ModelNode(); serverAddress.add("subsystem", "messaging-activemq"); READ_MESSAGING_SUBSYSTEM_OPERATION.get("address").set(serverAddress); READ_MESSAGING_SUBSYSTEM_OPERATION.get("operation").set("read-resource"); READ_MESSAGING_SUBSYSTEM_OPERATION.get("include-runtime").set(true); } public static Map<String, ModelNode> getResources(ManagementClient client) throws IOException { Map<String, ModelNode> resources = new HashMap<>(); List<Property> propertyList = client.getControllerClient().execute(READ_MESSAGING_SUBSYSTEM_OPERATION).require("result").asPropertyList(); for (Property property : propertyList) { resources.put(property.getName(), property.getValue()); } return resources; } public static void send(final Session session, final Destination dest, final String text, final boolean useRCF) throws JMSException { TextMessage message = session.createTextMessage(text); message.setJMSReplyTo(dest); message.setBooleanProperty("useRCF", useRCF); try (MessageProducer messageProducer = session.createProducer(dest)) { messageProducer.send(message); } } public static boolean useRCF(TextMessage message) throws JMSException { return message.getBooleanProperty("useRCF"); } public static void reply(final Session session, final Destination dest, final TextMessage message) throws JMSException { final Message replyMsg = session.createTextMessage(message.getText()); replyMsg.setJMSCorrelationID(message.getJMSMessageID()); try (MessageProducer messageProducer = session.createProducer(dest)) { messageProducer.send(message); } } public static TextMessage receiveReply(final Session session, final Destination dest, final long waitInMillis) throws JMSException { try (MessageConsumer consumer = session.createConsumer(dest)) { return (TextMessage) consumer.receive(waitInMillis); } } public static void assertGreater(String message, long greater, long lesser) { Assert.assertTrue(String.format("%s: expected <%d> is greater than <%d>", message, greater, lesser), greater > lesser); } public static void assertGreaterOrEqual(String message, long greater, long lesser) { Assert.assertTrue(String.format("%s: expected <%d> is greater or equal to <%d>", message, greater, lesser), greater >= lesser); } }
5,563
45.756303
146
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/metrics/ThreadPoolMetricsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, 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.jboss.as.test.integration.messaging.mgmt.metrics; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.annotation.Resource; import jakarta.jms.Connection; import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSException; import jakarta.jms.Queue; import jakarta.jms.Session; import jakarta.jms.TextMessage; import java.io.IOException; import java.util.Map; import java.util.PropertyPermission; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.io.File; import java.io.FilePermission; import org.jboss.remoting3.security.RemotingPermission; /** * @author Ivan Straka */ @RunWith(Arquillian.class) @ServerSetup({JMSThreadPoolMetricsSetup.class}) public class ThreadPoolMetricsTestCase { private static final Logger logger = Logger.getLogger(ThreadPoolMetricsTestCase.class); @Resource(mappedName = "java:/ConnectionFactory") ConnectionFactory connectionFactory; @Resource(mappedName = "java:jboss/metrics/queue") private Queue queue; @Resource(mappedName = "java:jboss/metrics/replyQueue") private Queue replyQueue; @ArquillianResource private ManagementClient managementClient; @Deployment public static JavaArchive getDeployment() { final JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, "ArtemisThreadpoolMetricsTestCase.jar"); ejbJar.addPackage(TimeoutUtil.class.getPackage()); ejbJar.addClasses(JMSThreadPoolMetricsSetup.class, JMSThreadPoolMetricsMDB.class, JMSThreadPoolMetricsUtil.class); ejbJar.addAsManifestResource(new StringAsset("Dependencies: org.jboss.as.controller-client, org.jboss.dmr, org.jboss.remoting\n"), "MANIFEST.MF"); ejbJar.addAsManifestResource(createPermissionsXmlAsset( new FilePermission(System.getProperty("jboss.inst") + File.separatorChar + "standalone" + File.separatorChar + "tmp" + File.separatorChar + "auth" + File.separatorChar + "*", "read"), new PropertyPermission("ts.timeout.factor", "read"), RemotingPermission.CREATE_ENDPOINT, RemotingPermission.CONNECT), "jboss-permissions.xml"); return ejbJar; } @Test public void metricsAvailableTest() throws IOException { Map<String, ModelNode> resources = JMSThreadPoolMetricsUtil.getResources(managementClient); // global thread pool metrics Assert.assertTrue(resources.containsKey(JMSThreadPoolMetricsUtil.ACTIVE_COUNT)); Assert.assertTrue(resources.containsKey(JMSThreadPoolMetricsUtil.COMPLETED_COUNT)); Assert.assertTrue(resources.containsKey(JMSThreadPoolMetricsUtil.CURRENT_COUNT)); Assert.assertTrue(resources.containsKey(JMSThreadPoolMetricsUtil.KEEPALIVE_TIME)); Assert.assertTrue(resources.containsKey(JMSThreadPoolMetricsUtil.LARGEST_COUNT)); Assert.assertTrue(resources.containsKey(JMSThreadPoolMetricsUtil.TASK_COUNT)); } @Test public void globalThreadPoolMetricsTestCase() throws JMSException, IOException, InterruptedException { Map<String, ModelNode> resources = JMSThreadPoolMetricsUtil.getResources(managementClient); long activeCount = resources.get(JMSThreadPoolMetricsUtil.ACTIVE_COUNT).asLong(); long completedCount = resources.get(JMSThreadPoolMetricsUtil.COMPLETED_COUNT).asLong(); long currentCount = resources.get(JMSThreadPoolMetricsUtil.CURRENT_COUNT).asLong(); long largestCount = resources.get(JMSThreadPoolMetricsUtil.LARGEST_COUNT).asLong(); long taskCount = resources.get(JMSThreadPoolMetricsUtil.TASK_COUNT).asLong(); long scheduledCompletedCount = resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_COMPLETED_COUNT).asLong(); long scheduledCurrentCount = resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_CURRENT_COUNT).asLong(); long scheduledLargestCount = resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_LARGEST_COUNT).asLong(); long scheduledTaskCount = resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_TASK_COUNT).asLong(); try (Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) { connection.start(); for (int i = 0; i < JMSThreadPoolMetricsUtil.MESSAGES_COUNT; i++) { JMSThreadPoolMetricsUtil.send(session, queue, "id=" + i, false); } // we are in the middle of processing Thread.sleep(100); resources = JMSThreadPoolMetricsUtil.getResources(managementClient); JMSThreadPoolMetricsUtil.assertGreater("active count", resources.get(JMSThreadPoolMetricsUtil.ACTIVE_COUNT).asLong(), activeCount); JMSThreadPoolMetricsUtil.assertGreater("current count", resources.get(JMSThreadPoolMetricsUtil.CURRENT_COUNT).asLong(), 0); JMSThreadPoolMetricsUtil.assertGreaterOrEqual("current count", resources.get(JMSThreadPoolMetricsUtil.CURRENT_COUNT).asLong(), currentCount); Assert.assertEquals("scheduled current count", scheduledCurrentCount, resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_CURRENT_COUNT).asLong()); // read responses for (int i = 0; i < JMSThreadPoolMetricsUtil.MESSAGES_COUNT; i++) { TextMessage textMessage = JMSThreadPoolMetricsUtil.receiveReply(session, replyQueue, TimeoutUtil.adjust(5000)); logger.trace("got reply for [" + textMessage.getText() + "]"); } } // messages have been processed resources = JMSThreadPoolMetricsUtil.getResources(managementClient); JMSThreadPoolMetricsUtil.assertGreater("completed count", resources.get(JMSThreadPoolMetricsUtil.COMPLETED_COUNT).asLong(), completedCount); JMSThreadPoolMetricsUtil.assertGreater("largest count", resources.get(JMSThreadPoolMetricsUtil.LARGEST_COUNT).asLong(), 0); JMSThreadPoolMetricsUtil.assertGreaterOrEqual("largest count", resources.get(JMSThreadPoolMetricsUtil.LARGEST_COUNT).asLong(), largestCount); JMSThreadPoolMetricsUtil.assertGreater("task count", resources.get(JMSThreadPoolMetricsUtil.TASK_COUNT).asLong(), taskCount); Assert.assertEquals("scheduled completed count", scheduledCompletedCount, resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_COMPLETED_COUNT).asLong()); Assert.assertEquals("scheduled count", scheduledCompletedCount, resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_COMPLETED_COUNT).asLong()); Assert.assertEquals("scheduled largest count", scheduledLargestCount, resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_LARGEST_COUNT).asLong()); Assert.assertEquals("scheduled task count", scheduledTaskCount, resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_TASK_COUNT).asLong()); } }
8,446
53.850649
199
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/metrics/JMSThreadPoolMetricsSetup.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, 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.jboss.as.test.integration.messaging.mgmt.metrics; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; import org.junit.Assert; import java.io.IOException; import org.jboss.as.controller.client.helpers.Operations; /** * @author Ivan Straka */ class JMSThreadPoolMetricsSetup implements ServerSetupTask { private JMSOperations jmsAdminOperations; private ModelNode rcfConnectors; private ModelNode readRemoteCFConnectors(ManagementClient client) throws IOException { ModelNode op = new ModelNode(); op.get("address").set(jmsAdminOperations.getServerAddress().add("connection-factory", "RemoteConnectionFactory")); op.get("operation").set("read-attribute"); op.get("name").set("connectors"); ModelNode execute = client.getControllerClient().execute(op); Assert.assertTrue(Operations.isSuccessfulOutcome(execute)); return Operations.readResult(execute); } private void writeRemoteCFConnectors(ManagementClient client, ModelNode connectors) throws IOException, MgmtOperationException { ModelNode op = new ModelNode(); op.get("address").set(jmsAdminOperations.getServerAddress().add("connection-factory", "RemoteConnectionFactory")); op.get("operation").set("write-attribute"); op.get("name").set("connectors"); op.get("value").set(new ModelNode().add("http-connector-throughput")); op.get("value").set(connectors); client.getControllerClient().execute(op); ServerReload.executeReloadAndWaitForCompletion(client); } @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { jmsAdminOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); jmsAdminOperations.createJmsQueue("metrics/queue", "java:jboss/metrics/queue"); jmsAdminOperations.createJmsQueue("metrics/replyQueue", "java:jboss/metrics/replyQueue"); // use scheduledThreadPoolExecutor - set http-connector-throughput for RemoteConnectionFactory (it is configured with batch delay) rcfConnectors = readRemoteCFConnectors(managementClient); writeRemoteCFConnectors(managementClient, new ModelNode().add("http-connector-throughput")); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { if (jmsAdminOperations != null) { jmsAdminOperations.removeJmsQueue("metrics/queue"); jmsAdminOperations.removeJmsQueue("metrics/replyQueue"); writeRemoteCFConnectors(managementClient, rcfConnectors); jmsAdminOperations.close(); } } }
4,076
44.808989
135
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/metrics/ScheduledThreadPoolMetricsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, 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.jboss.as.test.integration.messaging.mgmt.metrics; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.annotation.Resource; import jakarta.jms.Connection; import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSException; import jakarta.jms.Queue; import jakarta.jms.Session; import jakarta.jms.TextMessage; import java.io.IOException; import java.util.Map; import java.util.PropertyPermission; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.io.File; import java.io.FilePermission; import java.net.SocketPermission; import org.jboss.remoting3.security.RemotingPermission; /** * @author Ivan Straka */ @RunWith(Arquillian.class) @ServerSetup({JMSThreadPoolMetricsSetup.class}) public class ScheduledThreadPoolMetricsTestCase { private static final Logger logger = Logger.getLogger(ScheduledThreadPoolMetricsTestCase.class); @Resource(mappedName = "java:jboss/exported/jms/RemoteConnectionFactory") ConnectionFactory connectionFactory; @Resource(mappedName = "java:jboss/metrics/queue") private Queue queue; @Resource(mappedName = "java:jboss/metrics/replyQueue") private Queue replyQueue; @ArquillianResource private ManagementClient managementClient; @Deployment public static JavaArchive getDeployment() { final JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, "ArtemisScheduledThreadpoolMetricsTestCase.jar"); ejbJar.addPackage(TimeoutUtil.class.getPackage()); ejbJar.addClasses(JMSThreadPoolMetricsSetup.class, JMSThreadPoolMetricsMDB.class, JMSThreadPoolMetricsUtil.class); ejbJar.addAsManifestResource(new StringAsset("Dependencies: org.jboss.as.controller-client, org.jboss.dmr,org.jboss.remoting\n"), "MANIFEST.MF"); ejbJar.addAsManifestResource(createPermissionsXmlAsset( new FilePermission(System.getProperty("jboss.inst") + File.separatorChar + "standalone" + File.separatorChar + "tmp" + File.separatorChar + "auth" + File.separatorChar + "*", "read"), new PropertyPermission("ts.timeout.factor", "read"), RemotingPermission.CREATE_ENDPOINT, RemotingPermission.CONNECT, new SocketPermission("localhost", "resolve")), "jboss-permissions.xml"); return ejbJar; } @Test public void metricsAvailableTest() throws IOException { Map<String, ModelNode> resources = JMSThreadPoolMetricsUtil.getResources(managementClient); // scheduled thread pool metrics Assert.assertTrue(resources.containsKey(JMSThreadPoolMetricsUtil.SCHEDULED_ACTIVE_COUNT)); Assert.assertTrue(resources.containsKey(JMSThreadPoolMetricsUtil.SCHEDULED_COMPLETED_COUNT)); Assert.assertTrue(resources.containsKey(JMSThreadPoolMetricsUtil.SCHEDULED_CURRENT_COUNT)); Assert.assertTrue(resources.containsKey(JMSThreadPoolMetricsUtil.SCHEDULED_KEEPALIVE_TIME)); Assert.assertTrue(resources.containsKey(JMSThreadPoolMetricsUtil.SCHEDULED_LARGEST_COUNT)); Assert.assertTrue(resources.containsKey(JMSThreadPoolMetricsUtil.SCHEDULED_TASK_COUNT)); } @Test public void scheduledGlobalThreadPoolMetricsTestCase() throws JMSException, IOException, InterruptedException { Map<String, ModelNode> resources = JMSThreadPoolMetricsUtil.getResources(managementClient); long activeCount = resources.get(JMSThreadPoolMetricsUtil.ACTIVE_COUNT).asLong(); long completedCount = resources.get(JMSThreadPoolMetricsUtil.COMPLETED_COUNT).asLong(); long currentCount = resources.get(JMSThreadPoolMetricsUtil.CURRENT_COUNT).asLong(); long largestCount = resources.get(JMSThreadPoolMetricsUtil.LARGEST_COUNT).asLong(); long taskCount = resources.get(JMSThreadPoolMetricsUtil.TASK_COUNT).asLong(); long scheduledCompletedCount = resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_COMPLETED_COUNT).asLong(); long scheduledCurrentCount = resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_CURRENT_COUNT).asLong(); long scheduledLargestCount = resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_LARGEST_COUNT).asLong(); long scheduledTaskCount = resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_TASK_COUNT).asLong(); try (Connection connection = connectionFactory.createConnection("guest", "guest"); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) { connection.start(); for (int i = 0; i < JMSThreadPoolMetricsUtil.MESSAGES_COUNT; i++) { JMSThreadPoolMetricsUtil.send(session, queue, "id=" + i, true); } // we are in the middle of processing Thread.sleep(100); resources = JMSThreadPoolMetricsUtil.getResources(managementClient); JMSThreadPoolMetricsUtil.assertGreater("active count", resources.get(JMSThreadPoolMetricsUtil.ACTIVE_COUNT).asLong(), activeCount); JMSThreadPoolMetricsUtil.assertGreater("current count", resources.get(JMSThreadPoolMetricsUtil.CURRENT_COUNT).asLong(), currentCount); // there is no point in checking active count in scheduledThreadPool since we can not determine the exact time // tasks are being executed JMSThreadPoolMetricsUtil.assertGreater("scheduled current count", resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_CURRENT_COUNT).asLong(), 0); JMSThreadPoolMetricsUtil.assertGreaterOrEqual("scheduled current count", resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_CURRENT_COUNT).asLong(), scheduledCurrentCount); // read responses for (int i = 0; i < JMSThreadPoolMetricsUtil.MESSAGES_COUNT; i++) { TextMessage textMessage = JMSThreadPoolMetricsUtil.receiveReply(session, replyQueue, TimeoutUtil.adjust(5000)); logger.trace("got reply for [" + textMessage.getText() + "]"); } } // messages have been processed resources = JMSThreadPoolMetricsUtil.getResources(managementClient); JMSThreadPoolMetricsUtil.assertGreater("completed count", resources.get(JMSThreadPoolMetricsUtil.COMPLETED_COUNT).asLong(), completedCount); JMSThreadPoolMetricsUtil.assertGreater("largest count", resources.get(JMSThreadPoolMetricsUtil.LARGEST_COUNT).asLong(), 0); JMSThreadPoolMetricsUtil.assertGreaterOrEqual("largest count", resources.get(JMSThreadPoolMetricsUtil.LARGEST_COUNT).asLong(), largestCount); JMSThreadPoolMetricsUtil.assertGreater("task count", resources.get(JMSThreadPoolMetricsUtil.TASK_COUNT).asLong(), taskCount); JMSThreadPoolMetricsUtil.assertGreater("scheduled completed count", resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_COMPLETED_COUNT).asLong(), scheduledCompletedCount); JMSThreadPoolMetricsUtil.assertGreater("scheduled largest count", resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_LARGEST_COUNT).asLong(), 0); JMSThreadPoolMetricsUtil.assertGreaterOrEqual("scheduled largest count", resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_LARGEST_COUNT).asLong(), scheduledLargestCount); JMSThreadPoolMetricsUtil.assertGreater("scheduled task count", resources.get(JMSThreadPoolMetricsUtil.SCHEDULED_TASK_COUNT).asLong(), scheduledTaskCount); } }
8,946
55.987261
199
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/metrics/JMSThreadPoolMetricsMDB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, 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.jboss.as.test.integration.messaging.mgmt.metrics; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.ejb3.annotation.ResourceAdapter; import org.jboss.logging.Logger; import jakarta.annotation.Resource; import jakarta.ejb.ActivationConfigProperty; import jakarta.ejb.MessageDriven; import jakarta.jms.Connection; import jakarta.jms.ConnectionFactory; import jakarta.jms.Destination; import jakarta.jms.JMSException; import jakarta.jms.Message; import jakarta.jms.MessageListener; import jakarta.jms.Queue; import jakarta.jms.Session; import jakarta.jms.TextMessage; /** * @author Ivan Straka */ @MessageDriven(name = "MetricsBean", activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "jakarta.jms.Queue"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "jboss/metrics/queue")}) @ResourceAdapter("activemq-ra.rar") public class JMSThreadPoolMetricsMDB implements MessageListener { private static final Logger logger = Logger.getLogger(JMSThreadPoolMetricsMDB.class); @Resource(mappedName = "java:jboss/exported/jms/RemoteConnectionFactory") ConnectionFactory remoteCF; @Resource(mappedName = "java:/ConnectionFactory") ConnectionFactory invmCF; @Resource(mappedName = "java:jboss/metrics/replyQueue") private Queue replyQueue; @Override public void onMessage(Message m) { TextMessage message = (TextMessage) m; try (Connection connection = getConnection(message); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) { connection.start(); logger.trace("Simulate processing message: [" + message.getText() + "]"); Thread.sleep(TimeoutUtil.adjust(500)); final Destination replyTo = message.getJMSReplyTo(); if (replyTo == null) { return; } logger.trace("Sending a reply for[" + message.getText() + "] to destination " + replyTo); JMSThreadPoolMetricsUtil.reply(session, replyQueue, message); } catch (JMSException | InterruptedException e) { logger.error("Error processing message ", e); throw new RuntimeException(e); } } private Connection getConnection(TextMessage message) throws JMSException { return JMSThreadPoolMetricsUtil.useRCF(message) ? remoteCF.createConnection("guest", "guest") : invmCF.createConnection(); } }
3,531
40.069767
130
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/definitions/JMSResourceManagementTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.definitions; import static org.jboss.as.controller.operations.common.Util.getEmptyOperation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.io.IOException; import java.util.List; 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.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc. */ @RunAsClient @RunWith(Arquillian.class) public class JMSResourceManagementTestCase { private static final Logger LOGGER = Logger.getLogger(JMSResourceManagementTestCase.class); @ContainerResource private ManagementClient managementClient; private JMSOperations jmsOperations; @Before public void setUp() { jmsOperations = JMSOperationsProvider.getInstance(managementClient); } @Deployment public static JavaArchive createArchive() { JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "JMSResourceDefinitionsTestCase.jar") .addPackage(MessagingBean.class.getPackage()) .addAsManifestResource(MessagingBean.class.getPackage(), "ejb-jar.xml", "ejb-jar.xml") .addAsManifestResource( new StringAsset("<beans xmlns=\"https://jakarta.ee/xml/ns/jakartaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + "xsi:schemaLocation=\"https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/beans_3_0.xsd\"\n" + "bean-discovery-mode=\"all\">\n" + "</beans>"), "beans.xml"); return archive; } @Test public void testManagementOfDestinations() throws Exception { ModelNode readResourceWithRuntime = getOperation("jms-queue", "myQueue1", "read-resource"); readResourceWithRuntime.get("include-runtime").set(true); ModelNode result = execute(readResourceWithRuntime, true); assertEquals(true, result.get("durable").asBoolean()); assertFalse(result.hasDefined("selector")); // injectedQueue3 has been declared in the annotation with selector => color = 'red' // and durable = false readResourceWithRuntime = getOperation("jms-queue", "myQueue2", "read-resource"); readResourceWithRuntime.get("include-runtime").set(true); result = execute(readResourceWithRuntime, true); assertEquals(false, result.get("durable").asBoolean()); assertEquals("color = 'red'", result.get("selector").asString()); // injectedQueue3 has been declared in the ejb-jar.xml with selector => color = 'blue' // and durable => false readResourceWithRuntime = getOperation("jms-queue", "myQueue3", "read-resource"); readResourceWithRuntime.get("include-runtime").set(true); result = execute(readResourceWithRuntime, true); assertEquals(false, result.get("durable").asBoolean()); assertEquals("color = 'blue'", result.get("selector").asString()); // injectedTopic1 has been declared in the annotation readResourceWithRuntime = getOperation("jms-topic", "myTopic1", "read-resource"); readResourceWithRuntime.get("include-runtime").set(true); execute(readResourceWithRuntime, true); // injectedTopic2 has been declared in the ejb-jar.xml readResourceWithRuntime = getOperation("jms-topic", "myTopic2", "read-resource"); readResourceWithRuntime.get("include-runtime").set(true); execute(readResourceWithRuntime, true); } @Test public void testManagementOfConnectionFactories() throws Exception { ModelNode readResourceWithRuntime = getOperation("pooled-connection-factory", "*", "read-resource-description"); readResourceWithRuntime.get("include-runtime").set(true); readResourceWithRuntime.get("operations").set(true); execute(readResourceWithRuntime, true); readResourceWithRuntime = getOperation("pooled-connection-factory", "*", "read-resource-description"); readResourceWithRuntime.get("include-runtime").set(true); readResourceWithRuntime.get("operations").set(true); ModelNode result = execute(readResourceWithRuntime, true); //System.out.println("result = " + result.toJSONString(false)); readResourceWithRuntime = getOperation("pooled-connection-factory", "JMSResourceDefinitionsTestCase_JMSResourceDefinitionsTestCase_java_module/myFactory1", "read-resource"); readResourceWithRuntime.get("include-runtime").set(true); result = execute(readResourceWithRuntime, true); //System.out.println("result = " + result.toJSONString(false)); assertEquals(1, result.get("min-pool-size").asInt()); assertEquals(2, result.get("max-pool-size").asInt()); assertEquals(3, result.get("initial-connect-attempts").asInt()); assertEquals("guest", result.get("user").asString()); assertEquals("guest", result.get("password").asString()); assertEquals("myClientID1", result.get("client-id").asString()); readResourceWithRuntime = getOperation("pooled-connection-factory", "JMSResourceDefinitionsTestCase_MessagingBean_java_comp/env/myFactory2", "read-resource"); readResourceWithRuntime.get("include-runtime").set(true); result = execute(readResourceWithRuntime, true); //System.out.println("result = " + result.toJSONString(false)); assertEquals(0, result.get("min-pool-size").asInt()); assertEquals(20, result.get("max-pool-size").asInt()); assertFalse(result.toJSONString(false), result.hasDefined("user")); assertFalse(result.hasDefined("password")); assertFalse(result.hasDefined("client-id")); readResourceWithRuntime = getOperation("pooled-connection-factory", "JMSResourceDefinitionsTestCase_JMSResourceDefinitionsTestCase_java_global/myFactory3", "read-resource"); readResourceWithRuntime.get("include-runtime").set(true); result = execute(readResourceWithRuntime, true); assertEquals(3, result.get("min-pool-size").asInt()); assertEquals(4, result.get("max-pool-size").asInt()); assertEquals(5, result.get("initial-connect-attempts").asInt()); assertEquals("guest", result.get("user").asString()); assertEquals("guest", result.get("password").asString()); assertFalse(result.hasDefined("client-id")); readResourceWithRuntime = getOperation("pooled-connection-factory", "JMSResourceDefinitionsTestCase_JMSResourceDefinitionsTestCase_java_app/myFactory4", "read-resource"); readResourceWithRuntime.get("include-runtime").set(true); result = execute(readResourceWithRuntime, true); assertEquals(4, result.get("min-pool-size").asInt()); assertEquals(5, result.get("max-pool-size").asInt()); assertEquals(6, result.get("initial-connect-attempts").asInt()); assertEquals("guest", result.get("user").asString()); assertEquals("guest", result.get("password").asString()); assertEquals("myClientID4", result.get("client-id").asString()); } @Test public void testRuntimeQueues() throws Exception { //Tests https://issues.jboss.org/browse/WFLY-2807 PathAddress addr = PathAddress.pathAddress("subsystem", "messaging-activemq"); addr = addr.append("server", "default"); ModelNode readResource = Util.createEmptyOperation("read-resource", addr); readResource.get("recursive").set(true); ModelNode result = execute(readResource, true); Assert.assertTrue(result.has("runtime-queue")); Assert.assertFalse(result.hasDefined("runtime-queue")); readResource.get("include-runtime").set(true); result = execute(readResource, true); Assert.assertTrue(result.hasDefined("runtime-queue")); ModelNode queues = result.get("runtime-queue"); List<Property> propsList = queues.asPropertyList(); Assert.assertTrue(propsList.size() > 0); for (Property prop : propsList) { Assert.assertTrue(prop.getValue().isDefined()); } } private ModelNode getOperation(String resourceType, String resourceName, String operationName) { final ModelNode address = new ModelNode(); address.add("deployment", "JMSResourceDefinitionsTestCase.jar"); for (Property prop: jmsOperations.getServerAddress().asPropertyList()) { address.add(prop.getName(), prop.getValue().asString()); } address.add(resourceType, resourceName); return getEmptyOperation(operationName, address); } private ModelNode execute(final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { if (!"success".equals(outcome)) { LOGGER.trace(response); } assertEquals("success", outcome); return response.get("result"); } else { if ("success".equals(outcome)) { LOGGER.trace(response); } assertEquals("failed", outcome); return response.get("failure-description"); } } }
11,234
48.933333
181
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/definitions/MessagingBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.definitions; import static jakarta.jms.JMSContext.AUTO_ACKNOWLEDGE; import static org.junit.Assert.assertNotNull; import jakarta.annotation.Resource; import jakarta.ejb.Stateless; import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSConnectionFactoryDefinition; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSDestinationDefinition; import jakarta.jms.Queue; import jakarta.jms.QueueConnectionFactory; import jakarta.jms.Topic; import jakarta.jms.TopicConnectionFactory; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc. */ @JMSDestinationDefinition( name = "java:comp/env/myQueue4", interfaceName = "jakarta.jms.Queue" ) @JMSDestinationDefinition( name = "java:module/env/myQueue1", interfaceName = "jakarta.jms.Queue", destinationName = "myQueue1" ) @JMSDestinationDefinition( name = "java:module/env/myTopic1", interfaceName = "jakarta.jms.Topic", destinationName = "myTopic1" ) @JMSDestinationDefinition( // explicitly mention a resourceAdapter corresponding to a pooled-connection-factory resource resourceAdapter = "activemq-ra", name = "java:global/env/myQueue2", interfaceName = "jakarta.jms.Queue", destinationName = "myQueue2", properties = { "durable=false", "selector=color = 'red'" } ) @JMSConnectionFactoryDefinition( name = "java:module/myFactory1", properties = { "connector=http-connector", "initial-connect-attempts=3" }, user = "guest", password = "guest", clientId = "myClientID1", maxPoolSize = 2, minPoolSize = 1 ) @JMSConnectionFactoryDefinition( name = "java:comp/env/myFactory2" ) @JMSConnectionFactoryDefinition( name = "java:comp/env/myFactory5", interfaceName = "jakarta.jms.QueueConnectionFactory", user = "${test.userName}", password = "${test.password}" ) @JMSConnectionFactoryDefinition( // explicitly mention a resourceAdapter corresponding to a pooled-connection-factory resource resourceAdapter = "activemq-ra", name = "java:global/myFactory3", interfaceName = "jakarta.jms.QueueConnectionFactory", properties = { "connector=http-connector", "initial-connect-attempts=5" }, user = "guest", password = "guest", maxPoolSize = 4, minPoolSize = 3 ) @Stateless public class MessagingBean { // Use a @JMSDestinationDefinition inside a @JMSDestinationDefinitions @Resource(lookup = "java:module/env/myQueue1") private Queue queue1; // Use a @JMSDestinationDefinition @Resource(lookup = "java:global/env/myQueue2") private Queue queue2; // Use a jms-destination from the deployment descriptor @Resource(lookup = "java:app/env/myQueue3") private Queue queue3; // Use a @JMSDestinationDefinition inside the bean @Resource(lookup = "java:comp/env/myQueue4") private Queue queue4; // Use a @JMSDestinationDefinition inside a @JMSDestinationDefinitions @Resource(lookup = "java:module/env/myTopic1") private Topic topic1; // Use a jms-destination from the deployment descriptor @Resource(lookup = "java:app/env/myTopic2") private Topic topic2; // Use a @JMSConnectionFactoryDefinition inside a @JMSConnectionFactoryDefinitions @Resource(lookup = "java:module/myFactory1") private ConnectionFactory factory1; // Use a @JMSConnectionFactoryDefinition inside a @JMSConnectionFactoryDefinitions @Resource(lookup = "java:comp/env/myFactory2") private ConnectionFactory factory2; // Use a @JMSConnectionFactoryDefinition @Resource(lookup = "java:global/myFactory3") private QueueConnectionFactory factory3; // Use a jms-connection-factory from the deployment descriptor @Resource(lookup = "java:app/myFactory4") private TopicConnectionFactory factory4; // Use a @JMSConnectionFactoryDefinition inside a @JMSConnectionFactoryDefinitions // with vaulted attributes for the user credentials @Resource(lookup = "java:comp/env/myFactory5") private ConnectionFactory factory5; // Use a jms-connection-factory from the deployment descriptor // with vaulted attributes for the user credentials @Resource(lookup = "java:app/myFactory6") private TopicConnectionFactory factory6; public void checkInjectedResources() { assertNotNull(queue1); assertNotNull(queue2); assertNotNull(queue3); assertNotNull(queue4); assertNotNull(topic1); assertNotNull(topic2); assertNotNull(factory1); assertNotNull(factory2); assertNotNull(factory3); assertNotNull(factory4); assertNotNull(factory5); assertNotNull(factory6); JMSContext context = factory3.createContext("guest", "guest", AUTO_ACKNOWLEDGE); JMSConsumer consumer = context.createConsumer(queue4); assertNotNull(consumer); consumer.close(); } public void checkAnnotationBasedDefinitionsWithVaultedAttributes() { assertNotNull(factory5); // verify authentication using vaulted attributes works fine JMSContext context = factory5.createContext(); assertNotNull(context); context.close(); } public void checkDeploymendDescriptorBasedDefinitionsWithVaultedAttributes() { assertNotNull(factory6); // verify authentication using vaulted attributes works fine JMSContext context = factory6.createContext(); assertNotNull(context); context.close(); } }
6,830
34.21134
101
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/definitions/JMSResourceDefinitionsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.definitions; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; 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.VALUE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import static org.jboss.shrinkwrap.api.ArchivePaths.create; import static org.wildfly.test.security.common.SecureExpressionUtil.getDeploymentPropertiesAsset; import static org.wildfly.test.security.common.SecureExpressionUtil.setupCredentialStore; import static org.wildfly.test.security.common.SecureExpressionUtil.setupCredentialStoreExpressions; import static org.wildfly.test.security.common.SecureExpressionUtil.teardownCredentialStore; import java.io.IOException; import java.net.SocketPermission; import jakarta.ejb.EJB; import jakarta.jms.JMSException; 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.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.test.shared.PermissionUtils; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.security.common.SecureExpressionUtil; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc. */ @RunWith(Arquillian.class) @ServerSetup(JMSResourceDefinitionsTestCase.StoreVaultedPropertyTask.class) public class JMSResourceDefinitionsTestCase { static final String UNIQUE_NAME = "JMSResourceDefinitionsTestCase"; private static final SecureExpressionUtil.SecureExpressionData USERNAME = new SecureExpressionUtil.SecureExpressionData("guest", "test.userName"); private static final SecureExpressionUtil.SecureExpressionData PASSWORD = new SecureExpressionUtil.SecureExpressionData("guest", "test.password"); static final String STORE_LOCATION = JMSResourceDefinitionsTestCase.class.getResource("/").getPath() + "security/" + UNIQUE_NAME + ".cs"; static class StoreVaultedPropertyTask implements ServerSetupTask { @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { setupCredentialStore(managementClient, UNIQUE_NAME, STORE_LOCATION); // for annotation-based JMS definitions updatePropertyReplacement(managementClient, "annotation-property-replacement", true); // for deployment descriptor-based JMS definitions updatePropertyReplacement(managementClient, "spec-descriptor-property-replacement", true); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { updatePropertyReplacement(managementClient, "annotation-property-replacement", false); updatePropertyReplacement(managementClient, "spec-descriptor-property-replacement", false); teardownCredentialStore(managementClient, UNIQUE_NAME, STORE_LOCATION); } private void updatePropertyReplacement(ManagementClient managementClient, String propertyReplacement, boolean value) throws IOException { ModelNode op; op = new ModelNode(); op.get(OP_ADDR).add("subsystem", "ee"); op.get(OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(NAME).set(propertyReplacement); op.get(VALUE).set(value); managementClient.getControllerClient().execute(new OperationBuilder(op).build()); } } @EJB private MessagingBean bean; @Deployment public static JavaArchive createArchive() throws Exception { // Create the credential expressions so we can store them in the deployment setupCredentialStoreExpressions(UNIQUE_NAME, USERNAME, PASSWORD); JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "JMSResourceDefinitionsTestCase.jar") .addPackage(MessagingBean.class.getPackage()) .addClasses(SecureExpressionUtil.getDeploymentClasses()) .addAsManifestResource( MessagingBean.class.getPackage(), "ejb-jar.xml", "ejb-jar.xml") .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( new SocketPermission("localhost", "resolve")), "permissions.xml") .addAsManifestResource( EmptyAsset.INSTANCE, create("beans.xml")) .addAsManifestResource(getDeploymentPropertiesAsset(USERNAME, PASSWORD), "jboss.properties"); return archive; } @Test public void testInjectedDefinitions() throws JMSException { bean.checkInjectedResources(); } @Test public void testAnnotationBasedDefinitionsWithVaultedAttributes() throws JMSException { bean.checkAnnotationBasedDefinitionsWithVaultedAttributes(); } @Test public void testDeploymendDescriptorBasedDefinitionsWithVaultedAttributes() throws JMSException { bean.checkDeploymendDescriptorBasedDefinitionsWithVaultedAttributes(); } }
6,632
47.416058
150
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/localtransaction/LocalTransactionTestCase.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.jboss.as.test.integration.messaging.jms.localtransaction; import static org.jboss.shrinkwrap.api.ShrinkWrap.create; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.net.URL; import java.util.concurrent.TimeUnit; 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.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests the behaviour of allowing local transactions for a Jakarta Messaging session from a Servlet. * * Default behaviour is to disallow it. * It can be overridden by specifying allow-local-transactions=true on the pooled-connection-factory resource. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(LocalTransactionTestCase.SetupTask.class) public class LocalTransactionTestCase { @ArquillianResource private URL url; @Deployment public static WebArchive createArchive() { return create(WebArchive.class, "LocalTransactionTestCase.war") .addClass(MessagingServlet.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); } @Test public void testAllowLocalTransactions() throws Exception { callServlet(true); } @Test public void testDisallowLocalTransactions() throws Exception { callServlet(false); } private void callServlet(boolean allowLocalTransactions) throws Exception { URL url = new URL(this.url.toExternalForm() + "LocalTransactionTestCase?allowLocalTransactions=" + allowLocalTransactions); String reply = HttpRequest.get(url.toExternalForm(), 10, TimeUnit.SECONDS); assertNotNull(reply); assertEquals(allowLocalTransactions, Boolean.valueOf(reply)); } static class SetupTask implements ServerSetupTask{ @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { managementClient.getControllerClient().execute(Operations.createWriteAttributeOperation(new ModelNode().add("subsystem", "ee"), "annotation-property-replacement", true)); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); managementClient.getControllerClient().execute(Operations.createWriteAttributeOperation(new ModelNode().add("subsystem", "ee"), "annotation-property-replacement", ops.isRemoteBroker())); } } }
4,353
40.865385
198
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/localtransaction/MessagingServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.localtransaction; import java.io.IOException; import jakarta.annotation.Resource; import jakarta.jms.Connection; import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSConnectionFactoryDefinition; import jakarta.jms.JMSException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.Assert; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc. */ @JMSConnectionFactoryDefinition( name="java:module/CF_allow_local_tx", properties = { "connectors=${org.jboss.messaging.default-connector:in-vm}", "allow-local-transactions=true" } ) @WebServlet("/LocalTransactionTestCase") public class MessagingServlet extends HttpServlet { @Resource(lookup = "java:module/CF_allow_local_tx") private ConnectionFactory cFwithLocalTransaction; @Resource private ConnectionFactory defaultCF; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean allowLocalTransactions = Boolean.valueOf(req.getParameter("allowLocalTransactions")); final ConnectionFactory cf = allowLocalTransactions ? cFwithLocalTransaction : defaultCF; Connection connection = null; try { connection = cf.createConnection(); try { connection.createSession(true, 0); if (!allowLocalTransactions) { Assert.fail("Local transactions are not allowed"); } resp.getWriter().write("" + allowLocalTransactions); } catch (JMSException e) { if (allowLocalTransactions) { Assert.fail("Local transactions are allowed"); } resp.getWriter().write("" + allowLocalTransactions); } } catch (Throwable t) { resp.setStatus(500); t.printStackTrace(resp.getWriter()); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { } } } } }
3,436
35.956989
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/SendToExternalJMSQueueTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, 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.jboss.as.test.integration.messaging.jms.external; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.SocketPermission; import jakarta.annotation.Resource; import jakarta.jms.Connection; import jakarta.jms.ConnectionFactory; import jakarta.jms.Message; import jakarta.jms.MessageConsumer; import jakarta.jms.MessageProducer; import jakarta.jms.Queue; import jakarta.jms.Session; import jakarta.jms.TextMessage; 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.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.PermissionUtils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.ServerSnapshot; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.remoting3.security.RemotingPermission; import org.jboss.shrinkwrap.api.ArchivePaths; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Basic JMS test using a customly created JMS topic * * @author <a href="[email protected]">Jan Martiska</a> */ @RunWith(Arquillian.class) @ServerSetup(SendToExternalJMSQueueTestCase.SetupTask.class) public class SendToExternalJMSQueueTestCase { public static final String QUEUE_LOOKUP = "java:jboss/exported/queue/myAwesomeClientQueue"; static class SetupTask implements ServerSetupTask { private static final Logger logger = Logger.getLogger(SendToExternalJMSQueueTestCase.SetupTask.class); private AutoCloseable snapshot = null; @Override public void setup(org.jboss.as.arquillian.container.ManagementClient managementClient, String s) throws Exception { snapshot = ServerSnapshot.takeSnapshot(managementClient); ServerReload.executeReloadAndWaitForCompletion(managementClient, true); JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); boolean needRemoteConnector = ops.isRemoteBroker(); if (needRemoteConnector) { ops.addExternalRemoteConnector("remote-broker-connector", "messaging-activemq"); } else { ops.addExternalHttpConnector("http-test-connector", "http", "http-acceptor"); ops.createJmsQueue("myAwesomeQueue", "/queue/myAwesomeQueue"); } ModelNode op = Operations.createRemoveOperation(getInitialPooledConnectionFactoryAddress(ops.getServerAddress())); execute(managementClient, op, true); op = Operations.createAddOperation(getPooledConnectionFactoryAddress()); op.get("transaction").set("xa"); op.get("entries").add("java:/JmsXA java:jboss/DefaultJMSConnectionFactory"); if(needRemoteConnector) { op.get("connectors").add("remote-broker-connector"); } else { op.get("connectors").add("http-test-connector"); } execute(managementClient, op, true); op = Operations.createAddOperation(getClientQueueAddress()); op.get("entries").add(QUEUE_LOOKUP); op.get("entries").add("/queue/myAwesomeClientQueue"); execute(managementClient, op, true); ServerReload.executeReloadAndWaitForCompletion(managementClient); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); ops.removeJmsQueue("myAwesomeQueue"); if (snapshot != null) { snapshot.close(); } ServerReload.executeReloadAndWaitForCompletion(managementClient); } private ModelNode execute(final org.jboss.as.arquillian.container.ManagementClient managementClient, final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { assertEquals(response.toString(), "success", outcome); return response.get("result"); } else { assertEquals("failed", outcome); return response.get("failure-description"); } } ModelNode getPooledConnectionFactoryAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("pooled-connection-factory", "activemq-ra"); return address; } ModelNode getClientQueueAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("external-jms-queue", "myAwesomeQueue"); return address; } ModelNode getInitialPooledConnectionFactoryAddress(ModelNode serverAddress) { ModelNode address = serverAddress.clone(); address.add("pooled-connection-factory", "activemq-ra"); return address; } } private static final Logger logger = Logger.getLogger(SendToExternalJMSQueueTestCase.class); @Resource(lookup = QUEUE_LOOKUP) private Queue queue; @Resource(lookup = "java:/JmsXA") private ConnectionFactory factory; @Deployment public static JavaArchive createTestArchive() { return ShrinkWrap.create(JavaArchive.class, "test.jar") .addPackage(JMSOperations.class.getPackage()) .addClass(SendToExternalJMSQueueTestCase.SetupTask.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( RemotingPermission.CREATE_ENDPOINT, RemotingPermission.CONNECT, new SocketPermission("localhost", "resolve")), "permissions.xml") .addAsManifestResource( EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml")); } @Test public void sendMessage() throws Exception { Connection senderConnection = null; Connection consumerConnection = null; Session senderSession = null; Session consumerSession = null; MessageConsumer consumer = null; try { // CREATE SUBSCRIBER logger.trace("******* Creating connection for consumer"); consumerConnection = factory.createConnection("guest", "guest"); logger.trace("Creating session for consumer"); consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); logger.trace("Creating consumer"); consumer = consumerSession.createConsumer(queue); logger.trace("Start session"); consumerConnection.start(); // SEND A MESSAGE logger.trace("***** Start - sending message to topic"); senderConnection = factory.createConnection("guest", "guest"); logger.trace("Creating session.."); senderSession = senderConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = senderSession.createProducer(queue); TextMessage message = senderSession.createTextMessage("Hello world!"); logger.trace("Sending.."); producer.send(message); logger.trace("Message sent"); senderConnection.start(); } catch (Exception ex) { ex.printStackTrace(); } finally { logger.trace("Closing connections and sessions"); if (senderSession != null) { senderSession.close(); } if (senderConnection != null) { senderConnection.close(); } } Message receivedMessage = null; try { logger.trace("Receiving"); receivedMessage = consumer.receive(5000); logger.trace("Received: " + ((TextMessage) receivedMessage).getText()); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } finally { if (receivedMessage == null) { Assert.fail("received null instead of a TextMessage"); } if (consumerSession != null) { consumerSession.close(); } if (consumerConnection != null) { consumerConnection.close(); } } Assert.assertTrue("received a " + receivedMessage.getClass().getName() + " instead of a TextMessage", receivedMessage instanceof TextMessage); Assert.assertEquals("Hello world!", ((TextMessage) receivedMessage).getText()); } }
10,396
42.502092
178
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/QueueMDB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.external; import static org.jboss.as.test.integration.messaging.jms.external.ExternalMessagingDeploymentTestCase.QUEUE_LOOKUP; import static org.jboss.as.test.integration.messaging.jms.external.ExternalMessagingDeploymentTestCase.REMOTE_PCF; import jakarta.ejb.ActivationConfigProperty; import jakarta.ejb.MessageDriven; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSContext; import jakarta.jms.JMSPasswordCredential; import jakarta.jms.Message; import jakarta.jms.MessageListener; import jakarta.jms.TextMessage; import org.jboss.ejb3.annotation.ResourceAdapter; /** * @author Emmanuel Hugonnet (c) 2018 Red Hat, inc. */ @MessageDriven( activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "jakarta.jms.Queue"), @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = QUEUE_LOOKUP), @ActivationConfigProperty(propertyName="user", propertyValue="guest"), @ActivationConfigProperty(propertyName="password", propertyValue="guest") } ) @ResourceAdapter(REMOTE_PCF) // name of the pooled-connection-factory resource public class QueueMDB implements MessageListener { @Inject @JMSPasswordCredential(userName = "guest", password = "guest") private JMSContext context; @Override public void onMessage(final Message m) { try { TextMessage message = (TextMessage) m; Destination replyTo = m.getJMSReplyTo(); context.createProducer() .setJMSCorrelationID(message.getJMSMessageID()) .send(replyTo, message.getText()); } catch (Exception e) { e.printStackTrace(); } } }
2,846
39.671429
116
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/ExternalMessagingDeploymentTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, 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.jboss.as.test.integration.messaging.jms.external; import static org.jboss.shrinkwrap.api.ShrinkWrap.create; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.net.SocketPermission; import java.net.URL; import java.util.PropertyPermission; import java.util.UUID; import java.util.concurrent.TimeUnit; 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.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.PermissionUtils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; 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 invoking a management operation that removes a Jakarta Messaging resource that is used by a deployed archive must fail: * the resource must not be removed and any depending services must be recovered. * The deployment must still be operating after the failing management operation. * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(ExternalMessagingDeploymentTestCase.SetupTask.class) public class ExternalMessagingDeploymentTestCase { public static final String QUEUE_LOOKUP = "java:/jms/DependentMessagingDeploymentTestCase/myQueue"; public static final String TOPIC_LOOKUP = "java:/jms/DependentMessagingDeploymentTestCase/myTopic"; public static final String REMOTE_PCF = "remote-artemis"; private static final String QUEUE_NAME = "myQueue"; private static final String TOPIC_NAME = "myTopic"; @ArquillianResource private URL url; static class SetupTask extends SnapshotRestoreSetupTask { private static final Logger logger = Logger.getLogger(ExternalMessagingDeploymentTestCase.SetupTask.class); @Override public void doSetup(org.jboss.as.arquillian.container.ManagementClient managementClient, String s) throws Exception { ServerReload.executeReloadAndWaitForCompletion(managementClient, true); JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); ops.createJmsQueue(QUEUE_NAME, "/queue/" + QUEUE_NAME); ops.createJmsTopic(TOPIC_NAME, "/topic/" + TOPIC_NAME); boolean needRemoteConnector = ops.isRemoteBroker(); if(needRemoteConnector) { ops.addExternalRemoteConnector("remote-broker-connector", "messaging-activemq"); } else { ops.addExternalHttpConnector("http-test-connector", "http", "http-acceptor"); } ModelNode op = Operations.createRemoveOperation(getInitialPooledConnectionFactoryAddress(ops.getServerAddress())); managementClient.getControllerClient().execute(op); op = Operations.createAddOperation(getPooledConnectionFactoryAddress()); op.get("transaction").set("xa"); op.get("entries").add("java:/JmsXA java:jboss/DefaultJMSConnectionFactory"); if(needRemoteConnector) { op.get("connectors").add("remote-broker-connector"); } else { op.get("connectors").add("http-test-connector"); } execute(managementClient, op, true); op = Operations.createRemoveOperation(getClientTopicAddress()); managementClient.getControllerClient().execute(op); op = Operations.createAddOperation(getClientTopicAddress()); op.get("entries").add(TOPIC_LOOKUP); op.get("entries").add("/topic/myAwesomeClientTopic"); execute(managementClient, op, true); op = Operations.createRemoveOperation(getClientQueueAddress()); managementClient.getControllerClient().execute(op); op = Operations.createAddOperation(getClientQueueAddress()); op.get("entries").add(QUEUE_LOOKUP); op.get("entries").add("/queue/myAwesomeClientQueue"); execute(managementClient, op, true); ops.close(); ServerReload.executeReloadAndWaitForCompletion(managementClient); } private ModelNode execute(final org.jboss.as.arquillian.container.ManagementClient managementClient, final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { assertEquals(response.toString(), "success", outcome); return response.get("result"); } else { assertEquals("failed", outcome); return response.get("failure-description"); } } ModelNode getPooledConnectionFactoryAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("pooled-connection-factory", REMOTE_PCF); return address; } ModelNode getClientTopicAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("external-jms-topic", TOPIC_NAME); return address; } ModelNode getClientQueueAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("external-jms-queue", QUEUE_NAME); return address; } ModelNode getInitialPooledConnectionFactoryAddress(ModelNode serverAddress) { ModelNode address = serverAddress.clone(); address.add("pooled-connection-factory", "activemq-ra"); return address; } } @Deployment public static WebArchive createArchive() { return create(WebArchive.class, "ClientMessagingDeploymentTestCase.war") .addClasses(MessagingServlet.class, TimeoutUtil.class) .addClasses(QueueMDB.class, TopicMDB.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( new SocketPermission("localhost", "resolve"), new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read")), "permissions.xml") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); } @Test public void testSendMessageInClientQueue() throws Exception { sendAndReceiveMessage(true); } @Test public void testSendMessageInClientTopic() throws Exception { sendAndReceiveMessage(false); } private void sendAndReceiveMessage(boolean sendToQueue) throws Exception { String destination = sendToQueue ? "queue" : "topic"; String text = UUID.randomUUID().toString(); String serverUrl = this.url.toExternalForm(); if (!serverUrl.endsWith("/")) { serverUrl = serverUrl + "/"; } URL servletUrl = new URL(serverUrl + "ClientMessagingDeploymentTestCase?destination=" + destination + "&text=" + text); String reply = HttpRequest.get(servletUrl.toExternalForm(), TimeoutUtil.adjust(10), TimeUnit.SECONDS); assertNotNull(reply); assertEquals(text, reply); } }
9,017
44.316583
178
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/TopicMDB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.external; import static org.jboss.as.test.integration.messaging.jms.external.ExternalMessagingDeploymentTestCase.REMOTE_PCF; import static org.jboss.as.test.integration.messaging.jms.external.ExternalMessagingDeploymentTestCase.TOPIC_LOOKUP; import jakarta.ejb.ActivationConfigProperty; import jakarta.ejb.MessageDriven; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSContext; import jakarta.jms.JMSPasswordCredential; import jakarta.jms.Message; import jakarta.jms.MessageListener; import jakarta.jms.TextMessage; import org.jboss.ejb3.annotation.ResourceAdapter; /** * @author Emmanuel Hugonnet (c) 2018 Red Hat, inc. */ @MessageDriven( activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "jakarta.jms.Topic"), @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = TOPIC_LOOKUP), @ActivationConfigProperty(propertyName="user", propertyValue="guest"), @ActivationConfigProperty(propertyName="password", propertyValue="guest") } ) @ResourceAdapter(REMOTE_PCF) // name of the pooled-connection-factory resource public class TopicMDB implements MessageListener { @Inject @JMSPasswordCredential(userName = "guest", password = "guest") private JMSContext context; @Override public void onMessage(final Message m) { try { TextMessage message = (TextMessage) m; Destination replyTo = m.getJMSReplyTo(); context.createProducer() .setJMSCorrelationID(message.getJMSMessageID()) .send(replyTo, message.getText()); } catch (Exception e) { e.printStackTrace(); } } }
2,845
39.657143
116
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/DefaultResourceAdapterQueueMDB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.external; import static org.jboss.as.test.integration.messaging.jms.external.ExternalMessagingDeploymentTestCase.QUEUE_LOOKUP; import jakarta.ejb.ActivationConfigProperty; import jakarta.ejb.MessageDriven; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSContext; import jakarta.jms.JMSPasswordCredential; import jakarta.jms.Message; import jakarta.jms.MessageListener; import jakarta.jms.TextMessage; /** * @author Emmanuel Hugonnet (c) 2018 Red Hat, inc. */ @MessageDriven( activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "jakarta.jms.Queue"), @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = QUEUE_LOOKUP), @ActivationConfigProperty(propertyName="user", propertyValue="guest"), @ActivationConfigProperty(propertyName="password", propertyValue="guest") } ) public class DefaultResourceAdapterQueueMDB implements MessageListener { @Inject @JMSPasswordCredential(userName = "guest", password = "guest") private JMSContext context; @Override public void onMessage(final Message m) { try { TextMessage message = (TextMessage) m; Destination replyTo = m.getJMSReplyTo(); context.createProducer() .setJMSCorrelationID(message.getJMSMessageID()) .send(replyTo, message.getText()); } catch (Exception e) { e.printStackTrace(); } } }
2,623
38.164179
116
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/ExternalMessagingDeploymentRemoteTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, 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.jboss.as.test.integration.messaging.jms.external; import static org.jboss.as.controller.client.helpers.ClientConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.shrinkwrap.api.ShrinkWrap.create; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.net.SocketPermission; import java.net.URL; import java.util.PropertyPermission; import java.util.UUID; import java.util.concurrent.TimeUnit; 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.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.PermissionUtils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; 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 invoking a management operation that removes a JMS resource that is used by a deployed archive must fail: * the resource must not be removed and any depending services must be recovered. * The deployment must still be operating after the failing management operation. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(ExternalMessagingDeploymentRemoteTestCase.SetupTask.class) public class ExternalMessagingDeploymentRemoteTestCase { public static final String QUEUE_LOOKUP = "java:/jms/DependentMessagingDeploymentTestCase/myQueue"; public static final String TOPIC_LOOKUP = "java:/jms/DependentMessagingDeploymentTestCase/myTopic"; public static final String REMOTE_PCF = "remote-artemis"; private static final String QUEUE_NAME = "myQueue"; private static final String TOPIC_NAME = "myTopic"; @ArquillianResource private URL url; @ArquillianResource private ManagementClient managementClient; static class SetupTask extends SnapshotRestoreSetupTask { private static final Logger logger = Logger.getLogger(ExternalMessagingDeploymentRemoteTestCase.SetupTask.class); @Override public void doSetup(org.jboss.as.arquillian.container.ManagementClient managementClient, String s) throws Exception { ServerReload.executeReloadAndWaitForCompletion(managementClient, true); JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); boolean needRemoteConnector = ops.isRemoteBroker(); if (needRemoteConnector) { ops.addExternalRemoteConnector("remote-broker-connector", "messaging-activemq"); } else { ops.createJmsQueue(QUEUE_NAME, "/queue/" + QUEUE_NAME); ops.createJmsTopic(TOPIC_NAME, "/topic/" + TOPIC_NAME); execute(managementClient, addSocketBinding("legacy-messaging", 5445), true); ops.addExternalRemoteConnector("legacy-broker-connector", "legacy-messaging"); execute(managementClient, addRemoteAcceptor(ops.getServerAddress(), "legacy-broker-acceptor", "legacy-messaging"), true); } ModelNode op = Operations.createRemoveOperation(getInitialPooledConnectionFactoryAddress(ops.getServerAddress())); managementClient.getControllerClient().execute(op); op = Operations.createAddOperation(getPooledConnectionFactoryAddress()); op.get("transaction").set("xa"); op.get("entries").add("java:/JmsXA java:jboss/DefaultJMSConnectionFactory"); if (needRemoteConnector) { op.get("connectors").add("remote-broker-connector"); } else { op.get("connectors").add("legacy-broker-connector"); } execute(managementClient, op, true); op = Operations.createAddOperation(getExternalTopicAddress()); op.get("entries").add(TOPIC_LOOKUP); op.get("entries").add("/topic/myAwesomeClientTopic"); execute(managementClient, op, true); op = Operations.createAddOperation(getExternalQueueAddress()); op.get("entries").add(QUEUE_LOOKUP); op.get("entries").add("/queue/myAwesomeClientQueue"); execute(managementClient, op, true); op = Operations.createWriteAttributeOperation(PathAddress.parseCLIStyleAddress("/subsystem=ejb3").toModelNode(), "default-resource-adapter-name", REMOTE_PCF); execute(managementClient, op, true); ServerReload.executeReloadAndWaitForCompletion(managementClient); } private ModelNode execute(final org.jboss.as.arquillian.container.ManagementClient managementClient, final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { assertEquals(response.toString(), "success", outcome); return response.get("result"); } else { assertEquals("failed", outcome); return response.get("failure-description"); } } ModelNode getPooledConnectionFactoryAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("pooled-connection-factory", REMOTE_PCF); return address; } ModelNode getExternalTopicAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("external-jms-topic", TOPIC_NAME); return address; } ModelNode getExternalQueueAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("external-jms-queue", QUEUE_NAME); return address; } ModelNode getInitialPooledConnectionFactoryAddress(ModelNode serverAddress) { ModelNode address = serverAddress.clone(); address.add("pooled-connection-factory", "activemq-ra"); return address; } ModelNode addSocketBinding(String bindingName, int port) { ModelNode address = new ModelNode(); address.add("socket-binding-group", "standard-sockets"); address.add("socket-binding", bindingName); ModelNode socketBindingOp = new ModelNode(); socketBindingOp.get(OP).set(ADD); socketBindingOp.get(OP_ADDR).set(address); socketBindingOp.get("port").set(port); return socketBindingOp; } ModelNode addExternalRemoteConnector(ModelNode subsystemAddress, String name, String socketBinding) { ModelNode address = subsystemAddress.clone(); address.add("remote-connector", name); ModelNode socketBindingOp = new ModelNode(); socketBindingOp.get(OP).set(ADD); socketBindingOp.get(OP_ADDR).set(address); socketBindingOp.get("socket-binding").set(socketBinding); return socketBindingOp; } ModelNode addRemoteAcceptor(ModelNode serverAddress, String name, String socketBinding) { ModelNode address = serverAddress.clone(); address.add("remote-acceptor", name); ModelNode socketBindingOp = new ModelNode(); socketBindingOp.get(OP).set(ADD); socketBindingOp.get(OP_ADDR).set(address); socketBindingOp.get("socket-binding").set(socketBinding); return socketBindingOp; } } @Deployment public static WebArchive createArchive() { return create(WebArchive.class, "ClientMessagingDeploymentTestCase.war") .addClasses(RemoteMessagingServlet.class, TimeoutUtil.class) .addClasses(DefaultResourceAdapterQueueMDB.class, TopicMDB.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( new SocketPermission("localhost", "resolve"), new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read")), "permissions.xml") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); } @Test public void testSendMessageInClientQueue() throws Exception { sendAndReceiveMessage(true); checkCreatedPooledConnectionFactory(); } @Test public void testSendMessageInClientTopic() throws Exception { sendAndReceiveMessage(false); checkCreatedPooledConnectionFactory(); } private void sendAndReceiveMessage(boolean sendToQueue) throws Exception { String destination = sendToQueue ? "queue" : "topic"; String text = UUID.randomUUID().toString(); String serverUrl = this.url.toExternalForm(); if (!serverUrl.endsWith("/")) { serverUrl = serverUrl + "/"; } URL servletUrl = new URL(serverUrl + "ClientMessagingDeploymentTestCase?destination=" + destination + "&text=" + text); String reply = HttpRequest.get(servletUrl.toExternalForm(), TimeoutUtil.adjust(10), TimeUnit.SECONDS); assertNotNull(reply); assertEquals(text, reply); } private void checkCreatedPooledConnectionFactory() throws IOException { ModelNode op = Operations.createReadResourceOperation( PathAddress.pathAddress("deployment", "ClientMessagingDeploymentTestCase.war") .append("subsystem", "messaging-activemq") .append("pooled-connection-factory", "ClientMessagingDeploymentTestCase_ClientMessagingDeploymentTestCase_java_global/definedFactory") .toModelNode()); op.get("recursive").set(true); op.get("include-runtime").set(true); ModelNode response = managementClient.getControllerClient().execute(op); assertEquals(response.toString(), "success", response.get("outcome").asString()); } }
11,961
46.848
178
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/DiscoveryGroupExternalMessagingDeploymentTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, 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.jboss.as.test.integration.messaging.jms.external; import static org.jboss.as.controller.client.helpers.ClientConstants.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.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.jboss.shrinkwrap.api.ShrinkWrap.create; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.PropertyPermission; import java.util.UUID; import java.util.concurrent.TimeUnit; 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.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.IntermittentFailure; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jgroups.util.StackType; import org.jgroups.util.Util; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Test that invoking a management operation that removes a JMS resource that is used by a deployed archive must fail: * the resource must not be removed and any depending services must be recovered. * The deployment must still be operating after the failing management operation. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(DiscoveryGroupExternalMessagingDeploymentTestCase.SetupTask.class) public class DiscoveryGroupExternalMessagingDeploymentTestCase { @BeforeClass public static void beforeClass() { IntermittentFailure.thisTestIsFailingIntermittently("WFLY-10993 Unignore DiscoveryGroupExternalMessagingDeploymentTestCase"); } public static final boolean SKIP = AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> { boolean badIPv6System = Util.checkForWindows() || // https://issues.redhat.com/browse/WFLY-14070 "true".equals(System.getenv().get("GITHUB_ACTIONS")); return badIPv6System && (Util.getIpStackType() == StackType.IPv6); }); public static final String QUEUE_LOOKUP = "java:/jms/DependentMessagingDeploymentTestCase/myQueue"; public static final String TOPIC_LOOKUP = "java:/jms/DependentMessagingDeploymentTestCase/myTopic"; public static final String REMOTE_PCF = "remote-artemis"; private static final String QUEUE_NAME = "myQueue"; private static final String TOPIC_NAME = "myTopic"; private static final String DISCOVERY_GROUP_NAME = "dg1"; private static final String MULTICAST_SOCKET_BINDING = "messaging-group"; private static final String TESTSUITE_MCAST = System.getProperty("mcast", "230.0.0.4"); @ArquillianResource private URL url; static class SetupTask extends SnapshotRestoreSetupTask { private static final Logger logger = Logger.getLogger(DiscoveryGroupExternalMessagingDeploymentTestCase.SetupTask.class); @Override public void doSetup(org.jboss.as.arquillian.container.ManagementClient managementClient, String s) throws Exception { if(SKIP) { logger.info("We are running on Windows with IPV6 stack"); logger.info("[WFCI-32] Disable on Windows+IPv6 until CI environment is fixed"); return; } ServerReload.executeReloadAndWaitForCompletion(managementClient, true); JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); ops.createJmsQueue(QUEUE_NAME, "/queue/" + QUEUE_NAME); ops.createJmsTopic(TOPIC_NAME, "/topic/" + TOPIC_NAME); execute(managementClient, addMulticastSocketBinding(MULTICAST_SOCKET_BINDING, TESTSUITE_MCAST, "${jboss.messaging.group.port:45700}"), true); execute(managementClient, addClientDiscoveryGroup(DISCOVERY_GROUP_NAME, MULTICAST_SOCKET_BINDING), true); ModelNode op = Operations.createRemoveOperation(getInitialPooledConnectionFactoryAddress()); execute(managementClient, op, true); execute(managementClient, createBroadcastGroupWithSocketBinding(ops.getServerAddress(), "bg-group1", MULTICAST_SOCKET_BINDING, "http-connector"), true); execute(managementClient, createDiscoveryGroupWithSocketBinding(ops.getServerAddress(), "dg-group1", MULTICAST_SOCKET_BINDING), true); execute(managementClient, createClusterConnection(ops.getServerAddress(), "my-cluster", "jms", "http-connector", "dg-group1"), true); op = Operations.createAddOperation(getPooledConnectionFactoryAddress()); op.get("transaction").set("xa"); op.get("entries").add("java:/JmsXA java:jboss/DefaultJMSConnectionFactory"); op.get("discovery-group").set(DISCOVERY_GROUP_NAME); execute(managementClient, op, true); op = Operations.createAddOperation(getClientTopicAddress()); op.get("entries").add(TOPIC_LOOKUP); op.get("entries").add("/topic/myAwesomeClientTopic"); execute(managementClient, op, true); op = Operations.createAddOperation(getClientQueueAddress()); op.get("entries").add(QUEUE_LOOKUP); op.get("entries").add("/topic/myAwesomeClientQueue"); execute(managementClient, op, true); ServerReload.executeReloadAndWaitForCompletion(managementClient); } private ModelNode execute(final org.jboss.as.arquillian.container.ManagementClient managementClient, final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { assertEquals(response.toString(), "success", outcome); return response.get("result"); } else { assertEquals("failed", outcome); return response.get("failure-description"); } } ModelNode getPooledConnectionFactoryAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("pooled-connection-factory", REMOTE_PCF); return address; } ModelNode getClientTopicAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("external-jms-topic", TOPIC_NAME); return address; } ModelNode getClientQueueAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("external-jms-queue", QUEUE_NAME); return address; } ModelNode getInitialPooledConnectionFactoryAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("server", "default"); address.add("pooled-connection-factory", "activemq-ra"); return address; } ModelNode addClientDiscoveryGroup(String name, String socketBinding) { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("socket-discovery-group", name); ModelNode add = new ModelNode(); add.get(OP).set(ADD); add.get(OP_ADDR).set(address); add.get("socket-binding").set(socketBinding); add.get("initial-wait-timeout").set(TimeoutUtil.adjust(30000)); return add; } ModelNode addMulticastSocketBinding(String bindingName, String multicastAddress, String multicastPort) { ModelNode address = new ModelNode(); address.add("socket-binding-group", "standard-sockets"); address.add("socket-binding", bindingName); ModelNode socketBindingOp = new ModelNode(); socketBindingOp.get(OP).set(ADD); socketBindingOp.get(OP_ADDR).set(address); socketBindingOp.get("multicast-address").set(multicastAddress); socketBindingOp.get("multicast-port").set(multicastPort); return socketBindingOp; } ModelNode createDiscoveryGroupWithSocketBinding(ModelNode serverAddress, String discoveryGroupName, String socketBinding) throws Exception { ModelNode address = serverAddress.clone(); address.add("socket-discovery-group", discoveryGroupName); ModelNode op = Operations.createAddOperation(address); op.get("socket-binding").set(socketBinding); return op; } ModelNode createBroadcastGroupWithSocketBinding(ModelNode serverAddress, String broadcastGroupName, String socketBinding, String connector) throws Exception { ModelNode address = serverAddress.clone(); address.add("socket-broadcast-group", broadcastGroupName); ModelNode op = Operations.createAddOperation(address); op.get("socket-binding").set(socketBinding); op.get("connectors").add(connector); return op; } ModelNode createClusterConnection(ModelNode serverAddress, String name, String address, String connector, String discoveryGroup) throws Exception { ModelNode opAddress = serverAddress.clone(); opAddress.add("cluster-connection", name); ModelNode op = Operations.createAddOperation(opAddress); op.get("cluster-connection-address").set(address); op.get("connector-name").set(connector); op.get("discovery-group").set(discoveryGroup); return op; } } @Deployment public static WebArchive createArchive() { if(SKIP) { return create(WebArchive.class, "ClientMessagingDeploymentTestCase.war") .addAsWebResource(new StringAsset("Root file"), "root-file.txt"); } return create(WebArchive.class, "ClientMessagingDeploymentTestCase.war") .addClasses(MessagingServlet.class, TimeoutUtil.class) .addClasses(QueueMDB.class, TopicMDB.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read") ), "permissions.xml"); } @BeforeClass public static void skipSecurityManager() { AssumeTestGroupUtil.assumeSecurityManagerDisabled(); } @Before public void before() { Assume.assumeFalse("[WFCI-32] Disable on Windows+IPv6 until CI environment is fixed", SKIP); } @Test public void testSendMessageInClientQueue() throws Exception { sendAndReceiveMessage(true); } @Test public void testSendMessageInClientTopic() throws Exception { sendAndReceiveMessage(false); } private void sendAndReceiveMessage(boolean sendToQueue) throws Exception { String destination = sendToQueue ? "queue" : "topic"; String text = UUID.randomUUID().toString(); URL url = new URL(this.url.toExternalForm() + "ClientMessagingDeploymentTestCase?destination=" + destination + "&text=" + text); String reply = HttpRequest.get(url.toExternalForm(), TimeoutUtil.adjust(10), TimeUnit.SECONDS); assertNotNull(reply); assertEquals(text, reply); } }
13,705
47.775801
178
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/SendToExternalJMSTopicTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, 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.jboss.as.test.integration.messaging.jms.external; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.SocketPermission; import jakarta.annotation.Resource; import jakarta.jms.Connection; import jakarta.jms.ConnectionFactory; import jakarta.jms.Message; import jakarta.jms.MessageConsumer; import jakarta.jms.MessageProducer; import jakarta.jms.Session; import jakarta.jms.TextMessage; import jakarta.jms.Topic; 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.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.PermissionUtils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.ServerSnapshot; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.remoting3.security.RemotingPermission; import org.jboss.shrinkwrap.api.ArchivePaths; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Basic Jakarta Messaging test using a customly created Jakarta Messaging topic * * @author <a href="[email protected]">Jan Martiska</a> */ @RunWith(Arquillian.class) @ServerSetup(SendToExternalJMSTopicTestCase.SetupTask.class) public class SendToExternalJMSTopicTestCase { static class SetupTask implements ServerSetupTask { private static final Logger logger = Logger.getLogger(SendToExternalJMSTopicTestCase.SetupTask.class); private AutoCloseable snapshot = null; @Override public void setup(org.jboss.as.arquillian.container.ManagementClient managementClient, String s) throws Exception { snapshot = ServerSnapshot.takeSnapshot(managementClient); ServerReload.executeReloadAndWaitForCompletion(managementClient, true); JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); boolean needRemoteConnector = ops.isRemoteBroker(); if (needRemoteConnector) { ops.addExternalRemoteConnector("remote-broker-connector", "messaging-activemq"); } else { ops.addExternalHttpConnector("http-test-connector", "http", "http-acceptor"); ops.createJmsTopic("myAwesomeTopic", "/topic/myAwesomeTopic"); } ModelNode op = Operations.createRemoveOperation(getInitialPooledConnectionFactoryAddress(ops.getServerAddress())); execute(managementClient, op, true); op = Operations.createAddOperation(getPooledConnectionFactoryAddress()); op.get("transaction").set("xa"); op.get("entries").add("java:/JmsXA java:jboss/DefaultJMSConnectionFactory"); if(needRemoteConnector) { op.get("connectors").add("remote-broker-connector"); } else { op.get("connectors").add("http-test-connector"); } execute(managementClient, op, true); op = Operations.createAddOperation(getClientTopicAddress()); op.get("entries").add("java:jboss/exported/topic/myAwesomeClientTopic"); op.get("entries").add("/topic/myAwesomeClientTopic"); execute(managementClient, op, true); ServerReload.executeReloadAndWaitForCompletion(managementClient); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); ops.removeJmsTopic("myAwesomeTopic"); if (snapshot != null) { snapshot.close(); } ServerReload.executeReloadAndWaitForCompletion(managementClient); } private ModelNode execute(final org.jboss.as.arquillian.container.ManagementClient managementClient, final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { assertEquals(response.toString(), "success", outcome); return response.get("result"); } else { assertEquals("failed", outcome); return response.get("failure-description"); } } ModelNode getPooledConnectionFactoryAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("pooled-connection-factory", "activemq-ra"); return address; } ModelNode getClientTopicAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("external-jms-topic", "myAwesomeTopic"); return address; } ModelNode getInitialPooledConnectionFactoryAddress(ModelNode serverAddress) { ModelNode address = serverAddress.clone(); address.add("pooled-connection-factory", "activemq-ra"); return address; } } private static final Logger logger = Logger.getLogger(SendToExternalJMSTopicTestCase.class); @Resource(lookup = "java:jboss/exported/topic/myAwesomeClientTopic") private Topic topic; @Resource(lookup = "java:/JmsXA") private ConnectionFactory factory; @Deployment public static JavaArchive createTestArchive() { return ShrinkWrap.create(JavaArchive.class, "test.jar") .addPackage(JMSOperations.class.getPackage()) .addClass(SendToExternalJMSTopicTestCase.SetupTask.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( RemotingPermission.CREATE_ENDPOINT, RemotingPermission.CONNECT, new SocketPermission("localhost", "resolve")), "permissions.xml") .addAsManifestResource( EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml")); } @Test public void sendMessage() throws Exception { Connection senderConnection = null; Connection consumerConnection = null; Session senderSession = null; Session consumerSession = null; MessageConsumer consumer = null; try { // CREATE SUBSCRIBER logger.trace("******* Creating connection for consumer"); consumerConnection = factory.createConnection("guest", "guest"); logger.trace("Creating session for consumer"); consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); logger.trace("Creating consumer"); consumer = consumerSession.createConsumer(topic); logger.trace("Start session"); consumerConnection.start(); // SEND A MESSAGE logger.trace("***** Start - sending message to topic"); senderConnection = factory.createConnection("guest", "guest"); logger.trace("Creating session.."); senderSession = senderConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = senderSession.createProducer(topic); TextMessage message = senderSession.createTextMessage("Hello world!"); logger.trace("Sending.."); producer.send(message); logger.trace("Message sent"); senderConnection.start(); } catch (Exception ex) { ex.printStackTrace(); } finally { logger.trace("Closing connections and sessions"); if (senderSession != null) { senderSession.close(); } if (senderConnection != null) { senderConnection.close(); } } Message receivedMessage = null; try { logger.trace("Receiving"); receivedMessage = consumer.receive(5000); logger.trace("Received: " + ((TextMessage) receivedMessage).getText()); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } finally { if (receivedMessage == null) { Assert.fail("received null instead of a TextMessage"); } if (consumerSession != null) { consumerSession.close(); } if (consumerConnection != null) { consumerConnection.close(); } } Assert.assertTrue("received a " + receivedMessage.getClass().getName() + " instead of a TextMessage", receivedMessage instanceof TextMessage); Assert.assertEquals("Hello world!", ((TextMessage) receivedMessage).getText()); } }
10,400
42.701681
178
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/MessagingServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.external; import org.jboss.as.test.shared.TimeoutUtil; import static org.jboss.as.test.integration.messaging.jms.deployment.DependentMessagingDeploymentTestCase.QUEUE_LOOKUP; import static org.jboss.as.test.integration.messaging.jms.deployment.DependentMessagingDeploymentTestCase.TOPIC_LOOKUP; import java.io.IOException; import jakarta.annotation.Resource; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSConnectionFactory; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSPasswordCredential; import jakarta.jms.Queue; import jakarta.jms.Topic; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Emmanuel Hugonnet (c) 2018 Red Hat, inc. */ @WebServlet("/ClientMessagingDeploymentTestCase") public class MessagingServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Resource(lookup = QUEUE_LOOKUP) private Queue queue; @Resource(lookup = TOPIC_LOOKUP) private Topic topic; @Inject @JMSConnectionFactory("java:/JmsXA") @JMSPasswordCredential(userName = "guest", password = "guest") private JMSContext context; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean useTopic = req.getParameterMap().containsKey("topic"); final Destination destination = useTopic ? topic : queue; final String text = req.getParameter("text"); String reply = sendAndReceiveMessage(destination, text); resp.getWriter().write(reply); } private String sendAndReceiveMessage(Destination destination, String text) { Destination replyTo = context.createTemporaryQueue(); JMSConsumer consumer = context.createConsumer(replyTo); context.createProducer() .setJMSReplyTo(replyTo) .send(destination, text); return consumer.receiveBody(String.class, TimeoutUtil.adjust(5000)); } }
3,261
36.494253
119
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/RemoteMessagingServlet.java
/* * Copyright 2022 JBoss by Red Hat. * * 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.jboss.as.test.integration.messaging.jms.external; import static org.jboss.as.test.integration.messaging.jms.external.ExternalMessagingDeploymentTestCase.QUEUE_LOOKUP; import static org.jboss.as.test.integration.messaging.jms.external.ExternalMessagingDeploymentTestCase.TOPIC_LOOKUP; import jakarta.annotation.Resource; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSConnectionFactory; import jakarta.jms.JMSConnectionFactoryDefinition; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSPasswordCredential; import jakarta.jms.Queue; import jakarta.jms.Topic; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import org.jboss.as.test.shared.TimeoutUtil; /** * * @author Emmanuel Hugonnet (c) 2022 Red Hat, Inc. */ @JMSConnectionFactoryDefinition( resourceAdapter = "remote-artemis", name = "java:global/definedFactory", user = "guest", password = "guest" ) @WebServlet("/ClientMessagingDeploymentTestCase") public class RemoteMessagingServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Resource(lookup = QUEUE_LOOKUP) private Queue queue; @Resource(lookup = TOPIC_LOOKUP) private Topic topic; @Inject @JMSConnectionFactory("java:/JmsXA") @JMSPasswordCredential(userName = "guest", password = "guest") private JMSContext context; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean useTopic = req.getParameterMap().containsKey("topic"); final Destination destination = useTopic ? topic : queue; final String text = req.getParameter("text"); String reply = sendAndReceiveMessage(destination, text); resp.getWriter().write(reply); } private String sendAndReceiveMessage(Destination destination, String text) { Destination replyTo = context.createTemporaryQueue(); JMSConsumer consumer = context.createConsumer(replyTo); context.createProducer() .setJMSReplyTo(replyTo) .send(destination, text); return consumer.receiveBody(String.class, TimeoutUtil.adjust(5000)); } }
3,067
34.264368
116
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/prefix/QueueMDB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.external.prefix; import static org.jboss.as.test.integration.messaging.jms.external.prefix.ExternalJMSDestinationDefinitionMessagingDeploymentTestCase.REMOTE_PCF; import static org.jboss.as.test.integration.messaging.jms.external.prefix.ExternalJMSDestinationDefinitionMessagingDeploymentTestCase.QUEUE_LOOKUP; import jakarta.ejb.ActivationConfigProperty; import jakarta.ejb.MessageDriven; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSContext; import jakarta.jms.JMSPasswordCredential; import jakarta.jms.Message; import jakarta.jms.MessageListener; import jakarta.jms.TextMessage; import org.jboss.ejb3.annotation.ResourceAdapter; /** * @author Emmanuel Hugonnet (c) 2018 Red Hat, inc. */ @MessageDriven( activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "jakarta.jms.Queue"), @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = QUEUE_LOOKUP), @ActivationConfigProperty(propertyName="user", propertyValue="guest"), @ActivationConfigProperty(propertyName="password", propertyValue="guest") } ) @ResourceAdapter(REMOTE_PCF) // name of the pooled-connection-factory resource public class QueueMDB implements MessageListener { @Inject @JMSPasswordCredential(userName = "guest", password = "guest") private JMSContext context; @Override public void onMessage(final Message m) { try { TextMessage message = (TextMessage) m; Destination replyTo = m.getJMSReplyTo(); context.createProducer() .setJMSCorrelationID(message.getJMSMessageID()) .send(replyTo, message.getText()); } catch (Exception e) { e.printStackTrace(); } } }
2,916
39.513889
147
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/prefix/ExternalJMSDestinationDefinitionMessagingDeploymentTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, 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.jboss.as.test.integration.messaging.jms.external.prefix; import static org.jboss.shrinkwrap.api.ShrinkWrap.create; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.net.SocketPermission; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PropertyPermission; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.jboss.arquillian.container.test.api.Deployer; 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.ContainerResource; import org.jboss.as.arquillian.api.ServerSetup; 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.integration.common.HttpRequest; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.PermissionUtils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.ServerSnapshot; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; 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; /** * Test the creation of destination on a 'remote' Artemis broker via @JMSDestinationDefinition. * @author Emmanuel Hugonnet (c) 2021 Red Hat, Inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(ExternalJMSDestinationDefinitionMessagingDeploymentTestCase.SetupTask.class) public class ExternalJMSDestinationDefinitionMessagingDeploymentTestCase { public static final String QUEUE_LOOKUP = "java:/jms/AutomaticQueueCreationOnExternalMessagingDeploymentTestCase/myQueue"; public static final String TOPIC_LOOKUP = "java:/jms/AutomaticQueueCreationOnExternalMessagingDeploymentTestCase/myTopic"; public static final String REMOTE_PCF = "remote-artemis"; public static final String QUEUE_NAME = "myExternalQueue"; public static final String TOPIC_NAME = "myExternalTopic"; private static Set<String> initialQueues = null; static class SetupTask implements ServerSetupTask { private static final Logger logger = Logger.getLogger(ExternalJMSDestinationDefinitionMessagingDeploymentTestCase.SetupTask.class); private final Map<String, AutoCloseable> snapshots = new HashMap<>(); @Override public final void setup(ManagementClient managementClient, String containerId) throws Exception { snapshots.put(containerId, ServerSnapshot.takeSnapshot(managementClient)); Set<String> runtimeQueues = listRuntimeQueues(managementClient); ServerReload.executeReloadAndWaitForCompletion(managementClient, true); JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); boolean needRemoteConnector = ops.isRemoteBroker(); if (needRemoteConnector) { ops.addExternalRemoteConnector("remote-broker-connector", "messaging-activemq"); } else { ops.addExternalHttpConnector("http-test-connector", "http", "http-acceptor"); } //To avoid security limitations as default role guest doesn't have the 'manage' rights // /subsystem=messaging-activemq/server=default/security-setting=#/role=guest:write-attribute(name=manage, value=true) ops.disableSecurity(); ModelNode op = Operations.createRemoveOperation(getInitialPooledConnectionFactoryAddress(ops.getServerAddress())); managementClient.getControllerClient().execute(op); op = Operations.createAddOperation(getPooledConnectionFactoryAddress()); op.get("transaction").set("xa"); op.get("entries").add("java:/JmsXA java:jboss/DefaultJMSConnectionFactory"); if (needRemoteConnector) { op.get("connectors").add("remote-broker-connector"); } else { op.get("connectors").add("http-test-connector"); } op.get("enable-amq1-prefix").set(false); execute(managementClient, op, true); op = Operations.createRemoveOperation(getClientTopicAddress()); managementClient.getControllerClient().execute(op); op = Operations.createRemoveOperation(getClientQueueAddress()); managementClient.getControllerClient().execute(op); ops.close(); ServerReload.executeReloadAndWaitForCompletion(managementClient); ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); for (String runtimeQueue : runtimeQueues) { if (!"jms.queue.DLQ".equals(runtimeQueue) && !"jms.queue.ExpiryQueue".equals(runtimeQueue)) { ops.removeCoreQueue(runtimeQueue); } } ops.close(); } @Override public final void tearDown(ManagementClient managementClient, String containerId) throws Exception { JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); if (!ops.isRemoteBroker()) { Set<String> runtimeQueues = listRuntimeQueues(managementClient); runtimeQueues.remove("jms.queue.DLQ"); runtimeQueues.remove("jms.queue.ExpiryQueue"); if (!runtimeQueues.isEmpty()) { Map<String, ModelNode> runtimes = new HashMap<>(runtimeQueues.size()); for (String runtimeQueue : runtimeQueues) { runtimes.put(runtimeQueue, readRuntimeQueue(managementClient, ops, runtimeQueue)); } ops.close(); ServerReload.executeReloadAndWaitForCompletion(managementClient, true); ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); for (String runtimeQueue : runtimeQueues) { String address = runtimes.get(runtimeQueue).get("queue-address").asString(); String routingType = runtimes.get(runtimeQueue).get("routing-type").asString(); boolean durable = runtimes.get(runtimeQueue).get("durable").asBoolean(); ops.addCoreQueue(runtimeQueue, address, durable, routingType); } ops.close(); ServerReload.executeReloadAndWaitForCompletion(managementClient, false); ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); for (String runtimeQueue : runtimeQueues) { ops.removeCoreQueue(runtimeQueue); } ops.close(); ServerReload.executeReloadAndWaitForCompletion(managementClient, false); } } AutoCloseable snapshot = snapshots.remove(containerId); if (snapshot != null) { snapshot.close(); } } private ModelNode readRuntimeQueue(ManagementClient managementClient, JMSOperations ops, String name) throws IOException { ModelNode op = Operations.createReadResourceOperation(ops.getServerAddress().add("runtime-queue", name), false); op.get("include-runtime").set(true); op.get("include-defaults").set(true); return Operations.readResult(managementClient.getControllerClient().execute(op)); } private ModelNode execute(final org.jboss.as.arquillian.container.ManagementClient managementClient, final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { assertEquals(response.toString(), "success", outcome); return response.get("result"); } else { assertEquals("failed", outcome); return response.get("failure-description"); } } private ModelNode getPooledConnectionFactoryAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("pooled-connection-factory", REMOTE_PCF); return address; } private ModelNode getClientTopicAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("external-jms-topic", TOPIC_NAME); return address; } private ModelNode getClientQueueAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("external-jms-queue", QUEUE_NAME); return address; } private ModelNode getInitialPooledConnectionFactoryAddress(ModelNode serverAddress) { ModelNode address = serverAddress.clone(); address.add("pooled-connection-factory", "activemq-ra"); return address; } } @Deployment(managed = false, testable = false, name = "external-queues") public static WebArchive createArchive() { return create(WebArchive.class, "ClientMessagingDeploymentTestCase.war") .addClasses(AnnotatedMessagingServlet.class, TimeoutUtil.class) .addClasses(QueueMDB.class, TopicMDB.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( new SocketPermission("localhost", "resolve"), new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read")), "permissions.xml") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addAsWebInfResource(new StringAsset( "<jboss-web>" + "<context-root>/test</context-root>" + "</jboss-web>"), "jboss-web.xml"); } @ContainerResource private ManagementClient managementClient; @ArquillianResource private Deployer deployer; @Before public void setUp() throws IOException { if (initialQueues == null) { initialQueues = listRuntimeQueues(managementClient); } deployer.deploy("external-queues"); } @After public void tearDown() throws IOException { deployer.undeploy("external-queues"); } static Set<String> listRuntimeQueues(org.jboss.as.arquillian.container.ManagementClient managementClient) throws IOException { JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); ModelNode op = Operations.createOperation("read-children-names", ops.getServerAddress()); op.get("child-type").set("runtime-queue"); List<ModelNode> runtimeQueues = Operations.readResult(managementClient.getControllerClient().execute(op)).asList(); return runtimeQueues.stream().map(ModelNode::asString).collect(Collectors.toSet()); } @Test public void testSendMessage() throws Exception { sendAndReceiveMessage(true); sendAndReceiveMessage(false); checkRuntimeQueue(); } private void sendAndReceiveMessage(boolean sendToQueue) throws Exception { String destination = sendToQueue ? "queue" : "topic"; String text = UUID.randomUUID().toString(); String serverUrl = managementClient.getWebUri().toURL().toString() + "/test/"; URL servletUrl = new URL(serverUrl + "ClientMessagingDeploymentTestCase?destination=" + destination + "&text=" + text); String reply = HttpRequest.get(servletUrl.toExternalForm(), TimeoutUtil.adjust(10), TimeUnit.SECONDS); assertNotNull(reply); assertEquals(text, reply); } private void checkRuntimeQueue() throws IOException { JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); if (!ops.isRemoteBroker()) { ModelNode op = Operations.createOperation("read-children-names", ops.getServerAddress()); op.get("child-type").set("runtime-queue"); List<ModelNode> runtimeQueues = Operations.readResult(managementClient.getControllerClient().execute(op)).asList(); Set<String> queues = runtimeQueues.stream().map(ModelNode::asString).collect(Collectors.toSet()); Assert.assertEquals(initialQueues.size() + 2, queues.size()); Assert.assertTrue("We should have myExternalQueue queue", queues.contains("myExternalQueue")); queues.removeAll(initialQueues); queues.remove("myExternalQueue"); String topicId = queues.iterator().next(); checkRuntimeQueue(ops, "myExternalQueue", "ANYCAST", "myExternalQueue"); checkRuntimeQueue(ops, topicId, "MULTICAST", "myExternalTopic"); } } private void checkRuntimeQueue(JMSOperations ops, String name, String expectedRoutingType, String expectedQueueAddress) throws IOException { ModelNode op = Operations.createReadResourceOperation(ops.getServerAddress().add("runtime-queue", name), false); op.get("include-runtime").set(true); op.get("include-defaults").set(true); ModelNode result = Operations.readResult(managementClient.getControllerClient().execute(op)); Assert.assertEquals(expectedRoutingType, result.require("routing-type").asString()); Assert.assertEquals(expectedQueueAddress, result.require("queue-address").asString()); } }
15,362
50.039867
178
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/prefix/AnnotatedLegacyPrefixMessagingServlet.java
/* * Copyright 2021 JBoss by Red Hat. * * 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.jboss.as.test.integration.messaging.jms.external.prefix; import static org.jboss.as.test.integration.messaging.jms.external.prefix.ExternalJMSDestinationDefinitionLegacyPrefixMessagingDeploymentTestCase.QUEUE_NAME; import static org.jboss.as.test.integration.messaging.jms.external.prefix.ExternalJMSDestinationDefinitionLegacyPrefixMessagingDeploymentTestCase.TOPIC_LOOKUP; import static org.jboss.as.test.integration.messaging.jms.external.prefix.ExternalJMSDestinationDefinitionLegacyPrefixMessagingDeploymentTestCase.QUEUE_LOOKUP; import static org.jboss.as.test.integration.messaging.jms.external.prefix.ExternalJMSDestinationDefinitionLegacyPrefixMessagingDeploymentTestCase.REMOTE_PCF; import static org.jboss.as.test.integration.messaging.jms.external.prefix.ExternalJMSDestinationDefinitionLegacyPrefixMessagingDeploymentTestCase.TOPIC_NAME; import java.io.IOException; import jakarta.annotation.Resource; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSConnectionFactory; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSDestinationDefinition; import jakarta.jms.JMSDestinationDefinitions; import jakarta.jms.JMSPasswordCredential; import jakarta.jms.Queue; import jakarta.jms.Topic; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.jboss.as.test.shared.TimeoutUtil; /** * * @author Emmanuel Hugonnet (c) 2020 Red Hat, Inc. */ @JMSDestinationDefinitions( value = { @JMSDestinationDefinition( resourceAdapter = REMOTE_PCF, name = QUEUE_LOOKUP, interfaceName = "jakarta.jms.Queue", destinationName = QUEUE_NAME ), @JMSDestinationDefinition( resourceAdapter = REMOTE_PCF, name = TOPIC_LOOKUP, interfaceName = "jakarta.jms.Topic", destinationName = TOPIC_NAME, properties = {"enable-amq1-prefix=true"} ) } ) @WebServlet("/ClientMessagingDeploymentTestCase") public class AnnotatedLegacyPrefixMessagingServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Resource(lookup = QUEUE_LOOKUP) private Queue queue; @Resource(lookup = TOPIC_LOOKUP) private Topic topic; @Inject @JMSConnectionFactory("java:/JmsXA") @JMSPasswordCredential(userName = "guest", password = "guest") private JMSContext context; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean useTopic = req.getParameterMap().containsKey("topic"); final Destination destination = useTopic ? topic : queue; final String text = req.getParameter("text"); String reply = sendAndReceiveMessage(destination, text); resp.getWriter().write(reply); } private String sendAndReceiveMessage(Destination destination, String text) { Destination replyTo = context.createTemporaryQueue(); try (JMSConsumer consumer = context.createConsumer(replyTo)) { context.createProducer().setJMSReplyTo(replyTo).send(destination, text); return consumer.receiveBody(String.class, TimeoutUtil.adjust(5000)); } } }
4,123
41.081633
159
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/prefix/TopicMDB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.external.prefix; import static org.jboss.as.test.integration.messaging.jms.external.prefix.ExternalJMSDestinationDefinitionMessagingDeploymentTestCase.REMOTE_PCF; import static org.jboss.as.test.integration.messaging.jms.external.prefix.ExternalJMSDestinationDefinitionMessagingDeploymentTestCase.TOPIC_LOOKUP; import jakarta.ejb.ActivationConfigProperty; import jakarta.ejb.MessageDriven; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSContext; import jakarta.jms.JMSPasswordCredential; import jakarta.jms.Message; import jakarta.jms.MessageListener; import jakarta.jms.TextMessage; import org.jboss.ejb3.annotation.ResourceAdapter; /** * @author Emmanuel Hugonnet (c) 2018 Red Hat, inc. */ @MessageDriven( activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "jakarta.jms.Topic"), @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = TOPIC_LOOKUP), @ActivationConfigProperty(propertyName="user", propertyValue="guest"), @ActivationConfigProperty(propertyName="password", propertyValue="guest") } ) @ResourceAdapter(REMOTE_PCF) // name of the pooled-connection-factory resource public class TopicMDB implements MessageListener { @Inject @JMSPasswordCredential(userName = "guest", password = "guest") private JMSContext context; @Override public void onMessage(final Message m) { try { TextMessage message = (TextMessage) m; Destination replyTo = m.getJMSReplyTo(); context.createProducer() .setJMSCorrelationID(message.getJMSMessageID()) .send(replyTo, message.getText()); } catch (Exception e) { e.printStackTrace(); } } }
2,914
40.642857
147
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/prefix/ExternalJMSDestinationDefinitionLegacyPrefixMessagingDeploymentTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, 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.jboss.as.test.integration.messaging.jms.external.prefix; import static org.jboss.shrinkwrap.api.ShrinkWrap.create; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.net.SocketPermission; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PropertyPermission; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.jboss.arquillian.container.test.api.Deployer; 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.ContainerResource; import org.jboss.as.arquillian.api.ServerSetup; 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.integration.common.HttpRequest; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.PermissionUtils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.ServerSnapshot; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; 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; /** * Test the creation of destination on a 'remote' Artemis broker via @JMSDestinationDefinition using legacy prefix. * @author Emmanuel Hugonnet (c) 2021 Red Hat, Inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(ExternalJMSDestinationDefinitionLegacyPrefixMessagingDeploymentTestCase.SetupTask.class) public class ExternalJMSDestinationDefinitionLegacyPrefixMessagingDeploymentTestCase { public static final String QUEUE_LOOKUP = "java:/jms/AutomaticQueueCreationOnExternalMessagingDeploymentTestCase/myQueue"; public static final String TOPIC_LOOKUP = "java:/jms/AutomaticQueueCreationOnExternalMessagingDeploymentTestCase/myTopic"; public static final String REMOTE_PCF = "remote-artemis"; public static final String QUEUE_NAME = "myExternalQueue"; public static final String TOPIC_NAME = "myExternalTopic"; private static Set<String> initialQueues = null; static class SetupTask implements ServerSetupTask { private static final Logger logger = Logger.getLogger(ExternalJMSDestinationDefinitionLegacyPrefixMessagingDeploymentTestCase.SetupTask.class); private final Map<String, AutoCloseable> snapshots = new HashMap<>(); @Override public final void setup(ManagementClient managementClient, String containerId) throws Exception { snapshots.put(containerId, ServerSnapshot.takeSnapshot(managementClient)); Set<String> runtimeQueues = listRuntimeQueues(managementClient); ServerReload.executeReloadAndWaitForCompletion(managementClient, true); JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); boolean needRemoteConnector = ops.isRemoteBroker(); if (needRemoteConnector) { ops.addExternalRemoteConnector("remote-broker-connector", "messaging-activemq"); } else { ops.addExternalHttpConnector("http-test-connector", "http", "http-acceptor"); } //To avoid security limitations as default role guest doesn't have the 'manage' rights // /subsystem=messaging-activemq/server=default/security-setting=#/role=guest:write-attribute(name=manage, value=true) ops.disableSecurity(); ModelNode op = Operations.createRemoveOperation(getInitialPooledConnectionFactoryAddress(ops.getServerAddress())); managementClient.getControllerClient().execute(op); op = Operations.createAddOperation(getPooledConnectionFactoryAddress()); op.get("transaction").set("xa"); op.get("entries").add("java:/JmsXA java:jboss/DefaultJMSConnectionFactory"); if (needRemoteConnector) { op.get("connectors").add("remote-broker-connector"); } else { op.get("connectors").add("http-test-connector"); } op.get("enable-amq1-prefix").set(false); execute(managementClient, op, true); op = Operations.createRemoveOperation(getClientTopicAddress()); managementClient.getControllerClient().execute(op); op = Operations.createRemoveOperation(getClientQueueAddress()); managementClient.getControllerClient().execute(op); ops.close(); ServerReload.executeReloadAndWaitForCompletion(managementClient); ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); for (String runtimeQueue : runtimeQueues) { if (!"jms.queue.DLQ".equals(runtimeQueue) && !"jms.queue.ExpiryQueue".equals(runtimeQueue)) { ops.removeCoreQueue(runtimeQueue); } } ops.close(); } @Override public final void tearDown(ManagementClient managementClient, String containerId) throws Exception { JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); if (!ops.isRemoteBroker()) { Set<String> runtimeQueues = listRuntimeQueues(managementClient); runtimeQueues.remove("jms.queue.DLQ"); runtimeQueues.remove("jms.queue.ExpiryQueue"); if (!runtimeQueues.isEmpty()) { Map<String, ModelNode> runtimes = new HashMap<>(runtimeQueues.size()); for (String runtimeQueue : runtimeQueues) { runtimes.put(runtimeQueue, readRuntimeQueue(managementClient, ops, runtimeQueue)); } ops.close(); ServerReload.executeReloadAndWaitForCompletion(managementClient, true); ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); for (String runtimeQueue : runtimeQueues) { String address = runtimes.get(runtimeQueue).get("queue-address").asString(); String routingType = runtimes.get(runtimeQueue).get("routing-type").asString(); boolean durable = runtimes.get(runtimeQueue).get("durable").asBoolean(); ops.addCoreQueue(runtimeQueue, address, durable, routingType); } ops.close(); ServerReload.executeReloadAndWaitForCompletion(managementClient, false); ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); for (String runtimeQueue : runtimeQueues) { ops.removeCoreQueue(runtimeQueue); } ops.close(); ServerReload.executeReloadAndWaitForCompletion(managementClient, false); } } AutoCloseable snapshot = snapshots.remove(containerId); if (snapshot != null) { snapshot.close(); } } private ModelNode readRuntimeQueue(ManagementClient managementClient, JMSOperations ops, String name) throws IOException { ModelNode op = Operations.createReadResourceOperation(ops.getServerAddress().add("runtime-queue", name), false); op.get("include-runtime").set(true); op.get("include-defaults").set(true); return Operations.readResult(managementClient.getControllerClient().execute(op)); } private ModelNode execute(final org.jboss.as.arquillian.container.ManagementClient managementClient, final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { assertEquals(response.toString(), "success", outcome); return response.get("result"); } else { assertEquals("failed", outcome); return response.get("failure-description"); } } private ModelNode getPooledConnectionFactoryAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("pooled-connection-factory", REMOTE_PCF); return address; } private ModelNode getClientTopicAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("external-jms-topic", TOPIC_NAME); return address; } private ModelNode getClientQueueAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("external-jms-queue", QUEUE_NAME); return address; } private ModelNode getInitialPooledConnectionFactoryAddress(ModelNode serverAddress) { ModelNode address = serverAddress.clone(); address.add("pooled-connection-factory", "activemq-ra"); return address; } } @Deployment(managed = false, testable = false, name = "external-queues") public static WebArchive createArchive() { return create(WebArchive.class, "ClientMessagingDeploymentTestCase.war") .addClasses(AnnotatedLegacyPrefixMessagingServlet.class, TimeoutUtil.class) .addClasses(QueueMDB.class, TopicMDB.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( new SocketPermission("localhost", "resolve"), new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read")), "permissions.xml") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addAsWebInfResource(new StringAsset( "<jboss-web>" + "<context-root>/test</context-root>" + "</jboss-web>"), "jboss-web.xml"); } @ContainerResource private ManagementClient managementClient; @ArquillianResource private Deployer deployer; @Before public void setUp() throws IOException { if (initialQueues == null) { initialQueues = listRuntimeQueues(managementClient); } deployer.deploy("external-queues"); } @After public void tearDown() throws IOException { deployer.undeploy("external-queues"); } static Set<String> listRuntimeQueues(org.jboss.as.arquillian.container.ManagementClient managementClient) throws IOException { JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); ModelNode op = Operations.createOperation("read-children-names", ops.getServerAddress()); op.get("child-type").set("runtime-queue"); ModelNode result = Operations.readResult(managementClient.getControllerClient().execute(op)); if(! result.isDefined()) { return new HashSet<>(); } List<ModelNode> runtimeQueues = result.asList(); return runtimeQueues.stream().map(ModelNode::asString).collect(Collectors.toSet()); } @Test public void testSendMessage() throws Exception { sendAndReceiveMessage(true); sendAndReceiveMessage(false); checkRuntimeQueue(); } private void sendAndReceiveMessage(boolean sendToQueue) throws Exception { String destination = sendToQueue ? "queue" : "topic"; String text = UUID.randomUUID().toString(); String serverUrl = managementClient.getWebUri().toURL().toString() + "/test/"; URL servletUrl = new URL(serverUrl + "ClientMessagingDeploymentTestCase?destination=" + destination + "&text=" + text); String reply = HttpRequest.get(servletUrl.toExternalForm(), TimeoutUtil.adjust(10), TimeUnit.SECONDS); assertNotNull(reply); assertEquals(text, reply); checkRuntimeQueue(); } private void checkRuntimeQueue() throws IOException { JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); if (!ops.isRemoteBroker()) { ModelNode op = Operations.createOperation("read-children-names", ops.getServerAddress()); op.get("child-type").set("runtime-queue"); List<ModelNode> runtimeQueues = Operations.readResult(managementClient.getControllerClient().execute(op)).asList(); Set<String> queues = runtimeQueues.stream().map(ModelNode::asString).collect(Collectors.toSet()); Assert.assertEquals("expected:<" + (initialQueues.size() + 2) + "> but was:<" + queues.size()+ ">" + queues.toString() , initialQueues.size() + 2, queues.size()); Assert.assertTrue("We should have myExternalQueue queue", queues.contains("jms.queue.myExternalQueue")); queues.removeAll(initialQueues); queues.remove("jms.queue.myExternalQueue"); String topicId = queues.iterator().next(); checkRuntimeQueue(ops, "jms.queue.myExternalQueue", "ANYCAST", "jms.queue.myExternalQueue"); checkRuntimeQueue(ops, topicId, "MULTICAST", "jms.topic.myExternalTopic"); } } private void checkRuntimeQueue(JMSOperations ops, String name, String expectedRoutingType, String expectedQueueAddress) throws IOException { ModelNode op = Operations.createReadResourceOperation(ops.getServerAddress().add("runtime-queue", name), false); op.get("include-runtime").set(true); op.get("include-defaults").set(true); ModelNode result = Operations.readResult(managementClient.getControllerClient().execute(op)); Assert.assertEquals(expectedRoutingType, result.require("routing-type").asString()); Assert.assertEquals(expectedQueueAddress, result.require("queue-address").asString()); } }
15,752
50.312704
178
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/external/prefix/AnnotatedMessagingServlet.java
/* * Copyright 2021 JBoss by Red Hat. * * 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.jboss.as.test.integration.messaging.jms.external.prefix; import static org.jboss.as.test.integration.messaging.jms.external.prefix.ExternalJMSDestinationDefinitionMessagingDeploymentTestCase.QUEUE_NAME; import static org.jboss.as.test.integration.messaging.jms.external.prefix.ExternalJMSDestinationDefinitionMessagingDeploymentTestCase.TOPIC_LOOKUP; import static org.jboss.as.test.integration.messaging.jms.external.prefix.ExternalJMSDestinationDefinitionMessagingDeploymentTestCase.QUEUE_LOOKUP; import static org.jboss.as.test.integration.messaging.jms.external.prefix.ExternalJMSDestinationDefinitionMessagingDeploymentTestCase.REMOTE_PCF; import static org.jboss.as.test.integration.messaging.jms.external.prefix.ExternalJMSDestinationDefinitionMessagingDeploymentTestCase.TOPIC_NAME; import java.io.IOException; import jakarta.annotation.Resource; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSConnectionFactory; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSDestinationDefinition; import jakarta.jms.JMSDestinationDefinitions; import jakarta.jms.JMSPasswordCredential; import jakarta.jms.Queue; import jakarta.jms.Topic; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.jboss.as.test.shared.TimeoutUtil; /** * * @author Emmanuel Hugonnet (c) 2020 Red Hat, Inc. */ @JMSDestinationDefinitions( value = { @JMSDestinationDefinition( resourceAdapter = REMOTE_PCF, name = QUEUE_LOOKUP, interfaceName = "jakarta.jms.Queue", destinationName = QUEUE_NAME, properties = {"enable-amq1-prefix=false"} ), @JMSDestinationDefinition( resourceAdapter = REMOTE_PCF, name = TOPIC_LOOKUP, interfaceName = "jakarta.jms.Topic", destinationName = TOPIC_NAME, properties = {"enable-amq1-prefix=false"} ) } ) @WebServlet("/ClientMessagingDeploymentTestCase") public class AnnotatedMessagingServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Resource(lookup = QUEUE_LOOKUP) private Queue queue; @Resource(lookup = TOPIC_LOOKUP) private Topic topic; @Inject @JMSConnectionFactory("java:/JmsXA") @JMSPasswordCredential(userName = "guest", password = "guest") private JMSContext context; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean useTopic = req.getParameterMap().containsKey("topic"); final Destination destination = useTopic ? topic : queue; final String text = req.getParameter("text"); String reply = sendAndReceiveMessage(destination, text); resp.getWriter().write(reply); } private String sendAndReceiveMessage(Destination destination, String text) { Destination replyTo = context.createTemporaryQueue(); try (JMSConsumer consumer = context.createConsumer(replyTo)) { context.createProducer().setJMSReplyTo(replyTo).send(destination, text); return consumer.receiveBody(String.class, TimeoutUtil.adjust(5000)); } } }
4,115
40.575758
147
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/deployment/DependentMessagingDeploymentTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, 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.jboss.as.test.integration.messaging.jms.deployment; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.jboss.shrinkwrap.api.ShrinkWrap.create; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.net.URL; import java.util.PropertyPermission; import java.util.UUID; import java.util.concurrent.TimeUnit; 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.ContainerResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.TimeoutUtil; 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 invoking a management operation that removes a JMS resource that is used by a deployed archive must fail: * the resource must not be removed and any depending services must be recovered. * The deployment must still be operating after the failing management operation. * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(DependentMessagingDeploymentTestCase.MessagingResourcesSetupTask.class) public class DependentMessagingDeploymentTestCase { public static final String QUEUE_LOOKUP = "java:/jms/DependentMessagingDeploymentTestCase/myQueue"; public static final String TOPIC_LOOKUP = "java:/jms/DependentMessagingDeploymentTestCase/myTopic"; private static final String QUEUE_NAME = "myQueue"; private static final String TOPIC_NAME = "myTopic"; @ContainerResource private ManagementClient managementClient; @ArquillianResource private URL url; static class MessagingResourcesSetupTask implements ServerSetupTask { @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); jmsOperations.createJmsQueue(QUEUE_NAME, QUEUE_LOOKUP); jmsOperations.createJmsTopic(TOPIC_NAME, TOPIC_LOOKUP); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); jmsOperations.removeJmsQueue(QUEUE_NAME); jmsOperations.removeJmsTopic(TOPIC_NAME); } } @Deployment public static WebArchive createArchive() { return create(WebArchive.class, "DependentMessagingDeploymentTestCase.war") .addClasses(MessagingServlet.class, TimeoutUtil.class) .addClasses(QueueMDB.class, TopicMDB.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read") ), "permissions.xml"); } @Test public void testRemoveDependingQueue() throws Exception { sendAndReceiveMessage(true); try { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); jmsOperations.removeJmsQueue(QUEUE_NAME); fail("removing a JMS resource that the deployment is depending upon must fail"); } catch(Exception e) { } sendAndReceiveMessage(true); } @Test public void testRemoveDependingTopic() throws Exception { sendAndReceiveMessage(false); try { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); jmsOperations.removeJmsTopic(TOPIC_NAME); fail("removing a JMS resource that the deployment is depending upon must fail"); } catch(Exception e) { } sendAndReceiveMessage(false); } private void sendAndReceiveMessage(boolean sendToQueue) throws Exception { String destination = sendToQueue ? "queue" : "topic"; String text = UUID.randomUUID().toString(); URL servletUrl = new URL(this.url.toExternalForm() + "DependentMessagingDeploymentTestCase?destination=" + destination + "&text=" + text); String reply = HttpRequest.get(servletUrl.toExternalForm(), 10, TimeUnit.SECONDS); assertNotNull(reply); assertEquals(text, reply); } }
6,137
42.225352
146
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/deployment/QueueMDB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.deployment; import static org.jboss.as.test.integration.messaging.jms.deployment.DependentMessagingDeploymentTestCase.QUEUE_LOOKUP; import jakarta.ejb.ActivationConfigProperty; import jakarta.ejb.MessageDriven; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSContext; import jakarta.jms.Message; import jakarta.jms.MessageListener; import jakarta.jms.TextMessage; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc. */ @MessageDriven( activationConfig = { @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = QUEUE_LOOKUP) } ) public class QueueMDB implements MessageListener { @Inject private JMSContext context; @Override public void onMessage(final Message m) { try { TextMessage message = (TextMessage) m; Destination replyTo = m.getJMSReplyTo(); context.createProducer() .setJMSCorrelationID(message.getJMSMessageID()) .send(replyTo, message.getText()); } catch (Exception e) { e.printStackTrace(); } } }
2,249
34.714286
119
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/deployment/TopicMDB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.deployment; import static org.jboss.as.test.integration.messaging.jms.deployment.DependentMessagingDeploymentTestCase.TOPIC_LOOKUP; import jakarta.ejb.ActivationConfigProperty; import jakarta.ejb.MessageDriven; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSContext; import jakarta.jms.Message; import jakarta.jms.MessageListener; import jakarta.jms.TextMessage; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc. */ @MessageDriven( activationConfig = { @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = TOPIC_LOOKUP) } ) public class TopicMDB implements MessageListener { @Inject private JMSContext context; @Override public void onMessage(final Message m) { try { TextMessage message = (TextMessage) m; Destination replyTo = m.getJMSReplyTo(); context.createProducer() .setJMSCorrelationID(message.getJMSMessageID()) .send(replyTo, message.getText()); } catch (Exception e) { e.printStackTrace(); } } }
2,249
34.714286
119
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/deployment/MessagingServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.deployment; import org.jboss.as.test.shared.TimeoutUtil; import static org.jboss.as.test.integration.messaging.jms.deployment.DependentMessagingDeploymentTestCase.QUEUE_LOOKUP; import static org.jboss.as.test.integration.messaging.jms.deployment.DependentMessagingDeploymentTestCase.TOPIC_LOOKUP; import java.io.IOException; import jakarta.annotation.Resource; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.Queue; import jakarta.jms.Topic; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc. */ @WebServlet("/DependentMessagingDeploymentTestCase") public class MessagingServlet extends HttpServlet { @Resource(lookup = QUEUE_LOOKUP) private Queue queue; @Resource(lookup = TOPIC_LOOKUP) private Topic topic; @Inject private JMSContext context; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean useTopic = req.getParameterMap().containsKey("topic"); final Destination destination = useTopic ? topic : queue; final String text = req.getParameter("text"); String reply = sendAndReceiveMessage(destination, text); resp.getWriter().write(reply); } private String sendAndReceiveMessage(Destination destination, String text) { Destination replyTo = context.createTemporaryQueue(); JMSConsumer consumer = context.createConsumer(replyTo); context.createProducer() .setJMSReplyTo(replyTo) .send(destination, text); return consumer.receiveBody(String.class, TimeoutUtil.adjust(5000)); } }
3,075
35.619048
119
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/naming/JMSSender.java
/* * Copyright 2018 JBoss by Red Hat. * * 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.jboss.as.test.integration.messaging.jms.naming; import static jakarta.ejb.TransactionAttributeType.NOT_SUPPORTED; import jakarta.annotation.Resource; import jakarta.ejb.Singleton; import jakarta.ejb.TransactionAttribute; import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSConnectionFactoryDefinition; import jakarta.jms.JMSConnectionFactoryDefinitions; import jakarta.jms.JMSContext; import jakarta.jms.JMSDestinationDefinition; import jakarta.jms.JMSProducer; import jakarta.jms.Queue; @JMSDestinationDefinition( name = "java:app/jms/queue", interfaceName = "jakarta.jms.Queue" ) @JMSConnectionFactoryDefinitions( value = { @JMSConnectionFactoryDefinition( name = "java:app/jms/nonXAconnectionFactory", transactional = false, properties = { "connectors=${org.jboss.messaging.default-connector:in-vm}",} ) } ) @Singleton public class JMSSender { @Resource(lookup = "java:app/jms/nonXAconnectionFactory") private ConnectionFactory connectionFactory; @Resource(lookup = "java:app/jms/queue") private Queue queue; @TransactionAttribute(NOT_SUPPORTED) public void sendMessage(String payload) { try (JMSContext context = connectionFactory.createContext()) { JMSProducer producer = context.createProducer(); producer.send(queue, payload); } } }
2,020
31.596774
77
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/naming/JndiLookupMessagingDeploymentTestCase.java
/* * Copyright 2018 JBoss by Red Hat. * * 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.jboss.as.test.integration.messaging.jms.naming; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.jboss.shrinkwrap.api.ShrinkWrap.create; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.net.URL; import java.util.PropertyPermission; import java.util.UUID; import java.util.concurrent.TimeUnit; 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.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.dmr.ModelNode; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Simple test to cover https://issues.jboss.org/browse/WFLY-9305 * @author Emmanuel Hugonnet (c) 2019 Red Hat, Inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(JndiLookupMessagingDeploymentTestCase.SetupTask.class) public class JndiLookupMessagingDeploymentTestCase { @ArquillianResource private URL url; @Deployment public static WebArchive createArchive() { return create(WebArchive.class, "JndiMessagingDeploymentTestCase.war") .addClasses(MessagingServlet.class, TimeoutUtil.class) .addClasses(JMSSender.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read")), "permissions.xml"); } @Test public void testSendMessageInClientQueue() throws Exception { sendAndReceiveMessage(true); } private void sendAndReceiveMessage(boolean sendToQueue) throws Exception { String text = "test_" + UUID.randomUUID().toString(); URL url = new URL(this.url.toExternalForm() + "JndiMessagingDeploymentTestCase?text=" + text); String reply = HttpRequest.get(url.toExternalForm(), 10, TimeUnit.SECONDS); assertNotNull(reply); assertEquals(text, reply); } static class SetupTask implements ServerSetupTask{ @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { managementClient.getControllerClient().execute(Operations.createWriteAttributeOperation(new ModelNode().add("subsystem", "ee"), "annotation-property-replacement", true)); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); managementClient.getControllerClient().execute(Operations.createWriteAttributeOperation(new ModelNode().add("subsystem", "ee"), "annotation-property-replacement", ops.isRemoteBroker())); } } }
4,077
40.612245
198
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/naming/MessagingServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.naming; import org.jboss.as.test.shared.TimeoutUtil; import java.io.IOException; import jakarta.annotation.Resource; import jakarta.inject.Inject; import jakarta.jms.JMSConnectionFactory; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.Queue; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Emmanuel Hugonnet (c) 2018 Red Hat, inc. */ @WebServlet("/JndiMessagingDeploymentTestCase") public class MessagingServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Inject private JMSSender jmsSender; @Inject @JMSConnectionFactory("java:app/jms/nonXAconnectionFactory") private JMSContext context; @Resource(lookup = "java:app/jms/queue") private Queue queue; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final String text = req.getParameter("text"); String reply = sendAndReceiveMessage(text); resp.getWriter().write(reply); } private String sendAndReceiveMessage(String text) { JMSConsumer consumer = context.createConsumer(queue); jmsSender.sendMessage(text); return consumer.receiveBody(String.class, TimeoutUtil.adjust(5000)); } }
2,544
34.347222
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/InjectedJMSContextTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.jboss.as.test.shared.TimeoutUtil.adjust; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.hamcrest.MatcherAssert.assertThat; import java.util.PropertyPermission; import java.util.UUID; import jakarta.annotation.Resource; import jakarta.ejb.EJB; import jakarta.jms.ConnectionFactory; import jakarta.jms.Destination; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSException; import jakarta.jms.Message; import jakarta.jms.Queue; import jakarta.jms.TemporaryQueue; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.integration.messaging.jms.context.auxiliary.TransactedMDB; import org.jboss.as.test.integration.messaging.jms.context.auxiliary.TransactedMessageProducer; 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.JavaArchive; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc. */ @RunWith(Arquillian.class) public class InjectedJMSContextTestCase { public static final String QUEUE_NAME = "java:/InjectedJMSContextTestCaseQueue"; @Resource(mappedName = "/JmsXA") private ConnectionFactory factory; @Resource(lookup = QUEUE_NAME) private Queue queue; @EJB private TransactedMessageProducer producerBean; @Deployment public static JavaArchive createTestArchive() { return ShrinkWrap.create(JavaArchive.class, "InjectedJMSContextTestCase.jar") .addClass(TimeoutUtil.class) .addPackage(TransactedMDB.class.getPackage()) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addAsResource(createPermissionsXmlAsset(new PropertyPermission("ts.timeout.factor", "read")), "META-INF/jboss-permissions.xml"); } @After public void tearDown() throws JMSException { // drain the queue to remove any pending messages from it try(JMSContext context = factory.createContext()) { JMSConsumer consumer = context.createConsumer(queue); Message m; do { m = consumer.receiveNoWait(); } while (m != null); } } @Test public void sendAndReceiveWithContext() throws JMSException { String text = UUID.randomUUID().toString(); try (JMSContext context = factory.createContext()) { TemporaryQueue tempQueue = context.createTemporaryQueue(); context.createProducer() .send(tempQueue, text); assertMessageIsReceived(tempQueue, context, text, false); } } @Test public void testSendWith_REQUIRED_transaction() throws JMSException { sendWith_REQUIRED_transaction(false); } @Test public void testSendWith_REQUIRED_transactionAndRollback() throws JMSException { sendWith_REQUIRED_transaction(true); } private void sendWith_REQUIRED_transaction(boolean rollback) throws JMSException { String text = UUID.randomUUID().toString(); try (JMSContext context = factory.createContext()) { TemporaryQueue tempQueue = context.createTemporaryQueue(); producerBean.sendToDestination(tempQueue, text, rollback); assertMessageIsReceived(tempQueue, context, text, rollback); } } @Test public void testSendAndReceiveFromMDB() throws JMSException { sendAndReceiveFromMDB(false); } @Test public void testSendAndReceiveFromMDBWithRollback() throws JMSException { sendAndReceiveFromMDB(true); } private void sendAndReceiveFromMDB(boolean rollback) throws JMSException { String text = "sendAndReceiveFromMDB " + rollback; try (JMSContext context = factory.createContext()) { TemporaryQueue replyTo = context.createTemporaryQueue(); context.createProducer() .setJMSReplyTo(replyTo) .setProperty("rollback", rollback) .send(queue, text); assertMessageIsReceived(replyTo, context, text, rollback); } } private void assertMessageIsReceived(Destination destination, JMSContext ctx, String expectedText, boolean rollback) { try (JMSConsumer consumer = ctx.createConsumer(destination)) { String t = consumer.receiveBody(String.class, adjust(2000)); if (rollback) { assertThat("from " + destination, t, is(nullValue())); } else { assertThat("from " + destination, t, is(expectedText)); } } } }
6,094
34.852941
145
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/ScopedInjectedJMSContextTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context; import static jakarta.jms.DeliveryMode.NON_PERSISTENT; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.PropertyPermission; import java.util.UUID; import jakarta.annotation.Resource; import jakarta.ejb.EJB; import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.Queue; import jakarta.jms.TemporaryQueue; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.integration.messaging.jms.context.auxiliary.BeanManagedMessageConsumer; import org.jboss.as.test.integration.messaging.jms.context.auxiliary.RequestScopedMDB; 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.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc. */ @RunWith(Arquillian.class) public class ScopedInjectedJMSContextTestCase { public static final String QUEUE_NAME_FOR_REQUEST_SCOPE = "java:global/env/ScopedInjectedJMSContextTestCaseQueue-requestScoped"; public static final String QUEUE_NAME_FOR_TRANSACTION_SCOPE = "java:global/env/ScopedInjectedJMSContextTestCaseQueue-transactionScoped"; @Resource(mappedName = QUEUE_NAME_FOR_REQUEST_SCOPE) private Queue queueForRequestScope; @Resource(mappedName = QUEUE_NAME_FOR_TRANSACTION_SCOPE) private Queue queueForTransactionScope; @Resource(mappedName = "/JmsXA") private ConnectionFactory factory; @EJB private BeanManagedMessageConsumer transactedConsumer; @Deployment public static JavaArchive createTestArchive() { return ShrinkWrap.create(JavaArchive.class, "ScopedInjectedJMSContextTestCase.jar") .addClass(BeanManagedMessageConsumer.class) .addClass(RequestScopedMDB.class) .addClass(TimeoutUtil.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read")), "permissions.xml"); } /** * Test that a transaction-scoped JMSContext is properly cleaned up after the transaction completion. */ @Test public void transactionScoped() throws Exception { String text = UUID.randomUUID().toString(); try (JMSContext context = factory.createContext()) { context.createProducer() .setDeliveryMode(NON_PERSISTENT) .send(queueForTransactionScope, text); assertTrue(transactedConsumer.receive(queueForTransactionScope, text)); } } /** * Test that a request-scoped JMSContext is properly cleaned up after the transaction completion. */ @Test public void requestScoped() throws Exception { String text = UUID.randomUUID().toString(); try (JMSContext context = factory.createContext()) { TemporaryQueue tempQueue = context.createTemporaryQueue(); // send a request/reply message to ensure that the MDB as received the message // and set its consumer field context.createProducer() .setJMSReplyTo(tempQueue) .setDeliveryMode(NON_PERSISTENT) .send(queueForRequestScope, text); JMSConsumer consumer = context.createConsumer(tempQueue); String reply = consumer.receiveBody(String.class, TimeoutUtil.adjust(5000)); assertNotNull(reply); JMSConsumer consumerInMDB = RequestScopedMDB.consumer; assertNotNull(consumerInMDB); try { consumerInMDB.receiveBody(String.class); fail("the EJB must throw an exception as its injected JMSContext must be closed after the MDB handled the message"); } catch (Exception e) { } } } }
5,367
39.360902
140
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/VaultedInjectedJMSContextTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; 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.VALUE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import static org.jboss.as.test.shared.TimeoutUtil.adjust; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.junit.Assert.assertEquals; import static org.wildfly.test.security.common.SecureExpressionUtil.getDeploymentPropertiesAsset; import static org.wildfly.test.security.common.SecureExpressionUtil.setupCredentialStore; import static org.wildfly.test.security.common.SecureExpressionUtil.setupCredentialStoreExpressions; import static org.wildfly.test.security.common.SecureExpressionUtil.teardownCredentialStore; import java.io.IOException; import java.net.SocketPermission; import java.util.PropertyPermission; import java.util.UUID; import jakarta.annotation.Resource; import jakarta.ejb.EJB; import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSException; import jakarta.jms.TemporaryQueue; 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.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.test.integration.messaging.jms.context.auxiliary.VaultedMessageProducer; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.security.common.SecureExpressionUtil; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc. */ @RunWith(Arquillian.class) @ServerSetup(VaultedInjectedJMSContextTestCase.StoreVaultedPropertyTask.class) public class VaultedInjectedJMSContextTestCase { static final String UNIQUE_NAME = "VaultedInjectedJMSContextTestCase"; private static final SecureExpressionUtil.SecureExpressionData USERNAME = new SecureExpressionUtil.SecureExpressionData("guest", "test.userName"); private static final SecureExpressionUtil.SecureExpressionData PASSWORD = new SecureExpressionUtil.SecureExpressionData("guest", "test.password"); static final String STORE_LOCATION = VaultedInjectedJMSContextTestCase.class.getResource("/").getPath() + "security/" + UNIQUE_NAME + ".cs"; static class StoreVaultedPropertyTask implements ServerSetupTask { @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { setupCredentialStore(managementClient, UNIQUE_NAME, STORE_LOCATION); updateAnnotationPropertyReplacement(managementClient, true); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { teardownCredentialStore(managementClient, UNIQUE_NAME, STORE_LOCATION); updateAnnotationPropertyReplacement(managementClient, false); } private void updateAnnotationPropertyReplacement(ManagementClient managementClient, boolean value) throws IOException { ModelNode op; op = new ModelNode(); op.get(OP_ADDR).add("subsystem", "ee"); op.get(OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(NAME).set("annotation-property-replacement"); op.get(VALUE).set(value); managementClient.getControllerClient().execute(new OperationBuilder(op).build()); } } @Resource(mappedName = "/JmsXA") private ConnectionFactory factory; @EJB private VaultedMessageProducer producerBean; @Deployment public static JavaArchive createTestArchive() throws Exception { // Create the credential expressions so we can store them in the deployment setupCredentialStoreExpressions(UNIQUE_NAME, USERNAME, PASSWORD); return ShrinkWrap.create(JavaArchive.class, "VaultedInjectedJMSContextTestCase.jar") .addClass(TimeoutUtil.class) .addClasses(SecureExpressionUtil.getDeploymentClasses()) .addPackage(VaultedMessageProducer.class.getPackage()) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addAsResource(createPermissionsXmlAsset( new PropertyPermission("ts.timeout.factor", "read"), // required because the VaultedMessageProducer uses the RemoteConnectionFactory // (that requires auth with vaulted credentials) new SocketPermission("*", "connect"), new RuntimePermission("setContextClassLoader")), "META-INF/jboss-permissions.xml") .addAsManifestResource(getDeploymentPropertiesAsset(USERNAME, PASSWORD), "jboss.properties"); } @Test public void sendMessage() throws JMSException { String text = UUID.randomUUID().toString(); try (JMSContext context = factory.createContext()) { TemporaryQueue tempQueue = context.createTemporaryQueue(); producerBean.sendToDestination(tempQueue, text); JMSConsumer consumer = context.createConsumer(tempQueue); String reply = consumer.receiveBody(String.class, adjust(2000)); assertEquals(text, reply); } } }
6,993
46.90411
150
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/transactionscoped/TransactionScopedJMSContextTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context.transactionscoped; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.junit.Assert.assertEquals; import jakarta.annotation.Resource; import jakarta.ejb.EJB; import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSException; import jakarta.jms.Message; import jakarta.jms.Queue; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.integration.messaging.jms.context.transactionscoped.auxiliary.AppScopedBean; import org.jboss.as.test.integration.messaging.jms.context.transactionscoped.auxiliary.ThreadLauncher; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.security.permission.ElytronPermission; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc. */ @RunWith(Arquillian.class) public class TransactionScopedJMSContextTestCase { public static final String QUEUE_NAME = "java:app/TransactionScopedJMSContextTestCase"; @Resource(mappedName = "/JmsXA") private ConnectionFactory factory; @Resource(mappedName = QUEUE_NAME) private Queue queue; @EJB ThreadLauncher launcher; @Deployment public static JavaArchive createTestArchive() { return ShrinkWrap.create(JavaArchive.class, "TransactionScopedJMSContextTestCase.jar") .addPackage(AppScopedBean.class.getPackage()) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource(createPermissionsXmlAsset( new ElytronPermission("getSecurityDomain") ), "permissions.xml"); } @Test public void sendAndReceiveWithContext() throws JMSException, InterruptedException { int numThreads = 5; int numMessages = 10; launcher.start(numThreads, numMessages); int receivedMessages = 0; try(JMSContext context = factory.createContext()) { JMSConsumer consumer = context.createConsumer(queue); Message m; do { m = consumer.receive(1000); if (m != null) { receivedMessages++; } } while (m != null); } assertEquals(numThreads * numMessages, receivedMessages); } }
3,695
36.714286
106
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/transactionscoped/auxiliary/ThreadLauncher.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context.transactionscoped.auxiliary; import static org.jboss.as.test.integration.messaging.jms.context.transactionscoped.TransactionScopedJMSContextTestCase.QUEUE_NAME; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import jakarta.annotation.Resource; import jakarta.ejb.Stateful; import jakarta.enterprise.concurrent.ManagedThreadFactory; import jakarta.inject.Inject; import jakarta.jms.JMSDestinationDefinition; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc. */ @JMSDestinationDefinition( name = QUEUE_NAME, interfaceName = "jakarta.jms.Queue", destinationName = "InjectedJMSContextTestCaseQueue" ) @Stateful(passivationCapable = false) public class ThreadLauncher { @Resource private ManagedThreadFactory threadFactory; @Inject private AppScopedBean bean; public void start(int numThreads, int numMessages) throws InterruptedException { CountDownLatch latch = new CountDownLatch(numThreads); //System.out.println("starting threads"); for (int i = 0; i < numThreads; i++) { threadFactory.newThread(new SendRunnable(latch, numMessages)).start(); } //System.out.println("start finished"); latch.await(30, TimeUnit.SECONDS); //System.out.println("DONE"); } private class SendRunnable implements Runnable { private final CountDownLatch latch; private final int numMessages; SendRunnable(CountDownLatch latch, int numMessages) { this.latch = latch; this.numMessages = numMessages; } public void run() { //System.out.println("starting to send"); for (int i = 0; i < numMessages; i++) { bean.sendMessage(); } //System.out.println("done sending"); latch.countDown(); } } }
3,003
33.136364
131
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/transactionscoped/auxiliary/AppScopedBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context.transactionscoped.auxiliary; import static org.jboss.as.test.integration.messaging.jms.context.transactionscoped.TransactionScopedJMSContextTestCase.QUEUE_NAME; import jakarta.annotation.Resource; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.jms.JMSContext; import jakarta.jms.JMSProducer; import jakarta.jms.Queue; import jakarta.transaction.Transactional; @ApplicationScoped @Transactional public class AppScopedBean { @Inject private JMSContext context; @Resource(lookup = QUEUE_NAME) private Queue queue; public void sendMessage() { JMSProducer producer = context.createProducer(); producer.send(queue, "a message"); } }
1,811
33.188679
131
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/notclosinginjectedcontext/NotClosingInjectedContextTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context.notclosinginjectedcontext; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.messaging.jms.context.notclosinginjectedcontext.auxiliary.Mdb; import org.jboss.as.test.integration.messaging.jms.context.notclosinginjectedcontext.auxiliary.StartUp; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.annotation.Resource; import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSException; import jakarta.jms.Message; import jakarta.jms.Queue; import java.io.IOException; import java.util.List; import java.util.PropertyPermission; 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.SUBSYSTEM; import static org.jboss.as.test.shared.TimeoutUtil.adjust; import java.io.File; import java.io.FilePermission; import java.net.SocketPermission; import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils; import org.jboss.remoting3.security.RemotingPermission; /** * Test for issue https://issues.jboss.org/browse/WFLY-10531 (based on reproducer created by Gunter Zeilinger <[email protected]>. * * 500 messages should be send to mdb and each of them should be received in verify queue. * If error is still valid, there will be exceptions like: IJ000453: Unable to get managed connection for java:/JmsXA * * @author Jiri Ondrusek <[email protected]> */ @RunWith(Arquillian.class) @ServerSetup(NotClosingInjectedContextTestCase.NotClosingInjectedContextServerSetupTask.class) public class NotClosingInjectedContextTestCase { private static final Logger LOGGER = Logger.getLogger(NotClosingInjectedContextTestCase.class); private static final PathAddress LOG_FILE_ADDRESS = PathAddress.pathAddress() .append(SUBSYSTEM, "logging"); @Resource(mappedName = "java:/JmsXA") private ConnectionFactory factory; @Resource(mappedName = Mdb.JNDI_NAME) private Queue queue; @Resource(mappedName = Mdb.JNDI_VERIFY_NAME) private Queue queueVerify; @ArquillianResource private ManagementClient managementClient; @Deployment public static WebArchive createTestArchive() { WebArchive archive = ShrinkWrap.create(WebArchive.class, "NotClosingInjectedContextTestCase.war") .addPackage(StartUp.class.getPackage()) .addClass(TimeoutUtil.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( new FilePermission(System.getProperty("jboss.inst") + File.separatorChar + "standalone" + File.separatorChar + "tmp" + File.separatorChar + "auth" + File.separatorChar + "*", "read"), RemotingPermission.CREATE_ENDPOINT, RemotingPermission.CONNECT, new SocketPermission("localhost", "resolve"), new PropertyPermission("ts.timeout.factor", "read")), "jboss-permissions.xml") .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addClass(TimeoutUtil.class) .addAsManifestResource(new StringAsset("Dependencies: org.jboss.as.controller,org.jboss.remoting\n"), "MANIFEST.MF"); return archive; } @After public void tearDown() throws JMSException { // drain the queue to remove any pending messages from it try (JMSContext context = factory.createContext()) { JMSConsumer consumer = context.createConsumer(queue); Message m; do { m = consumer.receiveNoWait(); } while (m != null); consumer = context.createConsumer(queueVerify); do { m = consumer.receiveNoWait(); } while (m != null); } } @Test public void testLeakingConnection() throws Exception{ //length of log before execution String sizeBefore = getLogLineCount(managementClient.getControllerClient()); try (JMSContext context = factory.createContext(); JMSConsumer consumer = context.createConsumer(queueVerify)) { int j = 0; while (true) { String t = consumer.receiveBody(String.class, adjust(2000)); if (t == null) { LOGGER.info("Received null message"); break; } else { LOGGER.info("Received message:" + (++j)); } } Assert.assertEquals("There should be 2 received messages.", 2, j); //size of log after execution String sizeAfter = getLogLineCount(managementClient.getControllerClient()); long difference = Long.parseLong(sizeAfter) - Long.parseLong(sizeBefore); //validate, that there is no "IJ000100: Closing a connection for you. Please close them yourself" List<ModelNode> lines = getLogs(managementClient.getControllerClient(), difference); for (ModelNode line : lines) { if (line.asString().contains("IJ000100:")) { Assert.fail("JMS context is not closed"); } } } } private String getLogLineCount(final ModelControllerClient client) { ModelNode op = Util.createEmptyOperation("list-log-files", LOG_FILE_ADDRESS); ModelNode res = executeForResult(client, op); for (ModelNode node : res.asList()) { if ("server.log".equals(node.get("file-name").asString())) { return node.get("file-size").asString(); } } return "0"; } private List<ModelNode> getLogs(final ModelControllerClient client, long count) { // /subsystem=logging/log-file=server.log:read-log-file(lines=-1) ModelNode op = Util.createEmptyOperation("read-log-file", LOG_FILE_ADDRESS); op.get("lines").set(count); op.get("name").set("server.log"); return executeForResult(client, op).asList(); } private ModelNode executeForResult(final ModelControllerClient client, final ModelNode operation) { try { final ModelNode result = client.execute(operation); checkSuccessful(result); return result.get(ClientConstants.RESULT); } catch (IOException e) { throw new RuntimeException(e); } } private void checkSuccessful(final ModelNode result) { if (!ClientConstants.SUCCESS.equals(result.get(ClientConstants.OUTCOME).asString())) { throw new RuntimeException("operation has failed: " + result.get(ClientConstants.FAILURE_DESCRIPTION).toString()); } } /** * Enable debug for ccm */ static class NotClosingInjectedContextServerSetupTask extends SnapshotRestoreSetupTask { @Override protected void doSetup(ManagementClient client, String containerId) throws Exception { ModelNode address = new ModelNode(); address.add("subsystem", "jca"); address.add("cached-connection-manager", "cached-connection-manager"); ModelNode operation = new ModelNode(); operation.get(OP_ADDR).set(address); operation.get(OP).set("write-attribute"); operation.get("name").set("debug"); operation.get("value").set("true"); client.getControllerClient().execute(operation); ServerReload.executeReloadAndWaitForCompletion(client, TimeoutUtil.adjust(50000)); } } }
9,720
41.265217
207
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/notclosinginjectedcontext/auxiliary/StartUp.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context.notclosinginjectedcontext.auxiliary; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; import jakarta.inject.Inject; import java.util.concurrent.ScheduledFuture; /** * Start of ejb send message after creation of this bean. * * @author Gunter Zeilinger <[email protected]>, Jiri Ondrusek <[email protected]> * @since Sep 2018 */ @Singleton @Startup public class StartUp { private volatile ScheduledFuture<?> running; @Inject private Ejb ejb; @PostConstruct public void init() { ejb.send("msg"); } @PreDestroy public void destroy() { if (running != null) { running.cancel(true); } } }
1,841
29.7
96
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/notclosinginjectedcontext/auxiliary/Ejb.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context.notclosinginjectedcontext.auxiliary; import org.jboss.logging.Logger; import jakarta.ejb.Stateless; import jakarta.inject.Inject; import jakarta.jms.JMSContext; import jakarta.jms.Queue; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.as.test.shared.TimeoutUtil; /** * Ejb sends messages via two injected jmsContexts. * * @author Gunter Zeilinger <[email protected]>, Jiri Ondrusek <[email protected]> * @since Sep 2018 */ @Stateless public class Ejb { private static final Logger LOGGER = Logger.getLogger(Ejb.class); private static final long TIMEOUT = TimeoutUtil.adjust(60000); private static final long PAUSE = TimeoutUtil.adjust(200); @Inject private JMSContext jmsCtx1; @Inject private JMSContext jmsCtx2; public void send(String text) { send(text, jmsCtx1); send(text, jmsCtx2); } private void send(String text, JMSContext jmsContext) { try { LOGGER.info("Sending: " + text); long start = System.currentTimeMillis(); Queue queue = lookup(Mdb.JNDI_NAME); while(queue == null && (System.currentTimeMillis() - start < TIMEOUT)) { queue = lookup(Mdb.JNDI_NAME); Thread.sleep(PAUSE); } jmsContext.createProducer().send(queue, text); LOGGER.info("Sent:" + text); } catch (RuntimeException e) { LOGGER.error("FAILED to send:" + text); throw e; } catch (InterruptedException ex) { LOGGER.error("FAILED to send:" + text); throw new RuntimeException(ex); } } private Queue lookup(String jndiName) { try { return InitialContext.doLookup(jndiName); } catch (NamingException e) { throw new RuntimeException(e); } } }
2,966
33.5
96
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/notclosinginjectedcontext/auxiliary/Mdb.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context.notclosinginjectedcontext.auxiliary; import org.jboss.logging.Logger; import jakarta.annotation.Resource; import jakarta.ejb.ActivationConfigProperty; import jakarta.ejb.MessageDriven; import jakarta.inject.Inject; import jakarta.jms.JMSContext; import jakarta.jms.JMSDestinationDefinition; import jakarta.jms.JMSDestinationDefinitions; import jakarta.jms.Message; import jakarta.jms.MessageListener; import jakarta.jms.Queue; import jakarta.jms.TextMessage; /** * Message driven bean receives message from wfly10531_in queue and sends them into wfly10531_verify queue. * * @author Gunter Zeilinger <[email protected]>, Jiri Ondrusek <[email protected]> * @since Sep 2018 */ @JMSDestinationDefinitions( value= { @JMSDestinationDefinition( name = Mdb.JNDI_NAME, interfaceName = "jakarta.jms.Queue", destinationName = "wfly10531_in" ), @JMSDestinationDefinition( name = Mdb.JNDI_VERIFY_NAME, interfaceName = "jakarta.jms.Queue", destinationName = "wfly10531_verify" ) } ) @MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = Mdb.JNDI_NAME), @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "jakarta.jms.Queue")}) public class Mdb implements MessageListener { private static final Logger LOGGER = Logger.getLogger(Mdb.class); public static final String JNDI_NAME = "java:app/queue/wfly10531_in"; public static final String JNDI_VERIFY_NAME = "java:app/queue/wfly10531_verify"; @Inject private JMSContext context; @Resource(mappedName = JNDI_VERIFY_NAME) private Queue queue; public void onMessage(Message message) { try { String text = ((TextMessage) message).getText(); LOGGER.info("Received " + text); context.createProducer() .send(queue, text); } catch (Throwable e) { LOGGER.error("Failed to receive or send message", e); } } }
3,289
35.966292
107
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/auxiliary/TransactedMDB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context.auxiliary; import static jakarta.ejb.TransactionAttributeType.REQUIRED; import static jakarta.ejb.TransactionManagementType.CONTAINER; import static org.jboss.as.test.integration.messaging.jms.context.InjectedJMSContextTestCase.QUEUE_NAME; import jakarta.annotation.Resource; import jakarta.ejb.ActivationConfigProperty; import jakarta.ejb.MessageDriven; import jakarta.ejb.MessageDrivenContext; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionManagement; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSContext; import jakarta.jms.JMSDestinationDefinition; import jakarta.jms.Message; import jakarta.jms.MessageListener; import jakarta.jms.TextMessage; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc. */ @JMSDestinationDefinition( name = QUEUE_NAME, interfaceName = "jakarta.jms.Queue", destinationName = "InjectedJMSContextTestCaseQueue" ) @MessageDriven( name = "TransactedMDB", activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "jakarta.jms.Queue"), @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = QUEUE_NAME) } ) @TransactionManagement(value = CONTAINER) @TransactionAttribute(value = REQUIRED) public class TransactedMDB implements MessageListener { @Inject private JMSContext context; @Resource private MessageDrivenContext mdbContext; public void onMessage(final Message m) { try { // ignore redelivered message if (m.getJMSRedelivered()) { return; } TextMessage message = (TextMessage) m; Destination replyTo = m.getJMSReplyTo(); context.createProducer() .setJMSCorrelationID(message.getJMSMessageID()) .send(replyTo, message.getText()); if (m.getBooleanProperty("rollback")) { mdbContext.setRollbackOnly(); } } catch (Exception e) { e.printStackTrace(); } } }
3,242
35.438202
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/auxiliary/TransactedMessageProducer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context.auxiliary; import static jakarta.ejb.TransactionAttributeType.REQUIRED; import jakarta.annotation.Resource; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionAttribute; import jakarta.enterprise.context.RequestScoped; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSContext; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc. */ @Stateful(passivationCapable = false) @RequestScoped public class TransactedMessageProducer { @Inject private JMSContext context; @Resource private SessionContext sessionContext; @TransactionAttribute(value = REQUIRED) public void sendToDestination(Destination destination, String text, boolean rollback) { context.createProducer() .send(destination, text); if (rollback) { sessionContext.setRollbackOnly(); } } }
2,025
34.54386
91
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/auxiliary/BeanManagedMessageConsumer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context.auxiliary; import static jakarta.ejb.TransactionManagementType.BEAN; import static org.jboss.as.test.integration.messaging.jms.context.ScopedInjectedJMSContextTestCase.QUEUE_NAME_FOR_REQUEST_SCOPE; import static org.jboss.as.test.integration.messaging.jms.context.ScopedInjectedJMSContextTestCase.QUEUE_NAME_FOR_TRANSACTION_SCOPE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import jakarta.annotation.Resource; import jakarta.ejb.Stateless; import jakarta.ejb.TransactionManagement; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSDestinationDefinition; import jakarta.jms.JMSDestinationDefinitions; import jakarta.jms.JMSRuntimeException; import jakarta.transaction.UserTransaction; import org.jboss.as.test.shared.TimeoutUtil; import org.junit.Assert; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc. */ @JMSDestinationDefinitions( value = { @JMSDestinationDefinition( name = QUEUE_NAME_FOR_TRANSACTION_SCOPE, interfaceName = "jakarta.jms.Queue", destinationName = "ScopedInjectedJMSContextTestCaseQueue-transactionScope"), @JMSDestinationDefinition( name = QUEUE_NAME_FOR_REQUEST_SCOPE, interfaceName = "jakarta.jms.Queue", destinationName = "ScopedInjectedJMSContextTestCaseQueue-requestScope") } ) @TransactionManagement(BEAN) @Stateless public class BeanManagedMessageConsumer { @Inject private JMSContext context; @Resource UserTransaction transaction; public boolean receive(Destination destination, String expectedText) throws Exception { transaction.begin(); JMSConsumer consumer = context.createConsumer(destination); String text = consumer.receiveBody(String.class, TimeoutUtil.adjust(1000)); assertNotNull(text); assertEquals(expectedText, text); transaction.commit(); try { consumer.receiveBody(String.class, TimeoutUtil.adjust(1000)); Assert.fail("call must fail as the injected JMSContext is closed when the transaction is committed"); } catch (JMSRuntimeException e) { // exception is expected } catch (Exception e) { throw e; } return true; } }
3,593
37.234043
132
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/auxiliary/RequestScopedMDB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context.auxiliary; import static jakarta.ejb.TransactionManagementType.BEAN; import static org.jboss.as.test.integration.messaging.jms.context.ScopedInjectedJMSContextTestCase.QUEUE_NAME_FOR_REQUEST_SCOPE; import jakarta.ejb.ActivationConfigProperty; import jakarta.ejb.MessageDriven; import jakarta.ejb.TransactionManagement; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSException; import jakarta.jms.Message; import jakarta.jms.MessageListener; import jakarta.jms.TextMessage; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc. */ @MessageDriven( name = "RequestScopedMDB", activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "jakarta.jms.Queue"), @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = QUEUE_NAME_FOR_REQUEST_SCOPE) } ) @TransactionManagement(BEAN) public class RequestScopedMDB implements MessageListener { @Inject private JMSContext context; public static JMSConsumer consumer; public void onMessage(final Message m) { Destination tempQueue = context.createTemporaryQueue(); consumer = context.createConsumer(tempQueue); TextMessage textMessage = (TextMessage) m; try { context.createProducer() .setDeliveryDelay(500) .send(m.getJMSReplyTo(), textMessage.getText()); } catch (JMSException e) { throw new RuntimeException(e); } } }
2,726
36.875
128
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/jms/context/auxiliary/VaultedMessageProducer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jboss.as.test.integration.messaging.jms.context.auxiliary; import jakarta.ejb.Stateless; import jakarta.inject.Inject; import jakarta.jms.Destination; import jakarta.jms.JMSConnectionFactory; import jakarta.jms.JMSContext; import jakarta.jms.JMSPasswordCredential; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc. * <p> * Use the RemoteConnectionFactory Connection Factory that requires authentication. */ @Stateless public class VaultedMessageProducer { @Inject @JMSConnectionFactory("java:jboss/exported/jms/RemoteConnectionFactory") @JMSPasswordCredential(userName = "${test.userName}", password = "${test.password}") private JMSContext context; public void sendToDestination(Destination destination, String text) { context.createProducer() .send(destination, text); } }
1,915
37.32
91
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/xmldeployment/DeployedXmlJMSManagementTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, 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.jboss.as.test.integration.messaging.xmldeployment; import java.io.IOException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; 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.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.standalone.DeploymentPlan; import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentActionResult; import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentManager; import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentPlanResult; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.integration.management.base.AbstractMgmtServerSetupTask; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; 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.RESULT; /** * Test deployment of -ds.xml files * * @author Stuart Douglas */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(DeployedXmlJMSManagementTestCase.DeployedXmlJMSManagementTestCaseSetup.class) public class DeployedXmlJMSManagementTestCase { private static final String TEST_HORNETQ_JMS_XML = "test-hornetq-jms.xml"; private static final String TEST_ACTIVEMQ_JMS_XML = "test-activemq-jms.xml"; static class DeployedXmlJMSManagementTestCaseSetup extends AbstractMgmtServerSetupTask { @Override protected void doSetup(final ManagementClient managementClient) throws Exception { final ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(managementClient.getControllerClient()); final String packageName = DeployedXmlJMSManagementTestCase.class.getPackage().getName().replace(".", "/"); JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient); String xmlFile = (jmsOperations.getProviderName().equals("hornetq")) ? TEST_HORNETQ_JMS_XML : TEST_ACTIVEMQ_JMS_XML; final DeploymentPlan plan = manager.newDeploymentPlan().add(DeployedXmlJMSManagementTestCase.class.getResource("/" + packageName + "/" + xmlFile)).andDeploy().build(); final Future<ServerDeploymentPlanResult> future = manager.execute(plan); final ServerDeploymentPlanResult result = future.get(20, TimeUnit.SECONDS); final ServerDeploymentActionResult actionResult = result.getDeploymentActionResult(plan.getId()); if (actionResult != null) { if (actionResult.getDeploymentException() != null) { throw new RuntimeException(actionResult.getDeploymentException()); } } } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient); String xmlFile = (jmsOperations.getProviderName().equals("hornetq")) ? TEST_HORNETQ_JMS_XML : TEST_ACTIVEMQ_JMS_XML; final ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(managementClient.getControllerClient()); final DeploymentPlan undeployPlan = manager.newDeploymentPlan().undeploy(xmlFile).andRemoveUndeployed().build(); manager.execute(undeployPlan).get(); } } @ContainerResource private ManagementClient managementClient; private JMSOperations jmsOperations; @Before public void setUp() { jmsOperations = JMSOperationsProvider.getInstance(managementClient); } @Deployment public static Archive<?> deploy() { return ShrinkWrap.create(JavaArchive.class, "testJMSXmlDeployment.jar") .addClass(DeployedXmlJMSManagementTestCase.class) .addAsManifestResource(DeployedXmlJMSManagementTestCase.class.getPackage(), "MANIFEST.MF", "MANIFEST.MF"); } @Test public void testDeployedQueueInManagementModel() throws IOException { final ModelNode address = getDeployedResourceAddress("jms-queue", "queue1"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("read-attribute"); operation.get(OP_ADDR).set(address); operation.get(NAME).set("entries"); ModelNode result = managementClient.getControllerClient().execute(operation); Assert.assertEquals("java:/queue1", result.get(RESULT).asList().get(0).asString()); } @Test public void testDeployedTopicInManagementModel() throws IOException { final ModelNode address = getDeployedResourceAddress("jms-topic", "topic1"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("read-attribute"); operation.get(OP_ADDR).set(address); operation.get(NAME).set("entries"); //System.out.println("operation = " + operation); ModelNode result = managementClient.getControllerClient().execute(operation); //System.out.println("result = " + result); Assert.assertEquals("java:/topic1", result.get(RESULT).asList().get(0).asString()); } private ModelNode getDeployedResourceAddress(String type, String name) { ModelNode address = new ModelNode(); String deployment = jmsOperations.getProviderName().equals("hornetq") ? TEST_HORNETQ_JMS_XML : TEST_ACTIVEMQ_JMS_XML; address.add("deployment", deployment); for (Property property : jmsOperations.getServerAddress().asPropertyList()) { address.add(property.getName(), property.getValue()); } address.add(type, name); return address; } }
7,524
46.626582
179
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/xmldeployment/DeployedXmlJMSTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, 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.jboss.as.test.integration.messaging.xmldeployment; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import jakarta.jms.Queue; import jakarta.jms.Topic; import javax.naming.InitialContext; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; 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.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.standalone.DeploymentPlan; import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentActionResult; import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentManager; import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentPlanResult; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.integration.deployment.xml.datasource.DeployedXmlDataSourceTestCase; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Test deployment of -jms.xml files * * @author Stuart Douglas */ @RunWith(Arquillian.class) @ServerSetup(DeployedXmlJMSTestCase.DeployedXmlJMSTestCaseSetup.class) public class DeployedXmlJMSTestCase { private static final String TEST_HORNETQ_JMS_XML = "test-hornetq-jms.xml"; private static final String TEST_ACTIVEMQ_JMS_XML = "test-activemq-jms.xml"; static class DeployedXmlJMSTestCaseSetup implements ServerSetupTask { @Override public void setup(final ManagementClient managementClient, final String containerId) throws Exception { final ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(managementClient.getControllerClient()); final String packageName = DeployedXmlJMSTestCase.class.getPackage().getName().replace(".", "/"); JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient); String xmlFile = (jmsOperations.getProviderName().equals("hornetq")) ? TEST_HORNETQ_JMS_XML : TEST_ACTIVEMQ_JMS_XML; final DeploymentPlan plan = manager.newDeploymentPlan().add(DeployedXmlJMSTestCase.class.getResource("/" + packageName + "/" + xmlFile)).andDeploy().build(); final Future<ServerDeploymentPlanResult> future = manager.execute(plan); final ServerDeploymentPlanResult result = future.get(20, TimeUnit.SECONDS); final ServerDeploymentActionResult actionResult = result.getDeploymentActionResult(plan.getId()); if (actionResult != null) { if (actionResult.getDeploymentException() != null) { throw new RuntimeException(actionResult.getDeploymentException()); } } } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient); String xmlFile = (jmsOperations.getProviderName().equals("hornetq")) ? TEST_HORNETQ_JMS_XML : TEST_ACTIVEMQ_JMS_XML; final ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(managementClient.getControllerClient()); final DeploymentPlan undeployPlan = manager.newDeploymentPlan().undeploy(xmlFile).andRemoveUndeployed().build(); manager.execute(undeployPlan).get(); } } @Deployment public static Archive<?> deploy() { return ShrinkWrap.create(JavaArchive.class, "testDsXmlDeployment.jar") .addClass(DeployedXmlJMSTestCase.class) .addAsManifestResource(DeployedXmlDataSourceTestCase.class.getPackage(), "MANIFEST.MF", "MANIFEST.MF"); } @ArquillianResource private InitialContext initialContext; @Test public void testDeployedQueue() throws Throwable { final Queue queue = (Queue) initialContext.lookup("java:/queue1"); Assert.assertNotNull(queue); } @Test public void testDeployedTopic() throws Throwable { final Topic topic = (Topic) initialContext.lookup("java:/topic1"); Assert.assertNotNull(topic); } }
5,521
44.636364
169
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/TransactionManagerTest.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt 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.jboss.as.test.integration.transaction; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.transaction.TransactionManager; import jakarta.transaction.TransactionSynchronizationRegistry; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; 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; /** * Tests that the TransactionManager is bound to JNDI * @author Stuart Douglas */ @RunWith(Arquillian.class) public class TransactionManagerTest { @Deployment public static WebArchive deployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, "tranaction.war"); war.addPackage(TransactionManagerTest.class.getPackage()); return war; } @Test public void testTransactionManagerBoundToJndi() throws NamingException { TransactionManager tm = (TransactionManager)new InitialContext().lookup("java:jboss/TransactionManager"); Assert.assertNotNull(tm); } @Test public void testTransactionSynchronizationRegistryBoundToJndi() throws NamingException { TransactionSynchronizationRegistry tm = (TransactionSynchronizationRegistry)new InitialContext().lookup("java:jboss/TransactionSynchronizationRegistry"); Assert.assertNotNull(tm); } }
2,469
38.206349
161
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/UserTransactionBindingTest.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt 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.jboss.as.test.integration.transaction; import static java.util.concurrent.TimeUnit.SECONDS; import java.net.URL; 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.test.integration.common.HttpRequest; 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; /** * Tests that java:comp/UserTransaction is bound to JNDI for web requests * * @author Stuart Douglas */ @RunWith(Arquillian.class) @RunAsClient public class UserTransactionBindingTest { @ArquillianResource private URL url; @Deployment public static WebArchive deployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, "tranaction.war"); war.addPackage(UserTransactionBindingTest.class.getPackage()); war.addClass(HttpRequest.class); return war; } private String performCall(String urlPattern) throws Exception { return HttpRequest.get(url.toExternalForm() + urlPattern, 10, SECONDS); } @Test public void testUserTransactionBound() throws Exception { Assert.assertEquals("true", performCall("simple")); } }
2,415
33.514286
79
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/TransactionStatisticsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat Middleware LLC, 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.jboss.as.test.integration.transaction; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; 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.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.transactions.TestXAResource; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ValueExpression; import org.jboss.remoting3.security.RemotingPermission; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.annotation.Resource; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.RollbackException; import jakarta.transaction.TransactionManager; import javax.transaction.xa.XAResource; import java.io.FilePermission; import java.util.PropertyPermission; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_GROUP_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; @RunWith(Arquillian.class) @ServerSetup({TransactionStatisticsTestCase.TransactionEnabledSetup.class}) public class TransactionStatisticsTestCase { private static final PathAddress TX_SUBSYSTEM_ADDRESS = PathAddress.pathAddress().append(SUBSYSTEM, "transactions"); // for available attributes see org.jboss.as.txn.subsystem.TxStatsHandler private static final String STATISTICS_ENABLED_ATTR = "statistics-enabled"; private static final String GROUP_STATISTICS_ATTR = "statistics"; private static final String NUMBER_OF_TRANSACTIONS_ATTR = "number-of-transactions"; private static final String NUMBER_OF_COMMITTED_TRANSACTIONS_ATTR = "number-of-committed-transactions"; private static final String NUMBER_OF_ABORTED_TRANSACTIONS_ATTR = "number-of-aborted-transactions"; private static final String NUMBER_OF_APP_ABORTED_TRANSACTIONS_ATTR = "number-of-application-rollbacks"; private static final String NUMBER_OF_NESTED_TRANSACTIONS_ATTR = "number-of-nested-transactions"; private static final String NUMBER_OF_HEURISTICS_ATTR = "number-of-heuristics"; private static final String NUMBER_OF_INFLIGHT_TRANSACTIONS_ATTR = "number-of-inflight-transactions"; private static final String NUMBER_OF_TIMED_OUT_TRANSACTIONS_ATTR = "number-of-timed-out-transactions"; private static final String NUMBER_OF_RESOURCE_ROLLBACKS_ATTR = "number-of-resource-rollbacks"; private static final String NUMBER_OF_SYSTEM_ROLLBACKS_ATTR = "number-of-system-rollbacks"; private static final String AVERAGE_COMMIT_TIME_ATTR = "average-commit-time"; int numberBefore, numberCommittedBefore, numberAbortedBefore, numberAppAbortedBefore, numberNestedBefore, numberHeuristicsBefore, numberInflightBefore, numberTimedOutBefore, numberResourceRollbackBefore, numberSystemRollbackBefore; static class TransactionEnabledSetup implements ServerSetupTask { private ModelNode statisticsEnabledOriginValue; @Override public void setup(ManagementClient managementClient, String s) throws Exception { ModelNode opResult = MaximumTimeoutTestCase.executeForResult( managementClient.getControllerClient(), Util.getReadAttributeOperation(TX_SUBSYSTEM_ADDRESS, STATISTICS_ENABLED_ATTR)); // value can be either expression or boolean, let's tackle it with try/catch try { ValueExpression originalAsExpression = opResult.asExpression(); statisticsEnabledOriginValue = new ModelNode().set(originalAsExpression); } catch (Exception notAnExpression) { // let's try to use boolean boolean originalAsBoolean = opResult.asBoolean(); statisticsEnabledOriginValue = new ModelNode().set(originalAsBoolean); } writeStatisticsEnabled(managementClient, new ModelNode().set(true)); } @Override public void tearDown(ManagementClient managementClient, String s) throws Exception { writeStatisticsEnabled(managementClient, statisticsEnabledOriginValue); } private void writeStatisticsEnabled(ManagementClient client, ModelNode modelNodeWriteData) { ModelNode op = Util.getWriteAttributeOperation(TX_SUBSYSTEM_ADDRESS, STATISTICS_ENABLED_ATTR, modelNodeWriteData); MaximumTimeoutTestCase.executeForResult(client.getControllerClient(), op); } } @Resource(mappedName = "java:/TransactionManager") private static TransactionManager tm; @ArquillianResource private ManagementClient managementClient; @Deployment public static JavaArchive createDeployment() { return ShrinkWrap.create(JavaArchive.class) .addClasses(TransactionStatisticsTestCase.class, TransactionStatisticsTestCase.TransactionEnabledSetup.class, MaximumTimeoutTestCase.class, TimeoutUtil.class) .addPackage(TestXAResource.class.getPackage()) .addAsManifestResource(new StringAsset("Dependencies: org.jboss.as.controller, org.jboss.remoting\n"), "MANIFEST.MF") .addAsManifestResource(createPermissionsXmlAsset( // ManagementClient needs the following permissions and a dependency on 'org.jboss.remoting3' module new RemotingPermission("createEndpoint"), new RemotingPermission("connect"), new FilePermission(System.getProperty("jboss.inst") + "/standalone/tmp/auth/*", "read"), // TimeoutUtil.adjust needs permission for system property reading new PropertyPermission("ts.timeout.factor", "read") ), "permissions.xml"); } @Before public void readStatisticsBeforeTest() { numberBefore = readInt(NUMBER_OF_TRANSACTIONS_ATTR); numberCommittedBefore = readInt(NUMBER_OF_COMMITTED_TRANSACTIONS_ATTR); numberAbortedBefore = readInt(NUMBER_OF_ABORTED_TRANSACTIONS_ATTR); numberAppAbortedBefore = readInt(NUMBER_OF_APP_ABORTED_TRANSACTIONS_ATTR); numberNestedBefore = readInt(NUMBER_OF_NESTED_TRANSACTIONS_ATTR); numberHeuristicsBefore = readInt(NUMBER_OF_HEURISTICS_ATTR); numberInflightBefore = readInt(NUMBER_OF_INFLIGHT_TRANSACTIONS_ATTR); numberTimedOutBefore = readInt(NUMBER_OF_TIMED_OUT_TRANSACTIONS_ATTR); numberResourceRollbackBefore = readInt(NUMBER_OF_RESOURCE_ROLLBACKS_ATTR); numberSystemRollbackBefore = readInt(NUMBER_OF_SYSTEM_ROLLBACKS_ATTR); } @Test public void transactionStatisticsGrouped() throws Exception { XAResource xaer = new TestXAResource(); tm.begin(); tm.getTransaction().enlistResource(xaer); tm.commit(); tm.begin(); tm.getTransaction().enlistResource(xaer); tm.rollback(); Assert.assertEquals("Two more transactions in statistics are expected", numberBefore + 2, readInt(NUMBER_OF_TRANSACTIONS_ATTR)); Assert.assertEquals("One more committed transaction in statistics is expected", numberCommittedBefore + 1, readInt(NUMBER_OF_COMMITTED_TRANSACTIONS_ATTR)); Assert.assertEquals("One more aborted transaction in statistics is expected", numberAbortedBefore + 1, readInt(NUMBER_OF_ABORTED_TRANSACTIONS_ATTR)); Assert.assertEquals("One more application aborted transaction in statistics is expected", numberAppAbortedBefore + 1, readInt(NUMBER_OF_APP_ABORTED_TRANSACTIONS_ATTR)); Assert.assertEquals("No additional nested transaction is expected", numberNestedBefore, readInt(NUMBER_OF_NESTED_TRANSACTIONS_ATTR)); Assert.assertEquals("No additional heuristic transaction is expected", numberHeuristicsBefore, readInt(NUMBER_OF_HEURISTICS_ATTR)); Assert.assertEquals("No additional inflight transaction is expected", numberInflightBefore, readInt(NUMBER_OF_INFLIGHT_TRANSACTIONS_ATTR)); Assert.assertEquals("No additional timed out transaction is expected", numberTimedOutBefore, readInt(NUMBER_OF_TIMED_OUT_TRANSACTIONS_ATTR)); Assert.assertEquals("No additional resource rollback transaction is expected", numberResourceRollbackBefore, readInt(NUMBER_OF_RESOURCE_ROLLBACKS_ATTR)); Assert.assertEquals("No additional system rollback transaction is expected", numberSystemRollbackBefore, readInt(NUMBER_OF_SYSTEM_ROLLBACKS_ATTR)); Assert.assertTrue("Expected the commit time was non zero value", readAverage() > 0L); ModelNode grouped = readGrouped(); Assert.assertEquals("Two more transactions listed in grouped statistics are expected", numberBefore + 2, grouped.get(NUMBER_OF_TRANSACTIONS_ATTR).asInt()); Assert.assertEquals("One more committed transaction listed in grouped statistics is expected", numberCommittedBefore + 1, grouped.get(NUMBER_OF_COMMITTED_TRANSACTIONS_ATTR).asInt()); Assert.assertEquals("One more aborted transaction listed in grouped statistics is expected", numberAbortedBefore + 1, grouped.get(NUMBER_OF_ABORTED_TRANSACTIONS_ATTR).asInt()); Assert.assertEquals("One more application aborted transaction listed in grouped statistics is expected", numberAppAbortedBefore + 1, grouped.get(NUMBER_OF_APP_ABORTED_TRANSACTIONS_ATTR).asInt()); Assert.assertEquals("No additional nested transaction is expected in grouped statistics", numberNestedBefore, grouped.get(NUMBER_OF_NESTED_TRANSACTIONS_ATTR).asInt()); Assert.assertEquals("No additional heuristic transaction is expected in grouped statistics", numberHeuristicsBefore, grouped.get(NUMBER_OF_HEURISTICS_ATTR).asInt()); Assert.assertEquals("No additional inflight transaction is expected in grouped statistics", numberInflightBefore, grouped.get(NUMBER_OF_INFLIGHT_TRANSACTIONS_ATTR).asInt()); Assert.assertEquals("No additional timed out transaction is expected in grouped statistics", numberTimedOutBefore, grouped.get(NUMBER_OF_TIMED_OUT_TRANSACTIONS_ATTR).asInt()); Assert.assertEquals("No additional resource rollback transaction is expected in grouped statistics", numberResourceRollbackBefore, grouped.get(NUMBER_OF_RESOURCE_ROLLBACKS_ATTR).asInt()); Assert.assertEquals("No additional system rollback transaction is expected in grouped statistics", numberSystemRollbackBefore, grouped.get(NUMBER_OF_SYSTEM_ROLLBACKS_ATTR).asInt()); Assert.assertTrue("Expected the commit time was non zero value and is listed in grouped statistics", grouped.get(AVERAGE_COMMIT_TIME_ATTR).asLong() > 0L); } @Test public void transactionStatisticsInflight() throws Exception { tm.begin(); Assert.assertEquals("One more inflight transaction is expected being in progress", numberInflightBefore + 1, readInt(NUMBER_OF_INFLIGHT_TRANSACTIONS_ATTR)); ModelNode grouped = readGrouped(); Assert.assertEquals("One more inflight transaction is expected in grouped statistics", numberInflightBefore + 1, grouped.get(NUMBER_OF_INFLIGHT_TRANSACTIONS_ATTR).asInt()); tm.commit(); } @Test public void transactionStatisticsTimeout() throws Exception { try { tm.setTransactionTimeout(1); tm.begin(); Thread.sleep(TimeoutUtil.adjust(1100)); tm.commit(); Assert.fail("Expected the transaction commit fails as transaction was rolled-back with timeout"); } catch (RollbackException expected) { } finally { tm.setTransactionTimeout(0); } Assert.assertEquals("One more timed out transaction is expected", numberTimedOutBefore + 1, readInt(NUMBER_OF_TIMED_OUT_TRANSACTIONS_ATTR)); ModelNode grouped = readGrouped(); Assert.assertEquals("One more timed out transaction is expected in grouped statistics", numberTimedOutBefore + 1, grouped.get(NUMBER_OF_TIMED_OUT_TRANSACTIONS_ATTR).asInt()); } @Test public void transactionStatisticsHeuristics() throws Exception { XAResource xaer = new TestXAResource(); XAResource xaerHeur = new TestXAResource(TestXAResource.TestAction.COMMIT_THROW_XAER_RMERR); try { tm.begin(); tm.getTransaction().enlistResource(xaer); tm.getTransaction().enlistResource(xaerHeur); tm.commit(); Assert.fail("Expected the transaction commit fails as transaction was marked as heuristics by XAException"); } catch (HeuristicMixedException expected) { } Assert.assertEquals("One more heuristic transaction is expected", numberHeuristicsBefore + 1, readInt(NUMBER_OF_HEURISTICS_ATTR)); ModelNode grouped = readGrouped(); Assert.assertEquals("One more heuristic transaction is expected in grouped statistics", numberHeuristicsBefore + 1, grouped.get(NUMBER_OF_HEURISTICS_ATTR).asInt()); } @Test public void transactionStatisticsResourceRollback() throws Exception { XAResource xaerHeur = new TestXAResource(TestXAResource.TestAction.COMMIT_THROW_XA_RBROLLBACK); XAResource xaer = new TestXAResource(); try { tm.begin(); tm.getTransaction().enlistResource(xaerHeur); tm.getTransaction().enlistResource(xaer); tm.commit(); Assert.fail("Expected the transaction commit fails as transaction commit failed with XAException"); } catch (RollbackException expected) { } Assert.assertEquals("One more resource rollback transaction is expected", numberResourceRollbackBefore + 1, readInt(NUMBER_OF_RESOURCE_ROLLBACKS_ATTR)); Assert.assertEquals("One more aborted transaction is expected", numberAbortedBefore + 1, readInt(NUMBER_OF_ABORTED_TRANSACTIONS_ATTR)); ModelNode grouped = readGrouped(); Assert.assertEquals("One more resource rollback transaction is expected in grouped statistics", numberResourceRollbackBefore + 1, grouped.get(NUMBER_OF_RESOURCE_ROLLBACKS_ATTR).asInt()); Assert.assertEquals("One more aborted transaction is expected in grouped statistics", numberAbortedBefore + 1, grouped.get(NUMBER_OF_ABORTED_TRANSACTIONS_ATTR).asInt()); } private int readInt(String attributeName) { ModelNode opResult = MaximumTimeoutTestCase.executeForResult( managementClient.getControllerClient(), Util.getReadAttributeOperation(TX_SUBSYSTEM_ADDRESS, attributeName)); return opResult.asInt(); } private long readAverage() { ModelNode opResult = MaximumTimeoutTestCase.executeForResult( managementClient.getControllerClient(), Util.getReadAttributeOperation(TX_SUBSYSTEM_ADDRESS, AVERAGE_COMMIT_TIME_ATTR)); return opResult.asLong(); } private ModelNode readGrouped() { ModelNode groupReadOp = Util.createEmptyOperation(READ_ATTRIBUTE_GROUP_OPERATION, TX_SUBSYSTEM_ADDRESS); groupReadOp.get(NAME).set(GROUP_STATISTICS_ATTR); groupReadOp.get(INCLUDE_RUNTIME).set(true); return MaximumTimeoutTestCase.executeForResult(managementClient.getControllerClient(), groupReadOp).asObject(); } }
17,403
57.599327
139
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/TransactionTimeoutLeakServlet.java
/* * JBoss, Home of Professional Open Source * Copyright 2022, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt 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.jboss.as.test.integration.transaction; import java.io.IOException; import java.io.Writer; import javax.naming.InitialContext; import javax.transaction.xa.XAResource; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.transaction.TransactionManager; import org.jboss.as.test.integration.transactions.TestXAResource; @WebServlet(name = "TransactionTimeoutLeakServlet", urlPatterns = {"/timeout"}) public class TransactionTimeoutLeakServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { final TransactionManager tm = (TransactionManager) new InitialContext().lookup("java:/TransactionManager"); final String second = req.getParameter("second"); if (second != null) { final int timeoutValue = Integer.parseInt(second); if (timeoutValue > 0) { tm.setTransactionTimeout(timeoutValue); } } XAResource xaer = new TestXAResource(); tm.begin(); tm.getTransaction().enlistResource(xaer); int effectiveTimeout = xaer.getTransactionTimeout(); tm.commit(); Writer writer = resp.getWriter(); writer.write(String.valueOf(effectiveTimeout)); } catch (Exception e) { throw new ServletException(e); } } }
2,658
40.546875
119
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/TransactionTimeoutLeakTestCase.java
/* * JBoss, Home of Professional Open Source * Copyright 2022, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt 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.jboss.as.test.integration.transaction; import static java.util.concurrent.TimeUnit.SECONDS; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; 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.test.integration.common.HttpRequest; import org.jboss.as.test.integration.transactions.TestXAResource; 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; /** * Tests to verify that transaction timeout setting is cleaned up after a http request * is done, and is not carried over to the next request processing. * See <a href="https://issues.redhat.com/browse/WFLY-16514">WFLY-16514</a> */ @RunWith(Arquillian.class) @RunAsClient public class TransactionTimeoutLeakTestCase { @ArquillianResource private URL url; @Deployment public static WebArchive deployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, "transaction-timeout-leak.war"); war.addPackage(TestXAResource.class.getPackage()); war.addClass(TransactionTimeoutLeakTestCase.class); war.addClass(TransactionTimeoutLeakServlet.class); war.addClass(HttpRequest.class); return war; } /** * This test first sends to TransactionTimeoutLeakServlet a batch of concurrent * requests having a short tx timeout value. This instructs the target servlet * to set a custom transaction timeout value. The test then verifies * the effective transaction timeout. * Next, the test sends a batch of concurrent requests having no tx timeout value. * This instructs the target servlet to use the server default transaction * timeout value. The test verifies that the default transaction timeout * value is used, and that the value used in the first batch should not be * leaked to the 2nd batch of requests. * * @throws Exception upon error */ @Test public void testUserTransactionTimeoutLeak() throws Exception { final int threadCount = 10; final ExecutorService executorService = Executors.newFixedThreadPool(threadCount); test(2, threadCount, executorService); test(0, threadCount, executorService); executorService.shutdownNow(); } private void test(int timeout, int threadCount, ExecutorService executorService) throws Exception { final String customTimeout = Integer.toString(timeout); final String[] expected = new String[threadCount]; Arrays.fill(expected, timeout > 0 ? customTimeout : String.valueOf(300)); final String queryString = timeout > 0 ? "timeout?second=" + customTimeout : "timeout"; final String requestUrl = url.toExternalForm() + queryString; final List<Future<String>> futures = new ArrayList<>(); for (int i = 0; i < threadCount; i++) { futures.add(executorService.submit(() -> { String result; try { result = HttpRequest.get(requestUrl, 10, SECONDS); } catch (Exception e) { result = e.toString(); } return result; } )); } final String[] results = new String[threadCount]; for (int i = 0; i < threadCount; i++) { results[i] = futures.get(i).get(2, TimeUnit.MINUTES); } Assert.assertArrayEquals(expected, results); } }
4,968
41.110169
103
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/UserTransactionServlet.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt 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.jboss.as.test.integration.transaction; import java.io.IOException; import java.io.Writer; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.transaction.UserTransaction; /** * @author Stuart Douglas */ @WebServlet(name = "UserTransactionServlet", urlPatterns = {"/simple"}) public class UserTransactionServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { final UserTransaction transaction = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); Writer writer = resp.getWriter(); writer.write(Boolean.valueOf(transaction != null).toString()); } catch (NamingException e) { throw new RuntimeException(e); } } }
2,113
39.653846
123
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/MaximumTimeoutTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat Middleware LLC, 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.jboss.as.test.integration.transaction; import java.io.FilePermission; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; 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.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.transactions.TestXAResource; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.remoting3.security.RemotingPermission; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.annotation.Resource; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.NotSupportedException; import jakarta.transaction.RollbackException; import jakarta.transaction.SystemException; import jakarta.transaction.TransactionManager; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import java.io.IOException; import java.util.List; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; /** * Tests for EAP7-981 / WFLY-10009 * * @author istraka */ @RunWith(Arquillian.class) @ServerSetup({MaximumTimeoutTestCase.TimeoutSetup.class}) public class MaximumTimeoutTestCase { private static final String MESSAGE_REGEX = ".*\\bWARN\\b.*WFLYTX0039:.*%d"; private static final String MAX_TIMEOUT_ATTR = "maximum-timeout"; private static final String DEF_TIMEOUT_ATTR = "default-timeout"; private static final int MAX_TIMEOUT1 = 400; private static final int MAX_TIMEOUT2 = 500; private static final int DEFAULT_TIMEOUT = 100; private static final int NO_TIMEOUT = 0; private static final PathAddress TX_ADDRESS = PathAddress.pathAddress().append(SUBSYSTEM, "transactions"); private static final PathAddress LOG_FILE_ADDRESS = PathAddress.pathAddress() .append(SUBSYSTEM, "logging") .append("log-file", "server.log"); private static Logger LOGGER = Logger.getLogger(MaximumTimeoutTestCase.class); @Resource(mappedName = "java:/TransactionManager") private static TransactionManager txm; @ArquillianResource private ManagementClient managementClient; @Deployment public static JavaArchive createDeployment() { return ShrinkWrap.create(JavaArchive.class) .addClasses(MaximumTimeoutTestCase.class, MaximumTimeoutTestCase.TimeoutSetup.class) .addPackage(TestXAResource.class.getPackage()) .addAsManifestResource(new StringAsset("Dependencies: org.jboss.as.controller, org.jboss.remoting\n"), "MANIFEST.MF") .addAsManifestResource(createPermissionsXmlAsset( // ManagementClient needs the following permissions and a dependency on 'org.jboss.remoting3' module new RemotingPermission("createEndpoint"), new RemotingPermission("connect"), new FilePermission(System.getProperty("jboss.inst") + "/standalone/tmp/auth/*", "read") ), "permissions.xml"); } static void setMaximumTimeout(final ModelControllerClient client, int timeout) { ModelNode writeMaxTimeout = Util.getWriteAttributeOperation(TX_ADDRESS, MAX_TIMEOUT_ATTR, timeout); executeForResult(client, writeMaxTimeout); } static void setDefaultTimeout(final ModelControllerClient client, int timeout) { ModelNode writeMaxTimeout = Util.getWriteAttributeOperation(TX_ADDRESS, DEF_TIMEOUT_ATTR, timeout); executeForResult(client, writeMaxTimeout); } static List<ModelNode> getLogs(final ModelControllerClient client) { // /subsystem=logging/log-file=server.log:read-log-file(lines=-1) ModelNode op = Util.createEmptyOperation("read-log-file", LOG_FILE_ADDRESS); op.get("lines").set(-1); return executeForResult(client, op).asList(); } static ModelNode executeForResult(final ModelControllerClient client, final ModelNode operation) { try { final ModelNode result = client.execute(operation); checkSuccessful(result, operation); return result.get(ClientConstants.RESULT); } catch (IOException e) { throw new RuntimeException(e); } } static void checkSuccessful(final ModelNode result, final ModelNode operation) { if (!ClientConstants.SUCCESS.equals(result.get(ClientConstants.OUTCOME).asString())) { LOGGER.error("Operation " + operation + " did not succeed. Result was " + result); throw new RuntimeException("operation has failed: " + result.get(ClientConstants.FAILURE_DESCRIPTION).toString()); } } @Test public void testMaximumTimeout() throws IOException, SystemException, NotSupportedException, RollbackException, HeuristicRollbackException, HeuristicMixedException, XAException { setDefaultTimeout(managementClient.getControllerClient(), NO_TIMEOUT); setMaximumTimeout(managementClient.getControllerClient(), MAX_TIMEOUT1); txm.setTransactionTimeout(NO_TIMEOUT); XAResource xaer = new TestXAResource(); txm.begin(); txm.getTransaction().enlistResource(xaer); int timeout = xaer.getTransactionTimeout(); Assert.assertEquals(MAX_TIMEOUT1, timeout); txm.commit(); setMaximumTimeout(managementClient.getControllerClient(), MAX_TIMEOUT2); xaer = new TestXAResource(); txm.begin(); txm.getTransaction().enlistResource(xaer); timeout = xaer.getTransactionTimeout(); Assert.assertEquals(MAX_TIMEOUT2, timeout); txm.commit(); } @Test public void testDefaultTimeout() throws IOException, SystemException, NotSupportedException, RollbackException, HeuristicRollbackException, HeuristicMixedException, XAException { setMaximumTimeout(managementClient.getControllerClient(), MAX_TIMEOUT1); setDefaultTimeout(managementClient.getControllerClient(), DEFAULT_TIMEOUT); XAResource xaer = new TestXAResource(); txm.setTransactionTimeout(NO_TIMEOUT); txm.begin(); txm.getTransaction().enlistResource(xaer); int timeout = xaer.getTransactionTimeout(); Assert.assertEquals(DEFAULT_TIMEOUT, timeout); txm.commit(); xaer = new TestXAResource(); txm.setTransactionTimeout(20); txm.begin(); txm.getTransaction().enlistResource(xaer); timeout = xaer.getTransactionTimeout(); Assert.assertEquals(20, timeout); txm.commit(); xaer = new TestXAResource(); txm.setTransactionTimeout(NO_TIMEOUT); txm.begin(); txm.getTransaction().enlistResource(xaer); timeout = xaer.getTransactionTimeout(); Assert.assertEquals(DEFAULT_TIMEOUT, timeout); txm.commit(); } @Test public void testLogFile() { setMaximumTimeout(managementClient.getControllerClient(), MAX_TIMEOUT1); setDefaultTimeout(managementClient.getControllerClient(), NO_TIMEOUT); setMaximumTimeout(managementClient.getControllerClient(), MAX_TIMEOUT2); List<ModelNode> nodes = getLogs(managementClient.getControllerClient()); boolean firstMessageFound = false; boolean secondMessageFound = false; for (ModelNode node : nodes) { String line = node.asString(); if (!firstMessageFound) { if (line.matches(String.format(MESSAGE_REGEX, MAX_TIMEOUT1))) { firstMessageFound = true; } } else { if (line.matches(String.format(MESSAGE_REGEX, MAX_TIMEOUT2))) { secondMessageFound = true; } } } Assert.assertTrue(firstMessageFound && secondMessageFound); } static class TimeoutSetup implements ServerSetupTask { private int defaultTimeout; private int maxTimeout; @Override public void setup(ManagementClient managementClient, String s) throws Exception { ModelNode op = executeForResult(managementClient.getControllerClient(), Util.getReadAttributeOperation(TX_ADDRESS, MAX_TIMEOUT_ATTR)); maxTimeout = op.asInt(); op = executeForResult(managementClient.getControllerClient(), Util.getReadAttributeOperation(TX_ADDRESS, DEF_TIMEOUT_ATTR)); defaultTimeout = op.asInt(); LOGGER.debug("max timeout: " + maxTimeout); LOGGER.debug("default timeout: " + defaultTimeout); } @Override public void tearDown(ManagementClient managementClient, String s) throws Exception { setDefaultTimeout(managementClient.getControllerClient(), defaultTimeout); setMaximumTimeout(managementClient.getControllerClient(), maxTimeout); setup(managementClient, s); } } }
10,605
42.289796
182
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/inflow/TransactionInflowTextMessage.java
/* * JBoss, Home of Professional Open Source * Copyright 2016, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt 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.jboss.as.test.integration.transaction.inflow; import java.util.Enumeration; import java.util.Random; import jakarta.jms.Destination; import jakarta.jms.JMSException; /** * Test message used for testing in Jakarta Connectors inflow transaction rar. * * @author Ondrej Chaloupka <[email protected]> */ public class TransactionInflowTextMessage implements jakarta.jms.TextMessage { private int messageId = new Random().nextInt(); private String text; public TransactionInflowTextMessage(String text) { this.text = text; } public String getJMSMessageID() throws JMSException { return messageId + "-" + text; } public void setText(String string) throws JMSException { this.text = string; } public String getText() throws JMSException { return this.text; } public String getTextCleaned() { return this.text; } public void setJMSMessageID(String id) throws JMSException { throw new UnsupportedOperationException(); } public long getJMSTimestamp() throws JMSException { throw new UnsupportedOperationException(); } public void setJMSTimestamp(long timestamp) throws JMSException { throw new UnsupportedOperationException(); } public byte[] getJMSCorrelationIDAsBytes() throws JMSException { throw new UnsupportedOperationException(); } public void setJMSCorrelationIDAsBytes(byte[] correlationID) throws JMSException { throw new UnsupportedOperationException(); } public void setJMSCorrelationID(String correlationID) throws JMSException { throw new UnsupportedOperationException(); } public String getJMSCorrelationID() throws JMSException { throw new UnsupportedOperationException(); } public Destination getJMSReplyTo() throws JMSException { throw new UnsupportedOperationException(); } public void setJMSReplyTo(Destination replyTo) throws JMSException { throw new UnsupportedOperationException(); } public Destination getJMSDestination() throws JMSException { throw new UnsupportedOperationException(); } public void setJMSDestination(Destination destination) throws JMSException { throw new UnsupportedOperationException(); } public int getJMSDeliveryMode() throws JMSException { throw new UnsupportedOperationException(); } public void setJMSDeliveryMode(int deliveryMode) throws JMSException { throw new UnsupportedOperationException(); } public boolean getJMSRedelivered() throws JMSException { throw new UnsupportedOperationException(); } public void setJMSRedelivered(boolean redelivered) throws JMSException { throw new UnsupportedOperationException(); } public String getJMSType() throws JMSException { throw new UnsupportedOperationException(); } public void setJMSType(String type) throws JMSException { throw new UnsupportedOperationException(); } public long getJMSExpiration() throws JMSException { throw new UnsupportedOperationException(); } public void setJMSExpiration(long expiration) throws JMSException { throw new UnsupportedOperationException(); } public long getJMSDeliveryTime() throws JMSException { throw new UnsupportedOperationException(); } public void setJMSDeliveryTime(long deliveryTime) throws JMSException { throw new UnsupportedOperationException(); } public int getJMSPriority() throws JMSException { throw new UnsupportedOperationException(); } public void setJMSPriority(int priority) throws JMSException { throw new UnsupportedOperationException(); } public void clearProperties() throws JMSException { throw new UnsupportedOperationException(); } public boolean propertyExists(String name) throws JMSException { throw new UnsupportedOperationException(); } public boolean getBooleanProperty(String name) throws JMSException { throw new UnsupportedOperationException(); } public byte getByteProperty(String name) throws JMSException { throw new UnsupportedOperationException(); } public short getShortProperty(String name) throws JMSException { throw new UnsupportedOperationException(); } public int getIntProperty(String name) throws JMSException { throw new UnsupportedOperationException(); } public long getLongProperty(String name) throws JMSException { throw new UnsupportedOperationException(); } public float getFloatProperty(String name) throws JMSException { throw new UnsupportedOperationException(); } public double getDoubleProperty(String name) throws JMSException { throw new UnsupportedOperationException(); } public String getStringProperty(String name) throws JMSException { throw new UnsupportedOperationException(); } public Object getObjectProperty(String name) throws JMSException { throw new UnsupportedOperationException(); } @SuppressWarnings("rawtypes") public Enumeration getPropertyNames() throws JMSException { throw new UnsupportedOperationException(); } public void setBooleanProperty(String name, boolean value) throws JMSException { throw new UnsupportedOperationException(); } public void setByteProperty(String name, byte value) throws JMSException { throw new UnsupportedOperationException(); } public void setShortProperty(String name, short value) throws JMSException { throw new UnsupportedOperationException(); } public void setIntProperty(String name, int value) throws JMSException { throw new UnsupportedOperationException(); } public void setLongProperty(String name, long value) throws JMSException { throw new UnsupportedOperationException(); } public void setFloatProperty(String name, float value) throws JMSException { throw new UnsupportedOperationException(); } public void setDoubleProperty(String name, double value) throws JMSException { throw new UnsupportedOperationException(); } public void setStringProperty(String name, String value) throws JMSException { throw new UnsupportedOperationException(); } public void setObjectProperty(String name, Object value) throws JMSException { throw new UnsupportedOperationException(); } public void acknowledge() throws JMSException { throw new UnsupportedOperationException(); } public void clearBody() throws JMSException { throw new UnsupportedOperationException(); } public <T> T getBody(Class<T> c) throws JMSException { throw new UnsupportedOperationException(); } public boolean isBodyAssignableTo(@SuppressWarnings("rawtypes") Class c) throws JMSException { throw new UnsupportedOperationException(); } }
8,098
31.011858
98
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/inflow/TransactionInflowWork.java
/* * JBoss, Home of Professional Open Source * Copyright 2016, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt 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.jboss.as.test.integration.transaction.inflow; import jakarta.jms.MessageListener; import jakarta.resource.spi.UnavailableException; import jakarta.resource.spi.endpoint.MessageEndpoint; import jakarta.resource.spi.endpoint.MessageEndpointFactory; import jakarta.resource.spi.work.Work; import org.jboss.logging.Logger; /** * Jakarta Connectors work executing onMessage method with text message payload. * * @author Ondrej Chaloupka <[email protected]> */ public class TransactionInflowWork implements Work { private static final Logger log = Logger.getLogger(TransactionInflowWork.class); private MessageEndpointFactory messageFactory; private String msg; TransactionInflowWork(MessageEndpointFactory messageFactory, String msg) { this.messageFactory = messageFactory; this.msg = msg; } public void run() { MessageEndpoint messageEndpoint; try { messageEndpoint = messageFactory.createEndpoint(null); if (messageEndpoint instanceof MessageListener){ log.tracef("Calling on message on endpoint '%s' with data message '%s'", messageEndpoint, msg); TransactionInflowTextMessage textMessage = new TransactionInflowTextMessage(msg); ((MessageListener) messageEndpoint).onMessage(textMessage); } else { throw new IllegalStateException("Not supported message endpoint: " + messageEndpoint); } } catch (UnavailableException ue) { String msg = String.format("Not capable to create message factory '%s' endpoint", messageFactory); throw new IllegalStateException(msg, ue); } } public void release() { // nothing to release } }
2,786
39.391304
111
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/inflow/TransactionInflowResourceAdapter.java
/* * JBoss, Home of Professional Open Source * Copyright 2016, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt 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.jboss.as.test.integration.transaction.inflow; import jakarta.resource.ResourceException; import jakarta.resource.spi.ActivationSpec; import jakarta.resource.spi.BootstrapContext; import jakarta.resource.spi.ResourceAdapter; import jakarta.resource.spi.ResourceAdapterInternalException; import jakarta.resource.spi.endpoint.MessageEndpointFactory; import jakarta.resource.spi.work.TransactionContext; import jakarta.resource.spi.work.WorkException; import jakarta.resource.spi.work.WorkManager; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.logging.Logger; /** * Implementation of resource adapter for transaction inflow testing. * * @author Ondrej Chaloupka <[email protected]> */ public class TransactionInflowResourceAdapter implements ResourceAdapter { private static final Logger log = Logger.getLogger(TransactionInflowResourceAdapter.class); private BootstrapContext bootstrapContext; static final String MSG = "inflow RAR test message"; static final String ACTION_COMMIT = "commit"; static final String ACTION_ROLLBACK = "rollback"; public void start(BootstrapContext ctx) throws ResourceAdapterInternalException { log.tracef("Starting '%s' with context '%s'", TransactionInflowResourceAdapter.class.getSimpleName(), ctx); this.bootstrapContext = ctx; } public void stop() { log.tracef("Stopping (do nothing) '%s'", TransactionInflowResourceAdapter.class.getSimpleName()); } public void endpointActivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) throws ResourceException { Xid xid = TransactionInflowXid.getUniqueXid(42); TransactionInflowWork work = new TransactionInflowWork(endpointFactory, MSG); TransactionContext txnCtx = new TransactionContext(); txnCtx.setXid(xid); TransactionInflowWorkListener workListener = new TransactionInflowWorkListener(); try { bootstrapContext.getWorkManager().startWork(work, WorkManager.IMMEDIATE, txnCtx, workListener); } catch (WorkException e) { throw new IllegalStateException("Can't start work " + work + " with txn " + txnCtx); } // start Work blocks until the execution starts but not until its completion int timeout = TimeoutUtil.adjust(10_000); // timeout 10 seconds long start = System.currentTimeMillis(); while(!workListener.isCompleted() && (System.currentTimeMillis() - start < timeout)) { Thread.yield(); // active waiting } if(!workListener.isCompleted()) throw new IllegalStateException("Work " + work + " of xid " + xid + " does not finish."); try { bootstrapContext.getXATerminator().prepare(xid); // depends on value in spec we commit or roll-back TransactionInflowRaSpec activationSpec = (TransactionInflowRaSpec) spec; if(activationSpec.getAction().equals(ACTION_COMMIT)) { bootstrapContext.getXATerminator().commit(xid, false); } else if(activationSpec.getAction().equals(ACTION_ROLLBACK)) { bootstrapContext.getXATerminator().rollback(xid); } else { new IllegalStateException("Spec '" + activationSpec + "' defines unknown action"); } } catch (XAException xae) { throw new IllegalStateException("Can't process prepare/commit/rollback calls for xid: " + xid, xae); } } public void endpointDeactivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) { // nothing to do } public XAResource[] getXAResources(ActivationSpec[] specs) throws ResourceException { return null; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((bootstrapContext == null) ? 0 : bootstrapContext.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TransactionInflowResourceAdapter other = (TransactionInflowResourceAdapter) obj; if (bootstrapContext == null) { if (other.bootstrapContext != null) return false; } else if (!bootstrapContext.equals(other.bootstrapContext)) return false; return true; } }
5,649
40.544118
129
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/inflow/TransactionInflowWorkListener.java
/* * JBoss, Home of Professional Open Source * Copyright 2016, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt 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.jboss.as.test.integration.transaction.inflow; import java.util.concurrent.atomic.AtomicBoolean; import jakarta.resource.spi.work.WorkEvent; import jakarta.resource.spi.work.WorkListener; /** * Simple listener to monitor if work was done already. * * @author Ondrej Chaloupka <[email protected]> */ public class TransactionInflowWorkListener implements WorkListener { private AtomicBoolean isAccepted = new AtomicBoolean(false); private AtomicBoolean isRejected = new AtomicBoolean(false); private AtomicBoolean isStarted = new AtomicBoolean(false); private AtomicBoolean isCompleted = new AtomicBoolean(false); @Override public void workAccepted(WorkEvent e) { isAccepted.set(true); } @Override public void workRejected(WorkEvent e) { isRejected.set(true); } @Override public void workStarted(WorkEvent e) { isStarted.set(true); } @Override public void workCompleted(WorkEvent e) { isCompleted.set(true); } boolean isAccepted() { return isAccepted.get(); } boolean isRejected() { return isRejected.get(); } boolean isStarted() { return isStarted.get(); } boolean isCompleted() { return isCompleted.get(); } }
2,315
29.077922
73
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/inflow/TransactionInflowTestCase.java
/* * JBoss, Home of Professional Open Source * Copyright 2016, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt 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.jboss.as.test.integration.transaction.inflow; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.net.SocketPermission; import java.util.Hashtable; import java.util.PropertyPermission; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployer; 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.test.integration.transactions.TestXAResource; import org.jboss.as.test.integration.transactions.TransactionCheckerSingleton; import org.jboss.as.test.integration.transactions.TransactionCheckerSingletonRemote; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.as.test.shared.integration.ejb.security.Util; 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.ResourceAdapterArchive; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Testcase running Jakarta Connectors inflow transaction from deployed RAR. * Two mock XA resources are enlisted inside of MDB to proceed 2PC. * * @author Ondrej Chaloupka <[email protected]> */ @RunWith(Arquillian.class) @RunAsClient public class TransactionInflowTestCase { private static final String EJB_MODULE_NAME = "inflow-ejb-"; private static final String COMMIT = TransactionInflowResourceAdapter.ACTION_COMMIT; private static final String ROLLBACK = TransactionInflowResourceAdapter.ACTION_ROLLBACK; @ArquillianResource public Deployer deployer; @Deployment(name = TransactionInflowMdb.RESOURCE_ADAPTER_NAME, order = 1) public static ResourceAdapterArchive getResourceAdapterDeployment() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "inflow-txn-inside.jar") .addClasses(TransactionInflowResourceAdapter.class) .addClasses(TransactionInflowXid.class, TransactionInflowWork.class, TransactionInflowRaSpec.class, TransactionInflowTextMessage.class, TransactionInflowWorkListener.class, TimeoutUtil.class); ResourceAdapterArchive rar = ShrinkWrap.create(ResourceAdapterArchive.class, TransactionInflowMdb.RESOURCE_ADAPTER_NAME + ".rar") .addAsResource(TransactionInflowTestCase.class.getPackage(), "ra.xml", "META-INF/ra.xml") .addAsManifestResource(createPermissionsXmlAsset( new RuntimePermission("accessDeclaredMembers"), new RuntimePermission("getClassLoader"), new RuntimePermission("defineClassInPackage.org.jboss.as.test.integration.transaction.inflow"), new PropertyPermission("ts.timeout.factor", "read") ) , "jboss-permissions.xml") .addAsLibrary(jar); return rar; } /** * Based on action parameter particular ejb-jar*.xml file is added to archive. * The ejb-jar.xml defines RAR spec config property. */ public static JavaArchive getEjbDeployment(String action) { return ShrinkWrap.create(JavaArchive.class, EJB_MODULE_NAME + action + ".jar") .addClasses(TransactionInflowMdb.class) .addClasses(TransactionCheckerSingleton.class, TransactionCheckerSingletonRemote.class) .addClasses(TestXAResource.class) .addAsResource(TransactionInflowTestCase.class.getPackage(), "ejb-jar-" + action + ".xml", "META-INF/ejb-jar.xml") // module dependency on rar is added because we want to share class of TransactionInflowTextMessage // and arquillian packs this testcase class to container here and it needs to see rar classes as well .addAsManifestResource(new StringAsset("Dependencies: deployment." + TransactionInflowMdb.RESOURCE_ADAPTER_NAME+ ".rar\n"), "MANIFEST.MF") .addAsManifestResource(createPermissionsXmlAsset( new RuntimePermission("accessDeclaredMembers"), new SocketPermission("*", "resolve") // #getXid calls InetAddress#getLocalHost ) , "jboss-permissions.xml"); } @Deployment(name = EJB_MODULE_NAME + COMMIT, managed = false, testable = false) public static JavaArchive getCommitDeployment() { return getEjbDeployment(COMMIT); } @Deployment(name = EJB_MODULE_NAME + ROLLBACK, managed = false, testable = false) public static JavaArchive getRollbackDeployment() { return getEjbDeployment(ROLLBACK); } @After public void cleanUp() { deployer.undeploy(EJB_MODULE_NAME + COMMIT); deployer.undeploy(EJB_MODULE_NAME + ROLLBACK); } @Test public void inflowTransactionCommit() throws NamingException { deployer.deploy(EJB_MODULE_NAME + COMMIT); TransactionCheckerSingletonRemote checker = getSingletonChecker(EJB_MODULE_NAME + COMMIT); try { Assert.assertEquals("Expecting one message was passed from RAR to MDB", 1, checker.getMessages().size()); Assert.assertEquals("Expecting message with the content was passed from RAR to MDB", TransactionInflowResourceAdapter.MSG, checker.getMessages().iterator().next()); Assert.assertEquals("Two XAResources were enlisted thus expected to be prepared", 2, checker.getPrepared()); Assert.assertEquals("Two XAResources are expected to be committed", 2, checker.getCommitted()); Assert.assertEquals("Two XAResources were were committed thus not rolled-back", 0, checker.getRolledback()); } finally { checker.resetAll(); } } @Test public void inflowTransactionRollback() throws NamingException { deployer.deploy(EJB_MODULE_NAME + ROLLBACK); TransactionCheckerSingletonRemote checker = getSingletonChecker(EJB_MODULE_NAME + ROLLBACK); try { Assert.assertEquals("Expecting one message was passed from RAR to MDB", 1, checker.getMessages().size()); Assert.assertEquals("Expecting message with the content was passed from RAR to MDB", TransactionInflowResourceAdapter.MSG, checker.getMessages().iterator().next()); Assert.assertEquals("Two XAResources were enlisted thus expected to be prepared", 2, checker.getPrepared()); Assert.assertEquals("Two XAResources are expected to be rolled-back", 2, checker.getRolledback()); Assert.assertEquals("Two XAResources were were rolled-bck thus not committed", 0, checker.getCommitted()); } finally { checker.resetAll(); } } private TransactionCheckerSingletonRemote getSingletonChecker(String moduleName) throws NamingException { final Hashtable<String, String> jndiProperties = new Hashtable<String, String>(); jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); final Context context = new InitialContext(jndiProperties); String ejbLookupString = Util.createRemoteEjbJndiContext("", moduleName, "", TransactionCheckerSingleton.class.getSimpleName(), TransactionCheckerSingletonRemote.class.getName(), false); TransactionCheckerSingletonRemote checker = (TransactionCheckerSingletonRemote) context.lookup(ejbLookupString); return checker; } }
8,691
48.668571
126
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/inflow/TransactionInflowMdb.java
/* * JBoss, Home of Professional Open Source * Copyright 2016, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt 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.jboss.as.test.integration.transaction.inflow; import jakarta.annotation.Resource; import jakarta.ejb.EJB; import jakarta.jms.JMSException; import jakarta.jms.Message; import jakarta.jms.MessageListener; import jakarta.transaction.Status; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import org.jboss.as.test.integration.transactions.TestXAResource; import org.jboss.as.test.integration.transactions.TransactionCheckerSingleton; import org.jboss.ejb3.annotation.ResourceAdapter; import org.jboss.logging.Logger; /** * MDB bound to resource adapter deployed in test. * * @author Ondrej Chaloupka <[email protected]> */ // @MessageDriven is defined in ejb-jar.xml @ResourceAdapter(TransactionInflowMdb.RESOURCE_ADAPTER_NAME + ".rar") public class TransactionInflowMdb implements MessageListener { private static final Logger log = Logger.getLogger(TransactionInflowMdb.class); public static final String RESOURCE_ADAPTER_NAME = "inflow-txn-ra"; @EJB private TransactionCheckerSingleton checker; @Resource(lookup = "java:/TransactionManager") private TransactionManager transactionManager; public void onMessage(Message msg) { String text = getText(msg); log.tracef("%s.onMessage with message: %s[%s]", this.getClass().getSimpleName(), text, msg); try { Transaction tx = transactionManager.getTransaction(); if (tx == null || tx.getStatus() != Status.STATUS_ACTIVE) { log.error("Test method called without an active transaction!"); throw new IllegalStateException("Test method called without an active transaction!"); } } catch (SystemException e) { log.error("Cannot get the current transaction!", e); throw new RuntimeException("Cannot get the current transaction!", e); } enlistXAResource(); enlistXAResource(); checker.addMessage(text); log.tracef("Message '%s' processed", text); } protected void enlistXAResource() { log.trace(this.getClass().getSimpleName() + ".enlistXAResource()"); try { TestXAResource testXAResource = new TestXAResource(checker); transactionManager.getTransaction().enlistResource(testXAResource); } catch (Exception e) { log.error("Could not enlist TestXAResourceUnique", e); throw new IllegalStateException("Could not enlist TestXAResourceUnique", e); } } private String getText(Message msg) { try { return ((TransactionInflowTextMessage) msg).getText(); } catch (JMSException e) { throw new RuntimeException("Can't get text from message: " + msg, e); } } }
3,856
38.357143
101
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/inflow/TransactionInflowRaSpec.java
/* * JBoss, Home of Professional Open Source * Copyright 2016, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt 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.jboss.as.test.integration.transaction.inflow; import jakarta.resource.ResourceException; import jakarta.resource.spi.ActivationSpec; import jakarta.resource.spi.InvalidPropertyException; import jakarta.resource.spi.ResourceAdapter; /** * Mock spec rar class. Referred in ra.xml. * * @author Ondrej Chaloupka <[email protected]> */ public class TransactionInflowRaSpec implements ActivationSpec { private volatile ResourceAdapter resourceAdapter; private volatile String action; @Override public ResourceAdapter getResourceAdapter() { return resourceAdapter; } @Override public void setResourceAdapter(ResourceAdapter ra) throws ResourceException { this.resourceAdapter = ra; } @Override public void validate() throws InvalidPropertyException { // everything ok } public String getAction() { return action; } public void setAction(String action) { this.action = action; } @Override public String toString() { return String.format("%s <rar = %s, action = %s> [%s]", TransactionInflowRaSpec.class.getName(), resourceAdapter, action, super.toString()); } }
2,229
31.318841
96
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/transaction/inflow/TransactionInflowXid.java
/* * JBoss, Home of Professional Open Source * Copyright 2016, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt 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.jboss.as.test.integration.transaction.inflow; import java.net.Inet4Address; import java.util.Arrays; import java.util.Random; import javax.transaction.xa.Xid; /** * Test {@link Xid} implementation. * * @author Ondrej Chaloupka <[email protected]> */ class TransactionInflowXid implements Xid { private static byte[] localIP = null; private static int txnUniqueID = 0; public int formatId; public byte[] gtrid; public byte[] bqual; public byte[] getGlobalTransactionId() { return gtrid; } public byte[] getBranchQualifier() { return bqual; } public int getFormatId() { return formatId; } private TransactionInflowXid(int formatId, byte[] gtrid, byte[] bqual) { this.formatId = formatId; this.gtrid = gtrid; this.bqual = bqual; } public String toString() { int hexVal; StringBuffer sb = new StringBuffer(512); sb.append("formatId=" + formatId); sb.append(" gtrid(" + gtrid.length + ")={0x"); for (int i = 0; i < gtrid.length; i++) { hexVal = gtrid[i] & 0xFF; if (hexVal < 0x10) sb.append("0" + Integer.toHexString(gtrid[i] & 0xFF)); else sb.append(Integer.toHexString(gtrid[i] & 0xFF)); } sb.append("} bqual(" + bqual.length + ")={0x"); for (int i = 0; i < bqual.length; i++) { hexVal = bqual[i] & 0xFF; if (hexVal < 0x10) sb.append("0" + Integer.toHexString(bqual[i] & 0xFF)); else sb.append(Integer.toHexString(bqual[i] & 0xFF)); } sb.append("}"); return sb.toString(); } /** * Returns a globally unique transaction id. * * Xid "number" is based on provided tid argument, * inet local host address, static counter of generated ids * and a random int number. * * Xid format is static value 4660. */ static Xid getUniqueXid(int tid) { Random rnd = new Random(System.currentTimeMillis()); txnUniqueID++; int txnUID = txnUniqueID; int tidID = tid; int randID = rnd.nextInt(); return getXid(txnUID, tidID, randID); } /** * Returns a transaction id which is based on tid * calculated the same all the time. * * Variables which are part of the calculation * are inet local host address. * * Xid format is static value 4660. */ static Xid getStableXid(int tid) { int txnUID = 0; int tidID = tid; int answerToEverythingID = 42; return getXid(txnUID, tidID, answerToEverythingID); } private static Xid getXid(int txnUID, int tidID, int quaziRandID) { byte[] gtrid = new byte[64]; byte[] bqual = new byte[64]; if (null == localIP) { try { localIP = Inet4Address.getLocalHost().getAddress(); } catch (Exception ex) { localIP = new byte[] { 0x01, 0x02, 0x03, 0x04 }; } } // global transaction qualifier System.arraycopy(localIP, 0, gtrid, 0, 4); // branch transaction qualifier System.arraycopy(localIP, 0, bqual, 0, 4); for (int i = 0; i <= 3; i++) { gtrid[i + 4] = (byte) (txnUID % 0x100); bqual[i + 4] = (byte) (txnUID % 0x100); txnUID >>= 8; gtrid[i + 8] = (byte) (tidID % 0x100); bqual[i + 8] = (byte) (tidID % 0x100); tidID >>= 8; gtrid[i + 12] = (byte) (quaziRandID % 0x100); bqual[i + 12] = (byte) (quaziRandID % 0x100); quaziRandID >>= 8; } return new TransactionInflowXid(0x1234, gtrid, bqual); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(bqual); result = prime * result + formatId; result = prime * result + Arrays.hashCode(gtrid); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TransactionInflowXid other = (TransactionInflowXid) obj; if (!Arrays.equals(bqual, other.bqual)) return false; if (formatId != other.formatId) return false; if (!Arrays.equals(gtrid, other.gtrid)) return false; return true; } }
5,652
30.232044
76
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/elytron/ElytronDomainTestCase.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.elytron; import static org.junit.Assert.assertEquals; import java.net.URL; 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.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.servlets.SimpleSecuredServlet; import org.jboss.as.test.integration.security.common.servlets.SimpleServlet; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.PropertyFileBasedDomain; import org.wildfly.test.security.common.elytron.UndertowDomainMapper; /** * Smoke test for web application authentication using Elytron. * <p> * Configuration: The {@link SecurityDomainsSetup} server setup task creates a new Elytron domain backed by a PropertyRealm and * maps Undertow application domain (referenced as &lt;security-domain&gt; from {@code jboss-web.xml}) to it. * * @author Josef Cacek */ @RunWith(Arquillian.class) @ServerSetup({ ElytronDomainTestCase.SecurityDomainsSetup.class }) @RunAsClient public class ElytronDomainTestCase { private static final String NAME = ElytronDomainTestCase.class.getSimpleName(); /** * Creates WAR with a secured servlet and BASIC authentication configured in web.xml deployment descriptor. */ @Deployment(testable = false) public static WebArchive createDeployment() { return ShrinkWrap.create(WebArchive.class, NAME + ".war").addClasses(SimpleSecuredServlet.class, SimpleServlet.class) .addAsWebInfResource(new StringAsset("<web-app>\n" + // " <login-config><auth-method>BASIC</auth-method><realm-name>Test realm</realm-name></login-config>\n" + // "</web-app>"), "web.xml") .addAsWebInfResource(new StringAsset("<jboss-web>\n" + // " <security-domain>" + NAME + "</security-domain>\n" + // "</jboss-web>"), "jboss-web.xml"); } /** * Tests successful authentication and authorization. */ @Test public void testAuthnAuthz(@ArquillianResource URL url) throws Exception { final URL servletUrl = new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1)); // successful authentication and authorization assertEquals("Response body is not correct.", SimpleSecuredServlet.RESPONSE_BODY, Utils.makeCallWithBasicAuthn(servletUrl, "elytron1", "password", 200)); } /** * Tests successful authentication and failed authorization. */ @Test public void testAuthnNoAuthz(@ArquillianResource URL url) throws Exception { final URL servletUrl = new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1)); // successful authentication and authorization assertEquals("Response body is not correct.", SimpleSecuredServlet.RESPONSE_BODY, Utils.makeCallWithBasicAuthn(servletUrl, "elytron1", "password", 200)); // successful authentication and unsuccessful authorization Utils.makeCallWithBasicAuthn(servletUrl, "elytron2", "password", 403); // wrong password Utils.makeCallWithBasicAuthn(servletUrl, "elytron1", "pass", 401); Utils.makeCallWithBasicAuthn(servletUrl, "elytron2", "pass", 401); // no such user Utils.makeCallWithBasicAuthn(servletUrl, "elytron3", "pass", 401); } /** * Tests unsuccessful authentication. */ @Test public void testNoAuthn(@ArquillianResource URL url) throws Exception { final URL servletUrl = new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1)); // wrong password Utils.makeCallWithBasicAuthn(servletUrl, "elytron1", "pass", 401); Utils.makeCallWithBasicAuthn(servletUrl, "elytron2", "pass", 401); // no such user Utils.makeCallWithBasicAuthn(servletUrl, "elytron3", "pass", 401); } /** * Create properties-file backed Elytron domain with 2 users and mapping in Undertow. */ static class SecurityDomainsSetup extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { return new ConfigurableElement[] { PropertyFileBasedDomain.builder().withName(NAME) .withUser("elytron1", "password", SimpleSecuredServlet.ALLOWED_ROLE).withUser("elytron2", "password") .build(), UndertowDomainMapper.builder().withName(NAME).build() }; } } }
6,074
44
131
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/agroal/Datasource.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, 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.agroal; /** * @author <a href="mailto:[email protected]">Ondra Chaloupka</a> */ public final class Datasource { private String name, jndiName, driverName, driverModule, connectionUrl, userName, password, driverClass; private int minSize, initialSize, maxSize, blockingTimeout; private Datasource(Builder builder) { this.name = builder.datasourceName; this.jndiName = builder.jndiName; this.driverName = builder.driverName; this.driverModule = builder.driverModule; this.connectionUrl = builder.connectionUrl; this.userName = builder.userName; this.password = builder.password; this.driverClass = builder.driverClass; this.minSize = builder.minSize; this.initialSize = builder.initialSize; this.maxSize = builder.maxSize; this.blockingTimeout = builder.blockingTimeout; } public static Builder Builder(String datasourceName) { return new Builder(datasourceName); } public String getName() { return name; } public String getJndiName() { return jndiName; } public String getDriverName() { return driverName; } public String getDriverModule() { return driverModule; } public String getDriverClass() { return driverClass; } public String getConnectionUrl() { return connectionUrl; } public String getUserName() { return userName; } public String getPassword() { return password; } public int getMinSize() { return minSize; } public int getInitialSize() { return initialSize; } public int getMaxSize() { return maxSize; } public int getBlockingTimeout() { return blockingTimeout; } @Override public String toString() { return String.format("Datasource name: %s, jndi: %s, driver name: %s, driverModule %s, url: %s, user name: %s, password: %s, datasource-class: %s", name, jndiName, driverName, driverModule, connectionUrl, userName, password, driverClass); } public static final class Builder { private final String datasourceName; private String jndiName; private String driverName = System.getProperty("ds.jdbc.driver"); private String driverModule = System.getProperty("ds.jdbc.driver.module"); private String driverClass = System.getProperty("ds.jdbc.driver.class"); private String connectionUrl = System.getProperty("ds.jdbc.url"); private String userName = System.getProperty("ds.jdbc.user"); private String password = System.getProperty("ds.jdbc.pass"); private int minSize, initialSize, maxSize, blockingTimeout; private Builder(String datasourceName) { this.datasourceName = datasourceName; this.jndiName = "java:jboss/datasources/" + datasourceName; if (this.driverName == null) { driverName = "h2"; } if (this.driverModule == null) { driverModule = "com.h2database.h2"; } if (this.driverClass == null) { driverClass = "org.h2.jdbcx.JdbcDataSource"; } if (this.connectionUrl == null) { connectionUrl = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"; } if (this.userName == null) { userName = "sa"; } if (this.password == null) { password = "sa"; } maxSize = 10; } public Builder jndiName(String jndiName) { this.jndiName = jndiName; return this; } public Builder driverName(String driverName) { this.driverName = driverName; return this; } public Builder driverModule(String driverModule) { this.driverModule = driverModule; return this; } public Builder driverClass(String driverClass) { this.driverClass = driverClass; return this; } public Builder connectionUrl(String connectionUrl) { this.connectionUrl = connectionUrl; return this; } public Builder userName(String userName) { this.userName = userName; return this; } public Builder password(String password) { this.password = password; return this; } public Builder minSize(int minSize) { this.minSize = minSize; return this; } public Builder initialSize(int initialSize) { this.initialSize = initialSize; return this; } public Builder maxSize(int maxSize) { this.maxSize = maxSize; return this; } public Builder blockingTimeout(int blockingTimeout) { this.blockingTimeout = blockingTimeout; return this; } public Datasource build() { return new Datasource(this); } } }
6,240
29.593137
155
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/agroal/XADatasourceTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, 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.agroal; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.junit.runner.RunWith; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; /** * Running tests from {@link AgroalDatasourceTestBase} with standard non-XA datasource. * * @author <a href="mailto:[email protected]>Ondra Chaloupka</a> * @author <a href="mailto:[email protected]>Luis Barreiro</a> */ @RunWith(Arquillian.class) @RunAsClient public class XADatasourceTestCase extends AgroalDatasourceTestBase { private static final Logger log = Logger.getLogger(AgroalDatasourceTestBase.class); @Override protected ModelNode createDataSource(Datasource datasource) throws Exception { ModelNode address = getDataSourceAddress(datasource); ModelNode operation = getDataSourceOperation(address); operation.get("jndi-name").set(datasource.getJndiName()); operation.get("connection-factory").set(getConnectionFactoryObject(datasource)); operation.get("connection-pool").set(getConnectionPoolObject(datasource)); executeOperation(operation); return address; } @Override protected void removeDataSourceSilently(Datasource datasource) throws Exception { if (datasource == null || datasource.getName() == null) { return; } ModelNode address = getDataSourceAddress(datasource); try { ModelNode removeOperation = Operations.createRemoveOperation(address); removeOperation.get(ModelDescriptionConstants.OPERATION_HEADERS).get("allow-resource-service-restart").set(true); executeOperation(removeOperation); } catch (MgmtOperationException e) { log.debugf(e, "Can't remove datasource at address '%s': %s", address, e.getResult().get(FAILURE_DESCRIPTION)); } } @Override protected ModelNode getDataSourceAddress(Datasource datasource) { ModelNode address = new ModelNode().add(SUBSYSTEM, DATASOURCES_SUBSYSTEM).add("xa-datasource", datasource.getName()); address.protect(); return address; } @Override protected void testConnection(Datasource datasource) throws Exception { testConnectionBase(datasource.getName(), "xa-datasource"); } }
3,779
39.645161
125
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/agroal/AgroalDatasourceTestBase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, 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.agroal; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import static org.jboss.as.controller.client.helpers.Operations.*; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.*; /** * A basic testing of getting a connection from an agroal datasource. * * @author <a href="mailto:[email protected]">Luis Barreiro</a> */ @ServerSetup(AgroalDatasourceTestBase.SubsystemSetupTask.class) public abstract class AgroalDatasourceTestBase extends ContainerResourceMgmtTestBase { private static final Logger log = Logger.getLogger(AgroalDatasourceTestBase.class); protected static final String AGROAL_EXTENTION = "org.wildfly.extension.datasources-agroal"; protected static final String DATASOURCES_SUBSYSTEM = "datasources-agroal"; private static String wrapProp(String propertyName) { return String.format("${%s}", propertyName); } public static class SubsystemSetupTask extends SnapshotRestoreSetupTask { @Override protected void doSetup(final ManagementClient client, final String containerId) throws Exception { final CompositeOperationBuilder builder = CompositeOperationBuilder.create(); ModelNode extensionOp = new ModelNode(); extensionOp.get(OP_ADDR).set(new ModelNode().setEmptyList()).add(EXTENSION, AGROAL_EXTENTION); extensionOp.get(OP).set(ADD); builder.addStep(extensionOp); ModelNode subsystemOp = new ModelNode(); subsystemOp.get(OP_ADDR).set(SUBSYSTEM, DATASOURCES_SUBSYSTEM); subsystemOp.get(OP).set(ADD); builder.addStep(subsystemOp); executeOperation(client, builder.build()); // Reload before continuing ServerReload.executeReloadAndWaitForCompletion(client, TimeoutUtil.adjust(50000)); } private void executeOperation(final ManagementClient client, final Operation op) throws IOException { final ModelNode result = client.getControllerClient().execute(op); if (!isSuccessfulOutcome(result)) { // Throwing an exception does not seem to stop the tests from running, log the error as well for some // better details log.errorf("Failed to execute operation: %s%n%s", getFailureDescription(result).asString(), op.getOperation()); throw new RuntimeException("Failed to execute operation: " + getFailureDescription(result).asString()); } } } /* * A dummy deployment is required for a ServerSetupTask to run. */ @Deployment public static JavaArchive deployment() { return ShrinkWrap.create(JavaArchive.class, "dummy-deployment.jar") .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); } // --- // @Test public void addDatasource() throws Exception { Datasource ds = Datasource.Builder("testDatasourceEnabled").build(); try { createDriver(ds); createDataSource(ds); testConnection(ds); } finally { removeDataSourceSilently(ds); removeDriverSilently(ds); } } @Test public void allBySystemProperty() throws Exception { String url = "myds.url"; String username = "myds.username"; String password = "myds.password"; String jndiName = "myds.jndi"; Datasource ds = Datasource.Builder("testAllBySystem") .connectionUrl(wrapProp(url)) .userName(wrapProp(username)) .password(wrapProp(password)) .jndiName(wrapProp(jndiName)) .driverName("h2_ref") .build(); try { Datasource defaultPropertyDs = Datasource.Builder("temporary").build(); addSystemProperty(url, defaultPropertyDs.getConnectionUrl()); addSystemProperty(username, defaultPropertyDs.getUserName()); addSystemProperty(password, defaultPropertyDs.getPassword()); addSystemProperty(jndiName, defaultPropertyDs.getJndiName()); createDriver(ds); createDataSource(ds); testConnection(ds); } finally { removeDataSourceSilently(ds); removeDriverSilently(ds); removeSystemPropertySilently(url); removeSystemPropertySilently(username); removeSystemPropertySilently(password); removeSystemPropertySilently(jndiName); } } // --- // /* * Abstract methods overridden in test subclasses */ protected abstract ModelNode createDataSource(Datasource datasource) throws Exception; protected abstract void removeDataSourceSilently(Datasource datasource) throws Exception; protected abstract ModelNode getDataSourceAddress(Datasource datasource); protected abstract void testConnection(Datasource datasource) throws Exception; /** * Common attribute for add datasource operation for non-XA and XA datasource creation. */ protected ModelNode getDataSourceOperation(ModelNode address) { ModelNode operation = new ModelNode(); operation.get(OP).set(ADD); operation.get(OP_ADDR).set(address); return operation; } protected ModelNode getConnectionFactoryObject( Datasource datasource) { ModelNode factoryObject = new ModelNode(); factoryObject.get("driver").set(datasource.getDriverName()); factoryObject.get("url").set(datasource.getConnectionUrl()); factoryObject.get("username").set(datasource.getUserName()); factoryObject.get("password").set(datasource.getPassword()); return factoryObject; } protected ModelNode getConnectionPoolObject(Datasource datasource) { ModelNode poolObject = new ModelNode(); poolObject.get("min-size").set(datasource.getMinSize()); poolObject.get("initial-size").set(datasource.getInitialSize()); poolObject.get("max-size").set(datasource.getMaxSize()); poolObject.get("blocking-timeout").set(datasource.getBlockingTimeout()); return poolObject; } protected void createDriver(Datasource datasource) throws Exception { ModelNode address = new ModelNode().add(SUBSYSTEM, DATASOURCES_SUBSYSTEM).add("driver", datasource.getDriverName()); address.protect(); ModelNode driverOp = new ModelNode(); driverOp.get(OP).set(ADD); driverOp.get(OP_ADDR).set(address); driverOp.get("module").set(datasource.getDriverModule()); if (datasource.getDriverClass() != null) { driverOp.get("class").set(datasource.getDriverClass()); } try { executeOperation(driverOp); } catch (MgmtOperationException e) { Assert.fail(String.format( "Can't add driver '%s' by cli: %s", DATASOURCES_SUBSYSTEM, e.getResult().get(FAILURE_DESCRIPTION))); } } protected void removeDriverSilently(Datasource datasource) throws Exception { if (datasource == null || datasource.getDriverName() == null) { return; } ModelNode address = new ModelNode().add(SUBSYSTEM, DATASOURCES_SUBSYSTEM).add("driver", datasource.getDriverName()); address.protect(); try { ModelNode removeOperation = createRemoveOperation(address); removeOperation.get(ModelDescriptionConstants.OPERATION_HEADERS).get("allow-resource-service-restart").set(true); executeOperation(removeOperation); } catch (MgmtOperationException e) { log.warnf(e, "Can't remove driver at address '%s': %s", datasource.getDriverName(), e.getResult().get(FAILURE_DESCRIPTION)); } } // --- // protected void testConnectionBase(String dsName, String type) throws Exception { ModelNode address = new ModelNode(); address.add(SUBSYSTEM, DATASOURCES_SUBSYSTEM); address.add(type, dsName); address.protect(); ModelNode operation = new ModelNode(); operation.get(OP).set("test-connection"); operation.get(OP_ADDR).set(address); executeOperation(operation); } // --- // protected ModelNode readAttribute(ModelNode address, String attribute) throws Exception { ModelNode operation = new ModelNode(); operation.get(OP).set("read-attribute"); operation.get(NAME).set(attribute); operation.get(OP_ADDR).set(address); return executeOperation(operation); } protected ModelNode writeAttribute(ModelNode address, String attribute, String value) throws Exception { final ModelNode operation = new ModelNode(); operation.get(OP_ADDR).set(address); operation.get(OP).set("write-attribute"); operation.get("name").set(attribute); operation.get("value").set(value); return executeOperation(operation); } // --- // private ModelNode addSystemProperty(String name, String value) throws IOException, MgmtOperationException { ModelNode address = new ModelNode().add(SYSTEM_PROPERTY, name); address.protect(); ModelNode operation = new ModelNode(); operation.get(OP_ADDR).set(address); operation.get(OP).set(ADD); operation.get(VALUE).set(value); return executeOperation(operation); } protected void removeSystemPropertySilently(String name) { if (name == null) { return; } try { ModelNode address = new ModelNode().add(SYSTEM_PROPERTY, name); address.protect(); remove(address); } catch (Exception e) { log.warnf("Can't remove system property '%s' by cli: %s", name, e.getMessage()); } } }
11,880
38.735786
139
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/agroal/DatasourceTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, 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.agroal; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.junit.runner.RunWith; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; /** * Running tests from {@link AgroalDatasourceTestBase} with standard non-XA datsource. * * @author <a href="mailto:[email protected]>Ondra Chaloupka</a> * @author <a href="mailto:[email protected]>Luis Barreiro</a> */ @RunWith(Arquillian.class) @RunAsClient public class DatasourceTestCase extends AgroalDatasourceTestBase { private static final Logger log = Logger.getLogger(AgroalDatasourceTestBase.class); @Override protected ModelNode createDataSource(Datasource datasource) throws Exception { ModelNode address = getDataSourceAddress(datasource); ModelNode operation = getDataSourceOperation(address); operation.get("jndi-name").set(datasource.getJndiName()); operation.get("connection-factory").set(getConnectionFactoryObject(datasource)); operation.get("connection-pool").set(getConnectionPoolObject(datasource)); executeOperation(operation); return address; } @Override protected void removeDataSourceSilently(Datasource datasource) { if (datasource == null || datasource.getName() == null) { return; } ModelNode address = getDataSourceAddress(datasource); try { ModelNode removeOperation = Operations.createRemoveOperation(address); removeOperation.get(ModelDescriptionConstants.OPERATION_HEADERS).get("allow-resource-service-restart").set(true); executeOperation(removeOperation); } catch (Exception e) { log.debugf(e, "Can't remove datasource at address '%s'", address); } } @Override protected ModelNode getDataSourceAddress(Datasource datasource) { ModelNode address = new ModelNode().add(SUBSYSTEM, DATASOURCES_SUBSYSTEM).add("datasource", datasource.getName()); address.protect(); return address; } @Override protected void testConnection(Datasource datasource) throws Exception { testConnectionBase(datasource.getName(), "datasource"); } }
3,521
37.703297
125
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/health/HealthSecuredHTTPEndpointTestCase.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.health; import static org.junit.Assert.assertEquals; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; 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.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.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(HealthSecuredHTTPEndpointSetupTask.class) public class HealthSecuredHTTPEndpointTestCase { @ContainerResource ManagementClient managementClient; @Deployment public static Archive<?> deployment() { final Archive<?> deployment = ShrinkWrap.create(JavaArchive.class, "HealthSecuredHTTPEndpointTestCase.jar") .addClasses(HealthSecuredHTTPEndpointSetupTask.class); return deployment; } @Test public void securedHTTPEndpointWithoutUserDefined() throws Exception { final String healthURL = "http://" + managementClient.getMgmtAddress() + ":" + managementClient.getMgmtPort() + "/health"; try (CloseableHttpClient client = HttpClients.createDefault()) { CloseableHttpResponse resp = client.execute(new HttpGet(healthURL)); assertEquals(401, resp.getStatusLine().getStatusCode()); resp.close(); } } @Test public void securedHTTPEndpoint() throws Exception { final String healthURL = "http://" + managementClient.getMgmtAddress() + ":" + managementClient.getMgmtPort() + "/health"; try (CloseableHttpClient client = HttpClients.createDefault()) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("testSuite", "testSuitePassword")); HttpClientContext hcContext = HttpClientContext.create(); hcContext.setCredentialsProvider(credentialsProvider); CloseableHttpResponse resp = client.execute(new HttpGet(healthURL), hcContext); assertEquals(200, resp.getStatusLine().getStatusCode()); resp.close(); } } }
4,003
41.595745
130
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/health/EmptyMgmtUsersSetupTask.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.health; import java.io.File; import java.nio.file.Files; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; public class EmptyMgmtUsersSetupTask implements ServerSetupTask { static File mgmtUsersFile; byte[] bytes; static { String jbossHome = System.getProperty("jboss.home", null); if (jbossHome == null) { throw new IllegalStateException("jboss.home not set"); } mgmtUsersFile = new File(jbossHome + File.separatorChar + "standalone" + File.separatorChar + "configuration" + File.separatorChar + "mgmt-users.properties"); if (!mgmtUsersFile.exists()) { throw new IllegalStateException("Determined mgmt-users.properties path " + mgmtUsersFile + " does not exist"); } if (!mgmtUsersFile.isFile()) { throw new IllegalStateException("Determined mgmt-users.properties path " + mgmtUsersFile + " is not a file"); } } @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { bytes = Files.readAllBytes(mgmtUsersFile.toPath()); Files.write(mgmtUsersFile.toPath(), "".getBytes()); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { Files.write(mgmtUsersFile.toPath(), bytes); } }
2,484
38.444444
122
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/health/HealthHTTPEndpointTestCase.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.health; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.apache.http.client.methods.CloseableHttpResponse; 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.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.dmr.ModelNode; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2018 Red Hat inc. */ @RunWith(Arquillian.class) @RunAsClient public class HealthHTTPEndpointTestCase { @ContainerResource ManagementClient managementClient; @Test public void testHealthEndpoint() throws Exception { testHealthEndpoint("/health", 200); } @Test public void testHealthLiveEndpoint() throws Exception { testHealthEndpoint("/health/live", 200); } @Test public void testHealthReadyEndpoint() throws Exception { testHealthEndpoint("/health/ready", 200); } /** * Test that when a server is suspended, its readiness probe starts to fail (until it is resumed). * Test also that suspending a server has no impact on its liveness probe. * @throws Exception */ @Test public void testHealthReadyEndpointWhenServerIsSuspended() throws Exception { // server is live testHealthEndpoint("/health/live", 200); // and ready testHealthEndpoint("/health/ready", 200); // suspend the server changeSuspendState("suspend"); // server is still live testHealthEndpoint("/health/live", 200); // but no longer ready testHealthEndpoint("/health/ready", 503); // resume the server changeSuspendState("resume"); // server is still live testHealthEndpoint("/health/live", 200); // and ready again testHealthEndpoint("/health/ready", 200); } private void testHealthEndpoint(String requestPath, int expectedStatusCode) throws IOException { final String healthURL = "http://" + managementClient.getMgmtAddress() + ":" + managementClient.getMgmtPort() + requestPath; try (CloseableHttpClient client = HttpClientBuilder.create().build()) { CloseableHttpResponse resp = client.execute(new HttpGet(healthURL)); String content = EntityUtils.toString(resp.getEntity()); assertEquals(expectedStatusCode, resp.getStatusLine().getStatusCode()); resp.close(); } } private void changeSuspendState(String operation) throws IOException { final ModelNode op = Operations.createOperation(operation, new ModelNode().add("")); managementClient.getControllerClient().execute(op); } }
4,129
35.875
132
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/health/HealthSecuredHTTPEndpointSetupTask.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.health; 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 HealthSecuredHTTPEndpointSetupTask implements ServerSetupTask { @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { final ModelNode address = Operations.createAddress("subsystem", "health"); final ModelNode op = Operations.createWriteAttributeOperation(address, "security-enabled", true ); managementClient.getControllerClient().execute(op); ServerReload.reloadIfRequired(managementClient); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { final ModelNode address = Operations.createAddress("subsystem", "health"); final ModelNode op = Operations.createWriteAttributeOperation(address, "security-enabled", false ); managementClient.getControllerClient().execute(op); ServerReload.reloadIfRequired(managementClient); } }
2,252
43.176471
107
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/web/VirtualHostTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, 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.web; import static org.jboss.as.controller.client.helpers.ClientConstants.OUTCOME; import static org.jboss.as.controller.client.helpers.ClientConstants.SUCCESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS; import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode; import java.io.IOException; import java.net.InetAddress; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; 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.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; 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.Assume; import org.junit.Test; import org.junit.runner.RunWith; /** * Test that default-web-module works as it should for scenarios: * - default host on of single server * - non-default host of single server * - non default server * * @author Tomaz Cerar (c) 2015 Red Hat Inc. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(VirtualHostTestCase.VirtualHostSetupTask.class) //todo this test could probably be done in manual mode test with wildfly runner public class VirtualHostTestCase { @ContainerResource private ManagementClient managementClient; public static class VirtualHostSetupTask extends SnapshotRestoreSetupTask { @Override public void doSetup(ManagementClient managementClient, String containerId) throws Exception { ModelControllerClient client = managementClient.getControllerClient(); ModelNode addOp = createOpNode("subsystem=undertow/server=default-server/host=test", "add"); addOp.get("default-web-module").set("test.war"); addOp.get("alias").add(TestSuiteEnvironment.getServerAddress()); //either 127.0.0.1 or ::1 execute(client, addOp); addOp = createOpNode("socket-binding-group=standard-sockets/socket-binding=myserver", "add"); addOp.get("port").set(8181); execute(client, addOp); addOp = createOpNode("subsystem=undertow/server=myserver", "add"); addOp.get("default-host").set("another"); execute(client, addOp); addOp = createOpNode("subsystem=undertow/server=myserver/host=another", "add"); addOp.get("default-web-module").set("another-server.war"); execute(client, addOp); addOp = createOpNode("subsystem=undertow/server=myserver/http-listener=myserver", "add"); addOp.get("socket-binding").set("myserver"); execute(client, addOp); //this one is runtime addable } private void execute(ModelControllerClient client, ModelNode op) throws IOException { op.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true); ModelNode response = client.execute(op); if (!SUCCESS.equals(response.get(OUTCOME).asString())) { Assert.fail("Could not execute op: '" + op + "', result: " + response); } } } private static WebArchive createDeployment(String name) { WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war"); war.addAsWebResource(new StringAsset(name), "index.html"); return war; } @Deployment(name = "ROOT") public static Archive<?> getDefaultHostDeployment() { return createDeployment("ROOT"); } @Deployment(name = "test") public static Archive<?> getAnotherHostDeployment() { return createDeployment("test"); } @Deployment(name = "another-server") public static Archive<?> getAnotherServerDeployment() { return createDeployment("another-server"); } @Deployment(name = "default-common") public static Archive<?> getDefaultHostCommonDeployment() { return createDeployment("default-common"); } @Deployment(name = "another-common") public static Archive<?> getAnotherHostCommonDeployment() { WebArchive war = createDeployment("another-common"); war.addAsWebResource(new StringAsset("<jboss-web><server-instance>myserver</server-instance><virtual-host>another</virtual-host></jboss-web>"), "WEB-INF/jboss-web.xml"); return war; } private void callAndTest(String uri, String expectedResult) throws IOException { HttpClient client = HttpClients.createDefault(); HttpGet get = new HttpGet(uri); HttpResponse response = client.execute(get); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String result = EntityUtils.toString(response.getEntity()); Assert.assertEquals("Got response from wrong deployment", expectedResult, result); } private void checkUndertowInfo(String app, String server, String host, String context) throws IOException, MgmtOperationException { ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, app) .add(ModelDescriptionConstants.SUBSYSTEM, "undertow"); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); op.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set("true"); ModelNode result = managementClient.getControllerClient().execute(op); Assert.assertTrue("Undertow info OK for " + app, Operations.isSuccessfulOutcome(result)); Assert.assertEquals("context-root is set to " + context + " for " + app, context, result.get("result").get("context-root").asString()); Assert.assertEquals("virtual-host is set to " + host + " for " + app, host, result.get("result").get("virtual-host").asString()); Assert.assertEquals("server is set to " + server + " for " + app, server, result.get("result").get("server").asString()); } @Test public void testDefaultHost() throws IOException, MgmtOperationException { Assume.assumeTrue("This needs to be localhost, as it is by host mapping", InetAddress.getByName(TestSuiteEnvironment.getServerAddress()).isLoopbackAddress()); callAndTest("http://localhost:8080/", "ROOT"); checkUndertowInfo("ROOT.war", "default-server", "default-host", "/"); } @Test public void testNonDefaultHost() throws IOException, MgmtOperationException { callAndTest("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/", "test"); //second host on first server has alias 127.0.0.1 or ::1 checkUndertowInfo("test.war", "default-server", "test", "/"); } @Test public void testAnotherServerHost() throws IOException, MgmtOperationException { callAndTest("http://" + TestSuiteEnvironment.getServerAddress() + ":8181/", "another-server"); checkUndertowInfo("another-server.war", "myserver", "another", "/"); } @Test public void testDefaultHostCommonAplication() throws IOException, MgmtOperationException { Assume.assumeTrue("This needs to be localhost, as it is by host mapping", InetAddress.getByName(TestSuiteEnvironment.getServerAddress()).isLoopbackAddress()); callAndTest("http://localhost:8080/default-common/", "default-common"); checkUndertowInfo("default-common.war", "default-server", "default-host", "/default-common"); } @Test public void testAnotherHostCommonAplication() throws IOException, MgmtOperationException { callAndTest("http://" + TestSuiteEnvironment.getServerAddress() + ":8181/another-common/", "another-common"); checkUndertowInfo("another-common.war", "myserver", "another", "/another-common"); } }
9,723
46.901478
177
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/web/annotationsmodule/EarModuleDeploymentTestCase.java
/* * Copyright 2020 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.web.annotationsmodule; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; 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.test.api.ArquillianResource; import org.jboss.jandex.Index; import org.jboss.jandex.IndexWriter; import org.jboss.jandex.Indexer; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.ByteArrayAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URL; import static org.junit.Assert.assertEquals; @RunWith(Arquillian.class) public class EarModuleDeploymentTestCase { public static final String DEPLOYMENT_1 = "deployment1"; public static final String DEPLOYMENT_2 = "deployment2"; @Deployment(name = DEPLOYMENT_1) public static EnterpriseArchive deployment() throws Exception { EnterpriseArchive enterpriseArchive = ShrinkWrap.create(EnterpriseArchive.class, DEPLOYMENT_1 + ".ear"); enterpriseArchive .addAsModule(webArchive()) .addAsModule(jarArchive("library.jar", ModuleServlet.class, TestEjb.class)) .addAsModule(jarArchive("library2.jar", ModuleServlet2.class)) .addAsManifestResource(EarModuleDeploymentTestCase.class.getResource("application1.xml"), "application.xml") .addAsManifestResource(EarModuleDeploymentTestCase.class.getResource("jboss-deployment-structure1.xml"), "jboss-deployment-structure.xml"); return enterpriseArchive; } @Deployment(name = DEPLOYMENT_2) public static EnterpriseArchive deployment2() throws Exception { EnterpriseArchive enterpriseArchive = ShrinkWrap.create(EnterpriseArchive.class, DEPLOYMENT_2 + ".ear"); enterpriseArchive .addAsModule(webArchive()) .addAsModule(jarArchive("library.jar", ModuleServlet.class, TestEjb.class)) .addAsManifestResource(EarModuleDeploymentTestCase.class.getResource("application2.xml"), "application.xml") .addAsManifestResource(EarModuleDeploymentTestCase.class.getResource("jboss-deployment-structure2.xml"), "jboss-deployment-structure.xml"); return enterpriseArchive; } public static WebArchive webArchive() { return ShrinkWrap.create(WebArchive.class, "web.war") .addClass(TestServlet.class) .addAsWebInfResource(new StringAsset(""), "beans.xml"); } public static JavaArchive jarArchive(String name, Class<?>... classes) throws Exception { JavaArchive javaArchive = ShrinkWrap.create(JavaArchive.class, name) .addAsResource(new StringAsset("<ejb-jar version=\"3.0\" metadata-complete=\"true\"></ejb-jar>"), "META-INF/ejb-jar.xml"); Indexer indexer = new Indexer(); for (Class<?> aClass : classes) { javaArchive.addClass(aClass); try (InputStream resource = aClass.getResourceAsStream(aClass.getSimpleName() + ".class")) { indexer.index(resource); } } Index index = indexer.complete(); ByteArrayOutputStream data = new ByteArrayOutputStream(); IndexWriter writer = new IndexWriter(data); writer.write(index); javaArchive.addAsManifestResource(new ByteArrayAsset(data.toByteArray()), "jandex.idx"); return javaArchive; } @ArquillianResource private URL url; @Test @OperateOnDeployment(DEPLOYMENT_1) @RunAsClient public void testServlet() throws Exception { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpGet httpget = new HttpGet(url.toExternalForm() + "/servlet"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); assertEquals(200, statusLine.getStatusCode()); String result = EntityUtils.toString(entity); assertEquals(ModuleServlet.MODULE_SERVLET, result); } } @Test @OperateOnDeployment(DEPLOYMENT_1) @RunAsClient public void testServletInAdditinalJar() throws Exception { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpGet httpget = new HttpGet(url.toExternalForm() + "/servlet2"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); assertEquals(200, statusLine.getStatusCode()); String result = EntityUtils.toString(entity); assertEquals(ModuleServlet2.MODULE_SERVLET, result); } } @Test @OperateOnDeployment(DEPLOYMENT_1) @RunAsClient public void testEjbScan() throws Exception { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpGet httpget = new HttpGet(url.toExternalForm() + "/test"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); assertEquals(200, statusLine.getStatusCode()); String result = EntityUtils.toString(entity); assertEquals(TestEjb.TEST_EJB, result); } } @Test @OperateOnDeployment(DEPLOYMENT_2) @RunAsClient public void testServletInDeployment() throws Exception { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpGet httpget = new HttpGet(url.toExternalForm() + "/servlet"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); assertEquals(200, statusLine.getStatusCode()); String result = EntityUtils.toString(entity); assertEquals(ModuleServlet.MODULE_SERVLET, result); } } @Test @OperateOnDeployment(DEPLOYMENT_2) @RunAsClient public void testEjbScanInSubdeployment() throws Exception { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpGet httpget = new HttpGet(url.toExternalForm() + "/test"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); assertEquals(200, statusLine.getStatusCode()); String result = EntityUtils.toString(entity); assertEquals(TestEjb.TEST_EJB, result); } } }
7,997
39.393939
155
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/web/annotationsmodule/ModuleServlet2.java
/* * Copyright 2020 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.web.annotationsmodule; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author Stuart Douglas */ @WebServlet(name = "ModuleServlet2", urlPatterns = "/servlet2") public class ModuleServlet2 extends HttpServlet { public static final String MODULE_SERVLET = "Module Servlet2"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write(MODULE_SERVLET); } }
1,312
32.666667
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/web/annotationsmodule/TestServlet.java
/* * Copyright 2020 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.web.annotationsmodule; import org.jboss.as.naming.InitialContext; import jakarta.annotation.Resource; import javax.naming.NamingException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet(urlPatterns = "/test") public class TestServlet extends HttpServlet { @Resource private InitialContext initialContext; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { TestEjb ejb = lookup(); try(PrintWriter writer = resp.getWriter()) { if (ejb != null) { writer.write(ejb.hello()); resp.setStatus(200); } else { resp.setStatus(500); } } } private TestEjb lookup() { try { Object lookup = InitialContext.doLookup("java:app/web/TestEjb!org.wildfly.test.integration.web.annotationsmodule.TestEjb"); return (TestEjb) lookup; } catch (NamingException e) { e.printStackTrace(); } return null; } }
1,937
31.847458
135
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/web/annotationsmodule/ModuleServlet.java
/* * Copyright 2020 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.web.annotationsmodule; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author Stuart Douglas */ @WebServlet(name = "ModuleServlet", urlPatterns = "/servlet") public class ModuleServlet extends HttpServlet { public static final String MODULE_SERVLET = "Module Servlet"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write(MODULE_SERVLET); } }
1,308
32.564103
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/web/annotationsmodule/TestEjb.java
/* * Copyright 2020 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.web.annotationsmodule; import jakarta.ejb.Stateless; @Stateless public class TestEjb { public static final String TEST_EJB = "TestEjb"; public String hello() { return TEST_EJB; } }
838
26.966667
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/jmx/rbac/JmxAccessFromNonSecuredDeploymentWithRbacUsingUserRoleMappingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, 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.jmx.rbac; 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.as.arquillian.api.ServerSetup; import org.jboss.shrinkwrap.api.Archive; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @RunAsClient @ServerSetup({JmxAccessFromNonSecuredDeploymentWithRbacUsingUserRoleMappingTestCase.RbacWithUseIdenityRolesSetup.class}) public class JmxAccessFromNonSecuredDeploymentWithRbacUsingUserRoleMappingTestCase extends AbstractJmxAccessFromDeploymentWithRbacTest { @Deployment(testable = false) public static Archive<?> deploy() { return AbstractJmxAccessFromDeploymentWithRbacTest.deploy(false); } public JmxAccessFromNonSecuredDeploymentWithRbacUsingUserRoleMappingTestCase() { super(false); } static class RbacWithUseIdenityRolesSetup extends EnableRbacSetupTask { public RbacWithUseIdenityRolesSetup() { super(false, false); } } }
2,094
41.755102
136
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/jmx/rbac/JmxAccessFromSecuredDeploymentWithRbacUsingIdentityRolesTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, 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.jmx.rbac; 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.as.arquillian.api.ServerSetup; import org.jboss.shrinkwrap.api.Archive; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @RunAsClient @ServerSetup({JmxAccessFromSecuredDeploymentWithRbacUsingIdentityRolesTestCase.RbacWithUseIdenityRolesSetup.class}) public class JmxAccessFromSecuredDeploymentWithRbacUsingIdentityRolesTestCase extends AbstractJmxAccessFromDeploymentWithRbacTest { @Deployment(testable = false) public static Archive<?> deploy() { return AbstractJmxAccessFromDeploymentWithRbacTest.deploy(true); } static class RbacWithUseIdenityRolesSetup extends AbstractJmxAccessFromDeploymentWithRbacTest.EnableRbacSetupTask { public RbacWithUseIdenityRolesSetup() { super(true, true); } } }
2,011
43.711111
131
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/jmx/rbac/JmxAccessFromSecuredDeploymentWithRbacUsingUserRoleMappingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, 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.jmx.rbac; 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.as.arquillian.api.ServerSetup; import org.jboss.shrinkwrap.api.Archive; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @RunAsClient @ServerSetup({JmxAccessFromSecuredDeploymentWithRbacUsingUserRoleMappingTestCase.RbacWithUseIdenityRolesSetup.class}) public class JmxAccessFromSecuredDeploymentWithRbacUsingUserRoleMappingTestCase extends AbstractJmxAccessFromDeploymentWithRbacTest { @Deployment(testable = false) public static Archive<?> deploy() { return AbstractJmxAccessFromDeploymentWithRbacTest.deploy(true); } static class RbacWithUseIdenityRolesSetup extends EnableRbacSetupTask { public RbacWithUseIdenityRolesSetup() { super(false, true); } } }
1,972
42.844444
133
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/jmx/rbac/AbstractJmxAccessFromDeploymentWithRbacTest.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, 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.jmx.rbac; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.controller.security.ControllerPermission; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.shared.PermissionUtils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.remoting3.security.RemotingPermission; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.wildfly.security.permission.ElytronPermission; import org.wildfly.test.integration.jmx.rbac.deployment.JmxResource; import java.io.FilePermission; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ACCESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.AUTHORIZATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE_SERVICE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.IDENTITY; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROVIDER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLE_MAPPING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.USE_IDENTITY_ROLES; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import javax.management.MBeanServerPermission; public abstract class AbstractJmxAccessFromDeploymentWithRbacTest { @ArquillianResource private URL url; private boolean securedApplication; AbstractJmxAccessFromDeploymentWithRbacTest() { this(true); } AbstractJmxAccessFromDeploymentWithRbacTest(boolean securedApplication) { this.securedApplication = securedApplication; } // Subclasses will need to call this method from their @Deployment annotated methods. static Archive<?> deploy(boolean securedApplication) { WebArchive war = ShrinkWrap.create(WebArchive.class,"jmx-access-rbac.war"); war.addPackage(JmxResource.class.getPackage()); war.addAsManifestResource(AbstractJmxAccessFromDeploymentWithRbacTest.class.getResource("jboss-deployment-structure.xml"), "jboss-deployment-structure.xml") .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( // Required for JMXConnectorFactory.connect() new RuntimePermission("shutdownHooks"), new ElytronPermission("getSecurityDomain"), new MBeanServerPermission("findMBeanServer,createMBeanServer"), ControllerPermission.CAN_ACCESS_MODEL_CONTROLLER, ControllerPermission.CAN_ACCESS_IMMUTABLE_MANAGEMENT_RESOURCE_REGISTRATION, // Required for the service loader to load remoting-jmx new FilePermission("<<ALL FILES>>", "read"), new RemotingPermission("createEndpoint"), new RemotingPermission("connect") ), "permissions.xml"); if (securedApplication) { war.addAsWebInfResource(AbstractJmxAccessFromDeploymentWithRbacTest.class.getPackage(), "jboss-web.xml", "jboss-web.xml"); war.addAsWebInfResource(AbstractJmxAccessFromDeploymentWithRbacTest.class.getPackage(), "web.xml", "web.xml"); } return war; } private String performCall(String urlPattern) throws Exception { try (CloseableHttpClient httpclient = createHttpClient()) { HttpGet httpget = new HttpGet(url.toExternalForm() + urlPattern); HttpResponse response = httpclient.execute(httpget); assertNotNull("Response is 'null', we expected non-null response!", response); final String text = Utils.getContent(response); assertEquals(text, 200, response.getStatusLine().getStatusCode()); return text; } } private CloseableHttpClient createHttpClient() { HttpClientBuilder builder = HttpClients.custom(); if (securedApplication) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials("kabir", "kabir")); builder.setDefaultCredentialsProvider(credentialsProvider); } return builder.build(); } @Test public void testJmxCallWithPlatformMBeanServer() throws Exception { String result = performCall("platform"); assertEquals("ok", result); } @Test public void testJmxCallWithFoundMBeanServer() throws Exception { String result = performCall("found"); assertEquals("ok", result); } @Test public void testJmxCallWithRemoteMBeanServer() throws Exception { String result = performCall("remote"); assertEquals("ok", result); } static class EnableRbacSetupTask extends SnapshotRestoreSetupTask { private static final String APPLICATION_ROLES_PROPERTIES = "application-roles.properties"; private static final String APPLICATION_USERS_PROPERTIES = "application-users.properties"; private static final String MGMT_GROUPS_PROPERTIES = "mgmt-groups.properties"; private static final String MGMT_USERS_PROPERTIES = "mgmt-users.properties"; private static final String[] ALL_PROPERTIES = new String[]{ APPLICATION_ROLES_PROPERTIES, APPLICATION_USERS_PROPERTIES, MGMT_GROUPS_PROPERTIES, MGMT_USERS_PROPERTIES}; private final boolean useIdentityRoles; private boolean securedApplication; private final Set<String> skippedFiles = new HashSet<>(); EnableRbacSetupTask(boolean useIdentityRoles, boolean securedApplication) { this.useIdentityRoles = useIdentityRoles; this.securedApplication = securedApplication; if (!useIdentityRoles) { skippedFiles.add(MGMT_GROUPS_PROPERTIES); } } @Override protected void doSetup(ManagementClient managementClient, String containerId) throws Exception { super.doSetup(managementClient, containerId); // Essentially we overwrite all the properties files for the Application- and ManagementRealm/Domains. // We restore them in nonManagementCleanUp() backupOrRestoreConfigDirPropertyFiles(true); copyPropertiesToConfigFolder(); List<ModelNode> operations = new ArrayList<>(); // /core-service=management/access=authorization:write-attribute(name=provider,value=rbac) PathAddress addr = PathAddress.pathAddress(CORE_SERVICE, MANAGEMENT).append(ACCESS, AUTHORIZATION); operations.add(Util.getWriteAttributeOperation(addr, PROVIDER, "rbac")); if (useIdentityRoles) { // /core-service=management/access=authorization:write-attribute(name=use-identity-roles,value=true) addr = PathAddress.pathAddress(CORE_SERVICE, MANAGEMENT).append(ACCESS, AUTHORIZATION); operations.add(Util.getWriteAttributeOperation(addr, USE_IDENTITY_ROLES, true)); } else { if (securedApplication) { // /core-service=management/access=authorization/role-mapping=SuperUser/include=user-kabir:add(name=kabir,type=USER) operations.add(createSuperUserRoleMapping("kabir")); } else { // /core-service=management/access=authorization/role-mapping=SuperUser/include=user-anonymous:add(name=anonymous,type=USER) operations.add(createSuperUserRoleMapping("anonymous")); } } // /core-service=management/access=identity:add(security-domain=ManagementDomain) addr = PathAddress.pathAddress(CORE_SERVICE, MANAGEMENT).append(ACCESS, IDENTITY); ModelNode addAccessIdentity = Util.createAddOperation(addr); addAccessIdentity.get("security-domain").set("ManagementDomain"); operations.add(addAccessIdentity); // /subsystem=elytron/security-domain=ApplicationDomain:write-attribute(name=outflow-security-domains, value=[ManagementDomain]) addr = PathAddress.pathAddress(SUBSYSTEM, "elytron").append("security-domain", "ApplicationDomain"); ModelNode outflowDomains = new ModelNode(); outflowDomains.add("ManagementDomain"); operations.add(Util.getWriteAttributeOperation(addr, "outflow-security-domains", outflowDomains)); // /subsystem=elytron/security-domain=ManagementDomain:write-attribute(name=trusted-security-domains, value=[ApplicationDomain]) addr = PathAddress.pathAddress(SUBSYSTEM, "elytron").append("security-domain", "ManagementDomain"); ModelNode trustedDomains = new ModelNode(); trustedDomains.add("ApplicationDomain"); operations.add(Util.getWriteAttributeOperation(addr, "trusted-security-domains", trustedDomains)); ModelNode response = managementClient.getControllerClient().execute(Util.createCompositeOperation(operations)); Assert.assertEquals(SUCCESS, response.get(OUTCOME).asString()); ServerReload.executeReloadAndWaitForCompletion(managementClient, TimeoutUtil.adjust(10000)); } private ModelNode createSuperUserRoleMapping(String userName) { PathAddress addr = PathAddress.pathAddress(CORE_SERVICE, MANAGEMENT) .append(ACCESS, AUTHORIZATION) .append(ROLE_MAPPING, "SuperUser") .append(INCLUDE, "user-" + userName); ModelNode addSuperUserInclude = Util.createAddOperation(addr); addSuperUserInclude.get(NAME, userName); addSuperUserInclude.get(TYPE, "USER"); return addSuperUserInclude; } @Override protected void nonManagementCleanUp() throws Exception { if (!securedApplication) { return; } backupOrRestoreConfigDirPropertyFiles(false); super.nonManagementCleanUp(); } private void backupOrRestoreConfigDirPropertyFiles(boolean setup) throws Exception { if (!securedApplication) { return; } Path target = Paths.get("target/wildfly/standalone/configuration"); Assert.assertTrue(Files.exists(target)); for (String fileName : ALL_PROPERTIES) { if (skippedFiles.contains(fileName)) { continue; } String backupFileName = fileName + ".bak"; Path main = target.resolve(fileName); Path backup = target.resolve(backupFileName); if (setup) { if (Files.exists(backup)) { Files.delete(backup); } Files.move(main, backup); } else { if (Files.exists(backup)) { if (Files.exists(main)) { Files.delete(main); } Files.move(backup, main); } } } } private void copyPropertiesToConfigFolder() throws Exception { if (!securedApplication) { return; } Path target = Paths.get("target/wildfly/standalone/configuration"); for (String fileName : ALL_PROPERTIES) { if (skippedFiles.contains(fileName)) { continue; } URL url = AbstractJmxAccessFromDeploymentWithRbacTest.class.getResource(fileName); Path source = Paths.get(url.toURI()); Files.copy(source, target.resolve(fileName)); } } } }
14,776
47.29085
164
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/jmx/rbac/deployment/ApplicationClass.java
/* * * JBoss, Home of Professional Open Source. * Copyright 2022, 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.jmx.rbac.deployment; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.core.Application; @ApplicationPath("/") public class ApplicationClass extends Application { }
1,245
34.6
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/jmx/rbac/deployment/JmxResource.java
/* * * JBoss, Home of Professional Open Source. * Copyright 2022, 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.jmx.rbac.deployment; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import java.lang.management.ManagementFactory; import java.util.HashMap; import java.util.List; import java.util.Map; @Path("/") @Produces(MediaType.TEXT_PLAIN) public class JmxResource { private static final String MBEAN_NAME = "jboss.as:subsystem=datasources,data-source=ExampleDS,statistics=pool"; String HOST_NAME = "localhost"; String PORT = "9990"; @GET @Path("/platform") public Response usePlatformMBeanServer() { try { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); return callMBeanServer(server); } catch (Exception e) { e.printStackTrace(); throw e; } } @GET @Path("/found") public Response useFoundMBeanServer() throws Exception { List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null); Response response = null; for (int i = 0; i < servers.size(); i++) { MBeanServer server = servers.get(i); if (server.isRegistered(ObjectName.getInstance(MBEAN_NAME))) { response = callMBeanServer(server); } } if (response == null) { throw new IllegalStateException("No MBeanServer found"); } return response; } @GET @Path("/remote") public Response useRemoteMBeanServer() throws Exception { JMXServiceURL jmx_service_url = new JMXServiceURL("service:jmx:remote+http://" + HOST_NAME + ":" + PORT); Map<String,Object> environment = new HashMap<String,Object>(); JMXConnector connector = JMXConnectorFactory.connect(jmx_service_url, null); MBeanServerConnection conn = connector.getMBeanServerConnection(); try { return callMBeanServer(conn); } finally { connector.close(); } } private Response callMBeanServer(MBeanServerConnection server) { try { Object r = server.getAttribute(new ObjectName(MBEAN_NAME), "ActiveCount"); return Response.ok("ok").build(); } catch (Exception e) { throw new RuntimeException(e); } } }
3,711
33.055046
116
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/jmx/rbac/deployment/IdentityFilter.java
/* * Copyright 2017 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.jmx.rbac.deployment; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.annotation.WebFilter; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; import java.io.IOException; /** * A {@link Filter} implementation that will always runAs the current {@link SecurityIdentity} to activate * any outflow identities. * * @author <a href="mailto:[email protected]">Darran Lofthouse</a> */ @WebFilter(urlPatterns = { "/*" }) public class IdentityFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { SecurityIdentity identity = SecurityDomain.getCurrent().getCurrentSecurityIdentity(); try { identity.runAs(() -> { try { chain.doFilter(request, response); } catch (IOException | ServletException e) { throw new RuntimeException(e); } }); } catch (RuntimeException e) { Throwable cause = e.getCause(); if (cause instanceof ServletException) { throw (ServletException) cause; } else if (cause instanceof IOException) { throw (IOException) cause; } throw e; } } @Override public void destroy() { } }
2,366
32.338028
132
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/metrics/MetricsHelper.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.metrics; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.jboss.as.arquillian.container.ManagementClient; import org.junit.Assert; public class MetricsHelper { public static String getPrometheusMetrics(ManagementClient managementClient, boolean metricMustExist) throws IOException { String url = "http://" + managementClient.getMgmtAddress() + ":" + managementClient.getMgmtPort() + "/metrics"; try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet getMetrics = new HttpGet(url); try (CloseableHttpResponse resp = client.execute(getMetrics)) { if (metricMustExist) { assertEquals(200, resp.getStatusLine().getStatusCode()); String content = EntityUtils.toString(resp.getEntity()); assertNotNull(content); return content; } else { assertEquals(204, resp.getStatusLine().getStatusCode()); return null; } } } } public static double getMetricValueFromPrometheusOutput(String prometheusContent, String metricName) { assertNotNull(prometheusContent); String[] lines = prometheusContent.split("\\R"); for (String line : lines) { if (line.startsWith(metricName)) { String longStr = line.substring(line.lastIndexOf(' ')); return Double.parseDouble(longStr.trim()); } } Assert.fail(metricName + " metric not found in " + prometheusContent); return -1; } }
3,019
38.736842
126
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/metrics/MetricsFromJVMTestCase.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.metrics; import static org.junit.Assert.assertTrue; import static org.wildfly.test.integration.metrics.MetricsHelper.getMetricValueFromPrometheusOutput; import static org.wildfly.test.integration.metrics.MetricsHelper.getPrometheusMetrics; 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.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Test JVM metrics with the base "metrics" subsystem. */ @RunWith(Arquillian.class) @RunAsClient public class MetricsFromJVMTestCase { // Use an empty deployment as the test deals with base metrics only @Deployment(name = "MetricsFromJVMTestCase", managed = false) public static Archive<?> deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, "MetricsFromJVMTestCase.war"); return war; } @ContainerResource ManagementClient managementClient; @Test public void testBaseMetrics() throws Exception { long start = System.currentTimeMillis(); long sleep = 50; String metrics = getPrometheusMetrics(managementClient, true); System.out.println("metrics = " + metrics); double uptime1 = getMetricValueFromPrometheusOutput(metrics, "base_jvm_uptime"); assertTrue(uptime1 > 0); Thread.sleep(sleep); metrics = getPrometheusMetrics(managementClient, true); double uptime2 = getMetricValueFromPrometheusOutput(metrics, "base_jvm_uptime"); assertTrue(uptime2 > 0); long interval = System.currentTimeMillis() - start; double uptimeDeltaInMilliseconds = (uptime2 - uptime1) * 1000; assertTrue( uptime2 > uptime1); assertTrue(uptimeDeltaInMilliseconds >= sleep); assertTrue(uptimeDeltaInMilliseconds <= interval); } }
3,171
37.682927
100
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/metrics/MetricsFromWildFlyManagementModelTestCase.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.metrics; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STATISTICS_ENABLED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.test.shared.ServerReload.executeReloadAndWaitForCompletion; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.wildfly.test.integration.metrics.MetricsHelper.getPrometheusMetrics; import java.io.IOException; import java.net.URL; import java.util.concurrent.TimeUnit; 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.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.jboss.dmr.ModelNode; 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.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.metrics.application.TestApplication; import org.wildfly.test.integration.metrics.application.TestResource; @RunWith(Arquillian.class) @RunAsClient @ServerSetup({MetricsFromWildFlyManagementModelTestCase.EnablesUndertowStatistics.class}) public class MetricsFromWildFlyManagementModelTestCase { static class EnablesUndertowStatistics implements ServerSetupTask { @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { managementClient.getControllerClient().execute(enableStatistics(true)); executeReloadAndWaitForCompletion(managementClient); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { managementClient.getControllerClient().execute(enableStatistics(false)); executeReloadAndWaitForCompletion(managementClient); } private ModelNode enableStatistics(boolean enabled) { final ModelNode address = Operations.createAddress(SUBSYSTEM, "undertow"); return Operations.createWriteAttributeOperation(address, STATISTICS_ENABLED, enabled); } } @ContainerResource ManagementClient managementClient; @ArquillianResource private Deployer deployer; @Deployment(name = "MetricsFromWildFlyManagementModelTestCase", managed = false) public static Archive<?> deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, "MetricsFromWildFlyManagementModelTestCase.war") .addClasses(TestApplication.class) .addClass(TestResource.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); return war; } @BeforeClass public static void skipSecurityManager() { AssumeTestGroupUtil.assumeSecurityManagerDisabled(); } @BeforeClass public static void skipNonPreview() { AssumeTestGroupUtil.assumeNotWildFlyPreview(); } @Test @InSequence(1) public void testMetricsBeforeDeployment() throws Exception { // the request-count from the deployment must not exist checkMetricExistence("deployment=\"MetricsFromWildFlyManagementModelTestCase.war\"", false); // test the request-count metric on the deployment's undertow resources checkRequestCount(0, false); // deploy the archive deployer.deploy("MetricsFromWildFlyManagementModelTestCase"); } @Test @InSequence(2) @OperateOnDeployment("MetricsFromWildFlyManagementModelTestCase") public void testMetricsAfterDeployment(@ArquillianResource URL url) throws Exception { // test the request-count metric on the deployment's undertow resources checkRequestCount(0, true); performCall(url); performCall(url); performCall(url); checkRequestCount(3, true); // the request-count in the http-listener will have the same value checkRequestCount(3, false); } @Test @InSequence(3) public void testMetricsAfterUndeployment() throws Exception { deployer.undeploy("MetricsFromWildFlyManagementModelTestCase"); // the request-count in the http-listener will still be present after the undeployment checkRequestCount(3, false); // the request-count from the deployment must no longer exist checkMetricExistence("deployment=\"MetricsFromWildFlyManagementModelTestCase.war\"", false); } private static String performCall(URL url) throws Exception { URL appURL = new URL(url.toExternalForm() + "metrics-app/hello"); return HttpRequest.get(appURL.toExternalForm(), 10, TimeUnit.SECONDS); } private void checkMetricExistence(String label, boolean metricMustExist) throws IOException { String metricName = "wildfly_undertow_request_count_total"; String metrics = getPrometheusMetrics(managementClient, true); for (String line : metrics.split("\\R")) { if (line.startsWith(metricName)) { String[] split = line.split("\\s+"); String labels = split[0].substring((metricName).length()); if (labels.contains(label)) { if (metricMustExist) { return; } else { fail("Metric " + metricName + " was found"); } } } } if (metricMustExist) { fail("Metric " + metricName + " was not found"); } } private void checkRequestCount(int expectedCount, boolean metricForDeployment) throws IOException { String metricName = "wildfly_undertow_request_count_total"; String metrics = getPrometheusMetrics(managementClient, true); System.out.println(">>> metrics = " + metrics); for (String line : metrics.split("\\R")) { if (line.startsWith(metricName)) { String[] split = line.split("\\s+"); String labels = split[0].substring((metricName).length()); // we are only interested by the metric for this deployment if (metricForDeployment) { if (labels.contains("deployment=\"MetricsFromWildFlyManagementModelTestCase.war\"")) { Double value = Double.valueOf(split[1]); assertTrue(labels.contains("deployment=\"MetricsFromWildFlyManagementModelTestCase.war\"")); assertTrue(labels.contains("subdeployment=\"MetricsFromWildFlyManagementModelTestCase.war\"")); assertTrue(labels.contains("servlet=\"" + TestApplication.class.getName() + "\"")); assertEquals(metrics, Integer.valueOf(expectedCount).doubleValue(), value, 0); return; } } else { // check the metrics from the http-listener in the undertow subsystem if (labels.contains("http_listener=\"default\"")) { Double value = Double.valueOf(split[1]); assertTrue(labels.contains("server=\"default-server\"")); assertEquals(metrics, Integer.valueOf(expectedCount).doubleValue(), value, 0); return; } } } } fail(metricName + "metric not found"); } }
9,253
42.242991
119
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/metrics/application/TestApplication.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.metrics.application; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.core.Application; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2020 Red Hat inc. */ @ApplicationPath("/metrics-app") public class TestApplication extends Application { }
1,334
38.264706
78
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/metrics/application/TestResource.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.metrics.application; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Response; @Path("/hello") public class TestResource { @GET @Produces("text/plain") public Response hello() { return Response.ok("Hello From WildFly!").build(); } }
1,381
36.351351
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/jsp/DummyConstants.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jsp; /** * @author Jaikiran Pai */ public class DummyConstants { public static final String FOO = "bar"; }
1,179
34.757576
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/jsp/AnswerToEverythingComputation.java
package org.wildfly.test.integration.jsp; /** * @author Tomaz Cerar (c) 2015 Red Hat Inc. */ @FunctionalInterface public interface AnswerToEverythingComputation { int compute(); }
187
17.8
48
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/jsp/DummyBean.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.jsp; /** * * @author rmartinc */ public class DummyBean { public static final String DEFAULT_VALUE = "default value"; private String test = DEFAULT_VALUE; public String getTest() { return test; } public void setTest(String test) { this.test = test; } }
933
24.944444
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/jsp/DummyEnum.java
/* * Copyright 2016 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.jsp; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public enum DummyEnum { VALUE }
753
28
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/jsp/JspELTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, 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.jsp; 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.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; 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 java.net.URL; import java.util.concurrent.TimeUnit; /** * Tests EL evaluation in JSPs * * @author Jaikiran Pai */ @RunWith(Arquillian.class) @RunAsClient public class JspELTestCase { private static final String Servlet_No_Spec_War = "jsp-el-test-no-web-xml"; private static final String Servlet_Spec_4_0_War = "jsp-el-test-4_0_servlet_spec"; private static final String Servlet_Spec_3_1_War = "jsp-el-test-3_1_servlet_spec"; private static final String Servlet_Spec_3_0_War = "jsp-el-test-3_0_servlet_spec"; @Deployment(name = Servlet_No_Spec_War) public static WebArchive deploy() { return ShrinkWrap.create(WebArchive.class) .addClasses(DummyConstants.class, DummyEnum.class) .addAsWebResource(JspELTestCase.class.getResource("jsp-with-el.jsp"), "index.jsp"); } @Deployment(name = Servlet_Spec_4_0_War) public static WebArchive deploy40War() { return deploy().addAsWebInfResource(JspELTestCase.class.getResource("web-app_4_0.xml"), "web.xml"); } @Deployment(name = Servlet_Spec_3_1_War) public static WebArchive deploy31War() { return deploy().addAsWebInfResource(JspELTestCase.class.getResource("web-app_3_1.xml"), "web.xml"); } @Deployment(name = Servlet_Spec_3_0_War) public static WebArchive deploy30War() { return deploy().addAsWebInfResource(JspELTestCase.class.getResource("web-app_3_0.xml"), "web.xml"); } final String POSSIBLE_ISSUES_LINKS = "Might be caused by: https://issues.jboss.org/browse/WFLY-6939 or" + " https://issues.jboss.org/browse/WFLY-11065 or https://issues.jboss.org/browse/WFLY-11086"; /** * Test that for web application using default version of servlet spec, EL expressions that use implicitly imported * classes from <code>java.lang</code> package are evaluated correctly * * @param url * @throws Exception */ @OperateOnDeployment(Servlet_No_Spec_War) @Test public void testJavaLangImplicitClassELEvaluation(@ArquillianResource URL url) throws Exception { commonTestPart(url, POSSIBLE_ISSUES_LINKS); commonTestPart(url, POSSIBLE_ISSUES_LINKS); } /** * Test that for web application using 4.0 version of servlet spec, EL expressions that use implicitly imported * classes from <code>java.lang</code> package are evaluated correctly * * @param url * @throws Exception */ @OperateOnDeployment(Servlet_Spec_4_0_War) @Test public void testJavaLangImplicitClassELEvaluation40(@ArquillianResource URL url) throws Exception { commonTestPart(url, POSSIBLE_ISSUES_LINKS); commonTestPart(url, POSSIBLE_ISSUES_LINKS); } /** * Test that for web application using 3.1 version of servlet spec, EL expressions that use implicitly imported * classes from <code>java.lang</code> package are evaluated correctly * * @param url * @throws Exception */ @OperateOnDeployment(Servlet_Spec_3_1_War) @Test public void testJavaLangImplicitClassELEvaluation31(@ArquillianResource URL url) throws Exception { commonTestPart(url, POSSIBLE_ISSUES_LINKS); commonTestPart(url, POSSIBLE_ISSUES_LINKS); } private void commonTestPart(final URL url, final String possibleCausingIssues) throws Exception { final String responseBody = HttpRequest.get(url + "index.jsp", 10, TimeUnit.SECONDS); Assert.assertTrue("Unexpected EL evaluation for ${Boolean.TRUE}; " + possibleCausingIssues, responseBody.contains("Boolean.TRUE: --- " + Boolean.TRUE + " ---")); Assert.assertTrue("Unexpected EL evaluation for ${Integer.MAX_VALUE}; " + possibleCausingIssues, responseBody.contains("Integer.MAX_VALUE: --- " + Integer.MAX_VALUE + " ---")); Assert.assertTrue("Unexpected EL evaluation for ${DummyConstants.FOO}; " + possibleCausingIssues, responseBody.contains("DummyConstants.FOO: --- " + DummyConstants.FOO + " ---")); Assert.assertTrue("Unexpected EL evaluation for ${DummyEnum.VALUE}; " + possibleCausingIssues, responseBody.contains("DummyEnum.VALUE: --- " + DummyEnum.VALUE + " ---")); } /** * Test that for web application using servlet spec version lesser than 3.1, EL expressions can't consider classes * belonging to <code>java.lang</code> package as implicitly imported and usable in the EL expressions * * @param url * @throws Exception */ @OperateOnDeployment(Servlet_Spec_3_0_War) @Test public void testJavaLangImplicitClassELEvaluationForLesserSpecVersion(@ArquillianResource URL url) throws Exception { // with the Jakarta upgrade for jsp spec (WFLY-12439), we can now evaluate Boolean.TRUE and Integer.MAX_VALUE // even when using the previous spec version commonTestPart(url, POSSIBLE_ISSUES_LINKS); commonTestPart(url, POSSIBLE_ISSUES_LINKS); } }
6,598
43.288591
121
java