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/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/CoreBridgeCallTimeoutTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.manualmode.messaging; import org.jboss.arquillian.container.test.api.RunAsClient; 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.shared.TestSuiteEnvironment; import org.jboss.byteman.agent.submit.Submit; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.core.testrunner.Server; import org.wildfly.core.testrunner.ServerControl; import org.wildfly.core.testrunner.ServerController; import org.wildfly.core.testrunner.WildflyTestRunner; import jakarta.inject.Inject; import jakarta.jms.Connection; import jakarta.jms.ConnectionFactory; import jakarta.jms.DeliveryMode; 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 javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.io.IOException; import java.util.Collections; import java.util.Properties; import java.util.UUID; import static org.jboss.as.controller.client.helpers.ClientConstants.ADDRESS; import static org.jboss.as.controller.client.helpers.ClientConstants.OP; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * This test verifies that setting a call timeout on a core bridge takes an effect. * * @author Tomas Hofman */ @RunWith(WildflyTestRunner.class) @RunAsClient @ServerControl(manual = true) public class CoreBridgeCallTimeoutTestCase { private static final Logger logger = Logger.getLogger(CoreBridgeCallTimeoutTestCase.class); private static final String SERVER_CONFIG_NAME = "standalone-full.xml"; private static final String EXPORTED_PREFIX = "java:jboss/exported/"; private static final String REMOTE_CONNECTION_FACTORY_LOOKUP = "jms/RemoteConnectionFactory"; private static final String SOURCE_QUEUE_NAME = "SourceQueue"; private static final String SOURCE_QUEUE_LOOKUP = "jms/SourceQueue"; private static final String TARGET_QUEUE_NAME = "TargetQueue"; private static final String TARGET_QUEUE_LOOKUP = "jms/TargetQueue"; private static final String BRIDGE_NAME = "CoreBridge"; private static final String MESSAGE_TEXT = "Hello world!"; private static final String BYTEMAN_ADDRESS = System.getProperty("byteman.server.ipaddress", Submit.DEFAULT_ADDRESS); private static final Integer BYTEMAN_PORT = Integer.getInteger("byteman.server.port", Submit.DEFAULT_PORT); private static final Submit BYTEMAN = new Submit(BYTEMAN_ADDRESS, BYTEMAN_PORT); private static final String ORIGINAL_JVM_ARGS = System.getProperty("jvm.args", ""); private static final String BASE_DIR = System.getProperty("basedir", "./"); @Inject protected static ServerController container; private JMSOperations jmsOperations; private ManagementClient managementClient; @BeforeClass public static void startContainer() { System.out.println("jvm.args:" + System.getProperty("jvm.args")); System.out.println("basedir:" + System.getProperty("basedir")); System.setProperty("jvm.args", ORIGINAL_JVM_ARGS + " -Xmx512m -XX:MaxMetaspaceSize=256m " + "-Dorg.jboss.byteman.verbose " + "-Djboss.modules.system.pkgs=org.jboss.byteman " + "-Dorg.jboss.byteman.transform.all " + "-javaagent:" + BASE_DIR + "/target/lib/byteman.jar=listener:true,port:" + BYTEMAN_PORT + ",address:" + BYTEMAN_ADDRESS + ",policy:true"); container.start(SERVER_CONFIG_NAME, Server.StartMode.NORMAL); } @AfterClass public static void stopContainer() { System.setProperty("jvm.args", ORIGINAL_JVM_ARGS); container.stop(); } @Before public void setUp() throws IOException { managementClient = createManagementClient(); jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); // create source and target queues and a bridge jmsOperations.createJmsQueue(SOURCE_QUEUE_NAME, EXPORTED_PREFIX + SOURCE_QUEUE_LOOKUP); removeMessagesFromQueue(SOURCE_QUEUE_NAME); jmsOperations.createJmsQueue(TARGET_QUEUE_NAME, EXPORTED_PREFIX + TARGET_QUEUE_LOOKUP); removeMessagesFromQueue(TARGET_QUEUE_NAME); } @After public void tearDown() { // clean up jmsOperations.removeJmsQueue(SOURCE_QUEUE_NAME); jmsOperations.removeJmsQueue(TARGET_QUEUE_NAME); if (jmsOperations != null) { jmsOperations.close(); } if (managementClient != null) { managementClient.close(); } } /** * Scenario: * * <ol> * <li>Create a bridge without a call-timeout.</li> * <li>Verify that messages are transferred.</li> * </ol> */ @Test(timeout = 150000) public void testCoreBridge() throws Exception { Message receivedMessage = verifyCoreBridge(null); // no call timeout // assert that message was delivered assertNotNull("Expected message was not received", receivedMessage); } /** * Scenario: * * <ol> * <li>Create a bridge with call-timeout of 500 ms, and introduce delays to bridge calls via a byteman rule.</li> * <li>Verify that messages are not transferred.</li> * </ol> */ @Test(timeout = 150000) public void testCallTimeoutWithFailure() throws Exception { try { insertBytemanRules(); // introduce 1 sec delay to bridge calls Message receivedMessage = verifyCoreBridge(500L);// set call timeout to 500 ms // assert that message was delivered assertNull("No message was expected to be transferred by the bridge", receivedMessage); } finally { deleteBytemanRules(); } } private Message verifyCoreBridge(Long callTimeout) throws Exception { createCoreBridge(callTimeout); InitialContext remoteContext = createJNDIContext(); ConnectionFactory connectionFactory = (ConnectionFactory) remoteContext.lookup(REMOTE_CONNECTION_FACTORY_LOOKUP); // lookup source and target queues Queue sourceQueue = (Queue) remoteContext.lookup(SOURCE_QUEUE_LOOKUP); Queue targetQueue = (Queue) remoteContext.lookup(TARGET_QUEUE_LOOKUP); try (Connection connection = connectionFactory.createConnection("guest", "guest")) { try (Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) { // send a message on the source queue MessageProducer producer = session.createProducer(sourceQueue); String text = MESSAGE_TEXT + " " + UUID.randomUUID().toString(); Message message = session.createTextMessage(text); message.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); producer.send(message); // receive a message from the target queue MessageConsumer consumer = session.createConsumer(targetQueue); connection.start(); Message receivedMessage = consumer.receive(5000); // if some message was delivered, assert it's the same message which was sent if (receivedMessage != null) { assertTrue(receivedMessage instanceof TextMessage); assertEquals(text, ((TextMessage) receivedMessage).getText()); } return receivedMessage; } } finally { jmsOperations.removeCoreBridge(BRIDGE_NAME); remoteContext.close(); } } private void createCoreBridge(Long callTimeout) { ModelNode bridgeAttributes = new ModelNode(); bridgeAttributes.get("queue-name").set("jms.queue." + SOURCE_QUEUE_NAME); bridgeAttributes.get("forwarding-address").set("jms.queue." + TARGET_QUEUE_NAME); bridgeAttributes.get("static-connectors").add("in-vm"); bridgeAttributes.get("use-duplicate-detection").set(false); if (callTimeout != null) { bridgeAttributes.get("call-timeout").set(callTimeout); } bridgeAttributes.get("user").set("guest"); bridgeAttributes.get("password").set("guest"); jmsOperations.addCoreBridge(BRIDGE_NAME, bridgeAttributes); } private void removeMessagesFromQueue(String queueName) throws IOException { ModelNode operation = new ModelNode(); operation.get(ADDRESS).set(jmsOperations.getServerAddress().add("jms-queue", queueName)); operation.get(OP).set("remove-messages"); jmsOperations.getControllerClient().execute(operation); } private static void insertBytemanRules() throws Exception { logger.info("Installing byteman rules."); BYTEMAN.addRulesFromResources(Collections.singletonList( CoreBridgeCallTimeoutTestCase.class.getClassLoader().getResourceAsStream("byteman/" + CoreBridgeCallTimeoutTestCase.class.getSimpleName() + ".btm"))); } private static void deleteBytemanRules() throws Exception { logger.info("Removing byteman rules."); BYTEMAN.deleteAllRules(); } private static ManagementClient createManagementClient() { return new ManagementClient( TestSuiteEnvironment.getModelControllerClient(), TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddress()), TestSuiteEnvironment.getServerPort(), "remote+http"); } private static InitialContext createJNDIContext() throws NamingException { final Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "org.wildfly.naming.client.WildFlyInitialContextFactory"); env.put(Context.PROVIDER_URL, "remote+http://" + TestSuiteEnvironment.getServerAddress() + ":8080"); env.put(Context.SECURITY_PRINCIPAL, "guest"); env.put(Context.SECURITY_CREDENTIALS, "guest"); return new InitialContext(env); } }
11,632
41.301818
154
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/CorruptedLogTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, 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.manualmode.messaging; import java.io.File; import java.io.IOException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.controller.client.helpers.Operations; import java.net.UnknownHostException; import java.nio.file.Files; import java.nio.file.Path; import java.util.stream.Collectors; import java.util.Properties; import java.util.stream.Stream; import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSProducer; import jakarta.jms.Queue; import jakarta.jms.TextMessage; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.apache.commons.lang3.RandomStringUtils; import org.jboss.arquillian.container.test.api.ContainerController; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.repository.PathUtil; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * Test to check that we can configure properly how many journal files are stored in the attic when artemis journal is corrupted. * @author Emmanuel Hugonnet (c) 2020 Red Hat, Inc. */ @RunAsClient() @RunWith(Arquillian.class) public class CorruptedLogTestCase { private static final String DEFAULT_FULL_JBOSSAS = "default-full-jbossas"; @ArquillianResource protected static ContainerController container; private ManagementClient managementClient; private int counter = 0; @Before public void setup() throws Exception { if (!container.isStarted(DEFAULT_FULL_JBOSSAS)) { container.start(DEFAULT_FULL_JBOSSAS); } managementClient = createManagementClient(); JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); setJournalSize(100L); jmsOperations.createJmsQueue("corrupted", "java:jboss/exported/" + "queue/corrupted"); jmsOperations.close(); managementClient.close(); container.stop(DEFAULT_FULL_JBOSSAS); PathUtil.deleteRecursively(getAtticPath()); container.start(DEFAULT_FULL_JBOSSAS); managementClient = createManagementClient(); } @After public void tearDown() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); jmsOperations.removeJmsQueue("corrupted"); managementClient.getControllerClient().execute(Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "journal-file-size")); managementClient.getControllerClient().execute(Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "journal-max-attic-files")); jmsOperations.close(); managementClient.close(); if(counter > 1) { container.stop(DEFAULT_FULL_JBOSSAS); } PathUtil.deleteRecursively(getAtticPath()); } /** * Set the journal file size to 100k. * Send 100 messages of 20k. * Set the journal file size to 200k. * Restart the server. * Consume the messages. * Should have journal files in the attic. * * @throws javax.naming.NamingException * @throws java.io.IOException */ @Test public void testCorruptedJournal() throws NamingException, IOException { counter++; InitialContext remoteContext = createJNDIContext(); ConnectionFactory cf = (ConnectionFactory) remoteContext.lookup("jms/RemoteConnectionFactory"); Queue queue = (Queue) remoteContext.lookup("queue/corrupted"); try (JMSContext context = cf.createContext("guest", "guest", JMSContext.AUTO_ACKNOWLEDGE);) { JMSProducer producer = context.createProducer(); for (int i = 0; i < 100; i++) { producer.send(queue, context.createTextMessage(RandomStringUtils.randomAlphabetic(20000))); } } setJournalSize(200L); remoteContext.close(); managementClient.close(); container.stop(DEFAULT_FULL_JBOSSAS); container.start(DEFAULT_FULL_JBOSSAS); managementClient = createManagementClient(); remoteContext = createJNDIContext(); cf = (ConnectionFactory) remoteContext.lookup("jms/RemoteConnectionFactory"); queue = (Queue) remoteContext.lookup("queue/corrupted"); try (JMSContext context = cf.createContext("guest", "guest", JMSContext.AUTO_ACKNOWLEDGE);) { JMSConsumer consumer = context.createConsumer(queue); for (int i = 0; i < 100; i++) { TextMessage message = (TextMessage) consumer.receive(TimeoutUtil.adjust(500)); Assert.assertNotNull(message); } } Path attic = getAtticPath(); Assert.assertTrue("Couldn't find " + attic.toAbsolutePath(), Files.exists(attic)); Assert.assertTrue(Files.isDirectory(attic)); try (Stream<Path> stream = Files.list(attic)){ long nbAtticFiles = stream.collect(Collectors.counting()); Assert.assertTrue(nbAtticFiles > 0L); } } /** * Set the journal max attic files to 0 (aka don't store corrupted journal files). * Set the journal file size to 100k. * Send 100 messages of 20k. * Set the journal file size to 200k. * Restart the server. * Consume the messages. * Shouldn't have journal files in the attic. * * @throws javax.naming.NamingException * @throws java.io.IOException */ @Test public void testCorruptedJournalNotSaved() throws NamingException, IOException { Path attic = getAtticPath(); counter++; JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); managementClient.getControllerClient().execute(Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "journal-max-attic-files", 0)); jmsOperations.close(); managementClient.close(); container.stop(DEFAULT_FULL_JBOSSAS); PathUtil.deleteRecursively(attic); container.start(DEFAULT_FULL_JBOSSAS); Assert.assertFalse("Couldn't find " + attic.toAbsolutePath(), Files.exists(attic)); managementClient = createManagementClient(); InitialContext remoteContext = createJNDIContext(); ConnectionFactory cf = (ConnectionFactory) remoteContext.lookup("jms/RemoteConnectionFactory"); Queue queue = (Queue) remoteContext.lookup("queue/corrupted"); try (JMSContext context = cf.createContext("guest", "guest", JMSContext.AUTO_ACKNOWLEDGE);) { JMSProducer producer = context.createProducer(); for (int i = 0; i < 100; i++) { producer.send(queue, context.createTextMessage(RandomStringUtils.randomAlphabetic(20000))); } } setJournalSize(200L); remoteContext.close(); managementClient.close(); container.stop(DEFAULT_FULL_JBOSSAS); container.start(DEFAULT_FULL_JBOSSAS); managementClient = createManagementClient(); remoteContext = createJNDIContext(); cf = (ConnectionFactory) remoteContext.lookup("jms/RemoteConnectionFactory"); queue = (Queue) remoteContext.lookup("queue/corrupted"); try (JMSContext context = cf.createContext("guest", "guest", JMSContext.AUTO_ACKNOWLEDGE);) { JMSConsumer consumer = context.createConsumer(queue); for (int i = 0; i < 100; i++) { TextMessage message = (TextMessage) consumer.receive(TimeoutUtil.adjust(500)); Assert.assertNotNull(message); } } if (Files.exists(attic)) { Assert.assertTrue(Files.isDirectory(attic)); try ( Stream<Path> stream = Files.list(attic)) { long nbAtticFiles = stream.collect(Collectors.counting()); Assert.assertEquals("We shouldn't have any file in the attic", 0L, nbAtticFiles); } } } private void setJournalSize(long size) throws IOException { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); managementClient.getControllerClient().execute(Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "journal-file-size", 1024L * size)); jmsOperations.close(); } private static ManagementClient createManagementClient() throws UnknownHostException { return new ManagementClient( TestSuiteEnvironment.getModelControllerClient(), TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddress()), TestSuiteEnvironment.getServerPort(), "remote+http"); } protected static InitialContext createJNDIContext() throws NamingException { final Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "org.wildfly.naming.client.WildFlyInitialContextFactory"); String ipAdddress = TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddress()); env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, "remote+http://" + ipAdddress + ":8080")); env.put(Context.SECURITY_PRINCIPAL, "guest"); env.put(Context.SECURITY_CREDENTIALS, "guest"); return new InitialContext(env); } private Path getAtticPath() { Path jbossHome = new File(System.getProperty("jboss.home", "jboss-as")).toPath(); return jbossHome.resolve("standalone").resolve("data").resolve("activemq").resolve("journal").resolve("attic"); } }
11,178
44.628571
166
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/RuntimeJournalTypeManagementTestCase.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.manualmode.messaging; import static org.jboss.as.controller.client.helpers.ClientConstants.VALUE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.UnknownHostException; import org.jboss.arquillian.container.test.api.ContainerController; 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.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.junit.Test; import org.junit.runner.RunWith; /** * Test reading the journal runtime type. * * @author Emmanuel Hugonnet (c) 2019 Red Hat, Inc. */ @RunAsClient() @RunWith(Arquillian.class) public class RuntimeJournalTypeManagementTestCase { private static final String DEFAULT_FULL_JBOSSAS = "default-full-jbossas"; private static final ModelNode SERVER_ADDRESS = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default").toModelNode(); private static final ModelNode AIO_DISABLED_ADDRESS = Operations.createAddress("system-property", "org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory.DISABLED"); @ArquillianResource protected static ContainerController container; @Test public void testReadFileJournaltype() throws IOException { if (!container.isStarted(DEFAULT_FULL_JBOSSAS)) { container.start(DEFAULT_FULL_JBOSSAS); } ManagementClient managementClient = createManagementClient(); assertEquals("ASYNCIO", readJournalType(managementClient)); assertNotNull(readRuntimeJournalType(managementClient)); ModelNode op = Operations.createAddOperation(AIO_DISABLED_ADDRESS); op.get(VALUE).set(true); execute(managementClient, op, true); managementClient.close(); container.stop(DEFAULT_FULL_JBOSSAS); container.start(DEFAULT_FULL_JBOSSAS); managementClient = createManagementClient(); assertEquals("ASYNCIO", readJournalType(managementClient)); assertEquals("NIO", readRuntimeJournalType(managementClient)); op = Operations.createRemoveOperation(AIO_DISABLED_ADDRESS); execute(managementClient, op, true); container.stop(DEFAULT_FULL_JBOSSAS); } @Test public void testReadDatabaseJournaltype() throws IOException { if (!container.isStarted(DEFAULT_FULL_JBOSSAS)) { container.start(DEFAULT_FULL_JBOSSAS); } ManagementClient managementClient = createManagementClient(); assertEquals("ASYNCIO", readJournalType(managementClient)); assertNotNull(readRuntimeJournalType(managementClient)); ModelNode op = Operations.createWriteAttributeOperation(SERVER_ADDRESS, "journal-datasource", "ExampleDS"); execute(managementClient, op, true); managementClient.close(); container.stop(DEFAULT_FULL_JBOSSAS); container.start(DEFAULT_FULL_JBOSSAS); managementClient = createManagementClient(); assertEquals("ASYNCIO", readJournalType(managementClient)); assertEquals("DATABASE", readRuntimeJournalType(managementClient)); op = Operations.createUndefineAttributeOperation(SERVER_ADDRESS, "journal-datasource"); execute(managementClient, op, true); managementClient.close(); container.stop(DEFAULT_FULL_JBOSSAS); } @Test public void testReadNoneJournaltype() throws IOException { if (!container.isStarted(DEFAULT_FULL_JBOSSAS)) { container.start(DEFAULT_FULL_JBOSSAS); } ManagementClient managementClient = createManagementClient(); assertEquals("ASYNCIO", readJournalType(managementClient)); assertNotNull(readRuntimeJournalType(managementClient)); ModelNode op = Operations.createWriteAttributeOperation(SERVER_ADDRESS, "persistence-enabled", false); execute(managementClient, op, true); managementClient.close(); container.stop(DEFAULT_FULL_JBOSSAS); container.start(DEFAULT_FULL_JBOSSAS); managementClient = createManagementClient(); assertEquals("ASYNCIO", readJournalType(managementClient)); assertEquals("NONE", readRuntimeJournalType(managementClient)); op = Operations.createWriteAttributeOperation(SERVER_ADDRESS, "persistence-enabled", true); execute(managementClient, op, true); managementClient.close(); container.stop(DEFAULT_FULL_JBOSSAS); } @Test public void testReadNioJournaltype() throws IOException { if (!container.isStarted(DEFAULT_FULL_JBOSSAS)) { container.start(DEFAULT_FULL_JBOSSAS); } ManagementClient managementClient = createManagementClient(); assertEquals("ASYNCIO", readJournalType(managementClient)); assertNotNull(readRuntimeJournalType(managementClient)); ModelNode op = Operations.createWriteAttributeOperation(SERVER_ADDRESS, "journal-type", "NIO"); execute(managementClient, op, true); assertEquals("NIO", readJournalType(managementClient)); managementClient.close(); container.stop(DEFAULT_FULL_JBOSSAS); container.start(DEFAULT_FULL_JBOSSAS); managementClient = createManagementClient(); assertEquals("NIO", readJournalType(managementClient)); assertEquals("NIO", readRuntimeJournalType(managementClient)); op = Operations.createWriteAttributeOperation(SERVER_ADDRESS, "journal-type", "ASYNCIO"); execute(managementClient, op, true); managementClient.close(); container.stop(DEFAULT_FULL_JBOSSAS); } 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); if (expectSuccess) { assertTrue(response.toJSONString(true), Operations.isSuccessfulOutcome(response)); return Operations.readResult(response); } assertEquals("failed", response.get("outcome").asString()); return response.get("failure-description"); } private String readJournalType(ManagementClient managementClient) throws IOException { return execute(managementClient, Operations.createReadAttributeOperation(SERVER_ADDRESS, "journal-type"), true).asString(); } private String readRuntimeJournalType(ManagementClient managementClient) throws IOException { return execute(managementClient, Operations.createReadAttributeOperation(SERVER_ADDRESS, "runtime-journal-type"), true).asString(); } private static ManagementClient createManagementClient() throws UnknownHostException { return new ManagementClient( TestSuiteEnvironment.getModelControllerClient(), TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddress()), TestSuiteEnvironment.getServerPort(), "remote+http"); } }
8,410
46.519774
179
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/ActivemqServerAddonsTestCase.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.manualmode.messaging; 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.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URL; import java.net.UnknownHostException; import java.nio.file.Paths; import java.util.PropertyPermission; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.jboss.arquillian.container.test.api.ContainerController; 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.container.test.api.TargetsContainer; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; 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.manualmode.messaging.deployment.MessagingServlet; import org.jboss.as.test.manualmode.messaging.deployment.QueueMDB; import org.jboss.as.test.manualmode.messaging.deployment.TopicMDB; import org.jboss.as.test.module.util.TestModule; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.core.testrunner.ServerControl; /** * * @author Emmanuel Hugonnet (c) 2022 Red Hat, Inc. */ @RunAsClient() @RunWith(Arquillian.class) @ServerControl(manual = true) public class ActivemqServerAddonsTestCase { private static final String DEFAULT_FULL_JBOSSAS = "default-full-jbossas"; @ArquillianResource protected static ContainerController container; @ArquillianResource private Deployer deployer; private final TestModule module = new TestModule("org.apache.activemq.artemis.addons", "org.apache.activemq.artemis"); private static final String LB_CLASS_ATT = "connection-load-balancing-policy-class-name"; private static final String QUEUE_LOOKUP = "java:/jms/DependentMessagingDeploymentTestCase/myQueue"; private static final String TOPIC_LOOKUP = "java:/jms/DependentMessagingDeploymentTestCase/myTopic"; private static final String QUEUE_NAME = "myQueue"; private static final String TOPIC_NAME = "myTopic"; private static final String DEPLOYMENT = "addons-deployment"; @Before public void setup() throws Exception { try ( ManagementClient managementClient = createManagementClient()) { if (container.isStarted(DEFAULT_FULL_JBOSSAS)) { container.stop(DEFAULT_FULL_JBOSSAS); } final JavaArchive jar = module.addResource("artemis-lb-policy.jar"); jar.addClasses(OrderedLoadBalancingPolicy.class); System.setProperty("module.path", Paths.get("target" ,"wildfly", "modules").toAbsolutePath().toString()); module.create(true); if (!container.isStarted(DEFAULT_FULL_JBOSSAS)) { container.start(DEFAULT_FULL_JBOSSAS); } ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("server", "default"); address.add("pooled-connection-factory", "activemq-ra"); ModelNode op = Operations.createWriteAttributeOperation(address, LB_CLASS_ATT, OrderedLoadBalancingPolicy.class.getName()); execute(managementClient, op, true); JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); jmsOperations.createJmsQueue(QUEUE_NAME, QUEUE_LOOKUP); jmsOperations.createJmsTopic(TOPIC_NAME, TOPIC_LOOKUP); jmsOperations.close(); deployer.deploy(DEPLOYMENT); } } 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 boolean success = Operations.isSuccessfulOutcome(response); if (expectSuccess) { assertTrue(response.toString(), success); return Operations.readResult(response); } else { assertFalse(response.toString(), success); return Operations.getFailureDescription(response); } } @After public void tearDown() throws Exception { deployer.undeploy(DEPLOYMENT); try ( ManagementClient managementClient = createManagementClient()) { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); jmsOperations.removeJmsQueue(QUEUE_NAME); jmsOperations.removeJmsTopic(TOPIC_NAME); jmsOperations.close(); ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("server", "default"); address.add("pooled-connection-factory", "activemq-ra"); ModelNode op = Operations.createUndefineAttributeOperation(address, LB_CLASS_ATT); execute(managementClient, op, true); } container.stop(DEFAULT_FULL_JBOSSAS); module.remove(); System.clearProperty("module.path"); } private static ManagementClient createManagementClient() throws UnknownHostException { return new ManagementClient( TestSuiteEnvironment.getModelControllerClient(), TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddress()), TestSuiteEnvironment.getServerPort(), "remote+http"); } @Deployment(name = DEPLOYMENT, managed = false, testable = false) @TargetsContainer(DEFAULT_FULL_JBOSSAS) public static WebArchive createArchive() { return create(WebArchive.class, DEPLOYMENT +".war") .addClasses(MessagingServlet.class, TimeoutUtil.class) .addClasses(QueueMDB.class, TopicMDB.class) .addAsWebInfResource(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") .addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read") ), "permissions.xml"); } @Test public void testQueue() throws Exception { String destination = "queue"; String text = UUID.randomUUID().toString(); URL servletUrl = new URL(TestSuiteEnvironment.getHttpUrl().toExternalForm() + '/' + DEPLOYMENT + "/DependentMessagingDeploymentTestCase?destination=" + destination + "&text=" + text); String reply = HttpRequest.get(servletUrl.toExternalForm(), 10, TimeUnit.SECONDS); assertNotNull(reply); assertEquals(text, reply); } }
8,476
46.357542
191
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/RuntimeJMSTopicManagementTestCase.java
/* * Copyright 2020 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.manualmode.messaging; import static jakarta.jms.JMSContext.AUTO_ACKNOWLEDGE; import static org.jboss.as.controller.client.helpers.ClientConstants.NAME; import static org.jboss.as.controller.client.helpers.ClientConstants.VALUE; import static org.jboss.as.controller.client.helpers.ClientConstants.WRITE_ATTRIBUTE_OPERATION; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.UnknownHostException; import java.util.Properties; import jakarta.jms.Connection; import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSException; import jakarta.jms.MessageProducer; import jakarta.jms.Session; import jakarta.jms.TextMessage; import jakarta.jms.Topic; import jakarta.jms.TopicSubscriber; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.ContainerController; 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.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.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.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Emmanuel Hugonnet (c) 2020 Red Hat, Inc. */ @RunAsClient() @RunWith(Arquillian.class) public class RuntimeJMSTopicManagementTestCase { private static final String EXPORTED_PREFIX = "java:jboss/exported/"; private static long count = System.currentTimeMillis(); private static final String DEFAULT_FULL_JBOSSAS = "default-full-jbossas"; @ArquillianResource protected static ContainerController container; /** * Scenario: * - start the server * - pause the topic * - send a message to it and ensure that the consumer don't get it * - restart the server * - the topic should still be paused as its state was persisted * - the consumer shouldn't get the message * - resume the topic * - the consumer should get the message. * @throws IOException * @throws NamingException * @throws JMSException * @throws InterruptedException */ @Test public void testPauseAndResumePersisted() throws IOException, NamingException, JMSException, InterruptedException { count = System.currentTimeMillis(); if (!container.isStarted(DEFAULT_FULL_JBOSSAS)) { container.start(DEFAULT_FULL_JBOSSAS); } InitialContext remoteContext = createJNDIContext(); ManagementClient managementClient = createManagementClient(); JMSOperations adminSupport = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); adminSupport.createJmsTopic(getTopicName(), EXPORTED_PREFIX + getTopicJndiName()); addSecuritySettings(adminSupport); assertFalse("Topic should be running", isTopicPaused(managementClient)); ConnectionFactory cf = (ConnectionFactory) remoteContext.lookup("jms/RemoteConnectionFactory"); Topic topic = (Topic) remoteContext.lookup(getTopicJndiName()); final String subscriptionName = "pauseJMSTopicPersisted"; try (Connection conn = cf.createConnection("guest", "guest")) { conn.setClientID("sender"); try (Session session = conn.createSession(false, AUTO_ACKNOWLEDGE)) { conn.start(); try (Connection consumerConn = cf.createConnection("guest", "guest")) { consumerConn.setClientID("consumer"); try (Session consumerSession = consumerConn.createSession(false, AUTO_ACKNOWLEDGE)) { consumerConn.start(); TopicSubscriber consumer = consumerSession.createDurableSubscriber(topic, subscriptionName); pauseTopic(managementClient, true); MessageProducer producer = session.createProducer(topic); producer.send(session.createTextMessage("A")); TextMessage message = (TextMessage) consumer.receive(TimeoutUtil.adjust(500)); Assert.assertNull("The message was received by the consumer, this is wrong as the connection is paused", message); Assert.assertEquals(1, countMessageSubscriptions(managementClient, consumerConn.getClientID(), subscriptionName)); } } } } adminSupport.close(); managementClient.close(); remoteContext.close(); container.stop(DEFAULT_FULL_JBOSSAS); container.start(DEFAULT_FULL_JBOSSAS); remoteContext = createJNDIContext(); managementClient = createManagementClient(); assertTrue("Topic should be paused", isTopicPaused(managementClient)); cf = (ConnectionFactory) remoteContext.lookup("jms/RemoteConnectionFactory"); topic = (Topic) remoteContext.lookup(getTopicJndiName()); try (Connection consumerConn = cf.createConnection("guest", "guest")) { consumerConn.setClientID("consumer"); try (Session consumerSession = consumerConn.createSession(false, AUTO_ACKNOWLEDGE);) { consumerConn.start(); TopicSubscriber consumer = consumerSession.createDurableSubscriber(topic, subscriptionName); TextMessage message = (TextMessage) consumer.receive(TimeoutUtil.adjust(500)); Assert.assertNull("The message was received by the consumer, this is wrong as the connection is paused", message); Assert.assertEquals(1, countMessageSubscriptions(managementClient, consumerConn.getClientID(), subscriptionName)); resumeTopic(managementClient); assertFalse("Topic should be running", isTopicPaused(managementClient)); message = (TextMessage) consumer.receive(TimeoutUtil.adjust(500)); Assert.assertNotNull("The message was not received by the consumer, this is wrong as the connection is resumed", message); Assert.assertEquals("A", message.getText()); Thread.sleep(TimeoutUtil.adjust(500)); Assert.assertEquals(0, countMessageSubscriptions(managementClient, consumerConn.getClientID(), subscriptionName)); } } adminSupport = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); adminSupport.removeJmsTopic(getTopicName()); adminSupport.close(); managementClient.close(); remoteContext.close(); container.stop(DEFAULT_FULL_JBOSSAS); } /** * Scenario: * - start the server * - pause the topic * - send a message to it and ensure that the consumer don't get it * - restart the server * - the topic should resume as its state wasn't persisted * - the consumer should get the message. * @throws IOException * @throws NamingException * @throws JMSException * @throws InterruptedException */ @Test public void testPauseAndResume() throws IOException, NamingException, JMSException, InterruptedException { count = System.currentTimeMillis(); if (!container.isStarted(DEFAULT_FULL_JBOSSAS)) { container.start(DEFAULT_FULL_JBOSSAS); } InitialContext remoteContext = createJNDIContext(); ManagementClient managementClient = createManagementClient(); JMSOperations adminSupport = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); adminSupport.createJmsTopic(getTopicName(), EXPORTED_PREFIX + getTopicJndiName()); addSecuritySettings(adminSupport); assertFalse("Topic should be running", isTopicPaused(managementClient)); ConnectionFactory cf = (ConnectionFactory) remoteContext.lookup("jms/RemoteConnectionFactory"); Topic topic = (Topic) remoteContext.lookup(getTopicJndiName()); final String subscriptionName = "pauseJMSTopic"; try (Connection conn = cf.createConnection("guest", "guest")) { conn.setClientID("sender"); try (Session session = conn.createSession(false, AUTO_ACKNOWLEDGE)) { conn.start(); try (Connection consumerConn = cf.createConnection("guest", "guest")) { consumerConn.setClientID("consumer"); try (Session consumerSession = consumerConn.createSession(false, AUTO_ACKNOWLEDGE)) { consumerConn.start(); TopicSubscriber consumer = consumerSession.createDurableSubscriber(topic, subscriptionName); pauseTopic(managementClient, false); MessageProducer producer = session.createProducer(topic); producer.send(session.createTextMessage("A")); TextMessage message = (TextMessage) consumer.receive(TimeoutUtil.adjust(500)); Assert.assertNull("The message was received by the consumer, this is wrong as the connection is paused", message); Assert.assertEquals(1, countMessageSubscriptions(managementClient, consumerConn.getClientID(), subscriptionName)); consumer.close(); producer.close(); } } } } adminSupport.close(); managementClient.close(); remoteContext.close(); container.stop(DEFAULT_FULL_JBOSSAS); container.start(DEFAULT_FULL_JBOSSAS); remoteContext = createJNDIContext(); managementClient = createManagementClient(); assertFalse("Topic should be running", isTopicPaused(managementClient)); cf = (ConnectionFactory) remoteContext.lookup("jms/RemoteConnectionFactory"); topic = (Topic) remoteContext.lookup(getTopicJndiName()); try (Connection consumerConn = cf.createConnection("guest", "guest")) { consumerConn.setClientID("consumer"); try (Session consumerSession = consumerConn.createSession(false, AUTO_ACKNOWLEDGE);) { consumerConn.start(); TopicSubscriber consumer = consumerSession.createDurableSubscriber(topic, subscriptionName); TextMessage message = (TextMessage) consumer.receive(TimeoutUtil.adjust(500)); Assert.assertNotNull("The message was not received by the consumer, this is wrong as the connection is resumed", message); Assert.assertEquals("A", message.getText()); Thread.sleep(TimeoutUtil.adjust(500)); Assert.assertEquals(0, countMessageSubscriptions(managementClient, consumerConn.getClientID(), subscriptionName)); } } adminSupport = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); adminSupport.removeJmsTopic(getTopicName()); adminSupport.close(); managementClient.close(); remoteContext.close(); container.stop(DEFAULT_FULL_JBOSSAS); } private ModelNode getTopicAddress() { return PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/jms-topic=" + getTopicName()).toModelNode(); } private String getTopicName() { return getClass().getSimpleName() + count; } private String getTopicJndiName() { return "topic/" + getTopicName(); } private ModelNode pauseTopic(ManagementClient managementClient, boolean persist) throws IOException { ModelNode operation = Operations.createOperation("pause", getTopicAddress()); operation.get("persist").set(persist); return execute(managementClient.getControllerClient(), operation, true); } private int countMessageSubscriptions(ManagementClient managementClient, String clientID, String subscriptionName) throws IOException { ModelNode operation = Operations.createOperation("count-messages-for-subscription", getTopicAddress()); operation.get("client-id").set(clientID); operation.get("subscription-name").set(subscriptionName); return execute(managementClient.getControllerClient(), operation, true).asInt(); } private ModelNode resumeTopic(ManagementClient managementClient) throws IOException { return execute(managementClient.getControllerClient(), Operations.createOperation("resume", getTopicAddress()), true); } private ModelNode execute(final ModelControllerClient client, final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = client.execute(op); if (expectSuccess) { assertTrue(response.toJSONString(true), Operations.isSuccessfulOutcome(response)); return Operations.readResult(response); } assertEquals("failed", response.get("outcome").asString()); return response.get("failure-description"); } private boolean isTopicPaused(ManagementClient managementClient) throws IOException { ModelNode result = execute(managementClient.getControllerClient(), Operations.createReadAttributeOperation(getTopicAddress(), "paused"), true); if(result.getType() == ModelType.BOOLEAN) { return result.asBoolean(); } throw new IllegalArgumentException("Result " + result.asString() + " is not a Boolean"); } private void addSecuritySettings(JMSOperations adminSupport) throws IOException { // <jms server address>/security-setting=#/role=guest:write-attribute(name=create-durable-queue, value=TRUE) ModelNode address = adminSupport.getServerAddress() .add("security-setting", "#") .add("role", "guest"); ModelNode op = new ModelNode(); op.get(ClientConstants.OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(ClientConstants.OP_ADDR).set(address); op.get(NAME).set("create-durable-queue"); op.get(VALUE).set(true); execute(adminSupport.getControllerClient(), op, true); op = new ModelNode(); op.get(ClientConstants.OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(ClientConstants.OP_ADDR).set(address); op.get(NAME).set("delete-durable-queue"); op.get(VALUE).set(true); execute(adminSupport.getControllerClient(), op, true); } private static ManagementClient createManagementClient() throws UnknownHostException { return new ManagementClient( TestSuiteEnvironment.getModelControllerClient(), TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddress()), TestSuiteEnvironment.getServerPort(), "remote+http"); } protected static InitialContext createJNDIContext() throws NamingException { final Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "org.wildfly.naming.client.WildFlyInitialContextFactory"); String ipAdddress = TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddress()); env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, "remote+http://" + ipAdddress + ":8080")); env.put(Context.SECURITY_PRINCIPAL, "guest"); env.put(Context.SECURITY_CREDENTIALS, "guest"); return new InitialContext(env); } }
16,657
49.174699
151
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/CoreBridgeQueueToTopicTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.manualmode.messaging; import org.jboss.arquillian.container.test.api.ContainerController; 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.container.ManagementClient; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.jms.Connection; import jakarta.jms.ConnectionFactory; import jakarta.jms.DeliveryMode; 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 jakarta.jms.Topic; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.io.IOException; import java.util.Properties; import java.util.UUID; import static org.jboss.as.controller.client.helpers.ClientConstants.ADDRESS; import static org.jboss.as.controller.client.helpers.ClientConstants.OP; import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; /** * Tests of setting up a core bridge from a queue to topic works. * * @author <a href="mailto:lgao@redhat.com">Lin Gao</a> */ @RunAsClient() @RunWith(Arquillian.class) public class CoreBridgeQueueToTopicTestCase { private static final String ROUTING_TYPE_PROPERTY = "org.wildfly.messaging.core.bridge.CoreBridge.routing-type"; private static final String EXPORTED_PREFIX = "java:jboss/exported/"; private static final String DEFAULT_FULL_JBOSSAS = "default-full-jbossas"; private static final String REMOTE_CONNECTION_FACTORY_LOOKUP = "jms/RemoteConnectionFactory"; private static final String SOURCE_QUEUE_NAME = "SourceQueue"; private static final String SOURCE_QUEUE_LOOKUP = "jms/SourceQueue"; private static final String TARGET_TOPIC_NAME = "TargetTopic"; private static final String TARGET_TOPIC_LOOKUP = "jms/TargetTopic"; private static final String BRIDGE_NAME = "CoreBridge"; private static final String MESSAGE_TEXT = "Hello from Queue"; @ArquillianResource protected static ContainerController container; private JMSOperations jmsOperations; private ManagementClient managementClient; @Before public void setUp() throws Exception { if (!container.isStarted(DEFAULT_FULL_JBOSSAS)) { container.start(DEFAULT_FULL_JBOSSAS); } managementClient = createManagementClient(); jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); // create source and target topic and a bridge jmsOperations.createJmsQueue(SOURCE_QUEUE_NAME, EXPORTED_PREFIX + SOURCE_QUEUE_LOOKUP); removeMessages(false, SOURCE_QUEUE_NAME); jmsOperations.createJmsTopic(TARGET_TOPIC_NAME, EXPORTED_PREFIX + TARGET_TOPIC_LOOKUP); removeMessages(true, TARGET_TOPIC_NAME); } @After public void tearDown() throws Exception { // clean up queue, topic and bridge jmsOperations.removeJmsQueue(SOURCE_QUEUE_NAME); jmsOperations.removeJmsTopic(TARGET_TOPIC_NAME); if (jmsOperations != null) { jmsOperations.close(); } if (managementClient != null) { managementClient.close(); } container.stop(DEFAULT_FULL_JBOSSAS); } @Test public void testJMSMessageFromQueueToTopicFailure() throws Exception { try { createCoreBridge(); TextMessage receivedMessage = getBridgedMessage(""); assertNull("Expected message should be null because it won't pass message from queue to topic when routing-type is PASS", receivedMessage); } finally { jmsOperations.removeCoreBridge(BRIDGE_NAME); } } @Test public void testJMSMessageFromQueueToTopic() throws Exception { try { // set up system property to use STRIP routing type ModelNode operation = createOpNode("system-property=" + ROUTING_TYPE_PROPERTY, ModelDescriptionConstants.ADD); operation.get("value").set("STRIP"); Utils.applyUpdate(operation, managementClient.getControllerClient()); createCoreBridge(); String messageSuffix = UUID.randomUUID().toString(); TextMessage receivedMessage = getBridgedMessage(messageSuffix); assertNotNull("Expected message was not received", receivedMessage); assertEquals(createMessage(messageSuffix), receivedMessage.getText()); } finally { ModelNode operation = createOpNode("system-property=" + ROUTING_TYPE_PROPERTY, ModelDescriptionConstants.REMOVE); Utils.applyUpdate(operation, managementClient.getControllerClient()); jmsOperations.removeCoreBridge(BRIDGE_NAME); } } private String createMessage(String suffix) { return MESSAGE_TEXT + " ## " + suffix; } private TextMessage getBridgedMessage(String messageSuffix) throws Exception { InitialContext remoteContext = createJNDIContext(); try { ConnectionFactory connectionFactory = (ConnectionFactory) remoteContext.lookup(REMOTE_CONNECTION_FACTORY_LOOKUP); Queue sourceQueue = (Queue) remoteContext.lookup(SOURCE_QUEUE_LOOKUP); Topic targetTopic = (Topic) remoteContext.lookup(TARGET_TOPIC_LOOKUP); try (Connection conn = connectionFactory.createConnection("guest", "guest"); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(sourceQueue); MessageConsumer consumer = session.createConsumer(targetTopic)) { conn.start(); Message message = session.createTextMessage(createMessage(messageSuffix)); message.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); producer.send(message); return (TextMessage) consumer.receive(TimeoutUtil.adjust(500)); } } finally { remoteContext.close(); } } private void createCoreBridge() { ModelNode bridgeAttributes = new ModelNode(); bridgeAttributes.get("queue-name").set("jms.queue." + SOURCE_QUEUE_NAME); bridgeAttributes.get("forwarding-address").set("jms.topic." + TARGET_TOPIC_NAME); bridgeAttributes.get("static-connectors").add("in-vm"); bridgeAttributes.get("use-duplicate-detection").set(false); bridgeAttributes.get("user").set("guest"); bridgeAttributes.get("password").set("guest"); jmsOperations.addCoreBridge(BRIDGE_NAME, bridgeAttributes); } private void removeMessages(boolean topic, String name) throws IOException { ModelNode operation = new ModelNode(); String propertyName = topic ? "jms-topic" : "jms-queue"; operation.get(ADDRESS).set(jmsOperations.getServerAddress().add(propertyName, name)); operation.get(OP).set("remove-messages"); jmsOperations.getControllerClient().execute(operation); } private static ManagementClient createManagementClient() { return new ManagementClient( TestSuiteEnvironment.getModelControllerClient(), TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddress()), TestSuiteEnvironment.getServerPort(), "remote+http"); } protected static InitialContext createJNDIContext() throws NamingException { final Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "org.wildfly.naming.client.WildFlyInitialContextFactory"); String ipAdddress = TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddress()); env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, "remote+http://" + ipAdddress + ":8080")); env.put(Context.SECURITY_PRINCIPAL, "guest"); env.put(Context.SECURITY_CREDENTIALS, "guest"); return new InitialContext(env); } }
9,782
44.929577
151
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/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.manualmode.messaging.deployment; 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 = "java:/jms/DependentMessagingDeploymentTestCase/myQueue") } ) 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,168
33.983871
151
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/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.manualmode.messaging.deployment; 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 = "java:/jms/DependentMessagingDeploymentTestCase/myTopic") } ) 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,168
33.983871
151
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/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.manualmode.messaging.deployment; import org.jboss.as.test.shared.TimeoutUtil; 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 = "java:/jms/DependentMessagingDeploymentTestCase/myQueue") private Queue queue; @Resource(lookup = "java:/jms/DependentMessagingDeploymentTestCase/myTopic") 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)); } }
2,918
34.597561
113
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/ha/ReplicatedFailoverTestCase.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.jboss.as.test.manualmode.messaging.ha; 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.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.security.AccessController; import java.security.PrivilegedAction; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; 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.jgroups.util.Util; import org.junit.Assume; import org.junit.BeforeClass; /** * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc. */ public class ReplicatedFailoverTestCase extends FailoverTestCase { private static final ModelNode PRIMARY_STORE_ADDRESS = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/ha-policy=replication-primary").toModelNode(); private static final ModelNode SECONDARY_STORE_ADDRESS = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/ha-policy=replication-secondary").toModelNode(); @BeforeClass public static void beforeClass() { AccessController.doPrivileged((PrivilegedAction<Void>) () -> { Assume.assumeFalse("[WFLY-14481] Disable on Windows", Util.checkForWindows()); return null; }); } @Override protected void setUpServer1(ModelControllerClient client) throws Exception { configureCluster(client); // /subsystem=messaging-activemq/server=default/ha-policy=replication-primary:add(cluster-name=my-cluster, check-for-live-server=true) ModelNode operation = Operations.createAddOperation(PRIMARY_STORE_ADDRESS); operation.get("cluster-name").set("my-cluster"); operation.get("check-for-live-server").set(true); execute(client, operation); JMSOperations jmsOperations = JMSOperationsProvider.getInstance(client); jmsOperations.createJmsQueue(jmsQueueName, "java:jboss/exported/" + jmsQueueLookup); // jmsOperations.enableMessagingTraces(); } @Override protected void setUpServer2(ModelControllerClient client) throws Exception { configureCluster(client); // /subsystem=messaging-activemq/server=default/ha-policy=replication-secondary:add(cluster-name=my-cluster, restart-backup=true) ModelNode operation = Operations.createAddOperation(SECONDARY_STORE_ADDRESS); operation.get("cluster-name").set("my-cluster"); operation.get("restart-backup").set(true); execute(client, operation); JMSOperations jmsOperations = JMSOperationsProvider.getInstance(client); jmsOperations.createJmsQueue(jmsQueueName, "java:jboss/exported/" + jmsQueueLookup); // jmsOperations.enableMessagingTraces(); } @Override public void setUp() throws Exception { super.setUp(); // leave some time after servers are setup and reloaded so that the cluster is formed Thread.sleep(TimeoutUtil.adjust(2000)); } private void configureCluster(ModelControllerClient client) throws Exception { // /subsystem=messaging-activemq/server=default:write-attribute(name=cluster-user, value=clusteruser) ModelNode operation = new ModelNode(); operation.get(OP_ADDR).add(SUBSYSTEM, "messaging-activemq"); operation.get(OP_ADDR).add("server", "default"); operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION); operation.get(NAME).set("cluster-password"); operation.get(VALUE).set("clusterpassword"); execute(client, operation); // /subsystem=messaging-activemq/server=default:write-attribute(name=cluster-password, value=clusterpwd) operation = new ModelNode(); operation.get(OP_ADDR).add(SUBSYSTEM, "messaging-activemq"); operation.get(OP_ADDR).add("server", "default"); operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION); operation.get(NAME).set("cluster-user"); operation.get(VALUE).set("clusteruser"); execute(client, operation); } @Override protected void testPrimaryInSyncWithReplica(ModelControllerClient client) throws Exception { ModelNode operation = Operations.createReadAttributeOperation( PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/ha-policy=replication-primary").toModelNode(), "synchronized-with-backup"); boolean synced = false; long start = System.currentTimeMillis(); while (!synced && (System.currentTimeMillis() - start < TimeoutUtil.adjust(10000))) { synced = execute(client, operation).asBoolean(); } assertTrue(synced); } @Override protected void testSecondaryInSyncWithReplica(ModelControllerClient client) throws Exception { ModelNode operation = Operations.createReadAttributeOperation( PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/ha-policy=replication-secondary").toModelNode(), "synchronized-with-live"); assertTrue(execute(client, operation).asBoolean()); } @Override protected void testPrimaryOutOfSyncWithReplica(ModelControllerClient client) throws Exception { ModelNode operation = Operations.createReadAttributeOperation( PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/ha-policy=replication-primary").toModelNode(), "synchronized-with-backup"); boolean synced = false; long start = System.currentTimeMillis(); while (!synced && (System.currentTimeMillis() - start < TimeoutUtil.adjust(10000))) { synced = execute(client, operation).asBoolean(); } assertFalse(synced); } @Override protected void testSecondaryOutOfSyncWithReplica(ModelControllerClient client) throws Exception { ModelNode operation = Operations.createReadAttributeOperation( PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/ha-policy=replication-secondary").toModelNode(), "synchronized-with-live"); assertFalse(execute(client, operation).asBoolean()); } }
7,946
48.055556
188
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/ha/ReplicatedNettyFailoverTestCase.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.jboss.as.test.manualmode.messaging.ha; 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.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.security.AccessController; import java.security.PrivilegedAction; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; 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.jgroups.util.Util; import org.junit.Assume; import org.junit.BeforeClass; /** * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc. */ public class ReplicatedNettyFailoverTestCase extends FailoverTestCase { private static final ModelNode PRIMARY_STORE_ADDRESS = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/ha-policy=replication-primary").toModelNode(); private static final ModelNode SECONDARY_STORE_ADDRESS = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/ha-policy=replication-secondary").toModelNode(); @BeforeClass public static void beforeClass() { AccessController.doPrivileged((PrivilegedAction<Void>) () -> { Assume.assumeFalse("[WFLY-14481] Disable on Windows", Util.checkForWindows()); return null; }); } @Override protected void setUpServer1(ModelControllerClient client) throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(client); jmsOperations.createSocketBinding("messaging", null, 5445); jmsOperations.createRemoteAcceptor("netty", "messaging", null); jmsOperations.createRemoteConnector("netty", "messaging", null); configureCluster(client); // /subsystem=messaging-activemq/server=default/ha-policy=replication-primary:add(cluster-name=my-cluster, check-for-live-server=true) ModelNode operation = Operations.createAddOperation(PRIMARY_STORE_ADDRESS); operation.get("cluster-name").set("my-cluster"); operation.get("check-for-live-server").set(true); execute(client, operation); jmsOperations.createJmsQueue(jmsQueueName, "java:jboss/exported/" + jmsQueueLookup); // jmsOperations.enableMessagingTraces(); } @Override protected void setUpServer2(ModelControllerClient client) throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(client); jmsOperations.createSocketBinding("messaging", null, 5445); jmsOperations.createRemoteAcceptor("netty", "messaging", null); jmsOperations.createRemoteConnector("netty", "messaging", null); configureCluster(client); // /subsystem=messaging-activemq/server=default/ha-policy=replication-secondary:add(cluster-name=my-cluster, restart-backup=true) ModelNode operation = Operations.createAddOperation(SECONDARY_STORE_ADDRESS); operation.get("cluster-name").set("my-cluster"); operation.get("restart-backup").set(true); execute(client, operation); jmsOperations.createJmsQueue(jmsQueueName, "java:jboss/exported/" + jmsQueueLookup); // jmsOperations.enableMessagingTraces(); } @Override public void setUp() throws Exception { super.setUp(); // leave some time after servers are setup and reloaded so that the cluster is formed Thread.sleep(TimeoutUtil.adjust(2000)); } private void configureCluster(ModelControllerClient client) throws Exception { // /subsystem=messaging-activemq/server=default:write-attribute(name=cluster-user, value=clusteruser) ModelNode operation = new ModelNode(); operation.get(OP_ADDR).add(SUBSYSTEM, "messaging-activemq"); operation.get(OP_ADDR).add("server", "default"); operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION); operation.get(NAME).set("cluster-password"); operation.get(VALUE).set("clusterpassword"); execute(client, operation); // /subsystem=messaging-activemq/server=default:write-attribute(name=cluster-password, value=clusterpwd) operation = new ModelNode(); operation.get(OP_ADDR).add(SUBSYSTEM, "messaging-activemq"); operation.get(OP_ADDR).add("server", "default"); operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION); operation.get(NAME).set("cluster-user"); operation.get(VALUE).set("clusteruser"); execute(client, operation); operation = Operations.createWriteAttributeOperation( PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/broadcast-group=bg-group1").toModelNode(), "connectors", new ModelNode().add("netty")); execute(client, operation); operation = Operations.createWriteAttributeOperation( PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/broadcast-group=bg-group1").toModelNode(), "connectors", new ModelNode().add("netty")); execute(client, operation); operation = Operations.createWriteAttributeOperation( PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/cluster-connection=my-cluster").toModelNode(), "connector-name", "netty"); execute(client, operation); } @Override protected void testPrimaryInSyncWithReplica(ModelControllerClient client) throws Exception { ModelNode operation = Operations.createReadAttributeOperation( PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/ha-policy=replication-primary").toModelNode(), "synchronized-with-backup"); boolean synced = false; long start = System.currentTimeMillis(); while (!synced && (System.currentTimeMillis() - start < TimeoutUtil.adjust(10000))) { synced = execute(client, operation).asBoolean(); } assertTrue(synced); } @Override protected void testSecondaryInSyncWithReplica(ModelControllerClient client) throws Exception { ModelNode operation = Operations.createReadAttributeOperation( PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/ha-policy=replication-secondary").toModelNode(), "synchronized-with-live"); assertTrue(execute(client, operation).asBoolean()); } @Override protected void testPrimaryOutOfSyncWithReplica(ModelControllerClient client) throws Exception { ModelNode operation = Operations.createReadAttributeOperation( PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/ha-policy=replication-primary").toModelNode(), "synchronized-with-backup"); boolean synced = false; long start = System.currentTimeMillis(); while (!synced && (System.currentTimeMillis() - start < TimeoutUtil.adjust(10000))) { synced = execute(client, operation).asBoolean(); } assertFalse(synced); } @Override protected void testSecondaryOutOfSyncWithReplica(ModelControllerClient client) throws Exception { ModelNode operation = Operations.createReadAttributeOperation( PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/ha-policy=replication-secondary").toModelNode(), "synchronized-with-live"); assertFalse(execute(client, operation).asBoolean()); } }
9,258
49.595628
188
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/ha/AbstractMessagingHATestCase.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.jboss.as.test.manualmode.messaging.ha; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION; 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.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.test.shared.ServerReload.executeReloadAndWaitForCompletion; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Properties; import java.util.UUID; import jakarta.jms.ConnectionFactory; import jakarta.jms.Destination; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.ContainerController; 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.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import org.wildfly.test.api.Authentication; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc. */ @RunWith(Arquillian.class) @RunAsClient public abstract class AbstractMessagingHATestCase { public static final String SERVER1 = "jbossas-messaging-ha-server1"; public static final String SERVER2 = "jbossas-messaging-ha-server2"; private static final Logger log = Logger.getLogger(AbstractMessagingHATestCase.class); private static final int OFFSET = 100; // maximum time for HornetQ activation to detect node failover/failback protected static int ACTIVATION_TIMEOUT = TimeoutUtil.adjust(30000); private String snapshotForServer1; private String snapshotForServer2; @ArquillianResource protected static ContainerController container; protected static ModelControllerClient createClient1() { return TestSuiteEnvironment.getModelControllerClient(); } protected static ModelControllerClient createClient2() throws UnknownHostException { return ModelControllerClient.Factory.create(InetAddress.getByName(TestSuiteEnvironment.getServerAddressNode1()), TestSuiteEnvironment.getServerPort() + OFFSET, Authentication.getCallbackHandler()); } private static String takeSnapshot(ModelControllerClient client) throws Exception { ModelNode operation = new ModelNode(); operation.get(OP).set("take-snapshot"); ModelNode result = execute(client, operation); return result.asString(); } protected static void waitForHornetQServerActivation(JMSOperations operations, boolean expectedActive) throws IOException { long start = System.currentTimeMillis(); long now; do { try { boolean started = isHornetQServerStarted(operations); boolean active = isHornetQServerActive(operations); if (started && expectedActive == active) { // leave some time to the hornetq children resources to be installed after the server is activated Thread.sleep(TimeoutUtil.adjust(500)); return; } } catch (Exception e) { } try { Thread.sleep(100); } catch (InterruptedException e) { } now = System.currentTimeMillis(); } while (now - start < ACTIVATION_TIMEOUT); fail("Server did not become active in the imparted time."); } protected static boolean isHornetQServerStarted(JMSOperations operations) throws Exception { ModelNode operation = Operations.createReadAttributeOperation(operations.getServerAddress(), "started"); return execute(operations.getControllerClient(), operation).asBoolean(); } protected static boolean isHornetQServerActive(JMSOperations operations) throws Exception { ModelNode operation = Operations.createReadAttributeOperation(operations.getServerAddress(), "active"); return execute(operations.getControllerClient(), operation).asBoolean(); } protected static void checkHornetQServerStartedAndActiveAttributes(JMSOperations operations, boolean expectedStarted, boolean expectedActive) throws Exception { assertEquals(expectedStarted, isHornetQServerStarted(operations)); assertEquals(expectedActive, isHornetQServerActive(operations)); } protected static InitialContext createJNDIContextFromServer1() throws NamingException { final Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "org.wildfly.naming.client.WildFlyInitialContextFactory"); String ipAdddress = TestSuiteEnvironment.getServerAddress("node0"); env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, "remote+http://" + ipAdddress + ":" + TestSuiteEnvironment.getHttpPort())); env.put(Context.SECURITY_PRINCIPAL, "guest"); env.put(Context.SECURITY_CREDENTIALS, "guest"); return new InitialContext(env); } protected static InitialContext createJNDIContextFromServer2() throws NamingException { final Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "org.wildfly.naming.client.WildFlyInitialContextFactory"); String ipAdddress = TestSuiteEnvironment.getServerAddressNode1(); env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, "remote+http://" + ipAdddress + ":" + (TestSuiteEnvironment.getHttpPort() + OFFSET))); env.put(Context.SECURITY_PRINCIPAL, "guest"); env.put(Context.SECURITY_CREDENTIALS, "guest"); return new InitialContext(env); } protected static void sendMessage(Context ctx, String destinationLookup, String text) throws NamingException { log.trace("Looking up for the RemoteConnectionFactory with " + ctx); ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory"); assertNotNull(cf); log.trace("Looking up for the destination with " + ctx); Destination destination = (Destination) ctx.lookup(destinationLookup); assertNotNull(destination); try ( JMSContext context = cf.createContext("guest", "guest")) { context.createProducer().send(destination, text); } } protected static void receiveMessage(Context ctx, String destinationLookup, String expectedText) throws NamingException { log.trace("Looking up for the RemoteConnectionFactory with " + ctx); ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory"); assertNotNull(cf); log.trace("Looking up for the destination with " + ctx); Destination destination = (Destination) ctx.lookup(destinationLookup); assertNotNull(destination); try ( JMSContext context = cf.createContext("guest", "guest"); JMSConsumer consumer = context.createConsumer(destination)) { String text = consumer.receiveBody(String.class, TimeoutUtil.adjust(5000)); assertNotNull(text); assertEquals(expectedText, text); } } protected static void sendAndReceiveMessage(Context ctx, String destinationLookup) throws NamingException { String text = UUID.randomUUID().toString(); sendMessage(ctx, destinationLookup, text); receiveMessage(ctx, destinationLookup, text); } protected static void receiveNoMessage(Context ctx, String destinationLookup) throws NamingException { ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory"); assertNotNull(cf); Destination destination = (Destination) ctx.lookup(destinationLookup); assertNotNull(destination); try ( JMSContext context = cf.createContext("guest", "guest"); JMSConsumer consumer = context.createConsumer(destination)) { String text = consumer.receiveBody(String.class, TimeoutUtil.adjust(5000)); assertNull(text); } } protected static void checkJMSQueue(JMSOperations operations, String jmsQueueName, boolean active) throws Exception { ModelNode address = operations.getServerAddress().add("jms-queue", jmsQueueName); checkQueue0(operations.getControllerClient(), address, "queue-address", active); } protected static void checkQueue0(ModelControllerClient client, ModelNode address, String runtimeAttributeName, boolean active) throws Exception { ModelNode operation = new ModelNode(); operation.get(OP_ADDR).set(address); operation.get(OP).set(READ_RESOURCE_OPERATION); // runtime operation operation.get(OP).set("list-messages"); if (active) { execute(client, operation); } else { executeWithFailure(client, operation); } } private void restoreSnapshot(String snapshot) throws IOException { Path snapshotFile = new File(snapshot).toPath(); Path standaloneConfiguration = snapshotFile.getParent().getParent().getParent().resolve("standalone-full-ha.xml"); Files.move(snapshotFile, standaloneConfiguration, StandardCopyOption.REPLACE_EXISTING); } protected static ModelNode execute(ModelControllerClient client, ModelNode operation) throws Exception { ModelNode response = client.execute(operation); boolean success = Operations.isSuccessfulOutcome(response); if (success) { return response.get(RESULT); } throw new Exception("Operation failed " + Operations.getFailureDescription(response)); } protected static void executeWithFailure(ModelControllerClient client, ModelNode operation) throws IOException { ModelNode result = client.execute(operation); assertEquals(result.toJSONString(true), FAILED, result.get(OUTCOME).asString()); assertTrue(result.toJSONString(true), result.get(FAILURE_DESCRIPTION).asString().contains("WFLYMSGAMQ0066")); assertFalse(result.has(RESULT)); } @Before public void setUp() throws Exception { clearArtemisFiles(); // start server1 and reload it in admin-only container.start(SERVER1); ModelControllerClient client1 = createClient1(); snapshotForServer1 = takeSnapshot(client1); executeReloadAndWaitForCompletionOfServer1(client1, true); client1 = createClient1(); // start server2 and reload it in admin-only container.start(SERVER2); ModelControllerClient client2 = createClient2(); snapshotForServer2 = takeSnapshot(client2); executeReloadAndWaitForCompletionOfServer2(client2, true); client2 = createClient2(); // setup both servers try { setUpServer1(client1); setUpServer2(client2); } catch (Exception e) { tearDown(); throw e; } // reload server1 in normal mode executeReloadAndWaitForCompletionOfServer1(client1, false); client1 = createClient1(); // reload server2 in normal mode executeReloadAndWaitForCompletionOfServer2(client2, false); client2 = createClient2(); // both servers are started and configured assertTrue(container.isStarted(SERVER1)); client1.close(); assertTrue(container.isStarted(SERVER2)); client2.close(); } protected abstract void setUpServer1(ModelControllerClient client) throws Exception; protected abstract void setUpServer2(ModelControllerClient client) throws Exception; @After public void tearDown() throws Exception { if (container.isStarted(SERVER1)) { container.stop(SERVER1); } restoreSnapshot(snapshotForServer1); if (container.isStarted(SERVER2)) { container.stop(SERVER2); } restoreSnapshot(snapshotForServer2); clearArtemisFiles(); } private void executeReloadAndWaitForCompletionOfServer1(ModelControllerClient initialClient, boolean adminOnly) throws Exception { executeReloadAndWaitForCompletion(initialClient, ServerReload.TIMEOUT, adminOnly, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort()); } private void executeReloadAndWaitForCompletionOfServer2(ModelControllerClient initialClient, boolean adminOnly) throws Exception { executeReloadAndWaitForCompletion(initialClient, ServerReload.TIMEOUT, adminOnly, TestSuiteEnvironment.getServerAddressNode1(), TestSuiteEnvironment.getServerPort() + OFFSET); } protected static void clearArtemisFiles() { File server1 = new File(SERVER1).toPath().resolve("standalone").resolve("data").resolve("activemq").toFile(); deleteRecursive(server1); File server2 = new File(SERVER2).toPath().resolve("standalone").resolve("data").resolve("activemq").toFile(); deleteRecursive(server2); } protected static void deleteRecursive(File file) { File[] files = file.listFiles(); if(files != null) { File[] var2 = files; int var3 = files.length; for(int var4 = 0; var4 < var3; ++var4) { File f = var2[var4]; deleteRecursive(f); } } file.delete(); } }
15,793
43.490141
165
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/ha/FailoverTestCase.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.jboss.as.test.manualmode.messaging.ha; import javax.naming.InitialContext; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.logging.Logger; import org.junit.Test; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc. */ public abstract class FailoverTestCase extends AbstractMessagingHATestCase { private final Logger log = Logger.getLogger(FailoverTestCase.class); protected final String jmsQueueName = "FailoverTestCase-Queue"; protected final String jmsQueueLookup = "jms/" + jmsQueueName; @Test public void testBackupActivation() throws Exception { ModelControllerClient client2 = createClient2(); JMSOperations jmsOperations2 = JMSOperationsProvider.getInstance(client2); checkJMSQueue(jmsOperations2, jmsQueueName, false); InitialContext context1 = createJNDIContextFromServer1(); sendAndReceiveMessage(context1, jmsQueueLookup); // send a message to server1 before it is stopped String text = "sent to server1, received from server2 (after failover)"; sendMessage(context1, jmsQueueLookup, text); context1.close(); testPrimaryInSyncWithReplica(createClient1()); testSecondaryInSyncWithReplica(client2); log.trace("==================="); log.trace("STOP SERVER1..."); log.trace("==================="); container.stop(SERVER1); // let some time for the backup to detect the failure waitForHornetQServerActivation(jmsOperations2, true); checkJMSQueue(jmsOperations2, jmsQueueName, true); testSecondaryOutOfSyncWithReplica(client2); InitialContext context2 = createJNDIContextFromServer2(); // receive the message that was sent to server1 before failover occurs receiveMessage(context2, jmsQueueLookup, text); sendAndReceiveMessage(context2, jmsQueueLookup); String text2 = "sent to server2, received from server 1 (after failback)"; sendMessage(context2, jmsQueueLookup, text2); context2.close(); testSecondaryOutOfSyncWithReplica(client2); log.trace("===================="); log.trace("START SERVER1..."); log.trace("===================="); // restart the live server container.start(SERVER1); // let some time for the backup to detect the live node and failback ModelControllerClient client1 = createClient1(); JMSOperations jmsOperations1 = JMSOperationsProvider.getInstance(client1); waitForHornetQServerActivation(jmsOperations1, true); checkHornetQServerStartedAndActiveAttributes(jmsOperations1, true, true); // let some time for the backup to detect the failure waitForHornetQServerActivation(jmsOperations2, false); // backup server has been restarted in passive mode checkHornetQServerStartedAndActiveAttributes(jmsOperations2, true, false); checkJMSQueue(jmsOperations2, jmsQueueName, false); context1 = createJNDIContextFromServer1(); // receive the message that was sent to server2 before failback receiveMessage(context1, jmsQueueLookup, text2); // send & receive a message from server1 sendAndReceiveMessage(context1, jmsQueueLookup); context1.close(); testPrimaryInSyncWithReplica(client1); testSecondaryInSyncWithReplica(client2); log.trace("============================="); log.trace("RETURN TO NORMAL OPERATION..."); log.trace("============================="); log.trace("==================="); log.trace("STOP SERVER2..."); log.trace("==================="); container.stop(SERVER2); testPrimaryOutOfSyncWithReplica(client1); } @Test public void testBackupFailoverAfterFailback() throws Exception { ModelControllerClient client2 = createClient2(); JMSOperations backupJMSOperations = JMSOperationsProvider.getInstance(client2); checkJMSQueue(backupJMSOperations, jmsQueueName, false); InitialContext context1 = createJNDIContextFromServer1(); String text = "sent to server1, received from server2 (after failover)"; sendMessage(context1, jmsQueueLookup, text); context1.close(); testPrimaryInSyncWithReplica(createClient1()); testSecondaryInSyncWithReplica(client2); log.trace("############## 1 #############"); //listSharedStoreDir(); log.trace("==================="); log.trace("STOP SERVER1..."); log.trace("==================="); container.stop(SERVER1); log.trace("############## 2 #############"); //listSharedStoreDir(); // let some time for the backup to detect the failure waitForHornetQServerActivation(backupJMSOperations, true); checkJMSQueue(backupJMSOperations, jmsQueueName, true); testSecondaryOutOfSyncWithReplica(client2); InitialContext context2 = createJNDIContextFromServer2(); // receive the message that was sent to server1 before failover occurs receiveMessage(context2, jmsQueueLookup, text); // send a message to server2 before server1 fails back String text2 = "sent to server2, received from server 1 (after failback)"; sendMessage(context2, jmsQueueLookup, text2); context2.close(); testSecondaryOutOfSyncWithReplica(client2); log.trace("===================="); log.trace("START SERVER1..."); log.trace("===================="); // restart the live server container.start(SERVER1); // let some time for the backup to detect the live node and failback ModelControllerClient client1 = createClient1(); JMSOperations liveJMSOperations = JMSOperationsProvider.getInstance(client1); waitForHornetQServerActivation(liveJMSOperations, true); checkHornetQServerStartedAndActiveAttributes(liveJMSOperations, true, true); // let some time for the backup to detect the failure waitForHornetQServerActivation(backupJMSOperations, false); // backup server has been restarted in passive mode checkHornetQServerStartedAndActiveAttributes(backupJMSOperations, true, false); checkJMSQueue(backupJMSOperations, jmsQueueName, false); context1 = createJNDIContextFromServer1(); // receive the message that was sent to server2 before failback receiveMessage(context1, jmsQueueLookup, text2); String text3 = "sent to server1, received from server2 (after 2nd failover)"; // send a message to server1 before it is stopped a 2nd time sendMessage(context1, jmsQueueLookup, text3); context1.close(); testPrimaryInSyncWithReplica(client1); testSecondaryInSyncWithReplica(client2); log.trace("=============================="); log.trace("STOP SERVER1 A 2ND TIME..."); log.trace("=============================="); // shutdown server1 a 2nd time container.stop(SERVER1); // let some time for the backup to detect the failure waitForHornetQServerActivation(backupJMSOperations, true); checkHornetQServerStartedAndActiveAttributes(backupJMSOperations, true, true); checkJMSQueue(backupJMSOperations, jmsQueueName, true); context2 = createJNDIContextFromServer2(); // receive the message that was sent to server1 before failover occurs a 2nd time receiveMessage(context2, jmsQueueLookup, text3); context2.close(); log.trace("===================="); log.trace("START SERVER1 A 2ND TIME..."); log.trace("===================="); // restart the live server container.start(SERVER1); // let some time for the backup to detect the live node and failback client1 = createClient1(); liveJMSOperations = JMSOperationsProvider.getInstance(client1); waitForHornetQServerActivation(liveJMSOperations, true); checkHornetQServerStartedAndActiveAttributes(liveJMSOperations, true, true); // let some time for the backup to detect the failure waitForHornetQServerActivation(backupJMSOperations, false); // backup server has been restarted in passive mode checkHornetQServerStartedAndActiveAttributes(backupJMSOperations, true, false); checkJMSQueue(backupJMSOperations, jmsQueueName, false); context1 = createJNDIContextFromServer1(); // There should be no message to receive as it was consumed from the backup receiveNoMessage(context1, jmsQueueLookup); } protected void testPrimaryInSyncWithReplica(ModelControllerClient client) throws Exception {} protected void testSecondaryInSyncWithReplica(ModelControllerClient client) throws Exception {} protected void testPrimaryOutOfSyncWithReplica(ModelControllerClient client) throws Exception {} protected void testSecondaryOutOfSyncWithReplica(ModelControllerClient client) throws Exception {} }
10,306
43.813043
103
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/ha/SharedStoreFailoverTestCase.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.jboss.as.test.manualmode.messaging.ha; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME; 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.PATH; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION; import static org.jboss.as.test.manualmode.messaging.ha.AbstractMessagingHATestCase.execute; import java.io.File; import java.security.AccessController; import java.security.PrivilegedAction; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; 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.dmr.ModelNode; import org.jgroups.util.StackType; import org.jgroups.util.Util; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; /** * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc. */ public class SharedStoreFailoverTestCase extends FailoverTestCase { private static final File SHARED_STORE_DIR = new File(System.getProperty("java.io.tmpdir"), "activemq"); private static final ModelNode PRIMARY_STORE_ADDRESS = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/ha-policy=shared-store-primary").toModelNode(); private static final ModelNode SECONDARY_STORE_ADDRESS = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/ha-policy=shared-store-secondary").toModelNode(); @BeforeClass public static void beforeClass() { AccessController.doPrivileged((PrivilegedAction<Void>) () -> { Assume.assumeFalse("[WFCI-32] Disable on Windows+IPv6 until CI environment is fixed", Util.checkForWindows() && (Util.getIpStackType() == StackType.IPv6)); return null; }); } @Before @Override public void setUp() throws Exception { // remove shared store files deleteRecursive(SHARED_STORE_DIR); SHARED_STORE_DIR.mkdirs(); super.setUp(); } @Override protected void setUpServer1(ModelControllerClient client) throws Exception { // /subsystem=messaging-activemq/server=default/ha-policy=shared-store-primary:add(failover-on-server-shutdown=true) ModelNode operation = Operations.createAddOperation(PRIMARY_STORE_ADDRESS); operation.get("failover-on-server-shutdown").set(true); execute(client, operation); configureSharedStore(client); JMSOperations jmsOperations = JMSOperationsProvider.getInstance(client); jmsOperations.createJmsQueue(jmsQueueName, "java:jboss/exported/" + jmsQueueLookup); } @Override protected void setUpServer2(ModelControllerClient client) throws Exception { // /subsystem=messaging-activemq/server=default/ha-policy=shared-store-secondary:add(restart-backup=true) ModelNode operation = Operations.createAddOperation(SECONDARY_STORE_ADDRESS); operation.get("restart-backup").set(true); execute(client, operation); configureSharedStore(client); JMSOperations jmsOperations = JMSOperationsProvider.getInstance(client); jmsOperations.createJmsQueue(jmsQueueName, "java:jboss/exported/" + jmsQueueLookup); } @Override public void tearDown() throws Exception { super.tearDown(); // remove shared store files deleteRecursive(SHARED_STORE_DIR); } private void configureSharedStore(ModelControllerClient client) throws Exception { ModelNode operation = new ModelNode(); operation.get(OP_ADDR).add("subsystem", "messaging-activemq"); operation.get(OP_ADDR).add("server", "default"); operation.get(OP).set(READ_RESOURCE_OPERATION); operation.get(INCLUDE_RUNTIME).set(true); execute(client, operation); operation = Operations.createWriteAttributeOperation( PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default").toModelNode(), "cluster-password", "guest"); execute(client, operation); for (String path : new String[] {"journal-directory", "large-messages-directory", "bindings-directory", "paging-directory" }) { // /subsystem=messaging-activemq/server=default/path=XXX:wite-attribute(name=path, value=YYY) File f = new File(SHARED_STORE_DIR, path); ModelNode undefineRelativeToAttribute = Operations.createWriteAttributeOperation( PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/path=" + path).toModelNode(), PATH, f.getAbsolutePath()); execute(client, undefineRelativeToAttribute); } } }
6,138
45.157895
189
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/transaction/AddCMRTestCase.java
/* * JBoss, Home of Professional Open Source * Copyright 2020, 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.manualmode.transaction; import org.jboss.arquillian.container.test.api.ContainerController; 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.management.base.AbstractCliTestBase; import org.jboss.as.test.integration.management.util.CLIOpResult; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.logging.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import java.util.Map; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROCESS_STATE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESPONSE_HEADERS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @RunWith(Arquillian.class) @RunAsClient public class AddCMRTestCase extends AbstractCliTestBase { @SuppressWarnings("unused") private static Logger log = Logger.getLogger(AddCMRTestCase.class); private static final String CONTAINER = "default-jbossas"; private static final String CMR_CLI_CMD = "/subsystem=transactions/commit-markable-resource=\"java:jboss/datasources/test-cmr\""; @ArquillianResource private static ContainerController container; @Before public void before() throws Exception { if (!container.isStarted(CONTAINER)) { container.start(CONTAINER); } initCLI(TimeoutUtil.adjust(20 * 1000)); } @After public void after() throws Exception { if (container.isStarted(CONTAINER)) { container.stop(CONTAINER); } closeCLI(); } @Test public void testAddCMR() throws IOException { cli.sendLine(CMR_CLI_CMD + ":add()"); CLIOpResult result = cli.readAllAsOpResult(); assertNotNull("Failed to add CMR datasource (null CLIOpResult).", result); assertTrue("Failed to add CMR datasource.", result.isIsOutcomeSuccess()); try { if (result.getFromResponse(RESPONSE_HEADERS) != null) { assertEquals("restart-required", ((Map) result.getFromResponse(RESPONSE_HEADERS)).get(PROCESS_STATE)); } } finally { cli.sendLine(CMR_CLI_CMD + ":remove()"); } } }
3,515
36.010526
133
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/transaction/ObjectStoreTypeTestCase.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.manualmode.transaction; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROCESS_STATE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESPONSE_HEADERS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.util.Map; import org.jboss.arquillian.container.test.api.ContainerController; 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.management.base.AbstractCliTestBase; import org.jboss.as.test.integration.management.util.CLIOpResult; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * @author Ivo Studensky - <istudensky@redhat.com>, initial test case * @author Romain Pelisse - <belaran@redhat.com>, rework testcase for work on JBEAP-6449 * */ @RunWith(Arquillian.class) @RunAsClient public class ObjectStoreTypeTestCase extends AbstractCliTestBase { @SuppressWarnings("unused") private static Logger log = Logger.getLogger(ObjectStoreTypeTestCase.class); private static final String CONTAINER = "default-jbossas"; private static final String JDBC_STORE_DS_NAME = "ObjectStoreTestDS"; @ArquillianResource private static ContainerController container; @Before public void before() throws Exception { container.start(CONTAINER); initCLI(TimeoutUtil.adjust(20 * 1000)); String objectStoreType = readObjectStoreType(); assertTrue("Invalid store type: " + objectStoreType, objectStoreType.equals("journal") || objectStoreType.equals("default")); setDefaultObjectStore(); } @After public void after() throws Exception { closeCLI(); container.stop(CONTAINER); } @SuppressWarnings("rawtypes") private void check(String objectStoreTypeExpected) throws IOException, MgmtOperationException { final CLIOpResult ret = cli.readAllAsOpResult(); if (ret != null && ret.getFromResponse(RESPONSE_HEADERS) != null) { assertEquals("restart-required", (String) ((Map) ret.getFromResponse(RESPONSE_HEADERS)).get(PROCESS_STATE)); cli.sendLine("reload"); } String objectStoreType = readObjectStoreType(); assertEquals(objectStoreTypeExpected, objectStoreType); } @Test public void testHornetQObjectStore() throws IOException, MgmtOperationException { try { useJournalStore(); } finally { setDefaultObjectStore(); } } @Test public void testJournalObjectStore() throws IOException, MgmtOperationException { try { cli.sendLine("/subsystem=transactions:write-attribute(name=use-journal-store, value=true)"); check("journal"); } finally { setDefaultObjectStore(); } } @Test public void testJdbcObjectStore() throws IOException, MgmtOperationException { try { useJdbcStore(); check("jdbc"); } finally { cleanJdbcSettingsAndResetToObjectStore(); } } @Test public void ifJournalIsTrueThenHornetQToo() throws IOException, MgmtOperationException { useJournalStore(); checkThatAllUseAttributesAreConsistent("true", "false", "true"); } private void useJdbcStore() throws IOException, MgmtOperationException { useJdbcStore(true); } private void useJdbcStore(boolean expectedResults) throws IOException, MgmtOperationException { setDefaultObjectStore(); // 1 - Create DS - required for the JDBC store createDataSource(); // 2 - Set the value for 'jdbc-store-datasource' cli.sendLine("/subsystem=transactions:write-attribute(name=jdbc-store-datasource, value=java:jboss/datasources/" + JDBC_STORE_DS_NAME + ")"); CLIOpResult result = cli.readAllAsOpResult(); assertTrue("Failed to set jdbc-store-datasource.", result.isIsOutcomeSuccess()); // 3 - set 'use-jdbc-store' to true cli.sendLine("/subsystem=transactions:write-attribute(name=use-jdbc-store, value=true)"); result = cli.readAllAsOpResult(); assertEquals("Failed to set use-jdbc-store to expected value", expectedResults, result.isIsOutcomeSuccess()); } @Test public void testUseJdbcStoreWithoutDatasource() throws Exception { try { // try to set use-jdbc-store to true without defining datasource cli.sendLine("/subsystem=transactions:write-attribute(name=use-jdbc-store, value=true)", true); CLIOpResult result = cli.readAllAsOpResult(); assertFalse("Expected failure when jdbc-store-datasource is not set.", result.isIsOutcomeSuccess()); } finally { setDefaultObjectStore(); } } @Test public void testUndefinedJdbcStoreDSWhenJDBCisUsed() throws Exception { try { // Use JDBC store useJdbcStore(); // try, and fail, to undefine jdbc-store-datasource when use-jdbc-store is set to true cli.sendLine("/subsystem=transactions:undefine-attribute(name=jdbc-store-datasource", true); CLIOpResult result = cli.readAllAsOpResult(); if (result.isIsOutcomeSuccess()) fail("The jdbc-store-datasource attribute has been undefined, while JDBC store is in use."); } finally { cleanJdbcSettingsAndResetToObjectStore(); } } /** * Test if 0 can be set for default transaction timeout * @throws Exception */ @Test public void testSet0ToTransactionTimeout() throws Exception { try { cli.sendLine("/subsystem=transactions:write-attribute(name=default-timeout,value=0)", true); checkAttributeIsAsExpected("default-timeout", "0"); } finally { setDefaultObjectStore(); } } private void checkAttributeIsAsExpected(String attributeName, String expectedValue) { try { cli.sendLine("/subsystem=transactions:read-attribute(name=" + attributeName + ")"); CLIOpResult result = cli.readAllAsOpResult(); assertEquals(attributeName + " has not the expected value", expectedValue, result.getResult()); } catch (Exception e) { throw new IllegalStateException(e); } } private void checkThatAllUseAttributesAreConsistent(String useJournalStore, String useJdbcStore, String useHornetQStore) { checkAttributeIsAsExpected("use-jdbc-store", useJdbcStore); checkAttributeIsAsExpected("use-journal-store", useJournalStore); checkAttributeIsAsExpected("use-hornetq-store", useHornetQStore); } @Test public void testEitherJdbcOrJournalStore() throws Exception { try { // Set journal store useJournalStore(); // Check that attributes are consistent with setting checkThatAllUseAttributesAreConsistent("true", "false", "true"); // Use jdbcStore useJdbcStore(); // Check that attributes are consistent with setting checkThatAllUseAttributesAreConsistent("false", "true", "false"); } finally { cleanJdbcSettingsAndResetToObjectStore(); } } enum StorageMode { USE_JDBC_STORE("use-jdbc-store"), USE_JOURNAL_STORE("use-journal-store"), USE_HORNETQ_STORE("use-hornetq-store"); StorageMode(String attributeName) { this.attributeName = attributeName; } String attributeName; public static StorageMode buildFromAttributeName(String attributeName) { for ( StorageMode mode : StorageMode.values() ) { if ( mode.attributeName.equals(attributeName) ) return mode; } throw new IllegalArgumentException("No such storage mode available:" + attributeName); } } /* * Checks that using two different storage mechanisms, within a * batch, make the batch fails. * * See https://issues.jboss.org/browse/WFLY-8335 for more information */ @Test(expected=java.lang.AssertionError.class) public void testBatchCliFailsIfNoDSisDefined() throws IOException { createDataSource(); cli.sendLine("batch"); cli.sendLine("/subsystem=transactions:write-attribute(name=use-journal-store,value=true)"); cli.sendLine("/subsystem=transactions:write-attribute(name=jdbc-store-datasource, value=java:jboss/datasources/" + JDBC_STORE_DS_NAME + ")"); cli.sendLine("/subsystem=transactions:write-attribute(name=use-jdbc-store,value=true)"); cli.sendLine("run-batch"); } @Test public void testThatAlternatesAreProperlyDefined() throws IOException { cli.sendLine("/subsystem=transactions:read-resource-description"); CLIOpResult result = cli.readAllAsOpResult(); if ( result != null && result.getResultAsMap() != null ) { ModelNode atts = (ModelNode)result.getResponseNode().get("result").get("attributes"); for ( StorageMode mode : StorageMode.values() ) checkStorageMode(atts, mode); } else fail("Read resource description operation did provide any result"); } private void checkStorageMode(ModelNode atts, StorageMode mode) { ModelNode modeNode = atts.get(mode.attributeName); assertTrue(modeNode != null); ModelNode alternatives = modeNode.get("alternatives"); assertTrue(alternatives != null); final int alternativesCount = mode == StorageMode.USE_JDBC_STORE ? 2 : 1; assertEquals(alternativesCount, alternatives.asList().size()); for ( int nbAlternative = 0; nbAlternative < alternativesCount ; nbAlternative++ ) checkAlternative(alternatives.get(nbAlternative).asString(), mode); } private void checkAlternative(String alternative, StorageMode mode) { StorageMode alternativeStorageMode = StorageMode.buildFromAttributeName(alternative); assertTrue(alternativeStorageMode != mode ); } private void useJournalStore() throws IOException, MgmtOperationException { cli.sendLine("/subsystem=transactions:write-attribute(name=use-journal-store, value=true)"); check("journal"); } private void createDataSource() { cli.sendLine("data-source add --name=" + JDBC_STORE_DS_NAME + " --jndi-name=java:jboss/datasources/" + JDBC_STORE_DS_NAME + " --driver-name=h2 --connection-url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1 --jta=false"); } private void undefinedAttributeIfDefined(String attributeName) { try { cli.sendLine("/subsystem=transactions:read-attribute(name=" + attributeName + ")"); CLIOpResult result = cli.readAllAsOpResult(); if (result.getResponseNode().isDefined()) cli.sendLine("/subsystem=transactions:undefine-attribute(name=" + attributeName + ")"); } catch (IOException e) { throw new IllegalStateException(e); } } private void cleanJdbcSettingsAndResetToObjectStore() throws IOException, MgmtOperationException { try { cleanupSettingsUsedForJDBCStore(); } finally { setDefaultObjectStore(); } } private void removeDatasource() { try { cli.sendLine("data-source remove --name=" + JDBC_STORE_DS_NAME); } catch (Exception e) { // if the DS does not exist, not need to delete it... } } private void cleanupSettingsUsedForJDBCStore() { try { // Undefine 'use-jdbc-store' first, if defined undefinedAttributeIfDefined("use-jdbc-store"); // then undefine 'jdbc-store' undefinedAttributeIfDefined("jdbc-store-datasource"); // finally delete Datasource if exists removeDatasource(); // Reload configuration cli.sendLine("reload"); } catch (Exception e) { throw new IllegalStateException(e); } } private String readObjectStoreType() throws IOException, MgmtOperationException { cli.sendLine("/subsystem=transactions/log-store=log-store:read-attribute(name=type)"); final CLIOpResult res = cli.readAllAsOpResult(); return (String) res.getResult(); } private void setDefaultObjectStore() throws IOException, MgmtOperationException { final String objectStoreType = readObjectStoreType(); if ("default".equals(objectStoreType)) { return; } try { cli.sendLine("/subsystem=transactions:write-attribute(name=use-journal-store, value=false)"); } finally { cli.sendLine("reload"); } } }
14,419
39.27933
126
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/ReAuthnType.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.manual.elytron.seccontext; /** * Enum of ways which can be used for (re)authentication or identity propagation in Security context propagation tests. * * @see SeccontextUtil#switchIdentity(String, String, java.util.concurrent.Callable, ReAuthnType) * @author Josef Cacek */ public enum ReAuthnType { /** * Don't use any reauthentication. Just call the code. */ NO_REAUTHN, /** * Configure the current identity to be forwarded with own credentials. * ({@code AuthenticationConfiguration.useForwardedIdentity(SecurityDomain.getCurrent())}) */ FORWARDED_AUTHENTICATION, /** * Configure the current identity to be forwarded as authorization (without own credentials). * ({@code AuthenticationConfiguration.useForwardedIdentity(SecurityDomain.getCurrent())}) */ FORWARDED_AUTHORIZATION, /** * Use AuthenticationConfiguration to configure new identity to be used in Elytron. ({@code AuthenticationConfiguration.useName(name).usePassword(password)}) */ AC_AUTHENTICATION, /** * Use AuthenticationConfiguration to configure new authorization to be used in Elytron. ({@code AuthenticationConfiguration.useAuthorizationName}) */ AC_AUTHORIZATION, /** * Use Elytron SecurityDomain API to (re-)authenticate to the current security domain. * ({@code SecurityDomain.getCurrent().authenticate(username, new PasswordGuessEvidence(password))}) */ SD_AUTHENTICATION, /** * Use Elytron SecurityDomain API to (re-)authenticate to the current security domain and then configure it to forward the * identity. (It's a wrapped {@link #FORWARDED_IDENTITY} within the {@link #SECURITY_DOMAIN_AUTHENTICATE}.) */ SD_AUTHENTICATION_FORWARDED }
2,388
39.491525
161
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/WhoAmIServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 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.wildfly.test.manual.elytron.seccontext; import java.io.IOException; import java.io.PrintWriter; import jakarta.annotation.security.DeclareRoles; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * A servlet which prints the name of the caller principal. */ @WebServlet(urlPatterns = { WhoAmIServlet.SERVLET_PATH }) @ServletSecurity(@HttpConstraint(rolesAllowed = { "servlet", "admin" })) @DeclareRoles({ "entry", "whoami", "servlet", "admin" }) public class WhoAmIServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final String SERVLET_PATH = "/whoAmI"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); final PrintWriter writer = resp.getWriter(); writer.write(req.getUserPrincipal().getName()); writer.close(); } }
2,243
39.071429
113
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/AuthorizationForwardingSLSLTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Authorization forwarding (credential less forwarding) for security context propagation test. Variant which uses both Entry * and WhoAmI beans stateless. * * @author Josef Cacek */ public class AuthorizationForwardingSLSLTestCase extends AbstractAuthorizationForwardingTestCase { @Override protected boolean isEntryStateful() { return false; } @Override protected boolean isWhoAmIStateful() { return false; } }
1,549
35.046512
125
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/HAAuthorizationForwardingSLSFTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Tests authorization forwarding within a cluster. Variant which uses Entry bean stateless and WhoAmI bean stateful. See * superclass for details. * * @author Josef Cacek */ public class HAAuthorizationForwardingSLSFTestCase extends AbstractHAAuthorizationForwardingTestCase { @Override protected boolean isEntryStateful() { return false; } @Override protected boolean isWhoAmIStateful() { return true; } }
1,544
34.930233
121
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/Entry.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.manual.elytron.seccontext; import java.net.URL; import jakarta.ejb.Remote; /** * Interface for the bean used as the entry point to verify EJB3 security behaviour. */ @Remote public interface Entry { /** * @return The name of the Principal obtained from a call to EJBContext.getCallerPrincipal() */ String whoAmI(); /** * Obtains the name of the Principal obtained from a call to EJBContext.getCallerPrincipal() both for the bean called and * also from a call to a second bean (user may be switched before the second call - depending on arguments). * * @return An array containing the name from the local call first followed by the name from the second call. * @throws Exception - If there is an unexpected failure establishing the security context for the second call. */ String[] doubleWhoAmI(CallAnotherBeanInfo info); /** * Obtains the name of the Principal obtained from a call to EJBContext.getCallerPrincipal() for the bean called and * obtains IllegalStateException from a call to a second bean. * * @return An array containing the name from the local call first followed by the IllegalStateException from the second call. * @throws Exception - If there is an unexpected failure establishing the security context for the second call. */ String[] whoAmIAndIllegalStateException(CallAnotherBeanInfo info); /** * Obtains the name of the Principal obtained from a call to EJBContext.getCallerPrincipal() for the bean called and * obtains Server2Exception from a call to a second bean. * * @return An array containing the name from the local call first followed by the Server2Exception from the second call. * @throws Exception - If there is an unexpected failure establishing the security context for the second call. */ String[] whoAmIAndServer2Exception(CallAnotherBeanInfo info); /** * Read remote URL using simple HttpURLConnection. */ String readUrl(String username, String password, ReAuthnType type, final URL url); }
2,707
41.3125
129
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/EntryServlet.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.manual.elytron.seccontext; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_WHOAMI; import java.io.IOException; import java.io.PrintWriter; import java.security.Principal; import java.util.concurrent.Callable; import jakarta.annotation.security.DeclareRoles; import javax.naming.NamingException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Secured servlet which just calls remote {@link WhoAmI} bean and as a response it returns either the bean call result or * exception stack trace. * * @author Josef Cacek */ @WebServlet(urlPatterns = EntryServlet.SERVLET_PATH) @ServletSecurity(@HttpConstraint(rolesAllowed = { "servlet", "admin" })) @DeclareRoles({ "entry", "whoami", "servlet", "admin" }) public class EntryServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final String SERVLET_PATH = "/EntryServlet"; public static final String PARAM_PROVIDER_URL = "providerUrl"; public static final String PARAM_USERNAME = "username"; public static final String PARAM_PASSWORD = "password"; public static final String PARAM_REAUTHN_TYPE = "reAuthnType"; public static final String PARAM_STATEFULL = "statefull"; public static final String PARAM_CREATE_SESSION = "createSession"; public static final String PARAM_AUTHZ_NAME = "authzName"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final PrintWriter writer = resp.getWriter(); final String username = req.getParameter(PARAM_USERNAME); final String password = req.getParameter(PARAM_PASSWORD); final String providerUrl = req.getParameter(PARAM_PROVIDER_URL); final String type = req.getParameter(PARAM_REAUTHN_TYPE); final String statefull = req.getParameter(PARAM_STATEFULL); final String createSession = req.getParameter(PARAM_CREATE_SESSION); final String authzName = req.getParameter(PARAM_AUTHZ_NAME); if (Boolean.parseBoolean(createSession)) { req.getSession(); } final Principal beforePrincipal = req.getUserPrincipal(); final ReAuthnType reAuthnType = type != null ? ReAuthnType.valueOf(type) : ReAuthnType.FORWARDED_AUTHENTICATION; final Callable<String> callable = () -> { return getWhoAmIBean(providerUrl, Boolean.parseBoolean(statefull)).getCallerPrincipal().getName(); }; try { writer.write(SeccontextUtil.switchIdentity(username, password, authzName, callable, reAuthnType)); } catch (Exception e) { e.printStackTrace(writer); } finally { final Principal afterPrincipal = req.getUserPrincipal(); if (beforePrincipal != null && !beforePrincipal.equals(afterPrincipal)) { throw new IllegalStateException( "Local getUserPrincipal() changed from '" + beforePrincipal + "' to '" + afterPrincipal + "'"); } } } private WhoAmI getWhoAmIBean(String providerUrl, boolean statefullWhoAmI) throws NamingException { return SeccontextUtil.lookup( SeccontextUtil.getRemoteEjbName(WAR_WHOAMI, "WhoAmIBean", WhoAmI.class.getName(), statefullWhoAmI), providerUrl); } }
4,226
42.57732
129
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/IdentitySwitchingSFSLTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Identity switching for security context propagation test. Variant which uses Entry bean stateful and WhoAmI bean stateless. * * @author Josef Cacek */ public class IdentitySwitchingSFSLTestCase extends AbstractIdentitySwitchingTestCase { @Override protected boolean isEntryStateful() { return true; } @Override protected boolean isWhoAmIStateful() { return false; } }
1,506
34.880952
126
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/AuthenticationForwardingSLSLTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Authentication forwarding (credential forwarding) for security context propagation test. Variant which uses both Entry and * WhoAmI beans stateless. * * @author Josef Cacek */ public class AuthenticationForwardingSLSLTestCase extends AbstractAuthenticationForwardingTestCase { @Override protected boolean isEntryStateful() { return false; } @Override protected boolean isWhoAmIStateful() { return false; } }
1,547
35
125
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/WildFlyElytronClientDefaultSSLContextProviderTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, 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.wildfly.test.manual.elytron.seccontext; import static java.util.concurrent.TimeUnit.SECONDS; import static org.jboss.as.controller.client.helpers.Operations.createAddOperation; import static org.jboss.as.controller.client.helpers.Operations.createAddress; import static org.jboss.as.controller.client.helpers.Operations.createRemoveOperation; import java.io.File; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.Security; import javax.net.ssl.SSLContext; import jakarta.ws.rs.client.ClientBuilder; import jakarta.ws.rs.core.Response; import org.codehaus.plexus.util.FileUtils; import org.jboss.arquillian.container.test.api.ContainerController; 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.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.CoreUtils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.security.auth.client.WildFlyElytronClientDefaultSSLContextProvider; /** * Integration test for WildFlyElytronClientDefaultSSLContextProvider. * This test uses server that has 2-way SSL context configured with need-client-auth set to true. * WildFlyElytronClientDefaultSSLContextProvider is configured on client side to provide default SSL context that RESTEsy client utilizes to connect to the server. */ @RunWith(Arquillian.class) public class WildFlyElytronClientDefaultSSLContextProviderTestCase { private static final String[] SERVER_KEY_STORE1 = {"subsystem", "elytron", "key-store", "twoWayKS"}; private static final String[] SERVER_KEY_MANAGER1 = {"subsystem", "elytron", "key-manager", "twoWayKM"}; private static final String[] SERVER_TRUST_STORE1 = {"subsystem", "elytron", "key-store", "twoWayTS"}; private static final String[] SERVER_TRUST_MANAGER1 = {"subsystem", "elytron", "trust-manager", "twoWayTM"}; private static final String[] SERVER_SSL_CONTEXT1 = {"subsystem", "elytron", "server-ssl-context", "twoWaySSC"}; private static final String SERVER_KEYSTORE1_FILENAME = "server.keystore"; private static final String SERVER_TRUSTSTORE1_FILENAME = "server.truststore"; private static final String CONTAINER = "default-jbossas"; private static final String SERVER_ADDRESS = TestSuiteEnvironment.getServerAddress(); private static final String JKS = "JKS"; private static final File KEYSTORES_DIR = new File("target/keystores"); private static final String CONFIG_FILE = "./src/test/resources/wildfly-config-default-ssl-context.xml"; @ArquillianResource private static ContainerController serverController; @BeforeClass public static void generateKeyStoresAndConfigureWildFlyElytronClientDefaultSSLContextProvider() throws Exception { if (!KEYSTORES_DIR.exists()) { KEYSTORES_DIR.mkdirs(); } CoreUtils.createKeyMaterial(KEYSTORES_DIR, JKS); Security.insertProviderAt(new WildFlyElytronClientDefaultSSLContextProvider(CONFIG_FILE), 1); } @Test @RunAsClient @InSequence(1) public void startAndConfigureContainerToRequireClientAuth() { if (!serverController.isStarted(CONTAINER)) { serverController.start(CONTAINER); } try { ModelControllerClient modelControllerClient = TestSuiteEnvironment.getModelControllerClient(); ManagementClient managementClient = new ManagementClient(modelControllerClient, SERVER_ADDRESS, getManagementPort(), "remote+http"); configureSSLContextOnServer(managementClient, KEYSTORES_DIR, SERVER_KEYSTORE1_FILENAME, SERVER_KEY_STORE1, SERVER_KEY_MANAGER1, SERVER_TRUSTSTORE1_FILENAME, SERVER_TRUST_STORE1, SERVER_TRUST_MANAGER1, SERVER_SSL_CONTEXT1); reloadServer(modelControllerClient); } catch (Exception e) { Assert.fail(); } } @Test @InSequence(2) @RunAsClient public void testConnectionWithRESTEasyClient() { Assert.assertNotNull(Security.getProvider(WildFlyElytronClientDefaultSSLContextProvider.class.getSimpleName())); try { ResteasyClientBuilder builder = (ResteasyClientBuilder) ClientBuilder.newBuilder(); ResteasyClient resteasyClient = builder.sslContext(SSLContext.getDefault()).hostnameVerification(ResteasyClientBuilder.HostnameVerificationPolicy.ANY).build(); Assert.assertEquals(WildFlyElytronClientDefaultSSLContextProvider.class.getSimpleName(), resteasyClient.getSslContext().getProvider().getName()); Response response = resteasyClient.target("https://localhost:" + 8443).request().get(); Assert.assertEquals(200, response.getStatus()); response.close(); } catch (NoSuchAlgorithmException e) { Assert.fail("WildFlyElytronClientDefaultSSLContextProvider did not provide default SSLContext successfully"); } } @Test @RunAsClient @InSequence(3) public void restoreConfigAndStopContainer() throws IOException { try { ManagementClient managementClient = new ManagementClient(TestSuiteEnvironment.getModelControllerClient(), SERVER_ADDRESS, getManagementPort(), "remote+http"); restoreConfiguration(managementClient); } catch (Exception e) { Assert.fail(); } finally { serverController.stop(CONTAINER); FileUtils.deleteDirectory(KEYSTORES_DIR); Security.removeProvider(new WildFlyElytronClientDefaultSSLContextProvider().getName()); } } private static void configureSSLContextOnServer(ManagementClient managementClient, File directory, String keystoreFilename, String[] keyStore, String[] keyManager, String truststoreFilename, String[] trustStore, String[] trustManager, String[] sslContext1) { try { ModelNode credential = new ModelNode(); credential.get("clear-text").set("123456"); ModelNode modelNode = createAddOperation(createAddress(keyStore)); modelNode.get("type").set(JKS); modelNode.get("path").set(new File(directory, keystoreFilename).getAbsolutePath()); modelNode.get("credential-reference").set(credential); managementClient.getControllerClient().execute(modelNode); modelNode = createAddOperation(createAddress(keyManager)); modelNode.get("algorithm").set("SunX509"); modelNode.get("key-store").set(keyStore[keyStore.length - 1]); modelNode.get("credential-reference").set(credential); managementClient.getControllerClient().execute(modelNode); modelNode = createAddOperation(createAddress(trustStore)); modelNode.get("type").set(JKS); modelNode.get("path").set(new File(directory, truststoreFilename).getAbsolutePath()); modelNode.get("credential-reference").set(credential); managementClient.getControllerClient().execute(modelNode); modelNode = createAddOperation(createAddress(trustManager)); modelNode.get("algorithm").set("SunX509"); modelNode.get("key-store").set(trustStore[trustStore.length - 1]); modelNode.get("credential-reference").set(credential); managementClient.getControllerClient().execute(modelNode); modelNode = createAddOperation(createAddress(sslContext1)); modelNode.get("key-manager").set(keyManager[keyManager.length - 1]); modelNode.get("trust-manager").set(trustManager[trustManager.length - 1]); modelNode.get("protocols").set(new ModelNode().add("TLSv1.2")); modelNode.get("need-client-auth").set(true); Assert.assertTrue(managementClient.getControllerClient().execute(modelNode).asString().contains("\"outcome\" => \"success\"")); // Remove the reference to the legacy security realm and update the https-listener to use the ssl-context we just created CLIWrapper cli = new CLIWrapper(true); cli.sendLine("batch"); cli.sendLine("/subsystem=undertow/server=default-server/https-listener=https:write-attribute(name=ssl-context,value=twoWaySSC)"); cli.sendLine("run-batch"); cli.sendLine("reload"); } catch (Exception e) { Assert.fail(); } } private void restoreConfiguration(ManagementClient managementClient) throws IOException { managementClient.getControllerClient().execute(createRemoveOperation(createAddress(SERVER_SSL_CONTEXT1))); managementClient.getControllerClient().execute(createRemoveOperation(createAddress(SERVER_KEY_MANAGER1))); managementClient.getControllerClient().execute(createRemoveOperation(createAddress(SERVER_TRUST_MANAGER1))); managementClient.getControllerClient().execute(createRemoveOperation(createAddress(SERVER_KEY_STORE1))); managementClient.getControllerClient().execute(createRemoveOperation(createAddress(SERVER_TRUST_STORE1))); } private void reloadServer(ModelControllerClient managementClient) { ServerReload.executeReloadAndWaitForCompletion(managementClient, (int) SECONDS.toMillis(90), false, SERVER_ADDRESS, getManagementPort()); } private int getManagementPort() { return TestSuiteEnvironment.getServerPort(); } }
10,995
52.120773
262
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/EntryBean.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.manual.elytron.seccontext; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_WHOAMI; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.switchIdentity; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.util.concurrent.Callable; import jakarta.annotation.Resource; import jakarta.annotation.security.DeclareRoles; import jakarta.annotation.security.RolesAllowed; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateless; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import javax.naming.NamingException; /** * Stateless Jakarta Enterprise Beans responsible for calling remote Jakarta Enterprise Beans or Servlet. * * @author Josef Cacek */ @Stateless @RolesAllowed({ "entry", "admin", "no-server2-identity", "authz" }) @DeclareRoles({ "entry", "whoami", "servlet", "admin", "no-server2-identity", "authz" }) @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public class EntryBean implements Entry { @Resource private SessionContext context; @Override public String whoAmI() { return context.getCallerPrincipal().getName(); } @Override public String[] doubleWhoAmI(CallAnotherBeanInfo info) { final Callable<String> callable = () -> { return getWhoAmIBean(info.getLookupEjbAppName(), info.getProviderUrl(), info.isStatefullWhoAmI()).getCallerPrincipal().getName(); }; return whoAmIAndCall(info, callable); } public String[] whoAmIAndIllegalStateException(CallAnotherBeanInfo info) { final Callable<String> callable = () -> { return getWhoAmIBean(info.getLookupEjbAppName(), info.getProviderUrl(), info.isStatefullWhoAmI()).throwIllegalStateException(); }; return whoAmIAndCall(info, callable); } public String[] whoAmIAndServer2Exception(CallAnotherBeanInfo info) { final Callable<String> callable = () -> { return getWhoAmIBean(info.getLookupEjbAppName(), info.getProviderUrl(), info.isStatefullWhoAmI()).throwServer2Exception(); }; return whoAmIAndCall(info, callable); } @Override public String readUrl(String username, String password, ReAuthnType type, final URL url) { final Callable<String> callable = () -> { URLConnection conn = url.openConnection(); conn.connect(); try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { return br.readLine(); } }; String result = null; String firstWho = context.getCallerPrincipal().getName(); try { result = switchIdentity(username, password, callable, type); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); result = sw.toString(); } finally { String secondLocalWho = context.getCallerPrincipal().getName(); if (!secondLocalWho.equals(firstWho)) { throw new IllegalStateException( "Local getCallerPrincipal changed from '" + firstWho + "' to '" + secondLocalWho); } } return result; } private String[] whoAmIAndCall(CallAnotherBeanInfo info, Callable<String> callable) { String[] result = new String[2]; result[0] = context.getCallerPrincipal().getName(); try { result[1] = switchIdentity(info.getUsername(), info.getPassword(), info.getAuthzName(), callable, info.getType()); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); result[1] = sw.toString(); } finally { String secondLocalWho = context.getCallerPrincipal().getName(); if (!secondLocalWho.equals(result[0])) { throw new IllegalStateException( "Local getCallerPrincipal changed from '" + result[0] + "' to '" + secondLocalWho); } } return result; } private WhoAmI getWhoAmIBean(String ejbAppName, String providerUrl, boolean statefullWhoAmI) throws NamingException { return SeccontextUtil.lookup( SeccontextUtil.getRemoteEjbName(ejbAppName == null ? WAR_WHOAMI : ejbAppName, "WhoAmIBean", WhoAmI.class.getName(), statefullWhoAmI), providerUrl); } }
5,384
38.021739
128
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/AuthenticationForwardingSFSLTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Authentication forwarding (credential forwarding) for security context propagation test. Variant which uses Entry bean * stateful and WhoAmI bean stateless. * * @author Josef Cacek */ public class AuthenticationForwardingSFSLTestCase extends AbstractAuthenticationForwardingTestCase { @Override protected boolean isEntryStateful() { return true; } @Override protected boolean isWhoAmIStateful() { return false; } }
1,554
35.162791
121
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/IdentitySwitchingSFSFTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Identity switching for security context propagation test. Variant which uses both Entry and WhoAmI beans stateful. * * @author Josef Cacek */ public class IdentitySwitchingSFSFTestCase extends AbstractIdentitySwitchingTestCase { @Override protected boolean isEntryStateful() { return true; } @Override protected boolean isWhoAmIStateful() { return true; } }
1,496
34.642857
117
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/FirstServerChainBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.switchIdentity; import static org.wildfly.test.manual.elytron.seccontext.ServerChainSecurityContextPropagationTestCase.JAR_ENTRY_EJB_SERVER_CHAIN; import java.io.PrintWriter; import java.io.StringWriter; import java.util.concurrent.Callable; import jakarta.annotation.Resource; import jakarta.annotation.security.DeclareRoles; import jakarta.annotation.security.RolesAllowed; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateless; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import javax.naming.NamingException; /** * Stateless EJB responsible for calling remote EntryBean. * * @author olukas */ @Stateless @RolesAllowed({"entry", "admin", "no-server2-identity"}) @DeclareRoles({"entry", "whoami", "servlet", "admin", "no-server2-identity"}) @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public class FirstServerChainBean implements FirstServerChain { @Resource private SessionContext context; @Override public String whoAmI() { return context.getCallerPrincipal().getName(); } @Override public String[] tripleWhoAmI(CallAnotherBeanInfo firstBeanInfo, CallAnotherBeanInfo secondBeanInfo) { String[] result = new String[3]; result[0] = context.getCallerPrincipal().getName(); final Callable<String[]> callable = () -> { return getEntryBean(firstBeanInfo.getLookupEjbAppName(), firstBeanInfo.getProviderUrl(), firstBeanInfo.isStatefullWhoAmI()).doubleWhoAmI(secondBeanInfo); }; try { String[] resultFromAnotherBeans = switchIdentity(firstBeanInfo.getUsername(), firstBeanInfo.getPassword(), callable, firstBeanInfo.getType()); result[1] = resultFromAnotherBeans[0]; result[2] = resultFromAnotherBeans[1]; } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); result[1] = sw.toString(); } finally { String secondLocalWho = context.getCallerPrincipal().getName(); if (!secondLocalWho.equals(result[0])) { throw new IllegalStateException( "Local getCallerPrincipal changed from '" + result[0] + "' to '" + secondLocalWho); } } return result; } private Entry getEntryBean(String ejbAppName, String providerUrl, boolean statefullWhoAmI) throws NamingException { return SeccontextUtil.lookup( SeccontextUtil.getRemoteEjbName(ejbAppName == null ? JAR_ENTRY_EJB_SERVER_CHAIN : ejbAppName, "EntryBean", Entry.class.getName(), statefullWhoAmI), providerUrl); } }
3,904
40.989247
130
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/SeccontextUtil.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.manual.elytron.seccontext; import java.util.Properties; import java.util.concurrent.Callable; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.wildfly.security.auth.client.AuthenticationConfiguration; import org.wildfly.security.auth.client.AuthenticationContext; import org.wildfly.security.auth.client.MatchRule; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.evidence.PasswordGuessEvidence; import org.wildfly.security.sasl.SaslMechanismSelector; /** * Util class for Elytron security context propagation tests. It helps to switch identities and lookup Jakarta Enterprise Beans. * * @author Josef Cacek */ public class SeccontextUtil { /** * Name of the first (entry) server in arquillian configuration. */ public static final String SERVER1 = "seccontext-server1"; public static final String SERVER1_BACKUP = "seccontext-server1-backup"; /** * Name of the second (target) server in arquillian configuration. */ public static final String SERVER2 = "seccontext-server2"; /** * Name of the third (target for server chain) server in arquillian configuration. */ public static final String SERVER3 = "seccontext-server3"; /** * Name of deployment which contains EntryBean Jakarta Enterprise Beans. */ public static final String JAR_ENTRY_EJB = "entry-ejb"; /** * Name of deployment which contains WhoAmI bean and WhoAmIServlet. */ public static final String WAR_WHOAMI = "whoami"; /** * Name of deployment which contains secured EntryServlet with BASIC HTTP authentication mechanism configured. */ public static final String WAR_ENTRY_SERVLET_BASIC = "entry-servlet-basic"; /** * Name of deployment which contains secured EntryServlet with FORM HTTP authentication mechanism configured. */ public static final String WAR_ENTRY_SERVLET_FORM = "entry-servlet-form"; /** * Name of deployment which contains secured EntryServlet with BEARER_TOKEN HTTP authentication mechanism configured. */ public static final String WAR_ENTRY_SERVLET_BEARER_TOKEN = "entry-servlet-bearer"; /** * Method which handles {@link ReAuthnType} types by using Elytron API. Based on provided type new * {@link AuthenticationContext} is created and given callable is called within the context. * * @param username login name used for reauthentication scenarios (or null) * @param password password used for reauthentication scenarios (or null) * @param callable logic to be executed in the requested AuthenticationContext * @param type reauthentication type * @return result of the callable call */ public static <T> T switchIdentity(final String username, final String password, final Callable<T> callable, ReAuthnType type) throws Exception { return switchIdentity(username, password, null, callable, type); } /** * Method which handles {@link ReAuthnType} types by using Elytron API. Based on provided type new * {@link AuthenticationContext} is created and given callable is called within the context. * * @param username login name used for reauthentication scenarios (or null) * @param password password used for reauthentication scenarios (or null) * @param authzName used for authorization name * @param callable logic to be executed in the requested AuthenticationContext * @param type reauthentication type * @return result of the callable call */ public static <T> T switchIdentity(final String username, final String password, final String authzName, final Callable<T> callable, ReAuthnType type) throws Exception { if (type == null) { type = ReAuthnType.AC_AUTHENTICATION; } final SecurityDomain securityDomain = SecurityDomain.getCurrent(); AuthenticationConfiguration authCfg = AuthenticationConfiguration.empty() .setSaslMechanismSelector(SaslMechanismSelector.ALL); switch (type) { case FORWARDED_AUTHENTICATION: return AuthenticationContext.empty().with(MatchRule.ALL, authCfg.useForwardedIdentity(securityDomain)) .runCallable(callable); case FORWARDED_AUTHORIZATION: authCfg = authCfg.useForwardedAuthorizationIdentity(securityDomain); // fall through case AC_AUTHENTICATION: if (username != null) { authCfg = authCfg.useName(username); } if (password != null) { authCfg = authCfg.usePassword(password); } return AuthenticationContext.empty().with(MatchRule.ALL, authCfg).runCallable(callable); case AC_AUTHORIZATION: if (username != null) { authCfg = authCfg.useName(username); } if (password != null) { authCfg = authCfg.usePassword(password); } if (authzName != null) { authCfg = authCfg.useAuthorizationName(authzName); } return AuthenticationContext.empty().with(MatchRule.ALL, authCfg).runCallable(callable); case SD_AUTHENTICATION: return password == null ? null : securityDomain.authenticate(username, new PasswordGuessEvidence(password.toCharArray())) .runAs(callable); case SD_AUTHENTICATION_FORWARDED: final Callable<T> forwardIdentityCallable = () -> { return AuthenticationContext.empty() .with(MatchRule.ALL, AuthenticationConfiguration.empty() .setSaslMechanismSelector(SaslMechanismSelector.ALL) .useForwardedIdentity(securityDomain)) .runCallable(callable); }; return password == null ? null : securityDomain.authenticate(username, new PasswordGuessEvidence(password.toCharArray())) .runAs(forwardIdentityCallable); case NO_REAUTHN: default: return callable.call(); } } /** * Creates "ejb:/..." name for JNDI lookup. * * @return name to be used for Jakarta Enterprise Beans lookup. */ public static String getRemoteEjbName(String appName, String beanSimpleNameBase, String remoteInterfaceName, boolean stateful) { return "ejb:/" + appName + "/" + beanSimpleNameBase + (stateful ? "SFSB!" : "!") + remoteInterfaceName + (stateful ? "?stateful" : ""); } /** * Do JNDI lookup. */ @SuppressWarnings("unchecked") public static <T> T lookup(String name, String providerUrl) throws NamingException { final Properties jndiProperties = new Properties(); jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.wildfly.naming.client.WildFlyInitialContextFactory"); jndiProperties.put(Context.PROVIDER_URL, providerUrl); final Context context = new InitialContext(jndiProperties); return (T) context.lookup(name); } }
8,094
43.972222
128
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/AbstractAuthenticationForwardingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static org.jboss.as.test.integration.security.common.Utils.REDIRECT_STRATEGY; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; import static org.wildfly.test.manual.elytron.seccontext.AbstractSecurityContextPropagationTestBase.isEjbAccessException; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_ENTRY_SERVLET_BASIC; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_ENTRY_SERVLET_BEARER_TOKEN; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_ENTRY_SERVLET_FORM; import java.net.URL; import java.util.concurrent.Callable; import jakarta.ejb.EJBAccessException; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.as.test.integration.security.common.Utils; import org.junit.Ignore; import org.junit.Test; import org.wildfly.security.auth.client.AuthenticationConfiguration; import org.wildfly.security.auth.client.AuthenticationContext; import org.wildfly.security.auth.client.MatchRule; import org.wildfly.security.credential.BearerTokenCredential; import org.wildfly.security.sasl.SaslMechanismSelector; /** * Authentication forwarding (credential forwarding) for security context propagation test. * * @author Josef Cacek */ public abstract class AbstractAuthenticationForwardingTestCase extends AbstractSecurityContextPropagationTestBase { /** * Test forwarding authentication (credential forwarding) works for Jakarta Enterprise Beans calls. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean as admin user and Elytron AuthenticationContext API is used to * authentication forwarding to WhoAmIBean call * Then: credentials are reused for WhoAmIBean call and it correctly returns "admin" username * </pre> */ @Test public void testForwardedAuthenticationPasses() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("admin", "admin", getDoubleWhoAmICallable(ReAuthnType.FORWARDED_AUTHENTICATION, null, null), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertArrayEquals("Unexpected principal names returned from doubleWhoAmI", new String[]{"admin", "admin"}, doubleWhoAmI); } /** * Test the Jakarta Enterprise Beans call fails when using forwarding authentication (credential forwarding) and user has insufficient roles. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean as entry user and Elytron AuthenticationContext API is used to * authentication forwarding to WhoAmIBean call * Then: calling WhoAmIBean fails * </pre> */ @Test public void testForwardedIdentityInsufficientRolesFails() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("entry", "entry", getDoubleWhoAmICallable(ReAuthnType.FORWARDED_AUTHENTICATION, null, null), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertEquals("The result of doubleWhoAmI() has wrong lenght", 2, doubleWhoAmI.length); assertEquals("entry", doubleWhoAmI[0]); assertThat(doubleWhoAmI[1], isEjbAccessException()); } /** * Test the authentication propagation (credentials forwarding) works for OAUTHBEARER SASL mechanism. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean with valid OAuth bearer token of "admin" user. The * authentication forwarding is configured and WhoAmIBean is called * Then: the bearer token is forwarded and WhoAmIBean call returns "admin" username * </pre> */ @Test public void testOauthbearerPropagationPasses() throws Exception { String[] doubleWhoAmI = AuthenticationContext.empty() .with(MatchRule.ALL, AuthenticationConfiguration.empty().setSaslMechanismSelector(SaslMechanismSelector.ALL) .useBearerTokenCredential(new BearerTokenCredential(createJwtToken("admin")))) .runCallable(getDoubleWhoAmICallable(ReAuthnType.FORWARDED_AUTHENTICATION, null, null)); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertArrayEquals("Unexpected principal names returned from doubleWhoAmI", new String[]{"admin", "admin"}, doubleWhoAmI); } /** * Test the authentication propagation (credentials forwarding) fails for OAUTHBEARER SASL mechanism when user has * insufficient roles for the call. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean with valid OAuth bearer token of "entry" user. The * authentication forwarding is configured and WhoAmIBean is called * Then: the WhoAmIBean call fails as the "entry" user has not roles allowed for the call * </pre> */ @Test public void testOauthbearerPropagationInsufficientRolesFails() throws Exception { String[] doubleWhoAmI = AuthenticationContext.empty() .with(MatchRule.ALL, AuthenticationConfiguration.empty().setSaslMechanismSelector(SaslMechanismSelector.ALL) .useBearerTokenCredential(new BearerTokenCredential(createJwtToken("entry")))) .runCallable(getDoubleWhoAmICallable(ReAuthnType.FORWARDED_AUTHENTICATION, null, null)); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertEquals("The result of doubleWhoAmI() has wrong lenght", 2, doubleWhoAmI.length); assertEquals("entry", doubleWhoAmI[0]); assertThat(doubleWhoAmI[1], isEjbAccessException()); } /** * Test the Jakarta Enterprise Beans call using OAUTHBEARER SASL mechanism authentication fails when user has insufficient roles for the call. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean with valid OAuth bearer token of "whoami" user * Then: the EntryBean call fails as the "whoami" user has not roles allowed for the call * </pre> */ @Test public void testClientOauthbearerInsufficientRolesFails() throws Exception { try { AuthenticationContext.empty() .with(MatchRule.ALL, AuthenticationConfiguration.empty().setSaslMechanismSelector(SaslMechanismSelector.ALL) .useBearerTokenCredential(new BearerTokenCredential(createJwtToken("whoami")))) .runCallable(getDoubleWhoAmICallable(ReAuthnType.FORWARDED_AUTHENTICATION, null, null)); fail("Call to the protected bean should fail"); } catch (EJBAccessException e) { // OK - expected } } /** * Tests the HTTP calls to EntryServlet using BASIC mechanism authentication with forwarding authentication (credentials). * * <pre> * When: HTTP client calls EntryServlet (using BASIC authn) and Elytron API is used to forward authentication * to WhoAmIBean * Then: * - "entry" user is not allowed to call EntryServlet (SC_FORBIDDEN returned) * - "servlet" user is allowed to call EntryServlet, but WhoAmIBean call fails (insufficient roles) * - "admin" user is allowed to call EntryServlet and credentials are reused for WhoAmIBean call - returns "admin" * - once more called as "servlet" user - it's allowed to call EntryServlet, but WhoAmIBean call fails (insufficient roles) * </pre> */ @Test public void testServletBasicToEjbForwardedIdentity() throws Exception { final URL entryServletUrl = getEntryServletUrl(WAR_ENTRY_SERVLET_BASIC, null, null, ReAuthnType.FORWARDED_AUTHENTICATION); // call with user who doesn't have sufficient roles on Servlet Utils.makeCallWithBasicAuthn(entryServletUrl, "entry", "entry", SC_FORBIDDEN); // call with user who doesn't have sufficient roles on Jakarta Enterprise Beans assertThat(Utils.makeCallWithBasicAuthn(entryServletUrl, "servlet", "servlet", SC_OK), isEjbAccessException()); // call with user who has all necessary roles assertEquals("Unexpected username returned", "admin", Utils.makeCallWithBasicAuthn(entryServletUrl, "admin", "admin", SC_OK)); // call (again) with the user who doesn't have sufficient roles on Jakarta Enterprise Beans assertThat(Utils.makeCallWithBasicAuthn(entryServletUrl, "servlet", "servlet", SC_OK), isEjbAccessException()); } /** * Test credentials propagation from HTTP FORM authentication when the servlet which needs propagation is not the * authenticated one (i.e. it's requested after the user is already authenticated). * * <pre> * When: HTTP client calls WhoAmIServlet as "admin" (using FORM authn) and then EntryServlet (already authenticated); * the EntryServlet uses Elytron API to forward authentication (credentials) and call WhoAmIBean * Then: both call succeeds and WhoAmIBean returns "admin" * </pre> */ @Test public void testServletFormWhoAmIFirst() throws Exception { final URL entryServletUrl = getEntryServletUrl(WAR_ENTRY_SERVLET_FORM, null, null, ReAuthnType.FORWARDED_AUTHENTICATION); final URL whoAmIServletUrl = new URL( server1.getApplicationHttpUrl() + "/" + WAR_ENTRY_SERVLET_FORM + WhoAmIServlet.SERVLET_PATH); try (CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(REDIRECT_STRATEGY).build()) { assertEquals("Unexpected result from WhoAmIServlet", "admin", doHttpRequestFormAuthn(httpClient, whoAmIServletUrl, true, "admin", "admin", SC_OK)); assertEquals("Unexpected result from EntryServlet", "admin", doHttpRequest(httpClient, entryServletUrl, SC_OK)); } } /** * Test credentials propagation from HTTP FORM authentication when the servlet which needs propagation is not the * authenticated one (i.e. it's requested after the user is already authenticated). * * <pre> * When: HTTP client calls WhoAmIServlet as "servlet" (using FORM authn) and then EntryServlet (already authenticated); * the EntryServlet uses Elytron API to forward authentication (credentials) and call WhoAmIBean * Then: EntryServlet forwards credentials, but the "servlet" user has not roles allowed to call the WhoAmIBean and the call fails * </pre> */ @Test public void testServletFormWhoAmIFirstInsufficientRoles() throws Exception { final URL entryServletUrl = getEntryServletUrl(WAR_ENTRY_SERVLET_FORM, null, null, ReAuthnType.FORWARDED_AUTHENTICATION); final URL whoAmIServletUrl = new URL( server1.getApplicationHttpUrl() + "/" + WAR_ENTRY_SERVLET_FORM + WhoAmIServlet.SERVLET_PATH); try (CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(REDIRECT_STRATEGY).build()) { assertEquals("Unexpected result from WhoAmIServlet", "servlet", doHttpRequestFormAuthn(httpClient, whoAmIServletUrl, true, "servlet", "servlet", SC_OK)); assertThat("Unexpected result from EntryServlet", doHttpRequest(httpClient, entryServletUrl, SC_OK), isEjbAccessException()); } } /** * Test credentials propagation from HTTP FORM authentication when the servlet which needs propagation is the authenticated * one. * * <pre> * When: HTTP client calls EntryServlet as "admin" (using FORM authn); * the EntryServlet uses Elytron API to forward authentication (credentials) and call WhoAmIBean * subsequently the WhoAmIServlet is called (already authenticated) * Then: both servlet call succeeds and WhoAmIBean returns "admin" * </pre> */ @Test public void testServletFormEntryFirst() throws Exception { final URL entryServletUrl = getEntryServletUrl(WAR_ENTRY_SERVLET_FORM, null, null, ReAuthnType.FORWARDED_AUTHENTICATION); final URL whoAmIServletUrl = new URL( server1.getApplicationHttpUrl() + "/" + WAR_ENTRY_SERVLET_FORM + WhoAmIServlet.SERVLET_PATH); try (CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(REDIRECT_STRATEGY).build()) { assertEquals("Unexpected result from EntryServlet", "admin", doHttpRequestFormAuthn(httpClient, entryServletUrl, true, "admin", "admin", SC_OK)); assertEquals("Unexpected result from WhoAmIServlet", "admin", doHttpRequest(httpClient, whoAmIServletUrl, SC_OK)); } } /** * Test credentials propagation from HTTP FORM authentication when the servlet which needs propagation is the authenticated * one. * * <pre> * When: HTTP client calls EntryServlet as "servlet" (using FORM authn); * the EntryServlet uses Elytron API to forward authentication (credentials) and call WhoAmIBean * subsequently the WhoAmIServlet is called (already authenticated) * Then: WhoAmIBean call fails (as the "servlet" has not sufficient roles); the servlet calls pass * </pre> */ @Test public void testServletFormEntryFirstInsufficientRoles() throws Exception { final URL entryServletUrl = getEntryServletUrl(WAR_ENTRY_SERVLET_FORM, null, null, ReAuthnType.FORWARDED_AUTHENTICATION); final URL whoAmIServletUrl = new URL( server1.getApplicationHttpUrl() + "/" + WAR_ENTRY_SERVLET_FORM + WhoAmIServlet.SERVLET_PATH); try (CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(REDIRECT_STRATEGY).build()) { assertThat("Unexpected result from EntryServlet", doHttpRequestFormAuthn(httpClient, entryServletUrl, true, "servlet", "servlet", SC_OK), isEjbAccessException()); assertEquals("Unexpected result from WhoAmIServlet", "servlet", doHttpRequest(httpClient, whoAmIServletUrl, SC_OK)); } } /** * Test credentials propagation from HTTP BEARER_TOKEN authentication. */ @Test public void testServletBearerTokenPropagation() throws Exception { final URL entryServletUrl = getEntryServletUrl(WAR_ENTRY_SERVLET_BEARER_TOKEN, null, null, ReAuthnType.FORWARDED_AUTHENTICATION); final URL whoAmIServletUrl = new URL( server1.getApplicationHttpUrl() + "/" + WAR_ENTRY_SERVLET_BEARER_TOKEN + WhoAmIServlet.SERVLET_PATH); try (CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(REDIRECT_STRATEGY).build()) { final String jwtToken = createJwtToken("admin"); assertEquals("Unexpected result from WhoAmIServlet", "admin", doHttpRequestTokenAuthn(httpClient, whoAmIServletUrl, jwtToken, SC_OK)); assertEquals("Unexpected result from EntryServlet", "admin", doHttpRequestTokenAuthn(httpClient, entryServletUrl, jwtToken, SC_OK)); } // do the call without sufficient role in Jakarta Enterprise Beans (server2) try (CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(REDIRECT_STRATEGY).build()) { final String jwtToken = createJwtToken("servlet"); assertThat("Unexpected result from EntryServlet", doHttpRequestTokenAuthn(httpClient, entryServletUrl, jwtToken, SC_OK), isEjbAccessException()); assertEquals("Unexpected result from WhoAmIServlet", "servlet", doHttpRequestTokenAuthn(httpClient, whoAmIServletUrl, jwtToken, SC_OK)); } } /** * Test propagation of RuntimeException back to server1 during a call using the authentication forwarding. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean as admin user and Elytron AuthenticationContext API is used to * authentication forwarding to WhoAmIBean call with "server" user used as caller server identity * Then: WhoAmIBean.throwIllegalStateException call should result in expected IllegalStateException. * </pre> */ @Test public void testIllegalStateExceptionFromForwardedAuthn() throws Exception { String[] doubleWhoAmI = AuthenticationContext.empty() .with(MatchRule.ALL, AuthenticationConfiguration.empty().setSaslMechanismSelector(SaslMechanismSelector.ALL) .useBearerTokenCredential(new BearerTokenCredential(createJwtToken("admin")))) .runCallable(getWhoAmIAndIllegalStateExceptionCallable(ReAuthnType.FORWARDED_AUTHENTICATION, null, null)); assertNotNull("The entryBean.whoAmIAndIllegalStateException() should return not-null instance", doubleWhoAmI); assertEquals("admin", doubleWhoAmI[0]); assertThat(doubleWhoAmI[1], isExpectedIllegalStateException()); } /** * Test propagation of Server2Exception (unknown on server1) back to server1 during a call using the authentication * forwarding. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean as admin user and Elytron AuthenticationContext API is used to * authentication forwarding to WhoAmIBean call with "server" user used as caller server identity * Then: WhoAmIBean.throwServer2Exception call should result in expected ClassNotFoundException. * </pre> */ @Test public void testServer2ExceptionFromForwardedAuthn() throws Exception { String[] doubleWhoAmI = AuthenticationContext.empty() .with(MatchRule.ALL, AuthenticationConfiguration.empty().setSaslMechanismSelector(SaslMechanismSelector.ALL) .useBearerTokenCredential(new BearerTokenCredential(createJwtToken("admin")))) .runCallable(getWhoAmIAndServer2ExceptionCallable(ReAuthnType.FORWARDED_AUTHENTICATION, null, null)); assertNotNull("The entryBean.whoAmIAndServer2Exception() should return not-null instance", doubleWhoAmI); assertEquals("admin", doubleWhoAmI[0]); assertThat(doubleWhoAmI[1], isClassNotFoundException_Server2Exception()); } /** * Test identity forwarding for HttpURLConnection calls. */ @Test @Ignore("WFLY-9442") public void testHttpPropagation() throws Exception { Callable<String> callable = getEjbToServletCallable(ReAuthnType.FORWARDED_AUTHENTICATION, null, null); String servletResponse = SeccontextUtil.switchIdentity("admin", "admin", callable, ReAuthnType.AC_AUTHENTICATION); assertEquals("Unexpected principal name returned from servlet call", "admin", servletResponse); } }
20,577
53.728723
146
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/AbstractHAAuthorizationForwardingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static org.jboss.as.test.integration.security.common.Utils.REDIRECT_STRATEGY; import static org.junit.Assert.assertEquals; import static org.wildfly.test.manual.elytron.seccontext.AbstractSecurityContextPropagationTestBase.server1; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.SERVER1_BACKUP; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_ENTRY_SERVLET_FORM; import java.io.IOException; import java.net.URL; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.as.cli.CommandLineException; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.shrinkwrap.api.Archive; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; /** * Tests authorization forwarding within a cluster. * * <h3>Given</h3> * See the superclass for common implementation details. * <pre> * Additional started and configured servers: * - seccontext-server1-backup (standalone-ha.xml - creates cluster with seccontext-server1) - * * entry-servlet-form.war * </pre> * @author Josef Cacek */ public abstract class AbstractHAAuthorizationForwardingTestCase extends AbstractSecurityContextPropagationTestBase { private static final ServerHolder server1backup = new ServerHolder(SERVER1_BACKUP, TestSuiteEnvironment.getServerAddress(), 2000); /** * Creates deployment with Entry servlet and FORM authentication. */ @Deployment(name = WAR_ENTRY_SERVLET_FORM + "backup", managed = false, testable = false) @TargetsContainer(SERVER1_BACKUP) public static Archive<?> createDeploymentForBackup() { return createEntryServletFormAuthnDeployment(); } /** * Start server1backup. */ @Before public void startServer1backup() throws CommandLineException, IOException, MgmtOperationException { server1backup.resetContainerConfiguration(new ServerConfigurationBuilder() .withDeployments(WAR_ENTRY_SERVLET_FORM + "backup") .build()); } /** * Shut down server1backup. */ @AfterClass public static void shutdownServer1backup() throws IOException { server1backup.shutDown(); } /** * Verifies, the distributable web-app with FORM authentication supports session replication out of the box. * * <pre> * When: HTTP client calls WhoAmIServlet as "admin" (using FORM authn) on first cluster node and then * it calls WhoAmIServlet (without authentication needed) on the second cluster node * Then: the call to WhoAmIServlet on second node (without authentication) passes and returns "admin" * (i.e. SSO works with FORM authentication) * </pre> */ @Test public void testServletSso() throws Exception { final URL whoamiUrl = new URL( server1.getApplicationHttpUrl() + "/" + WAR_ENTRY_SERVLET_FORM + WhoAmIServlet.SERVLET_PATH); final URL whoamiBackupUrl = new URL( server1backup.getApplicationHttpUrl() + "/" + WAR_ENTRY_SERVLET_FORM + WhoAmIServlet.SERVLET_PATH); try (CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(REDIRECT_STRATEGY).build()) { assertEquals("Unexpected result from WhoAmIServlet", "admin", doHttpRequestFormAuthn(httpClient, whoamiUrl, true, "admin", "admin", SC_OK)); assertEquals("Unexpected result from WhoAmIServlet (backup-server)", "admin", doHttpRequest(httpClient, whoamiBackupUrl, SC_OK)); } } /** * Verifies, the authorization forwarding works within cluster (FORM authn). This simulates failover on * distributed web application (e.g. when load balancer is used). * * <pre> * When: HTTP client calls WhoAmIServlet as "admin" (using FORM authn) on second cluster node and then * it calls EntryServlet (without authentication needed) on the first cluster node; * the EntryServlet uses Elytron API to forward authz name to call remote WhoAmIBean * Then: the calls pass and WhoAmIBean returns "admin" username * </pre> */ @Test public void testServletSsoPropagation() throws Exception { final URL entryServletUrl = getEntryServletUrl(WAR_ENTRY_SERVLET_FORM, "server", "server", ReAuthnType.FORWARDED_AUTHORIZATION); final URL whoamiUrl = new URL( server1backup.getApplicationHttpUrl() + "/" + WAR_ENTRY_SERVLET_FORM + WhoAmIServlet.SERVLET_PATH); try (CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(REDIRECT_STRATEGY).build()) { assertEquals("Unexpected result from WhoAmIServlet (backup-server)", "admin", doHttpRequestFormAuthn(httpClient, whoamiUrl, true, "admin", "admin", SC_OK)); assertEquals("Unexpected result from EntryServlet", "admin", doHttpRequest(httpClient, entryServletUrl, SC_OK)); } } }
6,426
45.23741
127
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/HAAuthorizationForwardingSFSLTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Tests authorization forwarding within a cluster. Variant which uses Entry bean stateful and WhoAmI bean stateless. See * superclass for details. * * @author Josef Cacek */ public class HAAuthorizationForwardingSFSLTestCase extends AbstractHAAuthorizationForwardingTestCase { @Override protected boolean isEntryStateful() { return true; } @Override protected boolean isWhoAmIStateful() { return false; } }
1,544
34.930233
121
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/AbstractAuthorizationForwardingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.Test; /** * Authorization forwarding (credential less forwarding) for security context propagation test. * * @author Josef Cacek */ public abstract class AbstractAuthorizationForwardingTestCase extends AbstractSecurityContextPropagationTestBase { /** * Test the authorization forwarding (credential less propagation) works for EJB calls when {@link RunAsPrincipalPermission} * is assigned to caller server identity. * * <pre> * When: EJB client calls EntryBean as admin user and Elytron AuthenticationContext API is used to * authorization forwarding to WhoAmIBean call with "server" user used as caller server identity * Then: WhoAmIBean call is possible and returns "admin" username * </pre> */ @Test public void testForwardedAuthorizationPasses() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("admin", "admin", getDoubleWhoAmICallable(ReAuthnType.FORWARDED_AUTHORIZATION, "server", "server"), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertArrayEquals("Unexpected principal names returned from doubleWhoAmI", new String[]{"admin", "admin"}, doubleWhoAmI); } /** * Test the authorization forwarding works for EJB calls when {@link RunAsPrincipalPermission} is not assigned to the caller * identity, but the authentication identity == authorization identity (which has sufficient roles to call the EJB). * * <pre> * When: EJB client calls EntryBean as admin user and Elytron AuthenticationContext API is used to * authorization forwarding to WhoAmIBean call with "admin" user used as caller server identity. * Then: WhoAmIBean call is possible and returns "admin" username * </pre> */ @Test public void testSameAuthorizationIdentityPasses() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("admin", "admin", getDoubleWhoAmICallable(ReAuthnType.FORWARDED_AUTHORIZATION, "admin", "admin"), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertArrayEquals("Unexpected principal names returned from doubleWhoAmI", new String[]{"admin", "admin"}, doubleWhoAmI); } /** * Test the authorization forwarding fails for EJB calls when {@link RunAsPrincipalPermission} is not assigned to the caller * identity. * * <pre> * When: EJB client calls EntryBean as admin user and Elytron AuthenticationContext API is used to * authorization forwarding to WhoAmIBean call with either "server-norunas" or "whoami" users * used as caller server identity. * Then: WhoAmIBean call fails in both cases as the server identity don't have RunAsPrincipalPermission * </pre> */ @Test public void testForwardedAuthorizationIdentityWithoutRunAsFails() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("admin", "admin", getDoubleWhoAmICallable(ReAuthnType.FORWARDED_AUTHORIZATION, "server-norunas", "server-norunas"), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertThat(doubleWhoAmI[1], isEjbAuthenticationError()); doubleWhoAmI = SeccontextUtil.switchIdentity("admin", "admin", getDoubleWhoAmICallable(ReAuthnType.FORWARDED_AUTHORIZATION, "whoami", "whoami"), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertThat(doubleWhoAmI[1], isEjbAuthenticationError()); } /** * Test propagation of RuntimeException back to server1 during a call using the authorization forwarding. * * <pre> * When: EJB client calls EntryBean as admin user and Elytron AuthenticationContext API is used to * authorization forwarding to WhoAmIBean call with "server" user used as caller server identity * Then: WhoAmIBean.throwIllegalStateException call should result in expected IllegalStateException. * </pre> */ @Test public void testIllegalStateExceptionFromForwardedAuthz() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("admin", "admin", getWhoAmIAndIllegalStateExceptionCallable(ReAuthnType.FORWARDED_AUTHORIZATION, "server", "server"), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.whoAmIAndIllegalStateException() should return not-null instance", doubleWhoAmI); assertEquals("admin", doubleWhoAmI[0]); assertThat(doubleWhoAmI[1], isExpectedIllegalStateException()); } /** * Test propagation of Server2Exception (unknown on server1) back to server1 during a call using the authorization * forwarding. * * <pre> * When: EJB client calls EntryBean as admin user and Elytron AuthenticationContext API is used to * authorization forwarding to WhoAmIBean call with "server" user used as caller server identity * Then: WhoAmIBean.throwServer2Exception call should result in expected ClassNotFoundException. * </pre> */ @Test public void testServer2ExceptionFromForwardedAuthz() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("admin", "admin", getWhoAmIAndServer2ExceptionCallable(ReAuthnType.FORWARDED_AUTHORIZATION, "server", "server"), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.whoAmIAndServer2Exception() should return not-null instance", doubleWhoAmI); assertEquals("admin", doubleWhoAmI[0]); assertThat(doubleWhoAmI[1], isClassNotFoundException_Server2Exception()); } }
7,326
50.598592
128
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/AbstractSecurityContextPropagationTestBase.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.manual.elytron.seccontext; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static java.util.concurrent.TimeUnit.SECONDS; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.startsWith; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.JAR_ENTRY_EJB; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.SERVER1; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.SERVER2; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_ENTRY_SERVLET_BASIC; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_ENTRY_SERVLET_BEARER_TOKEN; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_ENTRY_SERVLET_FORM; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_WHOAMI; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.SocketPermission; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Base64.Encoder; import java.util.List; import java.util.concurrent.Callable; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.ContainerController; 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.container.test.api.TargetsContainer; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.cli.CommandContext; import org.jboss.as.cli.CommandLineException; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.network.NetworkUtils; import org.jboss.as.test.integration.domain.management.util.DomainTestUtils; import org.jboss.as.test.integration.management.util.CLIOpResult; import org.jboss.as.test.integration.management.util.CLITestUtil; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.integration.security.common.SecurityTestConstants; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.logging.Logger; 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.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.runner.RunWith; import org.wildfly.security.permission.ElytronPermission; /** * Tests for testing (re)authentication and security identity propagation between servers. Test scenarios use following * configuration. * * <h3>Given</h3> * <pre> * EJBs used for testing: * - WhoAmIBean & WhoAmIBeanSFSB - protected (whoami, admin and no-server2-identity roles are allowed), just returns caller principal * - EntryBean & EntryBeanSFSB - protected (entry, admin and no-server2-identity roles are allowed), configures identity propagation and calls a remote WhoAmIBean * * Servlets used for testing: * - WhoAmIServlet - protected (servlet and admin roles are allowed) - just returns name of the incoming user name * - EntryServlet - protected (servlet and admin roles are allowed) - configures identity propagation and calls a remote WhoAmIBean * * Deployments used for testing: * - entry-ejb.jar (EntryBean & EntryBeanSFSB) * - whoami.war (WhoAmIBean & WhoAmIBeanSFSB, WhoAmIServlet) * - entry-servlet-basic.war (EntryServlet, WhoAmIServlet) - authentication mechanism BASIC * - entry-servlet-form.war (EntryServlet, WhoAmIServlet) - authentication mechanism FORM * - entry-servlet-bearer.war (EntryServlet, WhoAmIServlet) - authentication mechanism BEARER_TOKEN * * Servers started and configured for context propagation scenarios: * - seccontext-server1 (standalone-ha.xml) * * entry-ejb.jar * * entry-servlet-basic.war * * entry-servlet-form.war * * entry-servlet-bearer.war * * first-server-chain.war * - seccontext-server2 (standalone.xml) * * whoami.war * * Users used for testing (username==password==role): * - entry * - whoami * - servlet * - admin * - server (has configured additional permission - RunAsPrincipalPermission) * - another-server (used for server chain scenarios) * - server-norunas * - no-server2-identity * </pre> * * @see ReAuthnType reauthentication types * @author Josef Cacek */ @RunWith(Arquillian.class) @RunAsClient public abstract class AbstractSecurityContextPropagationTestBase { private static final Logger LOGGER = Logger.getLogger(AbstractSecurityContextPropagationTestBase.class); protected static final ServerHolder server1 = new ServerHolder(SERVER1, TestSuiteEnvironment.getServerAddress(), 0); protected static final ServerHolder server2 = new ServerHolder(SERVER2, TestSuiteEnvironment.getServerAddressNode1(), 100); private static final Package PACKAGE = AbstractSecurityContextPropagationTestBase.class.getPackage(); private static final Encoder B64_ENCODER = Base64.getUrlEncoder().withoutPadding(); private static final String JWT_HEADER_B64 = B64_ENCODER .encodeToString("{\"alg\":\"none\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8)); @ArquillianResource private static volatile ContainerController containerController; @ArquillianResource private static volatile Deployer deployer; /** * Creates deployment with Entry bean - to be placed on the first server. */ @Deployment(name = JAR_ENTRY_EJB, managed = false, testable = false) @TargetsContainer(SERVER1) public static Archive<?> createEntryBeanDeployment() { return ShrinkWrap.create(JavaArchive.class, JAR_ENTRY_EJB + ".jar") .addClasses(EntryBean.class, EntryBeanSFSB.class, Entry.class, WhoAmI.class, ReAuthnType.class, SeccontextUtil.class, CallAnotherBeanInfo.class) .addAsManifestResource(createPermissionsXmlAsset(new ElytronPermission("authenticate"), new ElytronPermission("getPrivateCredentials"), new ElytronPermission("getSecurityDomain"), new SocketPermission(TestSuiteEnvironment.getServerAddressNode1() + ":8180", "connect,resolve")), "permissions.xml") .addAsManifestResource(Utils.getJBossEjb3XmlAsset("seccontext-entry"), "jboss-ejb3.xml"); } /** * Creates deployment with Entry servlet and BASIC authentication. */ @Deployment(name = WAR_ENTRY_SERVLET_BASIC, managed = false, testable = false) @TargetsContainer(SERVER1) public static Archive<?> createEntryServletBasicAuthnDeployment() { return createEntryServletDeploymentBase(WAR_ENTRY_SERVLET_BASIC) .addAsWebInfResource(new StringAsset(SecurityTestConstants.WEB_XML_BASIC_AUTHN), "web.xml"); } /** * Creates deployment with Entry servlet and FORM authentication. */ @Deployment(name = WAR_ENTRY_SERVLET_FORM, managed = false, testable = false) @TargetsContainer(SERVER1) public static Archive<?> createEntryServletFormAuthnDeployment() { return createEntryServletDeploymentBase(WAR_ENTRY_SERVLET_FORM) .addAsWebInfResource(PACKAGE, "web-form-authn.xml", "web.xml") .addAsWebResource(PACKAGE, "login.html", "login.html").addAsWebResource(PACKAGE, "error.html", "error.html"); } /** * Creates deployment with Entry servlet and BEARER authentication. */ @Deployment(name = WAR_ENTRY_SERVLET_BEARER_TOKEN, managed = false, testable = false) @TargetsContainer(SERVER1) public static Archive<?> createEntryServletBearerAuthnDeployment() { return createEntryServletDeploymentBase(WAR_ENTRY_SERVLET_BEARER_TOKEN).addAsWebInfResource(PACKAGE, "web-token-authn.xml", "web.xml"); } /** * Creates deployment with WhoAmI bean and servlet - to be placed on the second server. */ @Deployment(name = WAR_WHOAMI, managed = false, testable = false) @TargetsContainer(SERVER2) public static Archive<?> createEjbClientDeployment() { return ShrinkWrap.create(WebArchive.class, WAR_WHOAMI + ".war") .addClasses(WhoAmIBean.class, WhoAmIBeanSFSB.class, WhoAmI.class, WhoAmIServlet.class, Server2Exception.class) .addAsWebInfResource(Utils.getJBossWebXmlAsset("seccontext-web"), "jboss-web.xml") .addAsWebInfResource(new StringAsset(SecurityTestConstants.WEB_XML_BASIC_AUTHN), "web.xml") .addAsWebInfResource(Utils.getJBossEjb3XmlAsset("seccontext-whoami"), "jboss-ejb3.xml"); } /** * Start servers (if not yet started) and if it's the first execution it sets configuration of test servers and deploys test * applications. */ @Before public void before() throws CommandLineException, IOException, MgmtOperationException { setupServer1(); setupServer2(); } /** * Shut down servers. */ @AfterClass public static void afterClass() throws IOException { server1.shutDown(); server2.shutDown(); } /** * Setup seccontext-server1. */ protected void setupServer1() throws CommandLineException, IOException, MgmtOperationException { server1.resetContainerConfiguration(new ServerConfigurationBuilder() .withDeployments(JAR_ENTRY_EJB, WAR_ENTRY_SERVLET_BASIC, WAR_ENTRY_SERVLET_FORM, WAR_ENTRY_SERVLET_BEARER_TOKEN) .build()); } /** * Setup seccontext-server2. */ protected void setupServer2() throws CommandLineException, IOException, MgmtOperationException { server2.resetContainerConfiguration(new ServerConfigurationBuilder() .withDeployments(WAR_WHOAMI) .build()); } /** * Returns true if the stateful Entry bean variant should be used by the tests. False otherwise. */ protected abstract boolean isEntryStateful(); /** * Returns true if the stateful WhoAmI bean variant should be used by the tests. False otherwise. */ protected abstract boolean isWhoAmIStateful(); /** * Do HTTP GET request with given client. * * @param httpClient * @param url * @param expectedStatus expected status coe * @return response body */ protected String doHttpRequest(final CloseableHttpClient httpClient, final URL url, int expectedStatus) throws URISyntaxException, IOException, ClientProtocolException, UnsupportedEncodingException { return doHttpRequestFormAuthn(httpClient, url, false, null, null, expectedStatus); } /** * Do HTTP request using given client with possible FORM authentication. * * @param httpClient client instance * @param url URL to make request to * @param loginFormExpected flag which says if login (FORM) is expected, if true username and password arguments are used to * login. * @param username user to fill into the login form * @param password password to fill into the login form * @param expectedStatus expected status code * @return response body */ protected String doHttpRequestFormAuthn(final CloseableHttpClient httpClient, final URL url, boolean loginFormExpected, String username, String password, int expectedStatus) throws URISyntaxException, IOException, ClientProtocolException, UnsupportedEncodingException { HttpGet httpGet = new HttpGet(url.toURI()); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); assertNotNull(entity); String responseBody = EntityUtils.toString(entity); if (loginFormExpected) { assertThat("Login page was expected", responseBody, containsString("j_security_check")); assertEquals("HTTP OK response for login page was expected", SC_OK, response.getStatusLine().getStatusCode()); // We should now login with the user name and password HttpPost httpPost = new HttpPost( server1.getApplicationHttpUrl() + "/" + WAR_ENTRY_SERVLET_FORM + "/j_security_check"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("j_username", username)); nvps.add(new BasicNameValuePair("j_password", password)); httpPost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8)); response = httpClient.execute(httpPost); entity = response.getEntity(); assertNotNull(entity); responseBody = EntityUtils.toString(entity); } else { assertThat("Login page was not expected", responseBody, not(containsString("j_security_check"))); } assertEquals("Unexpected status code", expectedStatus, response.getStatusLine().getStatusCode()); return responseBody; } /** * Do HTTP request using given client with BEARER_TOKEN authentication. The implementation makes 2 calls - the first without * Authorization header provided (just to check response code and WWW-Authenticate header value), the second with * Authorization header. * * @param httpClient client instance * @param url URL to make request to * @param token bearer token * @param expectedStatus expected status code * @return response body */ protected String doHttpRequestTokenAuthn(final CloseableHttpClient httpClient, final URL url, String token, int expectedStatusCode) throws URISyntaxException, IOException, ClientProtocolException, UnsupportedEncodingException { final HttpGet httpGet = new HttpGet(url.toURI()); HttpResponse response = httpClient.execute(httpGet); assertEquals("Unexpected HTTP response status code.", SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); Header[] authenticateHeaders = response.getHeaders("WWW-Authenticate"); assertTrue("Expected WWW-Authenticate header was not present in the HTTP response", authenticateHeaders != null && authenticateHeaders.length > 0); boolean bearerAuthnHeaderFound = false; for (Header header : authenticateHeaders) { final String headerVal = header.getValue(); if (headerVal != null && headerVal.startsWith("Bearer")) { bearerAuthnHeaderFound = true; break; } } assertTrue("WWW-Authenticate response header didn't request expected Bearer token authentication", bearerAuthnHeaderFound); HttpEntity entity = response.getEntity(); if (entity != null) EntityUtils.consume(entity); httpGet.addHeader("Authorization", "Bearer " + token); response = httpClient.execute(httpGet); assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, response.getStatusLine().getStatusCode()); return EntityUtils.toString(response.getEntity()); } /** * Creates callable for executing {@link Entry#doubleWhoAmI(String, String, ReAuthnType, String)} as "whoami" user. * * @param type reauthentication reauthentication type used within the doubleWhoAmI * @return Callable */ protected Callable<String[]> getDoubleWhoAmICallable(final ReAuthnType type) { return getDoubleWhoAmICallable(type, "whoami", "whoami"); } /** * Creates callable for executing {@link Entry#doubleWhoAmI(String, String, ReAuthnType, String)} as "whoami" user. * * @param type reauthentication reauthentication type used within the doubleWhoAmI * @param authzName - authorization name * @return Callable */ protected Callable<String[]> getDoubleWhoAmICallable(final ReAuthnType type, final String authzName) { return getDoubleWhoAmICallable(type, "whoami", "whoami", authzName); } /** * Creates a callable for executing {@link Entry#doubleWhoAmI(String, String, ReAuthnType, String)} as given user. * * @param type reauthentication re-authentication type used within the doubleWhoAmI * @param username * @param password * @return */ protected Callable<String[]> getDoubleWhoAmICallable(final ReAuthnType type, final String username, final String password) { return getDoubleWhoAmICallable(type, username, password, null); } /** * Creates a callable for executing {@link Entry#doubleWhoAmI(CallAnotherBeanInfo)} as given user. * * @param type reauthentication re-authentication type used within the doubleWhoAmI * @param username * @param password * @param authzName - authorization name * @return */ protected Callable<String[]> getDoubleWhoAmICallable(final ReAuthnType type, final String username, final String password, final String authzName) { return () -> { final Entry bean = SeccontextUtil.lookup( SeccontextUtil.getRemoteEjbName(JAR_ENTRY_EJB, "EntryBean", Entry.class.getName(), isEntryStateful()), server1.getApplicationRemotingUrl()); final String server2Url = server2.getApplicationRemotingUrl(); return bean.doubleWhoAmI(new CallAnotherBeanInfo.Builder() .username(username) .password(password) .authzName(authzName) .type(type) .providerUrl(server2Url) .statefullWhoAmI(isWhoAmIStateful()) .build()); }; } /** * Creates a callable for executing {@link Entry#whoAmIAndIllegalStateException(CallAnotherBeanInfo)} as given user. * * @param type reauthentication re-authentication type used within the doubleWhoAmI * @param username * @param password * @return */ protected Callable<String[]> getWhoAmIAndIllegalStateExceptionCallable(final ReAuthnType type, final String username, final String password) { return () -> { final Entry bean = SeccontextUtil.lookup( SeccontextUtil.getRemoteEjbName(JAR_ENTRY_EJB, "EntryBean", Entry.class.getName(), isEntryStateful()), server1.getApplicationRemotingUrl()); final String server2Url = server2.getApplicationRemotingUrl(); return bean.whoAmIAndIllegalStateException(new CallAnotherBeanInfo.Builder() .username(username) .password(password) .type(type) .providerUrl(server2Url) .statefullWhoAmI(isWhoAmIStateful()) .build()); }; } /** * Creates a callable for executing {@link Entry#whoAmIAndServer2Exception(CallAnotherBeanInfo)} as given user. * * @param type reauthentication re-authentication type used within the doubleWhoAmI * @param username * @param password * @return */ protected Callable<String[]> getWhoAmIAndServer2ExceptionCallable(final ReAuthnType type, final String username, final String password) { return () -> { final Entry bean = SeccontextUtil.lookup( SeccontextUtil.getRemoteEjbName(JAR_ENTRY_EJB, "EntryBean", Entry.class.getName(), isEntryStateful()), server1.getApplicationRemotingUrl()); final String server2Url = server2.getApplicationRemotingUrl(); return bean.whoAmIAndServer2Exception(new CallAnotherBeanInfo.Builder() .username(username) .password(password) .type(type) .providerUrl(server2Url) .statefullWhoAmI(isWhoAmIStateful()) .build()); }; } protected Callable<String> getEjbToServletCallable(final ReAuthnType type, final String username, final String password) { return () -> { final Entry bean = SeccontextUtil.lookup( SeccontextUtil.getRemoteEjbName(JAR_ENTRY_EJB, "EntryBean", Entry.class.getName(), isEntryStateful()), server1.getApplicationRemotingUrl()); final String servletUrl = server2.getApplicationHttpUrl() + "/" + WAR_WHOAMI + WhoAmIServlet.SERVLET_PATH; return bean.readUrl(username, password, type, new URL(servletUrl)); }; } protected static org.hamcrest.Matcher<java.lang.String> isEjbAuthenticationError() { // different behavior for stateless and stateful beans // is reported under https://issues.jboss.org/browse/JBEAP-12439 return anyOf(startsWith("jakarta.ejb.NoSuchEJBException: EJBCLIENT000079"), startsWith("javax.naming.CommunicationException: EJBCLIENT000062"), containsString("JBREM000308"), containsString("javax.security.sasl.SaslException: Authentication failed")); } protected static org.hamcrest.Matcher<java.lang.String> isExpectedIllegalStateException() { return containsString("EJBException: java.lang.IllegalStateException: Expected IllegalStateException"); } protected static org.hamcrest.Matcher<java.lang.String> isClassNotFoundException_Server2Exception() { return allOf(startsWith("jakarta.ejb.EJBException"), containsString("ClassNotFoundException: org.wildfly.test.manual.elytron.seccontext.Server2Exception")); } protected static org.hamcrest.Matcher<java.lang.String> isEvidenceVerificationError() { return startsWith("java.lang.SecurityException: ELY01151"); } protected static org.hamcrest.Matcher<java.lang.String> isEjbAccessException() { return startsWith("jakarta.ejb.EJBAccessException"); } protected String createJwtToken(String userName) { String jwtPayload = String.format("{" // + "\"iss\": \"issuer.wildfly.org\"," // + "\"sub\": \"elytron@wildfly.org\"," // + "\"exp\": 2051222399," // + "\"aud\": \"%1$s\"," // + "\"groups\": [\"%1$s\"]" // + "}", userName); return JWT_HEADER_B64 + "." + B64_ENCODER.encodeToString(jwtPayload.getBytes(StandardCharsets.UTF_8)) + "."; } protected URL getEntryServletUrl(String warName, String username, String password, ReAuthnType type) throws IOException { return getEntryServletUrl(warName, username, password, null, type); } protected URL getEntryServletUrl(String warName, String username, String password, String authzName, ReAuthnType type) throws IOException { final StringBuilder sb = new StringBuilder(server1.getApplicationHttpUrl() + "/" + warName + EntryServlet.SERVLET_PATH); addQueryParam(sb, EntryServlet.PARAM_USERNAME, username); addQueryParam(sb, EntryServlet.PARAM_PASSWORD, password); addQueryParam(sb, EntryServlet.PARAM_AUTHZ_NAME, authzName); addQueryParam(sb, EntryServlet.PARAM_STATEFULL, String.valueOf(isWhoAmIStateful())); addQueryParam(sb, EntryServlet.PARAM_CREATE_SESSION, String.valueOf(true)); addQueryParam(sb, EntryServlet.PARAM_REAUTHN_TYPE, type.name()); addQueryParam(sb, EntryServlet.PARAM_PROVIDER_URL, server2.getApplicationRemotingUrl()); return new URL(sb.toString()); } private static void addQueryParam(StringBuilder sb, String paramName, String paramValue) { final String encodedPair = Utils.encodeQueryParam(paramName, paramValue); if (encodedPair != null) { sb.append(sb.indexOf("?") < 0 ? "?" : "&").append(encodedPair); } } /** * Creates deployment base with Entry servlet. It doesn't contain web.xml and related resources if needed (e.g. login page). */ private static WebArchive createEntryServletDeploymentBase(String name) { return ShrinkWrap.create(WebArchive.class, name + ".war") .addClasses(EntryServlet.class, WhoAmIServlet.class, WhoAmI.class, ReAuthnType.class, SeccontextUtil.class) .addAsManifestResource(createPermissionsXmlAsset(new ElytronPermission("authenticate"), new ElytronPermission("getPrivateCredentials"), new ElytronPermission("getSecurityDomain"), new SocketPermission(TestSuiteEnvironment.getServerAddressNode1() + ":8180", "connect,resolve")), "permissions.xml") .addAsWebInfResource(Utils.getJBossWebXmlAsset("seccontext-web"), "jboss-web.xml"); } protected static class ServerHolder { private final String name; private final String host; private final int portOffset; private volatile ModelControllerClient client; private volatile CommandContext commandCtx; private volatile ByteArrayOutputStream consoleOut = new ByteArrayOutputStream(); private final List<String> deployments = new ArrayList<>(); private String jbossServerConfigDir; private Path propertyFile; private volatile String snapshot; public ServerHolder(String name, String host, int portOffset) { this.name = name; this.host = host; this.portOffset = portOffset; } public void resetContainerConfiguration(ServerConfiguration config) throws CommandLineException, IOException, MgmtOperationException { if (!containerController.isStarted(name)) { containerController.start(name); client = ModelControllerClient.Factory.create(host, getManagementPort()); commandCtx = CLITestUtil.getCommandContext(host, getManagementPort(), null, consoleOut, -1); commandCtx.connectController(); readSnapshot(); jbossServerConfigDir = readJbossServerConfigDir(); if (snapshot == null) { // configure each server just once takeSnapshot(); createPropertyFile(config.getAdditionalUsers()); final File cliFIle = File.createTempFile("seccontext-", ".cli"); try (FileOutputStream fos = new FileOutputStream(cliFIle)) { IOUtils.copy( AbstractSecurityContextPropagationTestBase.class.getResourceAsStream("seccontext-setup.cli"), fos); } addCliCommands(cliFIle, config.getCliCommands()); runBatch(cliFIle); cliFIle.delete(); reload(); deployments.addAll(config.getDeployments()); for (String deployment : config.getDeployments()) { deployer.deploy(deployment); } } } } public void shutDown() throws IOException { if (containerController.isStarted(name)) { // deployer.undeploy(name); for (String deployment : deployments) { deployer.undeploy(deployment); } commandCtx.terminateSession(); client.close(); containerController.stop(name); reloadFromSnapshot(); Files.deleteIfExists(propertyFile); } } public int getManagementPort() { return 9990 + portOffset; } public int getApplicationPort() { return 8080 + portOffset; } public String getApplicationHttpUrl() throws IOException { return "http://" + NetworkUtils.formatPossibleIpv6Address(host) + ":" + getApplicationPort(); } public String getApplicationRemotingUrl() throws IOException { return "remote+" + getApplicationHttpUrl(); } /** * Sends command line to CLI. * * @param line specifies the command line. * @param ignoreError if set to false, asserts that handling the line did not result in a * {@link org.jboss.as.cli.CommandLineException}. * * @return true if the CLI is in a non-error state following handling the line */ public boolean sendLine(String line, boolean ignoreError) { consoleOut.reset(); if (ignoreError) { commandCtx.handleSafe(line); return commandCtx.getExitCode() == 0; } else { try { commandCtx.handle(line); } catch (CommandLineException e) { StringWriter stackTrace = new StringWriter(); e.printStackTrace(new PrintWriter(stackTrace)); Assert.fail(String.format("Failed to execute line '%s'%n%s", line, stackTrace.toString())); } } return true; } /** * Runs given CLI script file as a batch. * * @param batchFile CLI file to run in batch * @return true if CLI returns Success */ public boolean runBatch(File batchFile) throws IOException { for(String line : Files.readAllLines(batchFile.toPath())) { sendLine(line, false); } //sendLine("run-batch --file=\"" + batchFile.getAbsolutePath() + "\" -v", false); if (consoleOut.size() <= 0) { return false; } return new CLIOpResult(ModelNode.fromStream(new ByteArrayInputStream(consoleOut.toByteArray()))) .isIsOutcomeSuccess(); } private void takeSnapshot() throws IOException, MgmtOperationException { DomainTestUtils.executeForResult(Util.createOperation("take-snapshot", null), client); readSnapshot(); } private void readSnapshot() throws IOException, MgmtOperationException { ModelNode namesNode = DomainTestUtils.executeForResult(Util.createOperation("list-snapshots", null), client) .get("names"); if (namesNode == null || namesNode.getType() != ModelType.LIST) { throw new IllegalStateException("Unexpected return value from :list-snaphot operation: " + namesNode); } List<ModelNode> snapshots = namesNode.asList(); if (!snapshots.isEmpty()) { snapshot = namesNode.get(snapshots.size() - 1).asString(); } } private void reloadFromSnapshot() throws IOException { if (snapshot != null) { File snapshotFile = new File(jbossServerConfigDir + File.separator + "standalone_xml_history" + File.separator + "snapshot" + File.separator + snapshot); String standaloneName = snapshot.replaceAll("\\d", "").replaceFirst("-", ""); File standaloneFile = new File(jbossServerConfigDir + File.separator + standaloneName); Files.copy(snapshotFile.toPath(), standaloneFile.toPath(), REPLACE_EXISTING); snapshotFile.delete(); } } private void reload() { ServerReload.executeReloadAndWaitForCompletion(client, (int) SECONDS.toMillis(90), false, host, getManagementPort()); } /** * Create single property file with users and/or roles in standalone server config directory. It will be used for * property-realm configuration (see {@code seccontext-setup.cli} script) */ private void createPropertyFile(List<String> additionalUsers) throws IOException { String configDirPath = jbossServerConfigDir != null ? jbossServerConfigDir : readJbossServerConfigDir(); List<String> users = new ArrayList<>(); users.add("admin"); users.add("servlet"); users.add("entry"); users.add("whoami"); users.add("server"); users.add("server-norunas"); users.add("authz"); users.addAll(additionalUsers); String[] usersArr = new String[users.size()]; usersArr = users.toArray(usersArr); propertyFile = Paths.get(configDirPath, "seccontext.properties"); Files.write(propertyFile, Utils.createUsersFromRoles(usersArr).getBytes(StandardCharsets.ISO_8859_1)); } private String readJbossServerConfigDir() throws IOException { sendLine("/core-service=platform-mbean/type=runtime:read-attribute(name=system-properties)", false); assertTrue(consoleOut.size() > 0); ModelNode node = ModelNode.fromStream(new ByteArrayInputStream(consoleOut.toByteArray())); return node.get(ModelDescriptionConstants.RESULT).get("jboss.server.config.dir").asString(); } private void addCliCommands(File file, List<String> commands) throws IOException { try (BufferedWriter bw = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8, StandardOpenOption.APPEND)) { for (String command : commands) { bw.append(command); } } } } protected static class ServerConfiguration { private final List<String> deployments; private final List<String> additionalUsers; private final List<String> cliCommands; private ServerConfiguration(ServerConfigurationBuilder builder) { this.deployments = builder.deployments; this.additionalUsers = builder.additionalUsers; this.cliCommands = builder.cliCommands; } public List<String> getDeployments() { return deployments; } public List<String> getAdditionalUsers() { return additionalUsers; } public List<String> getCliCommands() { return cliCommands; } } protected static class ServerConfigurationBuilder { private List<String> deployments = new ArrayList<>(); private List<String> additionalUsers = new ArrayList<>(); private List<String> cliCommands = new ArrayList<>(); public ServerConfigurationBuilder withDeployments(String... deployments) { this.deployments.addAll(Arrays.asList(deployments)); return this; } public ServerConfigurationBuilder withAdditionalUsers(String... additionalUsers) { this.additionalUsers.addAll(Arrays.asList(additionalUsers)); return this; } public ServerConfigurationBuilder withCliCommands(String... cliCommands) { this.cliCommands.addAll(Arrays.asList(cliCommands)); return this; } public ServerConfiguration build() { return new ServerConfiguration(this); } } }
37,818
44.40096
162
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/AbstractIdentitySwitchingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.startsWith; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.JAR_ENTRY_EJB; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_ENTRY_SERVLET_BASIC; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_ENTRY_SERVLET_BEARER_TOKEN; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_ENTRY_SERVLET_FORM; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_WHOAMI; import java.io.IOException; import java.util.concurrent.Callable; import jakarta.ejb.EJBAccessException; import org.jboss.as.cli.CommandLineException; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.integration.security.common.Utils; import org.junit.Ignore; import org.junit.Test; /** * Identity switching for security context propagation test. * * @author Hynek Švábek <hsvabek@redhat.com> */ public abstract class AbstractIdentitySwitchingTestCase extends AbstractSecurityContextPropagationTestBase { /** * Setup seccontext-server1. */ protected void setupServer1() throws CommandLineException, IOException, MgmtOperationException { server1.resetContainerConfiguration(new ServerConfigurationBuilder() .withDeployments(JAR_ENTRY_EJB, WAR_ENTRY_SERVLET_BASIC, WAR_ENTRY_SERVLET_FORM, WAR_ENTRY_SERVLET_BEARER_TOKEN) .withCliCommands("/subsystem=elytron/simple-permission-mapper=seccontext-server-permissions" + ":write-attribute(name=permission-mappings[1],value={principals=[entry]," + "permissions=[{class-name=org.wildfly.security.auth.permission.LoginPermission}," + "{class-name=org.wildfly.security.auth.permission.RunAsPrincipalPermission, target-name=authz}," + "{class-name=org.wildfly.security.auth.permission.RunAsPrincipalPermission, target-name=" + "no-server2-identity}]})") .build()); } /** * Setup seccontext-server2. */ protected void setupServer2() throws CommandLineException, IOException, MgmtOperationException { server2.resetContainerConfiguration(new ServerConfigurationBuilder() .withDeployments(WAR_WHOAMI) .withCliCommands("/subsystem=elytron/simple-permission-mapper=seccontext-server-permissions" + ":write-attribute(name=permission-mappings[1],value={principals=[entry]," + "permissions=[{class-name=org.wildfly.security.auth.permission.LoginPermission}," + "{class-name=org.wildfly.security.auth.permission.RunAsPrincipalPermission, target-name=authz}," + "{class-name=org.wildfly.security.auth.permission.RunAsPrincipalPermission, target-name=" + "no-server2-identity}]})") .build()); } /** * Test Elytron API used to reauthorization. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean with {@link ReAuthnType#AC_AUTHENTICATION} and provides valid credentials and valid authorization name and * calls WhoAmIBean with {@link ReAuthnType#AC_AUTHORIZATION} and provides valid credentials and valid authorization name * Then: call passes and returned usernames are the expected ones; * </pre> */ @Test public void testAuthCtxAuthzPasses() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("entry", "entry", getDoubleWhoAmICallable(ReAuthnType.AC_AUTHORIZATION, "server", "server", "admin"), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertArrayEquals("Unexpected principal names returned from doubleWhoAmI", new String[] { "entry", "admin" }, doubleWhoAmI); } /** * Test Elytron API used to reauthorization. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean with {@link ReAuthnType#AC_AUTHORIZATION} and provides valid credentials and valid authorization name for both servers * Then: call passes and returned usernames are the expected ones; * </pre> */ @Test public void testAuthzCtxAuthzPasses() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("entry", "entry", "authz", getDoubleWhoAmICallable(ReAuthnType.AC_AUTHORIZATION, "server", "server", "whoami"), ReAuthnType.AC_AUTHORIZATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertArrayEquals("Unexpected principal names returned from doubleWhoAmI", new String[] { "authz", "whoami" }, doubleWhoAmI); } /** * Test Elytron API used to reauthorization. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean with {@link ReAuthnType#AC_AUTHENTICATION} and provides valid credentials and valid authorization name and * calls WhoAmIBean with {@link ReAuthnType#AC_AUTHENTICATION} and provides valid credentials * Then: call passes and returned usernames are the expected ones; * </pre> */ @Test public void testAuthzCtxAuthPasses() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("entry", "entry", "authz", getDoubleWhoAmICallable(ReAuthnType.AC_AUTHENTICATION, "whoami", "whoami"), ReAuthnType.AC_AUTHORIZATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertArrayEquals("Unexpected principal names returned from doubleWhoAmI", new String[] { "authz", "whoami" }, doubleWhoAmI); } /** * Test Jakarta Enterprise Beans call fails when user has insufficient roles. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean as a user without allowed roles assigned * Then: call fails with EJBAccessExcption * </pre> */ @Test public void testClientInsufficientRolesAuthz() throws Exception { try { SeccontextUtil.switchIdentity("server", "server", "whoami", getDoubleWhoAmICallable(ReAuthnType.AC_AUTHORIZATION), ReAuthnType.AC_AUTHORIZATION); fail("Calling Entry bean must fail when user without required roles is used"); } catch (EJBAccessException e) { // OK - expected } } /** * Test Jakarta Enterprise Beans call fails when invalid username/password combination is used for reauthorization. * * <pre> * When: Jakarta Enterprise Beans client calls (with valid credentials and authrozation name) EntryBean and Elytron AuthenticationContext API is used to * reauthorizate (with invalid username/password) and call the WhoAmIBean * Then: WhoAmIBean call fails * </pre> */ @Test public void testAuthzCtxWrongUserFail() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("entry", "entry", "authz", getDoubleWhoAmICallable(ReAuthnType.AC_AUTHORIZATION, "doesntexist", "whoami"), ReAuthnType.AC_AUTHORIZATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertEquals("The result of doubleWhoAmI() has wrong lenght", 2, doubleWhoAmI.length); assertEquals("authz", doubleWhoAmI[0]); assertThat(doubleWhoAmI[1], isEjbAuthenticationError()); } /** * Test Jakarta Enterprise Beans call fails when invalid username/password combination is used for reauthorization. * * <pre> * When: Jakarta Enterprise Beans client calls (with valid credentials and authrozation name) EntryBean and Elytron AuthenticationContext API is used to * reauthorizate (with invalid username/password) and call the WhoAmIBean * Then: WhoAmIBean call fails * </pre> */ @Test public void testAuthzCtxWrongPasswdFail() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("entry", "entry", "authz", getDoubleWhoAmICallable(ReAuthnType.AC_AUTHORIZATION, "whoami", "wrongpass"), ReAuthnType.AC_AUTHORIZATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertEquals("The result of doubleWhoAmI() has wrong lenght", 2, doubleWhoAmI.length); assertEquals("authz", doubleWhoAmI[0]); assertThat(doubleWhoAmI[1], isEjbAuthenticationError()); } /** * Test Jakarta Enterprise Beans call fails when invalidauthorization name is used for reauthorization. * * <pre> * When: Jakarta Enterprise Beans client calls (with valid credentials and authrozation name) EntryBean and Elytron AuthenticationContext API is used to * reauthorizate (with invalid authorization name) and call the WhoAmIBean * Then: WhoAmIBean call fails * </pre> */ @Test public void testAuthzCtxWrongAuthzNameFail() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("entry", "entry", "authz", getDoubleWhoAmICallable(ReAuthnType.AC_AUTHORIZATION, "whoami", "whoami", "doesntexist"), ReAuthnType.AC_AUTHORIZATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertEquals("The result of doubleWhoAmI() has wrong lenght", 2, doubleWhoAmI.length); assertEquals("authz", doubleWhoAmI[0]); assertThat(doubleWhoAmI[1], isEjbAuthenticationError()); } /** * Test Elytron API used to reauthentication. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean with {@link ReAuthnType#AC_AUTHENTICATION} and provides valid credentials for both servers * Then: call passes and returned usernames are the expected ones; * </pre> */ @Test public void testAuthCtxPasses() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("entry", "entry", getDoubleWhoAmICallable(ReAuthnType.AC_AUTHENTICATION), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertArrayEquals("Unexpected principal names returned from doubleWhoAmI", new String[]{"entry", "whoami"}, doubleWhoAmI); } /** * Test Jakarta Enterprise Beans call fails when user has insufficient roles. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean as a user without allowed roles assigned * Then: call fails with EJBAccessExcption * </pre> */ @Test public void testClientInsufficientRoles() throws Exception { try { SeccontextUtil.switchIdentity("whoami", "whoami", getDoubleWhoAmICallable(ReAuthnType.AC_AUTHENTICATION), ReAuthnType.AC_AUTHENTICATION); fail("Calling Entry bean must fail when user without required roles is used"); } catch (EJBAccessException e) { // OK - expected } } /** * Test Jakarta Enterprise Beans call fails when invalid username/password combination is used for reauthentication. * * <pre> * When: Jakarta Enterprise Beans client calls (with valid credentials) EntryBean and Elytron AuthenticationContext API is used to * reauthenticate (with invalid username/password) and call the WhoAmIBean * Then: WhoAmIBean call fails * </pre> */ @Test public void testAuthCtxWrongUserFail() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("entry", "entry", getDoubleWhoAmICallable(ReAuthnType.AC_AUTHENTICATION, "doesntexist", "whoami"), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertEquals("The result of doubleWhoAmI() has wrong lenght", 2, doubleWhoAmI.length); assertEquals("entry", doubleWhoAmI[0]); assertThat(doubleWhoAmI[1], isEjbAuthenticationError()); } /** * Test Jakarta Enterprise Beans call fails when invalid username/password combination is used for reauthentication. * * <pre> * When: Jakarta Enterprise Beans client calls (with valid credentials) EntryBean and Elytron AuthenticationContext API is used to * reauthenticate (with invalid username/password) and call the WhoAmIBean * Then: WhoAmIBean call fails * </pre> */ @Test public void testAuthCtxWrongPasswdFail() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("entry", "entry", getDoubleWhoAmICallable(ReAuthnType.AC_AUTHENTICATION, "whoami", "wrongpass"), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertEquals("The result of doubleWhoAmI() has wrong lenght", 2, doubleWhoAmI.length); assertEquals("entry", doubleWhoAmI[0]); assertThat(doubleWhoAmI[1], isEjbAuthenticationError()); } /** * Test the security domain reauthentication on one server is not propagated to second server without explicitly asking for * identity forwarding. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean as "entry" user and Elytron AuthenticationContext API is used to * re-authenticate to the security domain as "whoami" user; WhoAmIBean is called * Then: WhoAmIBean call fails as the whoami identity is not propagated * </pre> */ @Test public void testSecurityDomainAuthenticateWithoutForwarding() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("entry", "entry", getDoubleWhoAmICallable(ReAuthnType.SD_AUTHENTICATION), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertEquals("The result of doubleWhoAmI() has wrong lenght", 2, doubleWhoAmI.length); assertEquals("entry", doubleWhoAmI[0]); assertThat(doubleWhoAmI[1], isEjbAuthenticationError()); } /** * Test the security domain reauthentication fails when wrong password is used * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean as "entry" user and Elytron AuthenticationContext API is used to * re-authenticate to the security domain as "whoami" user with wrong password provided * Then: reauthentication fails * </pre> */ @Test public void testSecurityDomainAuthenticateWrongPassFails() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("entry", "entry", getDoubleWhoAmICallable(ReAuthnType.SD_AUTHENTICATION, "doesntexist", "whoami"), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertEquals("The result of doubleWhoAmI() has wrong lenght", 2, doubleWhoAmI.length); assertEquals("entry", doubleWhoAmI[0]); assertThat(doubleWhoAmI[1], isEvidenceVerificationError()); } /** * Test the security domain reauthentication followed by authentication forwarding is possible. * * <pre> * When: Jakarta Enterprise Beans client calls EntryBean as "entry" user and Elytron AuthenticationContext API is used to * re-authenticate to the security domain as "whoami" user and * the authentication forwarding is configured afterwards; WhoAmIBean is called * Then: WhoAmIBean returns "whoami" * </pre> */ @Test public void testSecurityDomainAuthenticateForwardedPasses() throws Exception { String[] doubleWhoAmI = SeccontextUtil.switchIdentity("entry", "entry", getDoubleWhoAmICallable(ReAuthnType.SD_AUTHENTICATION_FORWARDED), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The entryBean.doubleWhoAmI() should return not-null instance", doubleWhoAmI); assertArrayEquals("Unexpected principal names returned from doubleWhoAmI", new String[]{"entry", "whoami"}, doubleWhoAmI); } /** * Test reauthentication through authentication context API when using HTTP BASIC authentication. * * <pre> * When: HTTP client calls EntryServlet (using BASIC authn) and Elytron API is used to reauthenticate * and call the WhoAmIBean * Then: * - call as "servlet" and reauthenticate as "whoami" passes and returns "whoami" * - call as "servlet" and reauthenticate as "admin" passes and returns "admin" * - call as "servlet" and reauthenticate as "whoami" passes and returns "whoami" * - call as "admin" and reauthenticate as "xadmin" fails as "xadmin" is not valid user * - call as "admin" and reauthenticate as "admin" with wrong password fails * </pre> */ @Test public void testServletBasicToEjbAuthenticationContext() throws Exception { // call with users who have all necessary roles assertEquals("Unexpected username returned", "whoami", Utils.makeCallWithBasicAuthn( getEntryServletUrl(WAR_ENTRY_SERVLET_BASIC, "whoami", "whoami", ReAuthnType.AC_AUTHENTICATION), "servlet", "servlet", SC_OK)); // call with another user who have sufficient roles on Jakarta Enterprise Beans assertEquals("Unexpected username returned", "admin", Utils.makeCallWithBasicAuthn( getEntryServletUrl(WAR_ENTRY_SERVLET_BASIC, "admin", "admin", ReAuthnType.AC_AUTHENTICATION), "servlet", "servlet", SC_OK)); // call with another servlet user assertEquals("Unexpected username returned", "whoami", Utils.makeCallWithBasicAuthn( getEntryServletUrl(WAR_ENTRY_SERVLET_BASIC, "whoami", "whoami", ReAuthnType.AC_AUTHENTICATION), "admin", "admin", SC_OK)); // call with wrong Jakarta Enterprise Beans username assertThat(Utils.makeCallWithBasicAuthn( getEntryServletUrl(WAR_ENTRY_SERVLET_BASIC, "xadmin", "admin", ReAuthnType.AC_AUTHENTICATION), "admin", "admin", SC_OK), isEjbAuthenticationError()); // call with wrong Jakarta Enterprise Beans password assertThat(Utils.makeCallWithBasicAuthn( getEntryServletUrl(WAR_ENTRY_SERVLET_BASIC, "admin", "adminx", ReAuthnType.AC_AUTHENTICATION), "admin", "admin", SC_OK), isEjbAuthenticationError()); //authorization // call with users who have all necessary roles assertEquals("Unexpected username returned", "whoami", Utils.makeCallWithBasicAuthn( getEntryServletUrl(WAR_ENTRY_SERVLET_BASIC, "server", "server", "whoami", ReAuthnType.AC_AUTHORIZATION), "servlet", "servlet", SC_OK)); // call with another user who have sufficient roles on Jakarta Enterprise Beans assertEquals("Unexpected username returned", "authz", Utils.makeCallWithBasicAuthn( getEntryServletUrl(WAR_ENTRY_SERVLET_BASIC, "entry", "entry", "authz", ReAuthnType.AC_AUTHORIZATION), "servlet", "servlet", SC_OK)); // call with another servlet user assertEquals("Unexpected username returned", "authz", Utils.makeCallWithBasicAuthn( getEntryServletUrl(WAR_ENTRY_SERVLET_BASIC, "entry", "entry", "authz", ReAuthnType.AC_AUTHORIZATION), "admin", "admin", SC_OK)); // call with wrong Jakarta Enterprise Beans username assertThat(Utils.makeCallWithBasicAuthn( getEntryServletUrl(WAR_ENTRY_SERVLET_BASIC, "xentry", "entry", "authz", ReAuthnType.AC_AUTHORIZATION), "admin", "admin", SC_OK), isEjbAuthenticationError()); // call with wrong Jakarta Enterprise Beans password assertThat(Utils.makeCallWithBasicAuthn( getEntryServletUrl(WAR_ENTRY_SERVLET_BASIC, "entry", "entryx", "authz", ReAuthnType.AC_AUTHORIZATION), "admin", "admin", SC_OK), isEjbAuthenticationError()); } /** * Tests if re-authentication works for HttpURLConnection calls. */ @Test @Ignore("WFLY-9442") public void testHttpReauthn() throws Exception { Callable<String> callable = getEjbToServletCallable(ReAuthnType.AC_AUTHENTICATION, "servlet", "servlet"); String servletResponse = SeccontextUtil.switchIdentity("admin", "admin", callable, ReAuthnType.AC_AUTHENTICATION); assertEquals("Unexpected principal name returned from servlet call", "servlet", servletResponse); } /** * Tests propagation when user propagated to HttpURLConnection has insufficient roles. */ @Test @Ignore("WFLY-9442") public void testHttpReauthnInsufficientRoles() throws Exception { Callable<String> callable = getEjbToServletCallable(ReAuthnType.AC_AUTHENTICATION, "whoami", "whoami"); String servletResponse = SeccontextUtil.switchIdentity("entry", "entry", callable, ReAuthnType.AC_AUTHENTICATION); assertThat(servletResponse, allOf(startsWith("java.io.IOException"), containsString("403"))); } /** * Tests propagation when user propagated to HttpURLConnection has insufficient roles. */ @Test public void testHttpReauthnWrongPass() throws Exception { Callable<String> callable = getEjbToServletCallable(ReAuthnType.AC_AUTHENTICATION, "servlet", "whoami"); String servletResponse = SeccontextUtil.switchIdentity("entry", "entry", callable, ReAuthnType.AC_AUTHENTICATION); assertThat(servletResponse, allOf(startsWith("java.io.IOException"), containsString("401"))); } }
23,689
50.951754
179
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/AuthenticationForwardingSFSFTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Authentication forwarding (credential forwarding) for security context propagation test. Variant which uses both Entry and * WhoAmI beans stateful. * * @author Josef Cacek */ public class AuthenticationForwardingSFSFTestCase extends AbstractAuthenticationForwardingTestCase { @Override protected boolean isEntryStateful() { return true; } @Override protected boolean isWhoAmIStateful() { return true; } }
1,544
34.930233
125
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/AuthorizationForwardingSLSFTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Authorization forwarding (credential less forwarding) for security context propagation test. Variant which uses Entry bean * stateless and WhoAmI bean stateful. * * @author Josef Cacek */ public class AuthorizationForwardingSLSFTestCase extends AbstractAuthorizationForwardingTestCase { @Override protected boolean isEntryStateful() { return false; } @Override protected boolean isWhoAmIStateful() { return true; } }
1,556
35.209302
125
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/HAAuthorizationForwardingSFSFTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Tests authorization forwarding within a cluster. Variant which uses both Entry and WhoAmI beans stateful. See superclass for * details. * * @author Josef Cacek */ public class HAAuthorizationForwardingSFSFTestCase extends AbstractHAAuthorizationForwardingTestCase { @Override protected boolean isEntryStateful() { return true; } @Override protected boolean isWhoAmIStateful() { return true; } }
1,534
34.697674
127
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/CallAnotherBeanInfo.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; import java.io.Serializable; /** * Class which hold information about calling another {@link Entry} bean or {@link WhoAmI} bean. * * @author olukas */ public final class CallAnotherBeanInfo implements Serializable { private final String username; private final String password; private final ReAuthnType type; private final String providerUrl; private final Boolean statefullWhoAmI; private final String lookupEjbAppName; private final String authzName; private CallAnotherBeanInfo(Builder builder) { this.username = builder.username; this.password = builder.password; this.type = builder.type; this.providerUrl = builder.providerUrl; this.statefullWhoAmI = builder.statefullWhoAmI; this.lookupEjbAppName = builder.lookupEjbAppName; this.authzName = builder.authzName; } public String getUsername() { return username; } public String getPassword() { return password; } public ReAuthnType getType() { return type; } public String getProviderUrl() { return providerUrl; } public Boolean isStatefullWhoAmI() { return statefullWhoAmI; } public String getLookupEjbAppName() { return lookupEjbAppName; } public String getAuthzName() { return authzName; } public static final class Builder { private String username; private String password; private ReAuthnType type; private String providerUrl; private boolean statefullWhoAmI; private String lookupEjbAppName; private String authzName; public Builder username(String username) { this.username = username; return this; } public Builder password(String password) { this.password = password; return this; } public Builder type(ReAuthnType type) { this.type = type; return this; } public Builder providerUrl(String providerUrl) { this.providerUrl = providerUrl; return this; } public Builder statefullWhoAmI(Boolean statefullWhoAmI) { this.statefullWhoAmI = statefullWhoAmI; return this; } public Builder lookupEjbAppName(String lookupEjbAppName) { this.lookupEjbAppName = lookupEjbAppName; return this; } public Builder authzName(String authz) { this.authzName = authz; return this; } public CallAnotherBeanInfo build() { return new CallAnotherBeanInfo(this); } } }
3,794
28.192308
96
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/WhoAmIBean.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.manual.elytron.seccontext; import java.security.Principal; import jakarta.annotation.Resource; import jakarta.annotation.security.DeclareRoles; import jakarta.annotation.security.RolesAllowed; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateless; /** * Stateless implementation of the {@link WhoAmI}. * @author Josef Cacek */ @Stateless @RolesAllowed({ "whoami", "admin", "no-server2-identity", "authz" }) @DeclareRoles({ "entry", "whoami", "servlet", "admin", "no-server2-identity", "authz" }) public class WhoAmIBean implements WhoAmI { @Resource private SessionContext context; @Override public Principal getCallerPrincipal() { return context.getCallerPrincipal(); } @Override public String throwIllegalStateException() { throw new IllegalStateException("Expected IllegalStateException from WhoAmIBean."); } @Override public String throwServer2Exception() { throw new Server2Exception("Expected Server2Exception from WhoAmIBean."); } }
1,648
30.113208
91
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/WhoAmIBeanSFSB.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.manual.elytron.seccontext; import jakarta.ejb.Stateful; /** * Stateful version of the {@link WhoAmIBean}. * * @author Josef Cacek */ @Stateful public class WhoAmIBeanSFSB extends WhoAmIBean implements WhoAmI { }
839
27.965517
75
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/HAAuthorizationForwardingSLSLTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Tests authorization forwarding within a cluster. Variant which uses both Entry and WhoAmI beans stateless. See superclass for * details. * * @author Josef Cacek */ public class HAAuthorizationForwardingSLSLTestCase extends AbstractHAAuthorizationForwardingTestCase { @Override protected boolean isEntryStateful() { return false; } @Override protected boolean isWhoAmIStateful() { return false; } }
1,537
34.767442
128
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/IdentitySwitchingSLSLTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Identity switching for security context propagation test. Variant which uses both Entry and WhoAmI beans stateless. * * @author Josef Cacek */ public class IdentitySwitchingSLSLTestCase extends AbstractIdentitySwitchingTestCase { @Override protected boolean isEntryStateful() { return false; } @Override protected boolean isWhoAmIStateful() { return false; } }
1,498
35.560976
118
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/AuthorizationForwardingSFSFTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Authorization forwarding (credential less forwarding) for security context propagation test. Variant which uses both Entry * and WhoAmI beans stateful. * * @author Josef Cacek */ public class AuthorizationForwardingSFSFTestCase extends AbstractAuthorizationForwardingTestCase { @Override protected boolean isEntryStateful() { return true; } @Override protected boolean isWhoAmIStateful() { return true; } }
1,546
34.976744
125
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/FirstServerChain.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; import jakarta.ejb.Remote; /** * Interface for the bean used as first bean in chain of 3 servers for authentication/authorization forwarding testing. * * @author olukas */ @Remote public interface FirstServerChain { /** * @return The name of the Principal obtained from a call to EJBContext.getCallerPrincipal() */ String whoAmI(); /** * Obtains the name of the Principal obtained from a call to EJBContext.getCallerPrincipal() both for the bean called and * also from a call to a second bean (user may be switched before the second call - depending on arguments) and also from a * call to a third bean (user may be switched before the second call - depending on arguments). * * @return An array containing the name from the local call first followed by the name from the second call and third call. */ String[] tripleWhoAmI(CallAnotherBeanInfo firstBeanInfo, CallAnotherBeanInfo secondBeanInfo); }
2,047
41.666667
127
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/WhoAmI.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.manual.elytron.seccontext; import java.security.Principal; import jakarta.ejb.Remote; @Remote public interface WhoAmI { /** * @return the caller principal obtained from the EJBContext. */ Principal getCallerPrincipal(); /** * Throws IllegalStateException. */ String throwIllegalStateException(); /** * Throws Server2Exception. */ String throwServer2Exception(); }
1,043
25.769231
75
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/InitialContextPropertiesOverrideTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; import java.util.Properties; import java.util.concurrent.Callable; import javax.naming.Context; import javax.naming.InitialContext; import static org.junit.Assert.assertEquals; import org.junit.Test; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_WHOAMI; /** * Test that {@link InitialContext} properties (principal+credentials) takes priority over the Elytron authentication * configuration. * * @author Josef Cacek */ public class InitialContextPropertiesOverrideTestCase extends AbstractSecurityContextPropagationTestBase { /** * Test that {@link InitialContext} properties (principal+credentials) takes priority over the Elytron authentication * configuration. * * <pre> * When: EJB client calls WhoAmIBean using both Elytron AuthenticationContext API InitialContext properties to set * username/password combination * Then: username/password combination from InitialContext is used * </pre> */ @Test public void testInitialContextPropertiesOverride() throws Exception { // Let's call the WhoAmIBean with different username+password combinations in Elytron API and InitialContext properties Callable<String> callable = () -> { final Properties jndiProperties = new Properties(); jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.wildfly.naming.client.WildFlyInitialContextFactory"); jndiProperties.put(Context.PROVIDER_URL, server2.getApplicationRemotingUrl()); jndiProperties.put(Context.SECURITY_PRINCIPAL, "whoami"); jndiProperties.put(Context.SECURITY_CREDENTIALS, "whoami"); final Context context = new InitialContext(jndiProperties); final WhoAmI bean = (WhoAmI) context.lookup( SeccontextUtil.getRemoteEjbName(WAR_WHOAMI, "WhoAmIBean", WhoAmI.class.getName(), isWhoAmIStateful())); return bean.getCallerPrincipal().getName(); }; // Elytron API uses "entry" user, the InitialContext uses "whoami" String whoAmI = SeccontextUtil.switchIdentity("entry", "entry", callable, ReAuthnType.AC_AUTHENTICATION); // The identity should be created from InitialContext properties assertEquals("The whoAmIBean.whoAmI() returned unexpected principal", "whoami", whoAmI); } @Override protected boolean isEntryStateful() { return false; } @Override protected boolean isWhoAmIStateful() { return false; } }
3,610
43.580247
127
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/IdentitySwitchingSLSFTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Identity switching for security context propagation test. Variant which uses Entry bean stateless and WhoAmI bean stateful. * * @author Josef Cacek */ public class IdentitySwitchingSLSFTestCase extends AbstractIdentitySwitchingTestCase { @Override protected boolean isEntryStateful() { return false; } @Override protected boolean isWhoAmIStateful() { return true; } }
1,506
34.880952
126
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/Server2Exception.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.manual.elytron.seccontext; /** * Custom exception that should be available just in deployments on server2. * * @author Ondrej Kotek */ public class Server2Exception extends RuntimeException { public Server2Exception() { super(); } public Server2Exception(String s) { super(s); } }
940
27.515152
76
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/AuthenticationForwardingSLSFTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Authentication forwarding (credential forwarding) for security context propagation test. Variant which uses Entry bean * stateless and WhoAmI bean stateful. * * @author Josef Cacek */ public class AuthenticationForwardingSLSFTestCase extends AbstractAuthenticationForwardingTestCase { @Override protected boolean isEntryStateful() { return false; } @Override protected boolean isWhoAmIStateful() { return true; } }
1,554
35.162791
121
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/EntryBeanSFSB.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.manual.elytron.seccontext; import jakarta.ejb.Stateful; /** * Stateful version of the {@link EntryBean}. * * @author Josef Cacek */ @Stateful public class EntryBeanSFSB extends EntryBean implements Entry { }
835
27.827586
75
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/ServerChainSecurityContextPropagationTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.hamcrest.MatcherAssert.assertThat; import static org.wildfly.test.manual.elytron.seccontext.AbstractSecurityContextPropagationTestBase.server1; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.JAR_ENTRY_EJB; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.SERVER1; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.SERVER2; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.SERVER3; import static org.wildfly.test.manual.elytron.seccontext.SeccontextUtil.WAR_WHOAMI; import java.io.IOException; import java.net.SocketPermission; import java.util.concurrent.Callable; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.as.cli.CommandLineException; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.wildfly.security.permission.ElytronPermission; /** * Test case for authentication and authorization forwarding for 3 servers. Test scenarios use following configuration. * Description of used users and beans WhoAmIBean and EntryBean is in superclass. * * <h3>Given</h3> * * <pre> * Another Jakarta Enterprise Beans used for testing: * - FirstServerChainBean - protected (entry, admin and no-server2-identity roles are allowed), stateless, * configures identity propagation and calls a remote EntryBean * * Deployments used for testing: * - first-server-ejb.jar (FirstServerChainBean) * - entry-ejb-server-chain.jar (EntryBean) * - whoami-server-chain.jar (WhoAmIBean) * * Servers started and configured for context propagation scenarios: * - seccontext-server1 (standalone-ha.xml) * * first-server-ejb.jar * - seccontext-server2 (standalone.xml) * * entry-ejb-server-chain.jar * - seccontext-server3 * * whoami-server-chain.jar * </pre> * * @author olukas */ public class ServerChainSecurityContextPropagationTestCase extends AbstractSecurityContextPropagationTestBase { public static final String FIRST_SERVER_CHAIN_EJB = "first-server-chain"; public static final String JAR_ENTRY_EJB_SERVER_CHAIN = JAR_ENTRY_EJB + "-server-chain"; public static final String WAR_WHOAMI_SERVER_CHAIN = WAR_WHOAMI + "-server-chain"; private static final ServerHolder server3 = new ServerHolder(SERVER3, TestSuiteEnvironment.getServerAddressNode1(), 250); /** * Creates deployment with FirstServerChain bean - to be placed on the first server. */ @Deployment(name = FIRST_SERVER_CHAIN_EJB, managed = false, testable = false) @TargetsContainer(SERVER1) public static Archive<?> createServerChain1Deployment() { return ShrinkWrap.create(JavaArchive.class, FIRST_SERVER_CHAIN_EJB + ".jar") .addClasses(FirstServerChainBean.class, FirstServerChain.class, Entry.class, ReAuthnType.class, SeccontextUtil.class, CallAnotherBeanInfo.class) .addAsManifestResource(createPermissionsXmlAsset(new ElytronPermission("authenticate"), new ElytronPermission("getPrivateCredentials"), new ElytronPermission("getSecurityDomain"), new SocketPermission(TestSuiteEnvironment.getServerAddressNode1() + ":8180", "connect,resolve")), "permissions.xml") .addAsManifestResource(Utils.getJBossEjb3XmlAsset("seccontext-entry"), "jboss-ejb3.xml"); } /** * Creates deployment with Entry bean - to be placed on the second server. */ @Deployment(name = JAR_ENTRY_EJB_SERVER_CHAIN, managed = false, testable = false) @TargetsContainer(SERVER2) public static Archive<?> createServerChain2Deployment() { return ShrinkWrap.create(JavaArchive.class, JAR_ENTRY_EJB_SERVER_CHAIN + ".jar") .addClasses(EntryBean.class, Entry.class, WhoAmI.class, ReAuthnType.class, SeccontextUtil.class, CallAnotherBeanInfo.class) .addAsManifestResource(createPermissionsXmlAsset(new ElytronPermission("authenticate"), new ElytronPermission("getPrivateCredentials"), new ElytronPermission("getSecurityDomain"), new SocketPermission(TestSuiteEnvironment.getServerAddressNode1() + ":8330", "connect,resolve")), "permissions.xml") .addAsManifestResource(Utils.getJBossEjb3XmlAsset("seccontext-entry"), "jboss-ejb3.xml"); } /** * Creates deployment with WhoAmI bean - to be placed on the third server. */ @Deployment(name = WAR_WHOAMI_SERVER_CHAIN, managed = false, testable = false) @TargetsContainer(SERVER3) public static Archive<?> createServerChain3Deployment() { return ShrinkWrap.create(JavaArchive.class, WAR_WHOAMI_SERVER_CHAIN + ".jar") .addClasses(WhoAmIBean.class, WhoAmI.class, Server2Exception.class) .addAsManifestResource(Utils.getJBossEjb3XmlAsset("seccontext-whoami"), "jboss-ejb3.xml"); } @Before public void startServer3() throws CommandLineException, IOException, MgmtOperationException { server3.resetContainerConfiguration(new ServerConfigurationBuilder() .withDeployments(WAR_WHOAMI_SERVER_CHAIN) .withAdditionalUsers("another-server", "no-server2-identity") .withCliCommands("/subsystem=elytron/simple-permission-mapper=seccontext-server-permissions" + ":write-attribute(name=permission-mappings[1],value={principals=[another-server]," + "permissions=[{class-name=org.wildfly.security.auth.permission.LoginPermission}," + "{class-name=org.wildfly.security.auth.permission.RunAsPrincipalPermission, target-name=admin}," + "{class-name=org.wildfly.security.auth.permission.RunAsPrincipalPermission, target-name=" + "no-server2-identity}]})") .build()); } /** * Shut down servers. */ @AfterClass public static void shutdownServer3() throws IOException { server3.shutDown(); } /** * Setup seccontext-server1. */ @Override protected void setupServer1() throws CommandLineException, IOException, MgmtOperationException { server1.resetContainerConfiguration(new ServerConfigurationBuilder() .withAdditionalUsers("no-server2-identity") .withDeployments(FIRST_SERVER_CHAIN_EJB) .build()); } /** * Setup seccontext-server2. */ @Override protected void setupServer2() throws CommandLineException, IOException, MgmtOperationException { server2.resetContainerConfiguration(new ServerConfigurationBuilder() .withDeployments(JAR_ENTRY_EJB_SERVER_CHAIN) .build()); } /** * Test forwarding authentication (credential forwarding) works for Jakarta Enterprise Beans calls after another authentication forwarding. * * <pre> * When: Jakarta Enterprise Beans client calls FirstServerChainBean as admin user and Elytron AuthenticationContext API is used to * authentication forwarding to EntryBean call and Elytron AuthenticationContext API is used to * authentication forwarding to WhoAmIBean call. * Then: credentials are reused for EntryBean as well as WhoAmIBean call and it correctly returns "admin" username for both * beans. * </pre> */ @Test public void testForwardedAuthenticationPropagationChain() throws Exception { String[] tripleWhoAmI = SeccontextUtil.switchIdentity("admin", "admin", getTripleWhoAmICallable(ReAuthnType.FORWARDED_AUTHENTICATION, null, null, ReAuthnType.FORWARDED_AUTHENTICATION, null, null), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The firstServerChainBean.tripleWhoAmI() should return not-null instance", tripleWhoAmI); assertArrayEquals("Unexpected principal names returned from tripleWhoAmI", new String[]{"admin", "admin", "admin"}, tripleWhoAmI); } /** * Test forwarding authentication (credential forwarding) for Jakarta Enterprise Beans calls after another authentication forwarding is not * possible when given identity does not exist in intermediate server. * * <pre> * When: Jakarta Enterprise Beans client calls FirstServerChainBean as no-server2-identity user and Elytron AuthenticationContext API is used to * authentication forwarding to EntryBean call and Elytron AuthenticationContext API is used to * authentication forwarding to WhoAmIBean call. * Then: authentication for EntryBean should fail because no-server2-identity does not exist on seccontext-server2. * </pre> */ @Test public void testForwardedAuthenticationIdentityDoesNotExistOnIntermediateServer() throws Exception { String[] tripleWhoAmI = SeccontextUtil.switchIdentity("no-server2-identity", "no-server2-identity", getTripleWhoAmICallable(ReAuthnType.FORWARDED_AUTHENTICATION, null, null, ReAuthnType.FORWARDED_AUTHENTICATION, null, null), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The firstServerChainBean.tripleWhoAmI() should return not-null instance", tripleWhoAmI); assertEquals("Unexpected principal names returned from first call in tripleWhoAmI", "no-server2-identity", tripleWhoAmI[0]); assertThat("Access should be denied for second call in tripleWhoAmI when identity does not exist on second server", tripleWhoAmI[1], isEjbAuthenticationError()); assertNull("Third call in tripleWhoAmI should not exist", tripleWhoAmI[2]); } /** * Test forwarding authorization (credential less forwarding) works for Jakarta Enterprise Beans calls after another authorization forwarding. * {@link RunAsPrincipalPermission} is assigned to caller server and another-server identity. * * <pre> * When: Jakarta Enterprise Beans client calls FirstServerChainBean as admin user and Elytron AuthenticationContext API is used to * authorization forwarding to EntryBean call with "server" user used as caller server identity and * Elytron AuthenticationContext API is used to * authorization forwarding to WhoAmIBean call with "another-server" user used as caller server identity. * Then: EntryBean call is possible and returns "admin" username * and WhoAmIBean call is possible and returns "admin" username. * </pre> */ @Test public void testForwardedAuthorizationPropagationChain() throws Exception { String[] tripleWhoAmI = SeccontextUtil.switchIdentity("admin", "admin", getTripleWhoAmICallable(ReAuthnType.FORWARDED_AUTHORIZATION, "server", "server", ReAuthnType.FORWARDED_AUTHORIZATION, "another-server", "another-server"), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The firstServerChainBean.tripleWhoAmI() should return not-null instance", tripleWhoAmI); assertArrayEquals("Unexpected principal names returned from tripleWhoAmI", new String[]{"admin", "admin", "admin"}, tripleWhoAmI); } /** * Test forwarding authorization (credential less forwarding) for Jakarta Enterprise Beans calls after another authorization forwarding is not * possible when given authorization identity does not exist in intermediate server. {@link RunAsPrincipalPermission} is * assigned to caller server and another-server identity. * * <pre> * When: Jakarta Enterprise Beans client calls FirstServerChainBean as no-server2-identity user and Elytron AuthenticationContext API is used to * authorization forwarding to EntryBean call with "server" user used as caller server identity * and Elytron AuthenticationContext API is used to * authorization forwarding to WhoAmIBean call with "another-server" user used as caller server identity. * Then: authorization for EntryBean should fail because no-server2-identity does not exist on seccontext-server2. * </pre> */ @Test public void testForwardedAuthorizationIdentityDoesNotExistOnIntermediateServer() throws Exception { String[] tripleWhoAmI = SeccontextUtil.switchIdentity("no-server2-identity", "no-server2-identity", getTripleWhoAmICallable(ReAuthnType.FORWARDED_AUTHORIZATION, "server", "server", ReAuthnType.FORWARDED_AUTHORIZATION, "another-server", "another-server"), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The firstServerChainBean.tripleWhoAmI() should return not-null instance", tripleWhoAmI); assertEquals("Unexpected principal names returned from first call in tripleWhoAmI", "no-server2-identity", tripleWhoAmI[0]); assertThat("Access should be denied for second call in tripleWhoAmI when identity does not exist on second server", tripleWhoAmI[1], isEjbAuthenticationError()); assertNull("Third call in tripleWhoAmI should not exist", tripleWhoAmI[2]); } /** * Test forwarding authentication (credential forwarding) for Jakarta Enterprise Beans calls is not possible after authorization forwarding. * {@link RunAsPrincipalPermission} is assigned to caller server and another-server identity. * * <pre> * When: Jakarta Enterprise Beans client calls FirstServerChainBean as admin user and Elytron AuthenticationContext API is used to * authorization forwarding to EntryBean call with "server" user used as caller server identity and * Elytron AuthenticationContext API is used to authentication forwarding to WhoAmIBean. * Then: WhoAmIBean call is fails because credentails should not be available on seccontext-server2 after authorization * forwarding. * </pre> */ @Test public void testForwardingAuthenticationIsNotPossibleAfterForwardingAuthorization() throws Exception { String[] tripleWhoAmI = SeccontextUtil.switchIdentity("admin", "admin", getTripleWhoAmICallable(ReAuthnType.FORWARDED_AUTHORIZATION, "server", "server", ReAuthnType.FORWARDED_AUTHENTICATION, null, null), ReAuthnType.AC_AUTHENTICATION); assertNotNull("The firstServerChainBean.tripleWhoAmI() should return not-null instance", tripleWhoAmI); assertEquals("Unexpected principal names returned from first call in tripleWhoAmI", "admin", tripleWhoAmI[0]); assertEquals("Unexpected principal names returned from second call in tripleWhoAmI", "admin", tripleWhoAmI[1]); assertThat("Access should be denied for third call in tripleWhoAmI", tripleWhoAmI[2], isEjbAuthenticationError()); } protected Callable<String[]> getTripleWhoAmICallable(final ReAuthnType firstType, final String firstUsername, final String firstPassword, final ReAuthnType secondType, final String secondUsername, final String secondPassword) { return () -> { final FirstServerChain bean = SeccontextUtil.lookup( SeccontextUtil.getRemoteEjbName(FIRST_SERVER_CHAIN_EJB, "FirstServerChainBean", FirstServerChain.class.getName(), isEntryStateful()), server1.getApplicationRemotingUrl()); final String server2Url = server2.getApplicationRemotingUrl(); final String server3Url = server3.getApplicationRemotingUrl(); return bean.tripleWhoAmI(new CallAnotherBeanInfo.Builder() .username(firstUsername) .password(firstPassword) .type(firstType) .providerUrl(server2Url) .statefullWhoAmI(isWhoAmIStateful()) .build(), new CallAnotherBeanInfo.Builder() .username(secondUsername) .password(secondPassword) .type(secondType) .providerUrl(server3Url) .statefullWhoAmI(isWhoAmIStateful()) .lookupEjbAppName(WAR_WHOAMI_SERVER_CHAIN) .build()); }; } @Override protected boolean isEntryStateful() { return false; } @Override protected boolean isWhoAmIStateful() { return false; } }
18,314
54.668693
148
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/AuthorizationForwardingSFSLTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, 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.wildfly.test.manual.elytron.seccontext; /** * Authorization forwarding (credential less forwarding) for security context propagation test. Variant which uses Entry bean * stateful and WhoAmI bean stateless. * * @author Josef Cacek */ public class AuthorizationForwardingSFSLTestCase extends AbstractAuthorizationForwardingTestCase { @Override protected boolean isEntryStateful() { return true; } @Override protected boolean isWhoAmIStateful() { return false; } }
1,556
35.209302
125
java
null
wildfly-main/testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/management/ManagementOnlyModeTestCase.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.manual.management; import static org.jboss.as.controller.client.helpers.ClientConstants.RESPONSE_HEADERS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; 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.controller.descriptions.ModelDescriptionConstants.PROCESS_STATE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE; import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode; import java.net.URL; import jakarta.inject.Inject; import org.jboss.as.test.integration.management.util.WebUtil; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.core.testrunner.ServerControl; import org.wildfly.core.testrunner.ServerController; import org.wildfly.core.testrunner.WildflyTestRunner; /** * @author Dominik Pospisil <dpospisi@redhat.com> * @author Tomaz Cerar */ @ServerControl(manual = true) @RunWith(WildflyTestRunner.class) public class ManagementOnlyModeTestCase { private static final int TEST_PORT = 20491; @Inject private ServerController container; @Test public void testManagementOnlyMode() throws Exception { // restart server to management-only mode container.startInAdminMode(); // update the model in admin-only mode - add a web connector ModelNode op = createOpNode("socket-binding-group=standard-sockets/socket-binding=my-test-binding", ADD); op.get("interface").set("public"); op.get("port").set(TEST_PORT); container.getClient().executeForResult(op); op = createOpNode("subsystem=undertow/server=default-server/http-listener=my-test", ADD); op.get("socket-binding").set("my-test-binding"); container.getClient().executeForResult(op); //reload to normal mode container.reload(); // check that the changes made in admin-only mode have been applied - test the connector Assert.assertTrue("Could not connect to created connector.", WebUtil.testHttpURL(new URL( "http", TestSuiteEnvironment.getHttpAddress(), TEST_PORT, "/").toString())); // remove the conector op = createOpNode("subsystem=undertow/server=default-server/http-listener=my-test", REMOVE); op.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(false); container.getClient().executeForResult(op); op = createOpNode("socket-binding-group=standard-sockets/socket-binding=my-test-binding", REMOVE); op.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(false); ModelNode result = container.getClient().getControllerClient().execute(op); //reload shouldn't be required by operations above, if it is, there is a problem if (result.hasDefined(RESPONSE_HEADERS) && result.get(RESPONSE_HEADERS).hasDefined(PROCESS_STATE)) { Assert.assertTrue("reload-required".equals(result.get(RESPONSE_HEADERS).get(PROCESS_STATE).asString())); } } }
4,342
44.715789
116
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/TestsuiteSanityTestCase.java
package org.jboss.as.test.smoke; import java.io.File; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests whether properties we rely on in the tests were properly passed to JUnit. * * @author Ondrej Zizka */ @RunWith(Arquillian.class) public class TestsuiteSanityTestCase { private static final String[] EXPECTED_PROPS = new String[]{"jbossas.ts.submodule.dir", "jbossas.ts.integ.dir", "jbossas.ts.dir", "jbossas.project.dir", "jboss.dist", "jboss.inst"}; @Test public void testSystemProperties() throws Exception { for (String var : EXPECTED_PROPS) { String path = System.getProperty(var); Assert.assertNotNull("Property " + var + " is not set (in container).", path); File dir = new File(path); Assert.assertTrue("Directory " + dir.getAbsolutePath() + " doesn't exist, check Surefire's system property " + var, dir.exists()); } } @Test @RunAsClient public void testSystemPropertiesClient() throws Exception { for (String var : EXPECTED_PROPS) { String path = System.getProperty(var); Assert.assertNotNull("Property " + var + " is not set (outside container).", path); File dir = new File(path); Assert.assertTrue("Directory " + dir.getAbsolutePath() + " doesn't exist, check Surefire's system property " + var, dir.exists()); } } }// class
1,564
32.297872
185
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/mgmt/resourceadapter/ResourceAdapterOperationsUnitTestCase.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.smoke.mgmt.resourceadapter; 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.integration.management.jca.ComplexPropertiesParseUtils.checkModelParams; import static org.jboss.as.test.integration.management.jca.ComplexPropertiesParseUtils.raAdminProperties; import static org.jboss.as.test.integration.management.jca.ComplexPropertiesParseUtils.raCommonProperties; import static org.jboss.as.test.integration.management.jca.ComplexPropertiesParseUtils.raConnectionProperties; import static org.jboss.as.test.integration.management.jca.ComplexPropertiesParseUtils.setOperationParams; import java.io.IOException; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.connector.subsystems.resourceadapters.Namespace; import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdapterSubsystemParser; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.integration.management.jca.ConnectionSecurityType; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Resource adapter operation unit test. * * @author <a href="mailto:vrastsel@redhat.com">Vladimir Rastseluev</a> * @author Flavia Rainone */ @RunWith(Arquillian.class) @RunAsClient public class ResourceAdapterOperationsUnitTestCase extends ContainerResourceMgmtTestBase { private static final Deque<ModelNode> REMOVE_ADDRESSES = new LinkedList<>(); private static final ModelNode RAR_ADDRESS; static { final ModelNode address = new ModelNode(); address.add("subsystem", "resource-adapters"); address.add("resource-adapter", "some.rar"); address.protect(); RAR_ADDRESS = address; } @BeforeClass public static void configureElytron() throws Exception { try (ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient()) { addAuth(client, "AuthCtxt"); addAuth(client, "AuthCtxtAndApp"); } } @AfterClass public static void removeElytronConfig() throws Exception { try (ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient()) { ModelNode address; while ((address = REMOVE_ADDRESSES.pollFirst()) != null) { execute(client, Operations.createRemoveOperation(address)); } } } @After public void removeRar() throws IOException { // Don't let failure in one test leave cruft behind to break the rest try { remove(RAR_ADDRESS); } catch (MgmtOperationException ignored) { // ignore -- assume it's the usual case where the test method already removed this } } @Test public void addComplexResourceAdapterWithAppSecurity() throws Exception { complexResourceAdapterAddTest(ConnectionSecurityType.ELYTRON_AUTHENTICATION_CONTEXT_AND_APPLICATION, null); } @Test public void addComplexResourceAdapterWithAppSecurity_UserPassRecovery() throws Exception { complexResourceAdapterAddTest(ConnectionSecurityType.ELYTRON_AUTHENTICATION_CONTEXT_AND_APPLICATION, ConnectionSecurityType.USER_PASSWORD); } @Test public void addComplexResourceAdapterWithAppSecurity_ElytronRecovery() throws Exception { complexResourceAdapterAddTest(ConnectionSecurityType.ELYTRON_AUTHENTICATION_CONTEXT_AND_APPLICATION, ConnectionSecurityType.ELYTRON); } @Test public void addComplexResourceAdapterWithAppSecurity_ElytronAuthCtxtRecovery() throws Exception { complexResourceAdapterAddTest(ConnectionSecurityType.ELYTRON_AUTHENTICATION_CONTEXT_AND_APPLICATION, ConnectionSecurityType.ELYTRON_AUTHENTICATION_CONTEXT); } @Test public void addComplexResourceAdapterWithElytron() throws Exception { complexResourceAdapterAddTest(ConnectionSecurityType.ELYTRON, ConnectionSecurityType.ELYTRON); } @Test public void addComplexResourceAdapterWithElytron_NoRecoverySec() throws Exception { complexResourceAdapterAddTest(ConnectionSecurityType.ELYTRON, null); } @Test public void addComplexResourceAdapterWithElytron_UserPassRecoverySec() throws Exception { complexResourceAdapterAddTest(ConnectionSecurityType.ELYTRON, ConnectionSecurityType.USER_PASSWORD); } @Test public void addComplexResourceAdapterWithElytron_ElytronAuthCtxtRecoverySec() throws Exception { complexResourceAdapterAddTest(ConnectionSecurityType.ELYTRON, ConnectionSecurityType.ELYTRON_AUTHENTICATION_CONTEXT); } @Test public void addComplexResourceAdapterWithElytronAuthCtxt() throws Exception { complexResourceAdapterAddTest(ConnectionSecurityType.ELYTRON_AUTHENTICATION_CONTEXT, ConnectionSecurityType.ELYTRON_AUTHENTICATION_CONTEXT); } @Test public void addComplexResourceAdapterWithElytronAuthCtxtN_oRecoverySec() throws Exception { complexResourceAdapterAddTest(ConnectionSecurityType.ELYTRON_AUTHENTICATION_CONTEXT, null); } @Test public void addComplexResourceAdapterWithElytronAuthCtxt_UserPassRecoverySec() throws Exception { complexResourceAdapterAddTest(ConnectionSecurityType.ELYTRON_AUTHENTICATION_CONTEXT, ConnectionSecurityType.USER_PASSWORD); } @Test public void addComplexResourceAdapterWithElytronAuthCtxt_ElytronRecoverySec() throws Exception { complexResourceAdapterAddTest(ConnectionSecurityType.ELYTRON_AUTHENTICATION_CONTEXT, ConnectionSecurityType.ELYTRON); } private void complexResourceAdapterAddTest(ConnectionSecurityType connectionSecurityType, ConnectionSecurityType connectionRecoverySecurityType) throws Exception { final ModelNode address = RAR_ADDRESS; Properties params = raCommonProperties(); final ModelNode operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(address); setOperationParams(operation, params); operation.get("beanvalidationgroups").add("Class0"); operation.get("beanvalidationgroups").add("Class00"); executeOperation(operation); final ModelNode address1 = address.clone(); address1.add("config-properties", "Property"); address1.protect(); final ModelNode operation11 = new ModelNode(); operation11.get(OP).set("add"); operation11.get(OP_ADDR).set(address1); operation11.get("value").set("A"); executeOperation(operation11); final ModelNode conAddress = address.clone(); conAddress.add("connection-definitions", "Pool1"); conAddress.protect(); Properties conParams = raConnectionProperties(connectionSecurityType, connectionRecoverySecurityType); final ModelNode operation2 = new ModelNode(); operation2.get(OP).set("add"); operation2.get(OP_ADDR).set(conAddress); setOperationParams(operation2, conParams); executeOperation(operation2); final ModelNode con1Address = conAddress.clone(); con1Address.add("config-properties", "Property"); con1Address.protect(); final ModelNode operation21 = new ModelNode(); operation21.get(OP).set("add"); operation21.get(OP_ADDR).set(con1Address); operation21.get("value").set("B"); executeOperation(operation21); final ModelNode admAddress = address.clone(); admAddress.add("admin-objects", "Pool2"); admAddress.protect(); Properties admParams = raAdminProperties(); final ModelNode operation3 = new ModelNode(); operation3.get(OP).set("add"); operation3.get(OP_ADDR).set(admAddress); setOperationParams(operation3, admParams); executeOperation(operation3); final ModelNode adm1Address = admAddress.clone(); adm1Address.add("config-properties", "Property"); adm1Address.protect(); final ModelNode operation31 = new ModelNode(); operation31.get(OP).set("add"); operation31.get(OP_ADDR).set(adm1Address); operation31.get("value").set("D"); executeOperation(operation31); List<ModelNode> newList = marshalAndReparseRaResources("resource-adapter"); remove(address); Assert.assertNotNull(newList); ModelNode node = findNodeWithProperty(newList, "archive", "some.rar"); Assert.assertNotNull("There is no archive element:" + newList, node); Assert.assertTrue("compare failed, node:"+node.asString()+"\nparams:"+params,checkModelParams(node,params)); Assert.assertEquals("beanvalidationgroups element is incorrect:" + node.get("beanvalidationgroups").asString(), "[\"Class0\",\"Class00\"]", node.get("beanvalidationgroups").asString()); node = findNodeWithProperty(newList, "jndi-name", "java:jboss/name1"); Assert.assertNotNull("There is no connection jndi-name element:" + newList, node); Assert.assertTrue("compare failed, node:"+node.asString()+"\nparams:"+conParams,checkModelParams(node,conParams)); node = findNodeWithProperty(newList, "jndi-name", "java:jboss/Name3"); Assert.assertNotNull("There is no admin jndi-name element:" + newList, node); Assert.assertTrue("compare failed, node:" + node.asString() + "\nparams:" + admParams, checkModelParams(node, admParams)); node = findNodeWithProperty(newList, "value", "D"); Assert.assertNotNull("There is no admin-object config-property element:" + newList, node); Map<String, ModelNode> parseChildren = getChildren(node.get("address")); Assert.assertEquals("Pool2", parseChildren.get("admin-objects").asString()); Assert.assertEquals("Property", parseChildren.get("config-properties").asString()); node = findNodeWithProperty(newList, "value", "A"); Assert.assertNotNull("There is no resource-adapter config-property element:" + newList, node); parseChildren = getChildren(node.get("address")); Assert.assertEquals("some.rar", parseChildren.get("resource-adapter").asString()); Assert.assertEquals("Property", parseChildren.get("config-properties").asString()); node = findNodeWithProperty(newList, "value", "B"); Assert.assertNotNull("There is no connection config-property element:" + newList, node); parseChildren = getChildren(node.get("address")); Assert.assertEquals("Pool1", parseChildren.get("connection-definitions").asString()); Assert.assertEquals("Property", parseChildren.get("config-properties").asString()); } public List<ModelNode> marshalAndReparseRaResources(final String childType) throws Exception { ResourceAdapterSubsystemParser parser = new ResourceAdapterSubsystemParser(); return xmlToModelOperations(modelToXml("resource-adapters", childType, parser), Namespace.CURRENT.getUriString(), parser); } private static void addAuth(final ModelControllerClient client, final String name) throws IOException { ModelNode address = Operations.createAddress("subsystem", "elytron", "authentication-configuration", name); REMOVE_ADDRESSES.addLast(address.clone()); ModelNode op = Operations.createAddOperation(address); op.get("security-domain").set("ApplicationDomain"); final ModelNode cr = op.get("credential-reference").setEmptyObject(); cr.get("clear-text").set("value"); execute(client, op); address = Operations.createAddress("subsystem", "elytron", "authentication-context", name); REMOVE_ADDRESSES.addFirst(address.clone()); op = Operations.createAddOperation(address); final ModelNode mr = op.get("match-rules").setEmptyList(); final ModelNode ac = new ModelNode().setEmptyObject(); ac.get("authentication-configuration").set(name); mr.add(ac); execute(client, op); } private static void execute(final ModelControllerClient client, final ModelNode op) throws IOException { final ModelNode result = client.execute(op); if (!Operations.isSuccessfulOutcome(result)) { throw new RuntimeException(Operations.getFailureDescription(result).asString()); } } }
14,083
43.711111
164
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/mgmt/datasource/DataSourceOperationsUnitTestCase.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.smoke.mgmt.datasource; 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.integration.management.jca.ComplexPropertiesParseUtils.addExtensionProperties; import static org.jboss.as.test.integration.management.jca.ComplexPropertiesParseUtils.checkModelParams; import static org.jboss.as.test.integration.management.jca.ComplexPropertiesParseUtils.nonXaDsProperties; import static org.jboss.as.test.integration.management.jca.ComplexPropertiesParseUtils.setOperationParams; import static org.jboss.as.test.integration.management.jca.ComplexPropertiesParseUtils.xaDsProperties; import java.security.InvalidParameterException; import java.util.List; import java.util.Properties; 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.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.connector.subsystems.datasources.DataSourcesExtension; import org.jboss.as.connector.subsystems.datasources.Namespace; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.jca.ConnectionSecurityType; import org.jboss.as.test.integration.management.jca.DsMgmtTestBase; import org.jboss.dmr.ModelNode; 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; /** * Datasource operation unit test. * * @author <a href="mailto:stefano.maestri@redhat.com">Stefano Maestri</a> * @author <a href="mailto:jeff.zhang@jboss.org">Jeff Zhang</a> * @author <a href="mailto:vrastsel@redhat.com">Vladimir Rastseluev</a> * @author Flavia Rainone */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(DataSourceOperationsUnitTestCase.ServerSetup.class) public class DataSourceOperationsUnitTestCase extends DsMgmtTestBase { public static class ServerSetup implements ServerSetupTask { @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { ModelNode authContextAdd = Util.createAddOperation(PathAddress.pathAddress("subsystem", "elytron").append("authentication-context", "HsqlAuthCtxt")); ModelNode response = managementClient.getControllerClient().execute(authContextAdd); Assert.assertEquals(response.toString(), "success", response.get("outcome").asString()); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { ModelNode authContextRemove = Util.createRemoveOperation(PathAddress.pathAddress("subsystem", "elytron").append("authentication-context", "HsqlAuthCtxt")); ModelNode response = managementClient.getControllerClient().execute(authContextRemove); Assert.assertEquals(response.toString(), "success", response.get("outcome").asString()); } } @Deployment public static Archive<?> fakeDeployment() { return ShrinkWrap.create(JavaArchive.class); } @Test public void testAddDsAndTestConnection() throws Exception { final ModelNode address = new ModelNode(); address.add("subsystem", "datasources"); address.add("data-source", "MyNewDs"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(address); operation.get("name").set("MyNewDs"); operation.get("jndi-name").set("java:jboss/datasources/MyNewDs"); operation.get("enabled").set(true); // WFLY-16272 test a simple use-java-context with expression value in "test-connection-in-pool" operation. operation.get("use-java-context").set("${env.db_java_context:true}"); operation.get("driver-name").set("h2"); operation.get("pool-name").set("MyNewDs_Pool"); operation.get("connection-url").set("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); operation.get("user-name").set("sa"); operation.get("password").set("sa"); executeOperation(operation); testConnection("MyNewDs"); List<ModelNode> newList = marshalAndReparseDsResources("data-source"); remove(address); Assert.assertNotNull("Reparsing failed:", newList); Assert.assertNotNull(findNodeWithProperty(newList, "jndi-name", "java:jboss/datasources/MyNewDs")); } @Test public void testAddAndRemoveSameName() throws Exception { final String dsName = "SameNameDs"; final ModelNode address = new ModelNode(); address.add("subsystem", "datasources"); address.add("data-source", dsName); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(address); operation.get("name").set(dsName); operation.get("jndi-name").set("java:jboss/datasources/" + dsName); operation.get("enabled").set(false); operation.get("driver-name").set("h2"); operation.get("pool-name").set(dsName + "_Pool"); operation.get("connection-url").set("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); operation.get("user-name").set("sa"); operation.get("password").set("sa"); // do twice, test for AS7-720 for (int i = 1; i <= 2; i++) { executeOperation(operation); remove(address); } } /** * AS7-1206 test for jndi binding isn't unbound during remove if jndi name * and data-source name are different * * @throws Exception */ @Test public void testAddAndRemoveNameAndJndiNameDifferent() throws Exception { final String dsName = "DsName"; final String jndiDsName = "JndiDsName"; final ModelNode address = new ModelNode(); address.add("subsystem", "datasources"); address.add("data-source", dsName); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(address); operation.get("name").set(dsName); operation.get("jndi-name").set("java:jboss/datasources/" + jndiDsName); operation.get("enabled").set(false); operation.get("driver-name").set("h2"); operation.get("pool-name").set(dsName + "_Pool"); operation.get("connection-url").set("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); operation.get("user-name").set("sa"); operation.get("password").set("sa"); executeOperation(operation); remove(address); } @Test public void testAddAndRemoveXaDs() throws Exception { final String dsName = "XaDsName"; final String jndiDsName = "XaJndiDsName"; final ModelNode address = new ModelNode(); address.add("subsystem", "datasources"); address.add("xa-data-source", dsName); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(address); operation.get("name").set(dsName); operation.get("jndi-name").set("java:jboss/datasources/" + jndiDsName); operation.get("enabled").set(false); operation.get("driver-name").set("h2"); operation.get("pool-name").set(dsName + "_Pool"); operation.get("user-name").set("sa"); operation.get("password").set("sa"); executeOperation(operation); final ModelNode xaDatasourcePropertiesAddress = address.clone(); xaDatasourcePropertiesAddress.add("xa-datasource-properties", "URL"); xaDatasourcePropertiesAddress.protect(); final ModelNode xaDatasourcePropertyOperation = new ModelNode(); xaDatasourcePropertyOperation.get(OP).set("add"); xaDatasourcePropertyOperation.get(OP_ADDR).set(xaDatasourcePropertiesAddress); xaDatasourcePropertyOperation.get("value").set("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); executeOperation(xaDatasourcePropertyOperation); remove(address); } /** * AS7-1200 test case for xa datasource persistence to xml * * @throws Exception */ @Test public void testMarshallUnmarshallXaDs() throws Exception { final String dsName = "XaDsName2"; final String jndiDsName = "XaJndiDsName2"; final ModelNode address = new ModelNode(); address.add("subsystem", "datasources"); address.add("xa-data-source", dsName); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(address); operation.get("name").set(dsName); operation.get("jndi-name").set("java:jboss/datasources/" + jndiDsName); operation.get("enabled").set(false); operation.get("driver-name").set("h2"); operation.get("pool-name").set(dsName + "_Pool"); operation.get("user-name").set("sa"); operation.get("password").set("sa"); executeOperation(operation); final ModelNode xaDatasourcePropertiesAddress = address.clone(); xaDatasourcePropertiesAddress.add("xa-datasource-properties", "URL"); xaDatasourcePropertiesAddress.protect(); final ModelNode xaDatasourcePropertyOperation = new ModelNode(); xaDatasourcePropertyOperation.get(OP).set("add"); xaDatasourcePropertyOperation.get(OP_ADDR).set(xaDatasourcePropertiesAddress); xaDatasourcePropertyOperation.get("value").set("jdbc:h2:mem:test"); executeOperation(xaDatasourcePropertyOperation); final ModelNode operation2 = new ModelNode(); operation2.get(OP).set("write-attribute"); operation2.get("name").set("enabled"); operation2.get("value").set(true); operation2.get(OP_ADDR).set(address); executeOperation(operation2); List<ModelNode> newList = marshalAndReparseDsResources("xa-data-source"); remove(address); Assert.assertNotNull("Reparsing failed:", newList); // remove from xml too marshalAndReparseDsResources("xa-data-source"); Assert.assertNotNull(findNodeWithProperty(newList, "jndi-name", "java:jboss/datasources/" + jndiDsName)); } @Test public void testReadInstalledDrivers() throws Exception { final ModelNode address = new ModelNode(); address.add("subsystem", "datasources"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("installed-drivers-list"); operation.get(OP_ADDR).set(address); final ModelNode result = executeOperation(operation); final ModelNode result2 = result.get(0); Assert.assertNotNull("There are no installed JDBC drivers", result2); Assert.assertTrue("Name of JDBC driver is udefined", result2.hasDefined("driver-name")); if (!result2.hasDefined("deployment-name")) {//deployed drivers haven't these attributes Assert.assertTrue("Module name of JDBC driver is udefined", result2.hasDefined("driver-module-name")); Assert.assertTrue("Module slot of JDBC driver is udefined", result2.hasDefined("module-slot")); } } @Test public void testReadJdbcDriver() throws Exception { String h2DriverName = "h2backup"; final ModelNode addrAddH2DriverAddr = new ModelNode(); addrAddH2DriverAddr.add("subsystem", "datasources").add("jdbc-driver", h2DriverName); final ModelNode addH2DriverOp = new ModelNode(); addH2DriverOp.get(OP).set("add"); addH2DriverOp.get(OP_ADDR).set(addrAddH2DriverAddr); addH2DriverOp.get("driver-name").set(h2DriverName); addH2DriverOp.get("driver-module-name").set("com.h2database.h2"); executeOperation(addH2DriverOp); try { final ModelNode address = new ModelNode(); address.add("subsystem", "datasources"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("get-installed-driver"); operation.get(OP_ADDR).set(address); operation.get("driver-name").set(h2DriverName); final ModelNode result = executeOperation(operation).get(0); Assert.assertEquals(h2DriverName, result.get("driver-name").asString()); Assert.assertEquals("com.h2database.h2", result.get("driver-module-name").asString()); Assert.assertEquals("", result.get("driver-xa-datasource-class-name").asString()); } finally { remove(addrAddH2DriverAddr); } } /** * AS7-1203 test for missing xa-datasource properties * * @throws Exception */ @Test public void testAddXaDsWithProperties() throws Exception { final String xaDs = "MyNewXaDs"; final String xaDsJndi = "java:jboss/xa-datasources/" + xaDs; final ModelNode address = new ModelNode(); address.add("subsystem", "datasources"); address.add("xa-data-source", xaDs); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(address); operation.get("name").set(xaDs); operation.get("jndi-name").set(xaDsJndi); operation.get("enabled").set(false); operation.get("driver-name").set("h2"); operation.get("xa-datasource-class").set("org.jboss.as.connector.subsystems.datasources.ModifiableXaDataSource"); operation.get("pool-name").set(xaDs + "_Pool"); operation.get("user-name").set("sa"); operation.get("password").set("sa"); executeOperation(operation); final ModelNode xaDatasourcePropertiesAddress = address.clone(); xaDatasourcePropertiesAddress.add("xa-datasource-properties", "URL"); xaDatasourcePropertiesAddress.protect(); final ModelNode xaDatasourcePropertyOperation = new ModelNode(); xaDatasourcePropertyOperation.get(OP).set("add"); xaDatasourcePropertyOperation.get(OP_ADDR).set(xaDatasourcePropertiesAddress); xaDatasourcePropertyOperation.get("value").set("jdbc:h2:mem:test"); executeOperation(xaDatasourcePropertyOperation); final ModelNode operation2 = new ModelNode(); operation2.get(OP).set("write-attribute"); operation2.get("name").set("enabled"); operation2.get("value").set(true); operation2.get(OP_ADDR).set(address); executeOperation(operation2); List<ModelNode> newList = marshalAndReparseDsResources("xa-data-source"); remove(address); Assert.assertNotNull("Reparsing failed:", newList); Assert.assertNotNull(findNodeWithProperty(newList, "jndi-name", xaDsJndi)); } /** * AS7-2720 tests for parsing particular datasource in standalone mode * * @throws Exception */ @Test public void testAddComplexDsUsername() throws Exception { testAddComplexDs(ConnectionSecurityType.USER_PASSWORD); } @Test public void testAddComplexDsElytron() throws Exception { testAddComplexDs(ConnectionSecurityType.ELYTRON); } @Test public void testAddComplexDsElytronAuthenticationContext() throws Exception { testAddComplexDs(ConnectionSecurityType.ELYTRON_AUTHENTICATION_CONTEXT); } @Test public void testAddComplexDsSecurityDomain() throws Exception { testAddComplexDs(ConnectionSecurityType.SECURITY_DOMAIN); } private void testAddComplexDs(ConnectionSecurityType connectionSecurityType) throws Exception { final String complexDs; switch(connectionSecurityType) { case ELYTRON: complexDs = "complexDsElytronWithOutAuthCtx"; break; case ELYTRON_AUTHENTICATION_CONTEXT: complexDs = "complexDsElytronWithAuthCtx"; break; case SECURITY_DOMAIN: complexDs = "complexDs"; break; case USER_PASSWORD: complexDs = "complexDsWithUserName"; break; default: throw new InvalidParameterException("Unsupported connection security type for Data Sources: " + connectionSecurityType); } final String complexDsJndi = "java:jboss/datasources/" + complexDs; final ModelNode address = new ModelNode(); address.add("subsystem", "datasources"); address.add("data-source", complexDs); address.protect(); Properties params = nonXaDsProperties(complexDsJndi, connectionSecurityType); final ModelNode operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(address); operation.get("enabled").set(false); setOperationParams(operation, params); addExtensionProperties(operation); executeOperation(operation); final ModelNode datasourcePropertiesAddress = address.clone(); datasourcePropertiesAddress.add("connection-properties", "char.encoding"); datasourcePropertiesAddress.protect(); final ModelNode datasourcePropertyOperation = new ModelNode(); datasourcePropertyOperation.get(OP).set("add"); datasourcePropertyOperation.get(OP_ADDR).set(datasourcePropertiesAddress); datasourcePropertyOperation.get("value").set("UTF-8"); executeOperation(datasourcePropertyOperation); List<ModelNode> newList = marshalAndReparseDsResources("data-source"); remove(address); Assert.assertNotNull("Reparsing failed:", newList); ModelNode rightChild = findNodeWithProperty(newList, "jndi-name", complexDsJndi); Assert.assertTrue("node:" + rightChild.asString() + ";\nparams" + params, checkModelParams(rightChild, params)); Assert.assertEquals(rightChild.asString(), "Property2", rightChild.get("valid-connection-checker-properties", "name").asString()); Assert.assertEquals(rightChild.asString(), "Property4", rightChild.get("exception-sorter-properties", "name").asString()); Assert.assertEquals(rightChild.asString(), "Property3", rightChild.get("stale-connection-checker-properties", "name").asString()); Assert.assertEquals(rightChild.asString(), "Property1", rightChild.get("reauth-plugin-properties", "name").asString()); Assert.assertNotNull("connection-properties not propagated ", findNodeWithProperty(newList, "value", "UTF-8")); } /** * AS7-2720 tests for parsing particular XA-datasource in standalone mode * * @throws Exception */ @Test public void testAddComplexXaDsUsername() throws Exception { testAddComplexXaDs(ConnectionSecurityType.USER_PASSWORD); } @Test public void testAddComplexXaDsElytron() throws Exception { testAddComplexXaDs(ConnectionSecurityType.ELYTRON); } @Test public void testAddComplexXaDsElytronAuthenticationContext() throws Exception { testAddComplexXaDs(ConnectionSecurityType.ELYTRON_AUTHENTICATION_CONTEXT); } @Test public void testAddComplexXaDsComplexDs() throws Exception { testAddComplexXaDs(ConnectionSecurityType.SECURITY_DOMAIN); } private void testAddComplexXaDs(ConnectionSecurityType connectionSecurityType) throws Exception { final String complexXaDs; switch (connectionSecurityType) { case ELYTRON: complexXaDs = "complexXaDsWithElytron"; break; case ELYTRON_AUTHENTICATION_CONTEXT: complexXaDs = "complexXaDsWithElytronCtxt"; break; case SECURITY_DOMAIN: complexXaDs = "complexXaDs"; break; case USER_PASSWORD: complexXaDs = "complexXaDsWithUserName"; break; default: throw new InvalidParameterException("Unsupported connection security type in data sources: " + connectionSecurityType); } final String complexXaDsJndi = "java:jboss/xa-datasources/" + complexXaDs; final ModelNode address = new ModelNode(); address.add("subsystem", "datasources"); address.add("xa-data-source", complexXaDs); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(address); operation.get("enabled").set(false); Properties params = xaDsProperties(complexXaDsJndi, connectionSecurityType); setOperationParams(operation, params); addExtensionProperties(operation); operation.get("recovery-plugin-properties", "name").set("Property5"); operation.get("recovery-plugin-properties", "name1").set("Property6"); executeOperation(operation); final ModelNode xaDatasourcePropertiesAddress = address.clone(); xaDatasourcePropertiesAddress.add("xa-datasource-properties", "URL"); xaDatasourcePropertiesAddress.protect(); final ModelNode xaDatasourcePropertyOperation = new ModelNode(); xaDatasourcePropertyOperation.get(OP).set("add"); xaDatasourcePropertyOperation.get(OP_ADDR).set(xaDatasourcePropertiesAddress); xaDatasourcePropertyOperation.get("value").set("jdbc:h2:mem:test"); executeOperation(xaDatasourcePropertyOperation); List<ModelNode> newList = marshalAndReparseDsResources("xa-data-source"); remove(address); Assert.assertNotNull("Reparsing failed:", newList); ModelNode rightChild = findNodeWithProperty(newList, "jndi-name", complexXaDsJndi); Assert.assertTrue("node:" + rightChild.asString() + ";\nparams" + params, checkModelParams(rightChild, params)); Assert.assertEquals(rightChild.asString(), "Property2", rightChild.get("valid-connection-checker-properties", "name").asString()); Assert.assertEquals(rightChild.asString(), "Property4", rightChild.get("exception-sorter-properties", "name").asString()); Assert.assertEquals(rightChild.asString(), "Property3", rightChild.get("stale-connection-checker-properties", "name").asString()); Assert.assertEquals(rightChild.asString(), "Property1", rightChild.get("reauth-plugin-properties", "name").asString()); Assert.assertEquals(rightChild.asString(), "Property5", rightChild.get("recovery-plugin-properties", "name").asString()); Assert.assertEquals(rightChild.asString(), "Property6", rightChild.get("recovery-plugin-properties", "name1").asString()); Assert.assertNotNull("xa-datasource-properties not propagated ", findNodeWithProperty(newList, "value", "jdbc:h2:mem:test")); } private List<ModelNode> marshalAndReparseDsResources(String childType) throws Exception { DataSourcesExtension.DataSourceSubsystemParser parser = new DataSourcesExtension.DataSourceSubsystemParser(); return xmlToModelOperations(modelToXml("datasources", childType, parser), Namespace.CURRENT.getUriString(), parser); } }
24,818
39.686885
167
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/mgmt/datasource/TestDriver.java
/* * Copyright (c) 2022 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of Apache License v2.0 which * accompanies this distribution. * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * 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.smoke.mgmt.datasource; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Properties; import java.util.logging.Logger; /** * Test JDBC driver */ public class TestDriver implements Driver { /** * {@inheritDoc} */ public Connection connect(String url, Properties info) throws SQLException { return null; } /** * {@inheritDoc} */ public boolean acceptsURL(String url) throws SQLException { return true; } /** * {@inheritDoc} */ public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { Driver driver = DriverManager.getDriver(url); return driver.getPropertyInfo(url, info); } /** * {@inheritDoc} */ public int getMajorVersion() { return 1; } /** * {@inheritDoc} */ public int getMinorVersion() { return 0; } /** * {@inheritDoc} */ public boolean jdbcCompliant() { return false; } /** * {@inheritDoc} */ public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); } }
2,053
24.04878
98
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/mgmt/datasource/DataSourceResourcesUnitTestCase.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.smoke.mgmt.datasource; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.integration.management.jca.DsMgmtTestBase; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Datasource resources unit test. * * @author <a href="mailto:stefano.maestri@redhat.com">Stefano Maestri</a> * @author <a href="mailto:jeff.zhang@jboss.org">Jeff Zhang</a> * @author <a href="mailto:vrastsel@redhat.com">Vladimir Rastseluev</a> */ @RunWith(Arquillian.class) @RunAsClient public class DataSourceResourcesUnitTestCase extends DsMgmtTestBase { @Test public void testReadChildrenResources() throws Exception { final ModelNode address = new ModelNode(); address.add("subsystem", "datasources"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("read-children-resources"); operation.get("child-type").set("data-source"); operation.get(OP_ADDR).set(address); final ModelNode result = executeOperation(operation); final Map<String, ModelNode> children = getChildren(result); Assert.assertFalse(children.isEmpty()); for (final Entry<String, ModelNode> child : children.entrySet()) { Assert.assertNotNull("Default datasource not found", child.getKey()); Assert.assertTrue("Default datasource have no connection URL", child.getValue().hasDefined("connection-url")); Assert.assertTrue("Default datasource have no JNDI name", child.getValue().hasDefined("jndi-name")); Assert.assertTrue("Default datasource have no driver", child.getValue().hasDefined("driver-name")); } } @Test public void testReadResourceResources() throws Exception { final ModelNode address = new ModelNode(); address.add("subsystem", "datasources"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("read-resource-description"); operation.get(OP_ADDR).set(address); final ModelNode result = executeOperation(operation); final Map<String, ModelNode> children = getChildren( result.get("attributes").get("installed-drivers").get("value-type")); Assert.assertFalse(children.isEmpty()); HashSet<String> keys = new HashSet<String>(); for (final Entry<String, ModelNode> child : children.entrySet()) { Assert.assertNotNull("Default driver description have no attributes", child.getKey()); keys.add(child.getKey()); } Assert.assertTrue("Default driver description have no xa-datasource-class attribute", keys.contains("driver-xa-datasource-class-name")); Assert.assertTrue("Default driver description have no module-slot attribute", keys.contains("module-slot")); Assert.assertTrue("Default driver description have no driver-name attribute", keys.contains("driver-name")); } }
4,374
42.316832
144
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/mgmt/datasource/AddDataSourceOperationsUnitTestCase.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.smoke.mgmt.datasource; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import java.sql.Driver; 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.connector.subsystems.datasources.DataSourcesExtension; import org.jboss.as.connector.subsystems.datasources.Namespace; import org.jboss.as.test.integration.management.jca.DsMgmtTestBase; import org.jboss.dmr.ModelNode; 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; /** * Datasource operation unit test. * @author <a href="mailto:stefano.maestri@redhat.com">Stefano Maestri</a> * @author <a href="mailto:jeff.zhang@jboss.org">Jeff Zhang</a> * @author <a href="mailto:vrastsel@redhat.com">Vladimir Rastseluev</a> */ @RunWith(Arquillian.class) @RunAsClient public class AddDataSourceOperationsUnitTestCase extends DsMgmtTestBase{ private static final String JDBC_DRIVER_NAME = "test-jdbc.jar"; @Deployment(testable = false) public static Archive<?> getDeployment() { return ShrinkWrap.create(JavaArchive.class, JDBC_DRIVER_NAME) .addClass(TestDriver.class) .addAsServiceProvider(Driver.class, TestDriver.class); } @Test public void testAddDsAndTestConnection() throws Exception { final ModelNode address = new ModelNode(); address.add("subsystem", "datasources"); address.add("data-source", "MySqlDs_Pool"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(address); operation.get("jndi-name").set("java:jboss/datasources/MySqlDs"); operation.get("driver-name").set(JDBC_DRIVER_NAME); operation.get("connection-url").set("dont_care"); operation.get("user-name").set("sa"); operation.get("password").set("sa"); executeOperation(operation); final ModelNode operation0 = new ModelNode(); operation0.get(OP).set("take-snapshot"); executeOperation(operation0); List<ModelNode> newList = marshalAndReparseDsResources("data-source"); remove(address); Assert.assertNotNull("Reparsing failed:",newList); Assert.assertNotNull(findNodeWithProperty(newList,"jndi-name","java:jboss/datasources/MySqlDs")); } private List<ModelNode> marshalAndReparseDsResources(String childType) throws Exception { DataSourcesExtension.DataSourceSubsystemParser parser = new DataSourcesExtension.DataSourceSubsystemParser(); return xmlToModelOperations(modelToXml("datasources", childType, parser), Namespace.CURRENT.getUriString(), parser); } }
4,103
38.085714
124
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/socketbindings/SocketBindingBoundPortsTestCase.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.smoke.socketbindings; 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.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.*; /** * Test if the /socket-binding=* runtime attributes shows the open ports as bound. * * @author Claudio Miranda */ @RunWith(Arquillian.class) @RunAsClient public class SocketBindingBoundPortsTestCase { private static final String BOUND ="bound"; private static final String BOUND_PORT ="bound-port"; private static final String STANDARD_SOCKETS = "standard-sockets"; @ContainerResource private ManagementClient managementClient; @Test public void testHttpBoundSocket() throws IOException { final ModelNode address = new ModelNode(); address.add(SOCKET_BINDING_GROUP, "standard-sockets").add(SOCKET_BINDING, "http"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set(READ_RESOURCE_OPERATION); operation.get(INCLUDE_RUNTIME).set(true); operation.get(OP_ADDR).set(address); ModelNode response = execute(operation); ModelNode result = response.get(RESULT); Assert.assertTrue("http socket binding is not set as bound.", result.get(BOUND).asBoolean()); Assert.assertEquals(8080, result.get(BOUND_PORT).asInt()); } @Test public void testHttpsBoundSocket() throws IOException { final ModelNode address = new ModelNode(); address.add(SOCKET_BINDING_GROUP, STANDARD_SOCKETS).add(SOCKET_BINDING, "https"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set(READ_RESOURCE_OPERATION); operation.get(INCLUDE_RUNTIME).set(true); operation.get(OP_ADDR).set(address); ModelNode response = execute(operation); ModelNode result = response.get(RESULT); Assert.assertTrue("https socket binding is not set as bound.", result.get(BOUND).asBoolean()); Assert.assertEquals(8443, result.get(BOUND_PORT).asInt()); } @Test public void testIiopBoundSocket() throws IOException { final ModelNode address = new ModelNode(); address.add(SOCKET_BINDING_GROUP, "standard-sockets").add(SOCKET_BINDING, "iiop"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set(READ_RESOURCE_OPERATION); operation.get(INCLUDE_RUNTIME).set(true); operation.get(OP_ADDR).set(address); ModelNode response = execute(operation); ModelNode result = response.get(RESULT); Assert.assertTrue("iiop socket binding is not set as bound.", result.get(BOUND).asBoolean()); Assert.assertEquals(3528, result.get(BOUND_PORT).asInt()); } /** * Executes the operation and returns the result if successful. Else throws an exception */ private ModelNode execute(final ModelNode operation) throws IOException { final ModelNode result = managementClient.getControllerClient().execute(operation); if (result.hasDefined(ClientConstants.OUTCOME) && ClientConstants.SUCCESS.equals( result.get(ClientConstants.OUTCOME).asString())) { return result; } else if (result.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) { final String failureDesc = result.get(ClientConstants.FAILURE_DESCRIPTION).toString(); throw new RuntimeException(failureDesc); } else { throw new RuntimeException("Operation not successful; outcome = " + result.get(ClientConstants.OUTCOME)); } } }
5,043
42.111111
117
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/RaServlet.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.smoke.deployment; import java.io.IOException; import jakarta.annotation.Resource; 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.smoke.deployment.rar.MultipleAdminObject1; import org.jboss.as.test.smoke.deployment.rar.MultipleConnectionFactory1; /** * User: Jaikiran Pai */ @WebServlet(name = "RaServlet", urlPatterns = RaServlet.URL_PATTERN) public class RaServlet extends HttpServlet { public static final String SUCCESS = "SUCCESS"; public static final String URL_PATTERN = "/raservlet"; @Resource(name = "java:jboss/name1") private MultipleConnectionFactory1 connectionFactory1; @Resource(name = "java:jboss/Name3") private MultipleAdminObject1 adminObject1; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuffer sb = new StringBuffer(); if (connectionFactory1 == null) sb.append("CF1 is null."); if (adminObject1 == null) sb.append("AO1 is null."); resp.getOutputStream().print((sb.length() > 0) ? sb.toString() : SUCCESS); } }
2,344
37.442623
113
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleConnection1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; /** * MultipleConnection1 * * @version $Revision: $ */ public interface MultipleConnection1 { /** * test * * @param s s * @return String */ String test(String s); /** * Close */ void close(); }
1,331
29.976744
70
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/Multiple2ManagedConnectionMetaData.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import org.jboss.logging.Logger; import jakarta.resource.ResourceException; import jakarta.resource.spi.ManagedConnectionMetaData; /** * Multiple2ManagedConnectionMetaData * * @version $Revision: $ */ public class Multiple2ManagedConnectionMetaData implements ManagedConnectionMetaData { /** * The logger */ private static Logger log = Logger.getLogger("Multiple2ManagedConnectionMetaData"); /** * Default constructor */ public Multiple2ManagedConnectionMetaData() { } /** * Returns Product name of the underlying EIS instance connected through the ManagedConnection. * * @return Product name of the EIS instance * @throws ResourceException Thrown if an error occurs */ @Override public String getEISProductName() throws ResourceException { log.trace("getEISProductName()"); return null; //TODO } /** * Returns Product version of the underlying EIS instance connected through the ManagedConnection. * * @return Product version of the EIS instance * @throws ResourceException Thrown if an error occurs */ @Override public String getEISProductVersion() throws ResourceException { log.trace("getEISProductVersion()"); return null; //TODO } /** * Returns maximum limit on number of active concurrent connections * * @return Maximum limit for number of active concurrent connections * @throws ResourceException Thrown if an error occurs */ @Override public int getMaxConnections() throws ResourceException { log.trace("getMaxConnections()"); return 0; //TODO } /** * Returns name of the user associated with the ManagedConnection instance * * @return Name of the user * @throws ResourceException Thrown if an error occurs */ @Override public String getUserName() throws ResourceException { log.trace("getUserName()"); return null; //TODO } }
3,099
31.291667
102
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleAdminObject2Impl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import java.io.Serializable; import javax.naming.NamingException; import javax.naming.Reference; import jakarta.resource.Referenceable; import jakarta.resource.spi.ResourceAdapter; import jakarta.resource.spi.ResourceAdapterAssociation; /** * MultipleAdminObject2Impl * * @version $Revision: $ */ public class MultipleAdminObject2Impl implements MultipleAdminObject2, ResourceAdapterAssociation, Referenceable, Serializable { /** * Serial version uid */ private static final long serialVersionUID = 1L; /** * The resource adapter */ private ResourceAdapter ra; /** * Reference */ private Reference reference; /** * Name */ private String name; /** * Default constructor */ public MultipleAdminObject2Impl() { } /** * Set name * * @param name The value */ public void setName(String name) { this.name = name; } /** * Get name * * @return The value */ public String getName() { return name; } /** * Get the resource adapter * * @return The handle */ public ResourceAdapter getResourceAdapter() { return ra; } /** * Set the resource adapter * * @param ra The handle */ public void setResourceAdapter(ResourceAdapter ra) { this.ra = ra; } /** * Get the Reference instance. * * @return Reference instance * @throws NamingException Thrown if a reference can't be obtained */ @Override public Reference getReference() throws NamingException { return reference; } /** * Set the Reference instance. * * @param reference A Reference instance */ @Override public void setReference(Reference reference) { this.reference = reference; } /** * Returns a hash code value for the object. * * @return A hash code value for this object. */ @Override public int hashCode() { int result = 17; if (name != null) { result += 31 * result + 7 * name.hashCode(); } else { result += 31 * result + 7; } return result; } /** * Indicates whether some other object is equal to this one. * * @param other The reference object with which to compare. * @return true if this object is the same as the obj argument, false otherwise. */ @Override public boolean equals(Object other) { if (other == null) { return false; } if (other == this) { return true; } if (!(other instanceof MultipleAdminObject2Impl)) { return false; } MultipleAdminObject2Impl obj = (MultipleAdminObject2Impl) other; boolean result = true; if (result) { if (name == null) { result = obj.getName() == null; } else { result = name.equals(obj.getName()); } } return result; } }
4,045
25.103226
111
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleConnectionFactory2Impl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import org.jboss.logging.Logger; import javax.naming.NamingException; import javax.naming.Reference; import jakarta.resource.ResourceException; import jakarta.resource.spi.ConnectionManager; /** * MultipleConnectionFactory2Impl * * @version $Revision: $ */ public class MultipleConnectionFactory2Impl implements MultipleConnectionFactory2 { /** * The serial version UID */ private static final long serialVersionUID = 1L; /** * The logger */ private static Logger log = Logger.getLogger("MultipleConnectionFactory2Impl"); /** * Reference */ private Reference reference; /** * ManagedConnectionFactory */ private MultipleManagedConnectionFactory2 mcf; /** * ConnectionManager */ private ConnectionManager connectionManager; /** * Default constructor */ public MultipleConnectionFactory2Impl() { } /** * Default constructor * * @param mcf ManagedConnectionFactory * @param cxManager ConnectionManager */ public MultipleConnectionFactory2Impl(MultipleManagedConnectionFactory2 mcf, ConnectionManager cxManager) { this.mcf = mcf; this.connectionManager = cxManager; } /** * Get connection from factory * * @return MultipleConnection2 instance * @throws ResourceException Thrown if a connection can't be obtained */ @Override public MultipleConnection2 getConnection() throws ResourceException { log.trace("getConnection()"); return (MultipleConnection2) connectionManager.allocateConnection(mcf, null); } /** * Get the Reference instance. * * @return Reference instance * @throws NamingException Thrown if a reference can't be obtained */ @Override public Reference getReference() throws NamingException { log.trace("getReference()"); return reference; } /** * Set the Reference instance. * * @param reference A Reference instance */ @Override public void setReference(Reference reference) { log.trace("setReference()"); this.reference = reference; } }
3,284
27.318966
111
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleManagedConnection2.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import org.jboss.logging.Logger; import jakarta.resource.NotSupportedException; import jakarta.resource.ResourceException; import jakarta.resource.spi.ConnectionEvent; import jakarta.resource.spi.ConnectionEventListener; import jakarta.resource.spi.ConnectionRequestInfo; import jakarta.resource.spi.LocalTransaction; import jakarta.resource.spi.ManagedConnection; import jakarta.resource.spi.ManagedConnectionMetaData; import javax.security.auth.Subject; import javax.transaction.xa.XAResource; /** * MultipleManagedConnection2 * * @version $Revision: $ */ public class MultipleManagedConnection2 implements ManagedConnection { /** * The logger */ private static Logger log = Logger.getLogger("MultipleManagedConnection2"); /** * The logwriter */ private PrintWriter logwriter; /** * ManagedConnectionFactory */ private MultipleManagedConnectionFactory2 mcf; /** * Listeners */ private List<ConnectionEventListener> listeners; /** * Connection */ private Object connection; /** * Default constructor * * @param mcf mcf */ public MultipleManagedConnection2(MultipleManagedConnectionFactory2 mcf) { this.mcf = mcf; this.logwriter = null; this.listeners = new ArrayList<ConnectionEventListener>(1); this.connection = null; } /** * Creates a new connection handle for the underlying physical connection * represented by the ManagedConnection instance. * * @param subject Security context as JAAS subject * @param cxRequestInfo ConnectionRequestInfo instance * @return generic Object instance representing the connection handle. * @throws ResourceException generic exception if operation fails */ public Object getConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException { log.trace("getConnection()"); connection = new MultipleConnection2Impl(this, mcf); return connection; } /** * Used by the container to change the association of an * application-level connection handle with a ManagedConneciton instance. * * @param connection Application-level connection handle * @throws ResourceException generic exception if operation fails */ public void associateConnection(Object connection) throws ResourceException { log.trace("associateConnection()"); } /** * Application server calls this method to force any cleanup on the ManagedConnection instance. * * @throws ResourceException generic exception if operation fails */ public void cleanup() throws ResourceException { log.trace("cleanup()"); } /** * Destroys the physical connection to the underlying resource manager. * * @throws ResourceException generic exception if operation fails */ public void destroy() throws ResourceException { log.trace("destroy()"); } /** * Adds a connection event listener to the ManagedConnection instance. * * @param listener A new ConnectionEventListener to be registered */ public void addConnectionEventListener(ConnectionEventListener listener) { log.trace("addConnectionEventListener()"); if (listener == null) { throw new IllegalArgumentException("Listener is null"); } listeners.add(listener); } /** * Removes an already registered connection event listener from the ManagedConnection instance. * * @param listener already registered connection event listener to be removed */ public void removeConnectionEventListener(ConnectionEventListener listener) { log.trace("removeConnectionEventListener()"); if (listener == null) { throw new IllegalArgumentException("Listener is null"); } listeners.remove(listener); } /** * Close handle * * @param handle The handle */ public void closeHandle(MultipleConnection2 handle) { ConnectionEvent event = new ConnectionEvent(this, ConnectionEvent.CONNECTION_CLOSED); event.setConnectionHandle(handle); for (ConnectionEventListener cel : listeners) { cel.connectionClosed(event); } } /** * Gets the log writer for this ManagedConnection instance. * * @return Character ourput stream associated with this Managed-Connection instance * @throws ResourceException generic exception if operation fails */ public PrintWriter getLogWriter() throws ResourceException { log.trace("getLogWriter()"); return logwriter; } /** * Sets the log writer for this ManagedConnection instance. * * @param out Character Output stream to be associated * @throws ResourceException generic exception if operation fails */ public void setLogWriter(PrintWriter out) throws ResourceException { log.trace("setLogWriter()"); logwriter = out; } /** * Returns an <code>jakarta.resource.spi.LocalTransaction</code> instance. * * @return LocalTransaction instance * @throws ResourceException generic exception if operation fails */ public LocalTransaction getLocalTransaction() throws ResourceException { throw new NotSupportedException("LocalTransaction not supported"); } /** * Returns an <code>javax.transaction.xa.XAresource</code> instance. * * @return XAResource instance * @throws ResourceException generic exception if operation fails */ public XAResource getXAResource() throws ResourceException { throw new NotSupportedException("GetXAResource not supported not supported"); } /** * Gets the metadata information for this connection's underlying EIS resource manager instance. * * @return ManagedConnectionMetaData instance * @throws ResourceException generic exception if operation fails */ public ManagedConnectionMetaData getMetaData() throws ResourceException { log.trace("getMetaData()"); return new Multiple2ManagedConnectionMetaData(); } }
7,400
32.794521
100
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleActivationSpec.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import jakarta.resource.spi.ActivationSpec; import jakarta.resource.spi.InvalidPropertyException; import jakarta.resource.spi.ResourceAdapter; import org.jboss.logging.Logger; /** * MultipleActivationSpec * * @version $Revision: $ */ public class MultipleActivationSpec implements ActivationSpec { /** * The logger */ private static Logger log = Logger.getLogger(MultipleActivationSpec.class); /** * The resource adapter */ private ResourceAdapter ra; /** * Default constructor */ public MultipleActivationSpec() { } /** * This method may be called by a deployment tool to validate the overall * activation configuration information provided by the endpoint deployer. * * @throws InvalidPropertyException indicates invalid onfiguration property settings. */ public void validate() throws InvalidPropertyException { log.trace("validate()"); } /** * Get the resource adapter * * @return The handle */ public ResourceAdapter getResourceAdapter() { log.trace("getResourceAdapter()"); return ra; } /** * Set the resource adapter * * @param ra The handle */ public void setResourceAdapter(ResourceAdapter ra) { log.trace("setResourceAdapter()"); this.ra = ra; } }
2,450
28.53012
89
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleConnectionFactory1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import java.io.Serializable; import jakarta.resource.Referenceable; import jakarta.resource.ResourceException; /** * MultipleConnectionFactory1 * * @version $Revision: $ */ public interface MultipleConnectionFactory1 extends Serializable, Referenceable { /** * Get connection from factory * * @return MultipleConnection1 instance * @throws ResourceException Thrown if a connection can't be obtained */ MultipleConnection1 getConnection() throws ResourceException; }
1,586
35.906977
81
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleConnection2.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; /** * MultipleConnection2 * * @version $Revision: $ */ public interface MultipleConnection2 { /** * test * * @param s s * @return String */ String test(String s); /** * Close */ void close(); }
1,331
29.976744
70
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleRaMetaData.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import jakarta.resource.cci.ResourceAdapterMetaData; /** * MultipleRaMetaData * * @version $Revision: $ */ public class MultipleRaMetaData implements ResourceAdapterMetaData { /** * Default constructor */ public MultipleRaMetaData() { } /** * Gets the version of the resource adapter. * * @return String representing version of the resource adapter */ @Override public String getAdapterVersion() { return null; //TODO } /** * Gets the name of the vendor that has provided the resource adapter. * * @return String representing name of the vendor */ @Override public String getAdapterVendorName() { return null; //TODO } /** * Gets a tool displayable name of the resource adapter. * * @return String representing the name of the resource adapter */ @Override public String getAdapterName() { return null; //TODO } /** * Gets a tool displayable short desription of the resource adapter. * * @return String describing the resource adapter */ @Override public String getAdapterShortDescription() { return null; //TODO } /** * Returns a string representation of the version * * @return String representing the supported version of the connector architecture */ @Override public String getSpecVersion() { return null; //TODO } /** * Returns an array of fully-qualified names of InteractionSpec * * @return Array of fully-qualified class names of InteractionSpec classes */ @Override public String[] getInteractionSpecsSupported() { return null; //TODO } /** * Returns true if the implementation class for the Interaction * * @return boolean Depending on method support */ @Override public boolean supportsExecuteWithInputAndOutputRecord() { return false; //TODO } /** * Returns true if the implementation class for the Interaction * * @return boolean Depending on method support */ @Override public boolean supportsExecuteWithInputRecordOnly() { return false; //TODO } /** * Returns true if the resource adapter implements the LocalTransaction * * @return true If resource adapter supports resource manager local transaction demarcation */ @Override public boolean supportsLocalTransactionDemarcation() { return false; //TODO } }
3,639
26.78626
95
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleManagedConnection1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import org.jboss.logging.Logger; import jakarta.resource.NotSupportedException; import jakarta.resource.ResourceException; import jakarta.resource.spi.ConnectionEvent; import jakarta.resource.spi.ConnectionEventListener; import jakarta.resource.spi.ConnectionRequestInfo; import jakarta.resource.spi.LocalTransaction; import jakarta.resource.spi.ManagedConnection; import jakarta.resource.spi.ManagedConnectionMetaData; import javax.security.auth.Subject; import javax.transaction.xa.XAResource; /** * MultipleManagedConnection1 * * @version $Revision: $ */ public class MultipleManagedConnection1 implements ManagedConnection { /** * The logger */ private static Logger log = Logger.getLogger("MultipleManagedConnection1"); /** * The logwriter */ private PrintWriter logwriter; /** * ManagedConnectionFactory */ private MultipleManagedConnectionFactory1 mcf; /** * Listeners */ private List<ConnectionEventListener> listeners; /** * Connection */ private Object connection; /** * Default constructor * * @param mcf mcf */ public MultipleManagedConnection1(MultipleManagedConnectionFactory1 mcf) { this.mcf = mcf; this.logwriter = null; this.listeners = new ArrayList<ConnectionEventListener>(1); this.connection = null; } /** * Creates a new connection handle for the underlying physical connection * represented by the ManagedConnection instance. * * @param subject Security context as JAAS subject * @param cxRequestInfo ConnectionRequestInfo instance * @return generic Object instance representing the connection handle. * @throws ResourceException generic exception if operation fails */ public Object getConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException { log.trace("getConnection()"); connection = new MultipleConnection1Impl(this, mcf); return connection; } /** * Used by the container to change the association of an * application-level connection handle with a ManagedConneciton instance. * * @param connection Application-level connection handle * @throws ResourceException generic exception if operation fails */ public void associateConnection(Object connection) throws ResourceException { log.trace("associateConnection()"); } /** * Application server calls this method to force any cleanup on the ManagedConnection instance. * * @throws ResourceException generic exception if operation fails */ public void cleanup() throws ResourceException{ log.trace("cleanup()"); } /** * Destroys the physical connection to the underlying resource manager. * * @throws ResourceException generic exception if operation fails */ public void destroy() throws ResourceException { log.trace("destroy()"); } /** * Adds a connection event listener to the ManagedConnection instance. * * @param listener A new ConnectionEventListener to be registered */ public void addConnectionEventListener(ConnectionEventListener listener) { log.trace("addConnectionEventListener()"); if (listener == null) { throw new IllegalArgumentException("Listener is null"); } listeners.add(listener); } /** * Removes an already registered connection event listener from the ManagedConnection instance. * * @param listener already registered connection event listener to be removed */ public void removeConnectionEventListener(ConnectionEventListener listener) { log.trace("removeConnectionEventListener()"); if (listener == null) { throw new IllegalArgumentException("Listener is null"); } listeners.remove(listener); } /** * Close handle * * @param handle The handle */ public void closeHandle(MultipleConnection1 handle) { ConnectionEvent event = new ConnectionEvent(this, ConnectionEvent.CONNECTION_CLOSED); event.setConnectionHandle(handle); for (ConnectionEventListener cel : listeners) { cel.connectionClosed(event); } } /** * Gets the log writer for this ManagedConnection instance. * * @return Character ourput stream associated with this Managed-Connection instance * @throws ResourceException generic exception if operation fails */ public PrintWriter getLogWriter() throws ResourceException { log.trace("getLogWriter()"); return logwriter; } /** * Sets the log writer for this ManagedConnection instance. * * @param out Character Output stream to be associated * @throws ResourceException generic exception if operation fails */ public void setLogWriter(PrintWriter out) throws ResourceException { log.trace("setLogWriter()"); logwriter = out; } /** * Returns an <code>jakarta.resource.spi.LocalTransaction</code> instance. * * @return LocalTransaction instance * @throws ResourceException generic exception if operation fails */ public LocalTransaction getLocalTransaction() throws ResourceException { throw new NotSupportedException("LocalTransaction not supported"); } /** * Returns an <code>javax.transaction.xa.XAresource</code> instance. * * @return XAResource instance * @throws ResourceException generic exception if operation fails */ public XAResource getXAResource() throws ResourceException { throw new NotSupportedException("GetXAResource not supported not supported"); } /** * Gets the metadata information for this connection's underlying EIS resource manager instance. * * @return ManagedConnectionMetaData instance * @throws ResourceException generic exception if operation fails */ public ManagedConnectionMetaData getMetaData() throws ResourceException { log.trace("getMetaData()"); return new MultipleManagedConnectionMetaData(); } }
7,398
32.785388
100
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleConnection2Impl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import org.jboss.logging.Logger; /** * MultipleConnection2Impl * * @version $Revision: $ */ public class MultipleConnection2Impl implements MultipleConnection2 { /** * The logger */ private static Logger log = Logger.getLogger("MultipleConnection2Impl"); /** * ManagedConnection */ private MultipleManagedConnection2 mc; /** * ManagedConnectionFactory */ private MultipleManagedConnectionFactory2 mcf; /** * Default constructor * * @param mc MultipleManagedConnection2 * @param mcf MultipleManagedConnectionFactory2 */ public MultipleConnection2Impl(MultipleManagedConnection2 mc, MultipleManagedConnectionFactory2 mcf) { this.mc = mc; this.mcf = mcf; } /** * Call test * * @param s String * @return String */ public String test(String s) { log.trace("test()"); return null; } /** * Close */ public void close() { mc.closeHandle(this); } }
2,124
26.24359
106
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleAdminObject1Impl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import java.io.Serializable; import javax.naming.NamingException; import javax.naming.Reference; import jakarta.resource.Referenceable; import jakarta.resource.spi.ResourceAdapter; import jakarta.resource.spi.ResourceAdapterAssociation; /** * MultipleAdminObject1Impl * * @version $Revision: $ */ public class MultipleAdminObject1Impl implements MultipleAdminObject1, ResourceAdapterAssociation, Referenceable, Serializable { /** * Serial version uid */ private static final long serialVersionUID = 1L; /** * The resource adapter */ private ResourceAdapter ra; /** * Reference */ private Reference reference; /** * Name */ private String name; /** * Default constructor */ public MultipleAdminObject1Impl() { } /** * Set name * * @param name The value */ public void setName(String name) { this.name = name; } /** * Get name * * @return The value */ public String getName() { return name; } /** * Get the resource adapter * * @return The handle */ public ResourceAdapter getResourceAdapter() { return ra; } /** * Set the resource adapter * * @param ra The handle */ public void setResourceAdapter(ResourceAdapter ra) { this.ra = ra; } /** * Get the Reference instance. * * @return Reference instance * @throws NamingException Thrown if a reference can't be obtained */ @Override public Reference getReference() throws NamingException { return reference; } /** * Set the Reference instance. * * @param reference A Reference instance */ @Override public void setReference(Reference reference) { this.reference = reference; } /** * Returns a hash code value for the object. * * @return A hash code value for this object. */ @Override public int hashCode() { int result = 17; if (name != null) { result += 31 * result + 7 * name.hashCode(); } else { result += 31 * result + 7; } return result; } /** * Indicates whether some other object is equal to this one. * * @param other The reference object with which to compare. * @return true if this object is the same as the obj argument, false otherwise. */ @Override public boolean equals(Object other) { if (other == null) { return false; } if (other == this) { return true; } if (!(other instanceof MultipleAdminObject1Impl)) { return false; } MultipleAdminObject1Impl obj = (MultipleAdminObject1Impl) other; boolean result = true; if (result) { if (name == null) { result = obj.getName() == null; } else { result = name.equals(obj.getName()); } } return result; } }
4,045
25.103226
111
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleResourceAdapter2.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import org.jboss.logging.Logger; 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 javax.transaction.xa.XAResource; /** * MultipleResourceAdapter * * @version $Revision: $ */ public class MultipleResourceAdapter2 implements ResourceAdapter { /** * The logger */ private static Logger log = Logger.getLogger("MultipleResourceAdapter2"); /** * Name */ private String name; /** * Default constructor */ public MultipleResourceAdapter2() { } /** * Set name * * @param name The value */ public void setName(String name) { this.name = name; } /** * Get name * * @return The value */ public String getName() { return name; } /** * This is called during the activation of a message endpoint. * * @param endpointFactory A message endpoint factory instance. * @param spec An activation spec JavaBean instance. * @throws ResourceException generic exception */ public void endpointActivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) throws ResourceException { log.trace("endpointActivation()"); } /** * This is called when a message endpoint is deactivated. * * @param endpointFactory A message endpoint factory instance. * @param spec An activation spec JavaBean instance. */ public void endpointDeactivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) { log.trace("endpointDeactivation()"); } /** * This is called when a resource adapter instance is bootstrapped. * * @param ctx A bootstrap context containing references * @throws ResourceAdapterInternalException indicates bootstrap failure. */ public void start(BootstrapContext ctx) throws ResourceAdapterInternalException { log.trace("start()"); } /** * This is called when a resource adapter instance is undeployed or * during application server shutdown. */ public void stop() { log.trace("stop()"); } /** * This method is called by the application server during crash recovery. * * @param specs An array of ActivationSpec JavaBeans * @return An array of XAResource objects * @throws ResourceException generic exception */ public XAResource[] getXAResources(ActivationSpec[] specs) throws ResourceException { log.trace("getXAResources()"); return null; } /** * Returns a hash code value for the object. * * @return A hash code value for this object. */ @Override public int hashCode() { int result = 17; if (name != null) { result += 31 * result + 7 * name.hashCode(); } else { result += 31 * result + 7; } return result; } /** * Indicates whether some other object is equal to this one. * * @param other The reference object with which to compare. * @return true if this object is the same as the obj argument, false otherwise. */ @Override public boolean equals(Object other) { if (other == null) { return false; } if (other == this) { return true; } if (!(other instanceof MultipleResourceAdapter2)) { return false; } MultipleResourceAdapter2 obj = (MultipleResourceAdapter2) other; boolean result = true; if (result) { if (name == null) { result = obj.getName() == null; } else { result = name.equals(obj.getName()); } } return result; } }
5,052
30
111
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleAdminObject2.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import java.io.Serializable; import jakarta.resource.Referenceable; /** * MultipleAdminObject2 * * @version $Revision: $ */ public interface MultipleAdminObject2 extends Referenceable, Serializable { /** * Set name * * @param name The value */ void setName(String name); /** * Get name * * @return The value */ String getName(); }
1,477
28.56
75
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleConnectionFactory1Impl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import org.jboss.logging.Logger; import javax.naming.NamingException; import javax.naming.Reference; import jakarta.resource.ResourceException; import jakarta.resource.spi.ConnectionManager; /** * MultipleConnectionFactory1Impl * * @version $Revision: $ */ public class MultipleConnectionFactory1Impl implements MultipleConnectionFactory1 { /** * The serial version UID */ private static final long serialVersionUID = 1L; /** * The logger */ private static Logger log = Logger.getLogger("MultipleConnectionFactory1Impl"); /** * Reference */ private Reference reference; /** * ManagedConnectionFactory */ private MultipleManagedConnectionFactory1 mcf; /** * ConnectionManager */ private ConnectionManager connectionManager; /** * Default constructor */ public MultipleConnectionFactory1Impl() { } /** * Default constructor * * @param mcf ManagedConnectionFactory * @param cxManager ConnectionManager */ public MultipleConnectionFactory1Impl(MultipleManagedConnectionFactory1 mcf, ConnectionManager cxManager) { this.mcf = mcf; this.connectionManager = cxManager; } /** * Get connection from factory * * @return MultipleConnection1 instance * @throws ResourceException Thrown if a connection can't be obtained */ @Override public MultipleConnection1 getConnection() throws ResourceException { log.trace("getConnection()"); return (MultipleConnection1) connectionManager.allocateConnection(mcf, null); } /** * Get the Reference instance. * * @return Reference instance * @throws NamingException Thrown if a reference can't be obtained */ @Override public Reference getReference() throws NamingException { log.trace("getReference()"); return reference; } /** * Set the Reference instance. * * @param reference A Reference instance */ @Override public void setReference(Reference reference) { log.trace("setReference()"); this.reference = reference; } }
3,284
27.318966
111
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleManagedConnectionFactory2.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import java.io.PrintWriter; import java.util.Iterator; import java.util.Set; import org.jboss.logging.Logger; import jakarta.resource.ResourceException; import jakarta.resource.spi.ConnectionManager; import jakarta.resource.spi.ConnectionRequestInfo; import jakarta.resource.spi.ManagedConnection; import jakarta.resource.spi.ManagedConnectionFactory; import jakarta.resource.spi.ResourceAdapter; import jakarta.resource.spi.ResourceAdapterAssociation; import javax.security.auth.Subject; /** * MultipleManagedConnectionFactory2 * * @version $Revision: $ */ public class MultipleManagedConnectionFactory2 implements ManagedConnectionFactory, ResourceAdapterAssociation { /** * The serial version UID */ private static final long serialVersionUID = 1L; /** * The logger */ private static Logger log = Logger.getLogger("MultipleManagedConnectionFactory2"); /** * The resource adapter */ private ResourceAdapter ra; /** * The logwriter */ private PrintWriter logwriter; /** * Name */ private String name; /** * Default constructor */ public MultipleManagedConnectionFactory2() { } /** * Set name * * @param name The value */ public void setName(String name) { this.name = name; } /** * Get name * * @return The value */ public String getName() { return name; } /** * Creates a Connection Factory instance. * * @param cxManager ConnectionManager to be associated with created EIS connection factory instance * @return EIS-specific Connection Factory instance or jakarta.resource.cci.ConnectionFactory instance * @throws ResourceException Generic exception */ public Object createConnectionFactory(ConnectionManager cxManager) throws ResourceException { log.trace("createConnectionFactory()"); return new MultipleConnectionFactory2Impl(this, cxManager); } /** * Creates a Connection Factory instance. * * @return EIS-specific Connection Factory instance or jakarta.resource.cci.ConnectionFactory instance * @throws ResourceException Generic exception */ public Object createConnectionFactory() throws ResourceException { throw new ResourceException("This resource adapter doesn't support non-managed environments"); } /** * Creates a new physical connection to the underlying EIS resource manager. * * @param subject Caller's security information * @param cxRequestInfo Additional resource adapter specific connection request information * @return ManagedConnection instance * @throws ResourceException generic exception */ public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException { log.trace("createManagedConnection()"); return new MultipleManagedConnection2(this); } /** * Returns a matched connection from the candidate set of connections. * * @param connectionSet Candidate connection set * @param subject Caller's security information * @param cxRequestInfo Additional resource adapter specific connection request information * @return ManagedConnection if resource adapter finds an acceptable match otherwise null * @throws ResourceException generic exception */ public ManagedConnection matchManagedConnections(Set connectionSet, Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException { log.trace("matchManagedConnections()"); ManagedConnection result = null; Iterator it = connectionSet.iterator(); while (result == null && it.hasNext()) { ManagedConnection mc = (ManagedConnection) it.next(); if (mc instanceof MultipleManagedConnection2) { result = mc; } } return result; } /** * Get the log writer for this ManagedConnectionFactory instance. * * @return PrintWriter * @throws ResourceException generic exception */ public PrintWriter getLogWriter() throws ResourceException { log.trace("getLogWriter()"); return logwriter; } /** * Set the log writer for this ManagedConnectionFactory instance. * * @param out PrintWriter - an out stream for error logging and tracing * @throws ResourceException generic exception */ public void setLogWriter(PrintWriter out) throws ResourceException { log.trace("setLogWriter()"); logwriter = out; } /** * Get the resource adapter * * @return The handle */ public ResourceAdapter getResourceAdapter() { log.trace("getResourceAdapter()"); return ra; } /** * Set the resource adapter * * @param ra The handle */ public void setResourceAdapter(ResourceAdapter ra) { log.trace("setResourceAdapter()"); this.ra = ra; } /** * Returns a hash code value for the object. * * @return A hash code value for this object. */ @Override public int hashCode() { int result = 17; if (name != null) { result += 31 * result + 7 * name.hashCode(); } else { result += 31 * result + 7; } return result; } /** * Indicates whether some other object is equal to this one. * * @param other The reference object with which to compare. * @return true if this object is the same as the obj argument, false otherwise. */ @Override public boolean equals(Object other) { if (other == null) { return false; } if (other == this) { return true; } if (!(other instanceof MultipleManagedConnectionFactory2)) { return false; } MultipleManagedConnectionFactory2 obj = (MultipleManagedConnectionFactory2) other; boolean result = true; if (result) { if (name == null) { result = obj.getName() == null; } else { result = name.equals(obj.getName()); } } return result; } }
7,380
31.231441
133
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleConnection1Impl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import org.jboss.logging.Logger; /** * MultipleConnection1Impl * * @version $Revision: $ */ public class MultipleConnection1Impl implements MultipleConnection1 { /** * The logger */ private static Logger log = Logger.getLogger("MultipleConnection1Impl"); /** * ManagedConnection */ private MultipleManagedConnection1 mc; /** * ManagedConnectionFactory */ private MultipleManagedConnectionFactory1 mcf; /** * Default constructor * * @param mc MultipleManagedConnection1 * @param mcf MultipleManagedConnectionFactory1 */ public MultipleConnection1Impl(MultipleManagedConnection1 mc, MultipleManagedConnectionFactory1 mcf) { this.mc = mc; this.mcf = mcf; } /** * Call test * * @param s String * @return String */ public String test(String s) { log.trace("test()"); return null; } /** * Close */ public void close() { mc.closeHandle(this); } }
2,124
26.24359
106
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleManagedConnectionMetaData.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import org.jboss.logging.Logger; import jakarta.resource.ResourceException; import jakarta.resource.spi.ManagedConnectionMetaData; /** * MultipleManagedConnectionMetaData * * @version $Revision: $ */ public class MultipleManagedConnectionMetaData implements ManagedConnectionMetaData { /** * The logger */ private static Logger log = Logger.getLogger("MultipleManagedConnectionMetaData"); /** * Default constructor */ public MultipleManagedConnectionMetaData() { } /** * Returns Product name of the underlying EIS instance connected through the ManagedConnection. * * @return Product name of the EIS instance * @throws ResourceException Thrown if an error occurs */ @Override public String getEISProductName() throws ResourceException { log.trace("getEISProductName()"); return null; //TODO } /** * Returns Product version of the underlying EIS instance connected through the ManagedConnection. * * @return Product version of the EIS instance * @throws ResourceException Thrown if an error occurs */ @Override public String getEISProductVersion() throws ResourceException { log.trace("getEISProductVersion()"); return null; //TODO } /** * Returns maximum limit on number of active concurrent connections * * @return Maximum limit for number of active concurrent connections * @throws ResourceException Thrown if an error occurs */ @Override public int getMaxConnections() throws ResourceException { log.trace("getMaxConnections()"); return 0; //TODO } /** * Returns name of the user associated with the ManagedConnection instance * * @return Name of the user * @throws ResourceException Thrown if an error occurs */ @Override public String getUserName() throws ResourceException { log.trace("getUserName()"); return null; //TODO } }
3,095
31.25
102
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleManagedConnectionFactory1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import java.io.PrintWriter; import java.util.Iterator; import java.util.Set; import org.jboss.logging.Logger; import jakarta.resource.ResourceException; import jakarta.resource.spi.ConnectionManager; import jakarta.resource.spi.ConnectionRequestInfo; import jakarta.resource.spi.ManagedConnection; import jakarta.resource.spi.ManagedConnectionFactory; import jakarta.resource.spi.ResourceAdapter; import jakarta.resource.spi.ResourceAdapterAssociation; import javax.security.auth.Subject; /** * MultipleManagedConnectionFactory1 * * @version $Revision: $ */ public class MultipleManagedConnectionFactory1 implements ManagedConnectionFactory, ResourceAdapterAssociation { /** * The serial version UID */ private static final long serialVersionUID = 1L; /** * The logger */ private static Logger log = Logger.getLogger("MultipleManagedConnectionFactory1"); /** * The resource adapter */ private ResourceAdapter ra; /** * The logwriter */ private PrintWriter logwriter; /** * Name */ private String name; /** * Default constructor */ public MultipleManagedConnectionFactory1() { } /** * Set name * * @param name The value */ public void setName(String name) { this.name = name; } /** * Get name * * @return The value */ public String getName() { return name; } /** * Creates a Connection Factory instance. * * @param cxManager ConnectionManager to be associated with created EIS connection factory instance * @return EIS-specific Connection Factory instance or jakarta.resource.cci.ConnectionFactory instance * @throws ResourceException Generic exception */ public Object createConnectionFactory(ConnectionManager cxManager) throws ResourceException { log.trace("createConnectionFactory()"); return new MultipleConnectionFactory1Impl(this, cxManager); } /** * Creates a Connection Factory instance. * * @return EIS-specific Connection Factory instance or jakarta.resource.cci.ConnectionFactory instance * @throws ResourceException Generic exception */ public Object createConnectionFactory() throws ResourceException { return new MultipleManagedConnectionFactory1(); //throw new ResourceException("This resource adapter doesn't support non-managed environments"); } /** * Creates a new physical connection to the underlying EIS resource manager. * * @param subject Caller's security information * @param cxRequestInfo Additional resource adapter specific connection request information * @return ManagedConnection instance * @throws ResourceException generic exception */ public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException { log.trace("createManagedConnection()"); return new MultipleManagedConnection1(this); } /** * Returns a matched connection from the candidate set of connections. * * @param connectionSet Candidate connection set * @param subject Caller's security information * @param cxRequestInfo Additional resource adapter specific connection request information * @return ManagedConnection if resource adapter finds an acceptable match otherwise null * @throws ResourceException generic exception */ public ManagedConnection matchManagedConnections(Set connectionSet, Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException { log.trace("matchManagedConnections()"); ManagedConnection result = null; Iterator it = connectionSet.iterator(); while (result == null && it.hasNext()) { ManagedConnection mc = (ManagedConnection) it.next(); if (mc instanceof MultipleManagedConnection1) { result = mc; } } return result; } /** * Get the log writer for this ManagedConnectionFactory instance. * * @return PrintWriter * @throws ResourceException generic exception */ public PrintWriter getLogWriter() throws ResourceException { log.trace("getLogWriter()"); return logwriter; } /** * Set the log writer for this ManagedConnectionFactory instance. * * @param out PrintWriter - an out stream for error logging and tracing * @throws ResourceException generic exception */ public void setLogWriter(PrintWriter out) throws ResourceException { log.trace("setLogWriter()"); logwriter = out; } /** * Get the resource adapter * * @return The handle */ public ResourceAdapter getResourceAdapter() { log.trace("getResourceAdapter()"); return ra; } /** * Set the resource adapter * * @param ra The handle */ public void setResourceAdapter(ResourceAdapter ra) { log.trace("setResourceAdapter()"); this.ra = ra; } /** * Returns a hash code value for the object. * * @return A hash code value for this object. */ @Override public int hashCode() { int result = 17; if (name != null) { result += 31 * result + 7 * name.hashCode(); } else { result += 31 * result + 7; } return result; } /** * Indicates whether some other object is equal to this one. * * @param other The reference object with which to compare. * @return true if this object is the same as the obj argument, false otherwise. */ @Override public boolean equals(Object other) { if (other == null) { return false; } if (other == this) { return true; } if (!(other instanceof MultipleManagedConnectionFactory1)) { return false; } MultipleManagedConnectionFactory1 obj = (MultipleManagedConnectionFactory1) other; boolean result = true; if (result) { if (name == null) { result = obj.getName() == null; } else { result = name.equals(obj.getName()); } } return result; } }
7,438
31.343478
133
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleAdminObject1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import java.io.Serializable; import jakarta.resource.Referenceable; /** * MultipleAdminObject1 * * @version $Revision: $ */ public interface MultipleAdminObject1 extends Referenceable, Serializable { /** * Set name * * @param name The value */ void setName(String name); /** * Get name * * @return The value */ String getName(); }
1,477
28.56
75
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleResourceAdapter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import java.io.Serializable; import org.jboss.logging.Logger; 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 javax.transaction.xa.XAResource; /** * MultipleResourceAdapter * * @version $Revision: $ */ public class MultipleResourceAdapter implements ResourceAdapter, Serializable { /** * The logger */ private static Logger log = Logger.getLogger("MultipleResourceAdapter"); /** * Name */ private String name; /** * Default constructor */ public MultipleResourceAdapter() { } /** * Set name * * @param name The value */ public void setName(String name) { this.name = name; } /** * Get name * * @return The value */ public String getName() { return name; } /** * This is called during the activation of a message endpoint. * * @param endpointFactory A message endpoint factory instance. * @param spec An activation spec JavaBean instance. * @throws ResourceException generic exception */ public void endpointActivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) throws ResourceException { log.trace("endpointActivation()"); } /** * This is called when a message endpoint is deactivated. * * @param endpointFactory A message endpoint factory instance. * @param spec An activation spec JavaBean instance. */ public void endpointDeactivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) { log.trace("endpointDeactivation()"); } /** * This is called when a resource adapter instance is bootstrapped. * * @param ctx A bootstrap context containing references * @throws ResourceAdapterInternalException indicates bootstrap failure. */ public void start(BootstrapContext ctx) throws ResourceAdapterInternalException { log.trace("start()"); } /** * This is called when a resource adapter instance is undeployed or * during application server shutdown. */ public void stop() { log.trace("stop()"); } /** * This method is called by the application server during crash recovery. * * @param specs An array of ActivationSpec JavaBeans * @return An array of XAResource objects * @throws ResourceException generic exception */ public XAResource[] getXAResources(ActivationSpec[] specs) throws ResourceException { log.trace("getXAResources()"); return null; } /** * Returns a hash code value for the object. * * @return A hash code value for this object. */ @Override public int hashCode() { int result = 17; if (name != null) { result += 31 * result + 7 * name.hashCode(); } else { result += 31 * result + 7; } return result; } /** * Indicates whether some other object is equal to this one. * * @param other The reference object with which to compare. * @return true if this object is the same as the obj argument, false otherwise. */ @Override public boolean equals(Object other) { if (other == null) { return false; } if (other == this) { return true; } if (!(other instanceof MultipleResourceAdapter)) { return false; } MultipleResourceAdapter obj = (MultipleResourceAdapter) other; boolean result = true; if (result) { if (name == null) { result = obj.getName() == null; } else { result = name.equals(obj.getName()); } } return result; } }
5,089
30.036585
111
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/MultipleConnectionFactory2.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar; import java.io.Serializable; import jakarta.resource.Referenceable; import jakarta.resource.ResourceException; /** * MultipleConnectionFactory2 * * @version $Revision: $ */ public interface MultipleConnectionFactory2 extends Serializable, Referenceable { /** * Get connection from factory * * @return MultipleConnection2 instance * @throws ResourceException Thrown if a connection can't be obtained */ MultipleConnection2 getConnection() throws ResourceException; }
1,586
35.906977
81
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/tests/redeployment/ReDeploymentTestCase.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.smoke.deployment.rar.tests.redeployment; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.junit.Assert.assertNotNull; import java.util.List; import javax.naming.Context; 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.container.ManagementClient; import org.jboss.as.connector.subsystems.resourceadapters.Namespace; import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdapterSubsystemParser; import org.jboss.as.test.integration.management.base.AbstractMgmtServerSetupTask; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.shared.FileUtils; import org.jboss.as.test.smoke.deployment.rar.MultipleAdminObject1; import org.jboss.as.test.smoke.deployment.rar.MultipleConnectionFactory1; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="vrastsel@redhat.com">Vladimir Rastseluev</a> * JBQA-5968 test for undeployment and re-deployment */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(ReDeploymentTestCase.ReDeploymentTestCaseSetup.class) public class ReDeploymentTestCase extends ContainerResourceMgmtTestBase { static String deploymentName = "re-deployment.rar"; @ContainerResource private Context context; @ArquillianResource private Deployer deployer; static class ReDeploymentTestCaseSetup extends AbstractMgmtServerSetupTask { @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { final ModelNode address = new ModelNode(); address.add("subsystem", "resource-adapters"); address.add("resource-adapter", deploymentName); address.protect(); remove(address); } @Override protected void doSetup(final ManagementClient managementClient) throws Exception { } } private void setup() throws Exception { String xml = FileUtils.readFile(ReDeploymentTestCase.class, "re-deployment.xml"); List<ModelNode> operations = xmlToModelOperations(xml, Namespace.RESOURCEADAPTERS_1_0.getUriString(), new ResourceAdapterSubsystemParser()); executeOperation(operationListToCompositeOperation(operations)); //since it is created after deployment it needs activation final ModelNode address = new ModelNode(); address.add("subsystem", "resource-adapters"); address.add("resource-adapter", deploymentName); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("activate"); operation.get(OP_ADDR).set(address); executeOperation(operation); } /** * Define the deployment * * @return The deployment archive */ @Deployment(name = "re-deployment.rar", managed = false) public static ResourceAdapterArchive createDeployment() throws Exception { ResourceAdapterArchive raa = ShrinkWrap.create(ResourceAdapterArchive.class, deploymentName); JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "multiple.jar"); ja.addPackage(MultipleConnectionFactory1.class.getPackage()); raa.addAsLibrary(ja); raa.addAsManifestResource(ReDeploymentTestCase.class.getPackage(), "ra.xml", "ra.xml"); return raa; } /** * Test configuration * * @throws Throwable Thrown if case of an error */ @Test public void testConfiguration() throws Throwable { deployer.deploy(deploymentName); setup(); deployer.undeploy(deploymentName); deployer.deploy(deploymentName); MultipleAdminObject1 adminObject1 = (MultipleAdminObject1) context.lookup("redeployed/Name3"); assertNotNull("AO1 not found", adminObject1); deployer.undeploy(deploymentName); } }
5,593
38.673759
148
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/tests/multiactivation/MultipleActivationTestCase.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.smoke.deployment.rar.tests.multiactivation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.util.List; import jakarta.annotation.Resource; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.connector.subsystems.resourceadapters.Namespace; import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdapterSubsystemParser; import org.jboss.as.test.integration.management.base.AbstractMgmtServerSetupTask; import org.jboss.as.test.integration.management.base.AbstractMgmtTestBase; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.FileUtils; import org.jboss.as.test.smoke.deployment.rar.MultipleAdminObject1; import org.jboss.as.test.smoke.deployment.rar.MultipleConnectionFactory1; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="vrastsel@redhat.com">Vladimir Rastseluev</a> * JBQA-5740 multiple resources deployment */ @RunWith(Arquillian.class) @ServerSetup(MultipleActivationTestCase.MultipleActivationTestCaseSetup.class) public class MultipleActivationTestCase { static class MultipleActivationTestCaseSetup extends AbstractMgmtServerSetupTask { @Override public void doSetup(final ManagementClient managementClient) throws Exception { String xml = FileUtils.readFile(MultipleActivationTestCase.class, "simple.xml"); List<ModelNode> operations = xmlToModelOperations(xml, Namespace.RESOURCEADAPTERS_1_0.getUriString(), new ResourceAdapterSubsystemParser()); executeOperation(operationListToCompositeOperation(operations)); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws IOException, MgmtOperationException { final ModelNode address = new ModelNode(); address.add("subsystem", "resource-adapters"); address.add("resource-adapter", "archive.rar"); address.protect(); remove(address); } } /** * Define the deployment * * @return The deployment archive */ @Deployment public static ResourceAdapterArchive createDeployment() throws Exception { String deploymentName = "archive.rar"; ResourceAdapterArchive raa = ShrinkWrap.create(ResourceAdapterArchive.class, deploymentName); JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "multiple.jar"); ja.addPackage(MultipleConnectionFactory1.class.getPackage()). addClasses(MultipleActivationTestCase.class); ja.addPackage(AbstractMgmtTestBase.class.getPackage()); // needed to process the @ServerSetup annotation on the server side raa.addAsLibrary(ja); raa.addAsManifestResource(MultipleActivationTestCase.class.getPackage(), "ra.xml", "ra.xml"); return raa; } @Resource(mappedName = "java:jboss/name1") private MultipleConnectionFactory1 connectionFactory1; @Resource(mappedName = "java:jboss/name2") private MultipleConnectionFactory1 connectionFactory2; @Resource(mappedName = "java:jboss/Name3") private MultipleAdminObject1 adminObject1; @Resource(mappedName = "java:jboss/Name4") private MultipleAdminObject1 adminObject2; /** * Test configuration * * @throws Throwable Thrown if case of an error */ @Test public void testConfiguration() throws Throwable { assertNotNull("CF1 not found", connectionFactory1); assertNotNull("CF2 not found", connectionFactory2); assertNotNull("AO1 not found", adminObject1); assertNotNull("AO2 not found", adminObject2); assertEquals("not equal AOs", adminObject1, adminObject2); } }
5,252
39.72093
152
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/tests/eardeployment/EarDeploymentTestCase.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.smoke.deployment.rar.tests.eardeployment; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.StandardCharsets; 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.container.ManagementClient; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.smoke.deployment.RaServlet; import org.jboss.as.test.smoke.deployment.rar.MultipleConnectionFactory1; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; 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.ResourceAdapterArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="vrastsel@redhat.com">Vladimir Rastseluev</a> * JBQA-5828 RAR inside EAR */ @RunWith(Arquillian.class) @RunAsClient public class EarDeploymentTestCase extends ContainerResourceMgmtTestBase { @ArquillianResource private ManagementClient managementClient; @ArquillianResource private URL url; static String subdeploymentName = "complex_ij.rar"; static String deploymentName = "new.ear"; /** * Define the deployment * * @return The deployment archive */ @Deployment public static EnterpriseArchive createDeployment() throws Exception { ResourceAdapterArchive raa = ShrinkWrap.create(ResourceAdapterArchive.class, subdeploymentName); JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "multiple.jar"); ja.addPackage(MultipleConnectionFactory1.class.getPackage()); raa.addAsManifestResource(EarDeploymentTestCase.class.getPackage(), "ironjacamar.xml", "ironjacamar.xml") .addAsManifestResource(EarDeploymentTestCase.class.getPackage(), "ra.xml", "ra.xml") .addAsManifestResource(new StringAsset("Dependencies: org.jboss.as.controller-client,org.jboss.dmr,javax.inject.api,org.jboss.as.connector\n"), "MANIFEST.MF"); WebArchive wa = ShrinkWrap.create(WebArchive.class, "servlet.war"); wa.addClasses(RaServlet.class); EnterpriseArchive ea = ShrinkWrap.create(EnterpriseArchive.class, deploymentName); ea.addAsModule(raa) .addAsModule(wa) .addAsLibrary(ja); return ea; } /** * Test configuration * * @throws Throwable Thrown if case of an error */ @Test public void testWebConfiguration() throws Throwable { URL servletURL = new URL("http://" + url.getHost() + ":8080/servlet" + RaServlet.URL_PATTERN); BufferedReader br = new BufferedReader(new InputStreamReader(servletURL.openStream(), StandardCharsets.UTF_8)); String message = br.readLine(); assertEquals(RaServlet.SUCCESS, message); } @Test public void testConfiguration() throws Throwable { assertNotNull("Deployment metadata for ear not found", managementClient.getProtocolMetaData(deploymentName)); final ModelNode address = new ModelNode(); address.add("deployment", deploymentName).add("subdeployment", subdeploymentName).add("subsystem", "resource-adapters"); address.protect(); final ModelNode snapshot = new ModelNode(); snapshot.get(OP).set("read-resource"); snapshot.get("recursive").set(true); snapshot.get(OP_ADDR).set(address); executeOperation(snapshot); } }
5,104
40.504065
175
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/tests/multiobjectpartialactivation/MultipleObjectPartialActivationTestCase.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.smoke.deployment.rar.tests.multiobjectpartialactivation; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.util.List; import jakarta.annotation.Resource; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.connector.subsystems.resourceadapters.Namespace; import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdapterSubsystemParser; import org.jboss.as.test.integration.management.base.AbstractMgmtServerSetupTask; import org.jboss.as.test.integration.management.base.AbstractMgmtTestBase; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.FileUtils; import org.jboss.as.test.smoke.deployment.rar.MultipleAdminObject1; import org.jboss.as.test.smoke.deployment.rar.MultipleConnectionFactory1; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="vrastsel@redhat.com">Vladimir Rastseluev</a> * JBQA-5739 multiple object activation (partial) */ @RunWith(Arquillian.class) @ServerSetup(MultipleObjectPartialActivationTestCase.MultipleObjectPartialActivationTestCaseSetup.class) public class MultipleObjectPartialActivationTestCase { static class MultipleObjectPartialActivationTestCaseSetup extends AbstractMgmtServerSetupTask { @Override public void doSetup(final ManagementClient managementClient) throws Exception { String xml = FileUtils.readFile(MultipleObjectPartialActivationTestCase.class, "multiple_part.xml"); List<ModelNode> operations = xmlToModelOperations(xml, Namespace.RESOURCEADAPTERS_1_0.getUriString(), new ResourceAdapterSubsystemParser()); executeOperation(operationListToCompositeOperation(operations)); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws IOException, MgmtOperationException { final ModelNode address = new ModelNode(); address.add("subsystem", "resource-adapters"); address.add("resource-adapter", "archive_multi_partial.rar"); address.protect(); remove(address); } } /** * Define the deployment * * @return The deployment archive */ @Deployment public static ResourceAdapterArchive createDeployment() throws Exception { String deploymentName = "archive_multi_partial.rar"; ResourceAdapterArchive raa = ShrinkWrap.create(ResourceAdapterArchive.class, deploymentName); JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "multiple.jar"); ja.addPackage(MultipleConnectionFactory1.class.getPackage()). addClasses(MultipleObjectPartialActivationTestCase.class, MultipleObjectPartialActivationTestCaseSetup.class); ja.addPackage(AbstractMgmtTestBase.class.getPackage()); // needed to process the @ServerSetup annotation on the server side raa.addAsLibrary(ja); raa.addAsManifestResource(MultipleObjectPartialActivationTestCase.class.getPackage(), "ra.xml", "ra.xml"); //org.apache.httpcomponents, return raa; } @Resource(mappedName = "java:jboss/name1") private MultipleConnectionFactory1 connectionFactory1; @Resource(mappedName = "java:jboss/Name3") private MultipleAdminObject1 adminObject1; /** * Test configuration * * @throws Throwable Thrown if case of an error */ @Test public void testConfiguration() throws Throwable { assertNotNull("CF1 not found", connectionFactory1); assertNotNull("AO1 not found", adminObject1); } }
5,061
40.834711
152
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/tests/afterresourcecreation/AfterResourceCreationDeploymentTestCase.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.smoke.deployment.rar.tests.afterresourcecreation; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.junit.Assert.assertNotNull; import java.util.List; import javax.naming.Context; 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.connector.subsystems.resourceadapters.Namespace; import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdapterSubsystemParser; import org.jboss.as.test.integration.management.base.AbstractMgmtServerSetupTask; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.shared.FileUtils; import org.jboss.as.test.smoke.deployment.rar.MultipleAdminObject1; import org.jboss.as.test.smoke.deployment.rar.MultipleConnectionFactory1; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="vrastsel@redhat.com">Vladimir Rastseluev</a> * JBQA-5841 test for RA activation */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(AfterResourceCreationDeploymentTestCase.AfterResourceCreationDeploymentTestCaseSetup.class) public class AfterResourceCreationDeploymentTestCase extends ContainerResourceMgmtTestBase { static String deploymentName = "basic-after.rar"; @ContainerResource private Context context; static class AfterResourceCreationDeploymentTestCaseSetup extends AbstractMgmtServerSetupTask { @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { final ModelNode address = new ModelNode(); address.add("subsystem", "resource-adapters"); address.add("resource-adapter", deploymentName); address.protect(); remove(address); } @Override protected void doSetup(final ManagementClient managementClient) throws Exception { } } private void setup() throws Exception { String xml = FileUtils.readFile(AfterResourceCreationDeploymentTestCase.class, "basic-after.xml"); List<ModelNode> operations = xmlToModelOperations(xml, Namespace.RESOURCEADAPTERS_1_0.getUriString(), new ResourceAdapterSubsystemParser()); executeOperation(operationListToCompositeOperation(operations)); //since it is created after deployment it needs activation final ModelNode address = new ModelNode(); address.add("subsystem", "resource-adapters"); address.add("resource-adapter", deploymentName); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("activate"); operation.get(OP_ADDR).set(address); executeOperation(operation); } /** * Define the deployment * * @return The deployment archive */ @Deployment(name = "basic-after.rar") public static ResourceAdapterArchive createDeployment() throws Exception { ResourceAdapterArchive raa = ShrinkWrap.create(ResourceAdapterArchive.class, deploymentName); JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "multiple.jar"); ja.addPackage(MultipleConnectionFactory1.class.getPackage()); raa.addAsLibrary(ja); raa.addAsManifestResource(AfterResourceCreationDeploymentTestCase.class.getPackage(), "ra.xml", "ra.xml"); return raa; } /** * Test configuration * * @throws Throwable Thrown if case of an error */ @Test public void testConfiguration() throws Throwable { setup(); MultipleAdminObject1 adminObject1 = (MultipleAdminObject1) context.lookup("after/Name3"); assertNotNull("AO1 not found", adminObject1); } }
5,334
39.112782
148
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/tests/earpackage/EarPackagedDeploymentTestCase.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.smoke.deployment.rar.tests.earpackage; import static org.junit.Assert.assertNotNull; import java.util.List; import jakarta.annotation.Resource; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.connector.subsystems.resourceadapters.Namespace; import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdapterSubsystemParser; import org.jboss.as.test.integration.management.base.AbstractMgmtServerSetupTask; import org.jboss.as.test.integration.management.base.AbstractMgmtTestBase; import org.jboss.as.test.shared.FileUtils; import org.jboss.as.test.smoke.deployment.rar.MultipleAdminObject1; import org.jboss.as.test.smoke.deployment.rar.MultipleConnectionFactory1; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="robert.reimann@googlemail.com">Robert Reimann</a> * Deployment of a RAR packaged inside an EAR. */ @RunWith(Arquillian.class) @ServerSetup(EarPackagedDeploymentTestCase.EarPackagedDeploymentTestCaseSetup.class) public class EarPackagedDeploymentTestCase { static class EarPackagedDeploymentTestCaseSetup extends AbstractMgmtServerSetupTask { @Override public void doSetup(final ManagementClient managementClient) throws Exception { String xml = FileUtils.readFile(EarPackagedDeploymentTestCase.class, "ear_packaged.xml"); List<ModelNode> operations = xmlToModelOperations(xml, Namespace.RESOURCEADAPTERS_1_0.getUriString(), new ResourceAdapterSubsystemParser()); executeOperation(operationListToCompositeOperation(operations)); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { final ModelNode address = new ModelNode(); address.add("subsystem", "resource-adapters"); address.add("resource-adapter", "ear_packaged.ear#ear_packaged.rar"); address.protect(); remove(address); } } /** * Define the deployment * * @return The deployment archive */ @Deployment public static EnterpriseArchive createDeployment() { String deploymentName = "ear_packaged.ear"; String subDeploymentName = "ear_packaged.rar"; ResourceAdapterArchive raa = ShrinkWrap.create(ResourceAdapterArchive.class, subDeploymentName); JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "multiple.jar"); ja.addPackage(MultipleConnectionFactory1.class.getPackage()). addClasses(EarPackagedDeploymentTestCase.class); ja.addPackage(AbstractMgmtTestBase.class.getPackage()); // needed to process the @ServerSetup annotation on the server side raa.addAsLibrary(ja); raa.addAsManifestResource(EarPackagedDeploymentTestCase.class.getPackage(), "ra.xml", "ra.xml"); final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, deploymentName); ear.addAsModule(raa); ear.addAsManifestResource(EarPackagedDeploymentTestCase.class.getPackage(), "application.xml", "application.xml"); return ear; } @Resource(mappedName = "java:jboss/name1") private MultipleConnectionFactory1 connectionFactory1; @Resource(mappedName = "java:jboss/Name3") private MultipleAdminObject1 adminObject1; /** * Test configuration * * @throws Throwable Thrown if case of an error */ @Test public void testConfiguration() throws Throwable { assertNotNull("CF1 not found", connectionFactory1); assertNotNull("AO1 not found", adminObject1); } }
5,097
39.784
152
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/tests/pure/PureTestCase.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.smoke.deployment.rar.tests.pure; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.Set; 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.connector.util.ConnectorServices; import org.jboss.as.test.smoke.deployment.rar.inflow.PureInflowResourceAdapter; import org.jboss.jca.core.spi.mdr.MetadataRepository; import org.jboss.jca.core.spi.rar.ResourceAdapterRepository; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceController; 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.Test; import org.junit.runner.RunWith; /** * @author <a href="vrastsel@redhat.com">Vladimir Rastseluev</a> * JBQA-5742 -Pure RA deployment test */ @RunWith(Arquillian.class) public class PureTestCase { /** * Define the deployment * * @return The deployment archive */ @Deployment public static ResourceAdapterArchive createDeployment() { String deploymentName = "pure.rar"; ResourceAdapterArchive raa = ShrinkWrap.create(ResourceAdapterArchive.class, deploymentName); JavaArchive javaArchive = ShrinkWrap.create(JavaArchive.class, "multiple.jar"); javaArchive.addClasses(PureTestCase.class); javaArchive.addPackage(PureInflowResourceAdapter.class.getPackage()); raa.addAsLibrary(javaArchive); raa.addAsManifestResource(PureTestCase.class.getPackage(), "ra.xml", "ra.xml") .addAsManifestResource(new StringAsset("Dependencies: javax.inject.api,org.jboss.as.connector\n"), "MANIFEST.MF"); return raa; } @ArquillianResource ServiceContainer serviceContainer; /** * Test configuration * * @throws Throwable Thrown if case of an error */ @Test public void testRegistryConfiguration() throws Throwable { ServiceController<?> controller = serviceContainer.getService(ConnectorServices.RA_REPOSITORY_SERVICE); assertNotNull(controller); ResourceAdapterRepository repository = (ResourceAdapterRepository) controller.getValue(); assertNotNull(repository); Set<String> ids = repository.getResourceAdapters(); assertNotNull(ids); int pureInflowListener = 0; for (String id : ids) { if (id.indexOf("PureInflow") != -1) { pureInflowListener++; } } assertEquals(1, pureInflowListener); for (String piId : ids) { assertNotNull(piId); assertNotNull(repository.getResourceAdapter(piId)); } } @Test public void testMetadataConfiguration() throws Throwable { ServiceController<?> controller = serviceContainer.getService(ConnectorServices.IRONJACAMAR_MDR); assertNotNull(controller); MetadataRepository repository = (MetadataRepository) controller.getValue(); assertNotNull(repository); Set<String> ids = repository.getResourceAdapters(); assertNotNull(ids); for (String piId : ids) { assertNotNull(piId); assertNotNull(repository.getResourceAdapter(piId)); } } }
4,505
35.934426
130
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/tests/activation/IronJacamarActivationTestCase.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.smoke.deployment.rar.tests.activation; import static org.junit.Assert.assertNotNull; import jakarta.annotation.Resource; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.smoke.deployment.rar.MultipleAdminObject1; import org.jboss.as.test.smoke.deployment.rar.MultipleAdminObject2; import org.jboss.as.test.smoke.deployment.rar.MultipleConnectionFactory1; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="vrastsel@redhat.com">Vladimir Rastseluev</a> * JBQA-5736 -IronJacamar deployment test */ @RunWith(Arquillian.class) public class IronJacamarActivationTestCase { /** * Define the deployment * * @return The deployment archive */ @Deployment public static ResourceAdapterArchive createDeployment() { String deploymentName = "archive_ij.rar"; ResourceAdapterArchive raa = ShrinkWrap.create(ResourceAdapterArchive.class, deploymentName); JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "multiple.jar"); ja.addPackage(MultipleConnectionFactory1.class.getPackage()). addClasses(IronJacamarActivationTestCase.class); raa.addAsLibrary(ja); raa.addAsManifestResource(IronJacamarActivationTestCase.class.getPackage(), "ra.xml", "ra.xml") .addAsManifestResource(IronJacamarActivationTestCase.class.getPackage(), "ironjacamar.xml", "ironjacamar.xml"); return raa; } @Resource(mappedName = "java:jboss/name1") private MultipleConnectionFactory1 connectionFactory1; @Resource(mappedName = "java:jboss/Name3") private MultipleAdminObject1 adminObject1; @Resource(mappedName = "java:jboss/Name4") private MultipleAdminObject2 adminObject2; /** * Test configuration * * @throws Throwable Thrown if case of an error */ @Test public void testConfiguration() throws Throwable { assertNotNull("CF1 not found", connectionFactory1); assertNotNull("AO1 not found", adminObject1); assertNotNull("AO2 not found", adminObject2); } }
3,381
35.365591
127
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/tests/inflow/InflowTestCase.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.smoke.deployment.rar.tests.inflow; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.List; import java.util.Set; import jakarta.resource.spi.ActivationSpec; 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.connector.util.ConnectorServices; import org.jboss.as.test.smoke.deployment.rar.inflow.PureInflowResourceAdapter; import org.jboss.jca.core.spi.mdr.MetadataRepository; import org.jboss.jca.core.spi.rar.Endpoint; import org.jboss.jca.core.spi.rar.MessageListener; import org.jboss.jca.core.spi.rar.ResourceAdapterRepository; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceController; 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.Test; import org.junit.runner.RunWith; /** * @author <a href="vrastsel@redhat.com">Vladimir Rastseluev</a> * JBQA-5741 -Inflow RA deployment test */ @RunWith(Arquillian.class) public class InflowTestCase { /** * Define the deployment * * @return The deployment archive */ @Deployment public static ResourceAdapterArchive createDeployment() throws Exception { String deploymentName = "inflow.rar"; ResourceAdapterArchive raa = ShrinkWrap.create(ResourceAdapterArchive.class, deploymentName); JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "multiple.jar"); ja.addPackage(PureInflowResourceAdapter.class.getPackage()). addClasses(InflowTestCase.class); raa.addAsLibrary(ja); raa.addAsManifestResource(InflowTestCase.class.getPackage(), "ra.xml", "ra.xml") .addAsManifestResource(InflowTestCase.class.getPackage(), "ironjacamar.xml", "ironjacamar.xml") .addAsManifestResource(new StringAsset("Dependencies: javax.inject.api,org.jboss.as.connector\n"), "MANIFEST.MF"); return raa; } @ArquillianResource ServiceContainer serviceContainer; /** * Test configuration * * @throws Throwable Thrown if case of an error */ @Test public void testRegistryConfiguration() throws Throwable { ServiceController<?> controller = serviceContainer.getService(ConnectorServices.RA_REPOSITORY_SERVICE); assertNotNull(controller); ResourceAdapterRepository repository = (ResourceAdapterRepository) controller.getValue(); assertNotNull(repository); Set<String> ids = repository.getResourceAdapters(jakarta.jms.MessageListener.class); assertNotNull(ids); int pureInflowListener = 0; for (String id : ids) { if (id.indexOf("PureInflow") != -1) { pureInflowListener++; } } assertEquals(1, pureInflowListener); String piId = ids.iterator().next(); assertNotNull(piId); Endpoint endpoint = repository.getEndpoint(piId); assertNotNull(endpoint); List<MessageListener> listeners = repository.getMessageListeners(piId); assertNotNull(listeners); assertEquals(1, listeners.size()); MessageListener listener = listeners.get(0); ActivationSpec as = listener.getActivation().createInstance(); assertNotNull(as); assertNotNull(as.getResourceAdapter()); } @Test public void testMetadataConfiguration() throws Throwable { ServiceController<?> controller = serviceContainer.getService(ConnectorServices.IRONJACAMAR_MDR); assertNotNull(controller); MetadataRepository repository = (MetadataRepository) controller.getValue(); assertNotNull(repository); Set<String> ids = repository.getResourceAdapters(); assertNotNull(ids); String piId = ids.iterator().next(); assertNotNull(piId); assertNotNull(repository.getResourceAdapter(piId)); } }
5,187
36.868613
130
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/tests/multiobjectactivation/MultipleObjectActivationTestCase.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.smoke.deployment.rar.tests.multiobjectactivation; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.util.List; import jakarta.annotation.Resource; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.connector.subsystems.resourceadapters.Namespace; import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdapterSubsystemParser; import org.jboss.as.test.integration.management.base.AbstractMgmtServerSetupTask; import org.jboss.as.test.integration.management.base.AbstractMgmtTestBase; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.FileUtils; import org.jboss.as.test.smoke.deployment.rar.MultipleAdminObject1; import org.jboss.as.test.smoke.deployment.rar.MultipleAdminObject2; import org.jboss.as.test.smoke.deployment.rar.MultipleConnectionFactory1; import org.jboss.as.test.smoke.deployment.rar.MultipleConnectionFactory2; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="vrastsel@redhat.com">Vladimir Rastseluev</a> * JBQA-5738 multiple object activation(full) */ @RunWith(Arquillian.class) @ServerSetup(MultipleObjectActivationTestCase.MultipleObjectActivationTestCaseSetup.class) public class MultipleObjectActivationTestCase { static class MultipleObjectActivationTestCaseSetup extends AbstractMgmtServerSetupTask { @Override public void doSetup(final ManagementClient managementClient) throws Exception { String xml = FileUtils.readFile(MultipleObjectActivationTestCase.class, "multiple.xml"); List<ModelNode> operations = xmlToModelOperations(xml, Namespace.RESOURCEADAPTERS_1_0.getUriString(), new ResourceAdapterSubsystemParser()); executeOperation(operationListToCompositeOperation(operations)); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws IOException, MgmtOperationException { final ModelNode address = new ModelNode(); address.add("subsystem", "resource-adapters"); address.add("resource-adapter", "archive_mult.rar"); address.protect(); remove(address); } } /** * Define the deployment * * @return The deployment archive */ @Deployment public static ResourceAdapterArchive createDeployment() throws Exception { String deploymentName = "archive_mult.rar"; ResourceAdapterArchive raa = ShrinkWrap.create(ResourceAdapterArchive.class, deploymentName); JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "multiple.jar"); ja.addPackage(MultipleConnectionFactory1.class.getPackage()). addClasses(MultipleObjectActivationTestCase.class); ja.addPackage(AbstractMgmtTestBase.class.getPackage()); // needed to process the @ServerSetup annotation on the server side raa.addAsLibrary(ja); raa.addAsManifestResource(MultipleObjectActivationTestCase.class.getPackage(), "ra.xml", "ra.xml"); return raa; } @Resource(mappedName = "java:jboss/name1") private MultipleConnectionFactory1 connectionFactory1; @Resource(mappedName = "java:jboss/name2") private MultipleConnectionFactory2 connectionFactory2; @Resource(mappedName = "java:jboss/Name3") private MultipleAdminObject1 adminObject1; @Resource(mappedName = "java:jboss/Name4") private MultipleAdminObject2 adminObject2; /** * Test configuration * * @throws Throwable Thrown if case of an error */ @Test public void testConfiguration() throws Throwable { assertNotNull("CF1 not found", connectionFactory1); assertNotNull("CF2 not found", connectionFactory2); assertNotNull("AO1 not found", adminObject1); assertNotNull("AO2 not found", adminObject2); } }
5,344
41.086614
152
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/tests/raconnection/RaTestConnectionTestCase.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.smoke.deployment.rar.tests.raconnection; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.junit.Assert.assertTrue; 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.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.connector.subsystems.resourceadapters.Namespace; import org.jboss.as.connector.subsystems.resourceadapters.ResourceAdapterSubsystemParser; import org.jboss.as.test.integration.management.base.AbstractMgmtServerSetupTask; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.shared.FileUtils; import org.jboss.as.test.smoke.deployment.rar.MultipleConnectionFactory1; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="vrastsel@redhat.com">Vladimir Rastseluev</a> * JBQA-5967 test connection in pool */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(RaTestConnectionTestCase.RaTestConnectionTestCaseSetup.class) public class RaTestConnectionTestCase extends ContainerResourceMgmtTestBase { private static ModelNode address; private static String deploymentName = "testcon_mult.rar"; static class RaTestConnectionTestCaseSetup extends AbstractMgmtServerSetupTask { @Override public void doSetup(final ManagementClient managementClient) throws Exception { address = new ModelNode(); address.add("subsystem", "resource-adapters"); address.add("resource-adapter", deploymentName); address.protect(); String xml = FileUtils.readFile(RaTestConnectionTestCase.class, "testcon_multiple.xml"); List<ModelNode> operations = xmlToModelOperations(xml, Namespace.RESOURCEADAPTERS_1_0.getUriString(), new ResourceAdapterSubsystemParser()); executeOperation(operationListToCompositeOperation(operations)); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { remove(address); } } /** * Define the deployment * * @return The deployment archive */ @Deployment public static ResourceAdapterArchive createDeployment() throws Exception { ResourceAdapterArchive raa = ShrinkWrap.create(ResourceAdapterArchive.class, deploymentName); JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "multiple.jar"); ja.addPackage(MultipleConnectionFactory1.class.getPackage()); raa.addAsLibrary(ja); raa.addAsManifestResource(RaTestConnectionTestCase.class.getPackage(), "ra.xml", "ra.xml"); return raa; } @Test public void testConnection() throws Exception { ModelNode testAddress = address.clone(); testAddress.add("connection-definitions", "Pool1"); ModelNode op = new ModelNode(); op.get(OP).set("test-connection-in-pool"); op.get(OP_ADDR).set(testAddress); assertTrue(executeOperation(op).asBoolean()); } @Test public void flushConnections() throws Exception { ModelNode testAddress = address.clone(); testAddress.add("connection-definitions", "Pool1"); ModelNode op = new ModelNode(); op.get(OP).set("flush-idle-connection-in-pool"); op.get(OP_ADDR).set(testAddress); executeOperation(op); } }
4,928
40.771186
152
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/tests/earmultirar/EarPackagedMultiRarDeploymentTestCase.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.smoke.deployment.rar.tests.earmultirar; import static org.junit.Assert.assertNotNull; import jakarta.annotation.Resource; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.integration.management.base.AbstractMgmtTestBase; import org.jboss.as.test.smoke.deployment.rar.MultipleAdminObject1; import org.jboss.as.test.smoke.deployment.rar.MultipleAdminObject2; import org.jboss.as.test.smoke.deployment.rar.MultipleConnectionFactory1; import org.jboss.as.test.smoke.deployment.rar.MultipleConnectionFactory2; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="robert.reimann@googlemail.com">Robert Reimann</a> * Deployment of a RAR packaged inside an EAR. */ @RunWith(Arquillian.class) public class EarPackagedMultiRarDeploymentTestCase { /** * Define the deployment * * @return The deployment archive */ @Deployment public static EnterpriseArchive createDeployment() throws Exception { String deploymentName = "ear_packaged.ear"; String subDeploymentName = "ear_packaged.rar"; String subDeploymentName2 = "ear_packaged2.rar"; ResourceAdapterArchive raa = ShrinkWrap.create(ResourceAdapterArchive.class, subDeploymentName); raa.addAsManifestResource(EarPackagedMultiRarDeploymentTestCase.class.getPackage(), "ra.xml", "ra.xml") .addAsManifestResource(EarPackagedMultiRarDeploymentTestCase.class.getPackage(), "ironjacamar.xml", "ironjacamar.xml"); ResourceAdapterArchive raa2 = ShrinkWrap.create(ResourceAdapterArchive.class, subDeploymentName2); raa2.addAsManifestResource(EarPackagedMultiRarDeploymentTestCase.class.getPackage(), "ra2.xml", "ra.xml") .addAsManifestResource(EarPackagedMultiRarDeploymentTestCase.class.getPackage(), "ironjacamar2.xml", "ironjacamar.xml"); final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, deploymentName); JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "multiple.jar"); ja.addPackage(MultipleConnectionFactory1.class.getPackage()). addClasses(EarPackagedMultiRarDeploymentTestCase.class); ja.addPackage(AbstractMgmtTestBase.class.getPackage()); ear.addAsLibrary(ja); ear.addAsModule(raa); ear.addAsModule(raa2); ear.addAsManifestResource(EarPackagedMultiRarDeploymentTestCase.class.getPackage(), "application.xml", "application.xml"); return ear; } @Resource(mappedName = "java:jboss/name3") private MultipleConnectionFactory1 connectionFactory1; @Resource(mappedName = "java:jboss/Name5") private MultipleAdminObject1 adminObject1; @Resource(mappedName = "java:jboss/name2") private MultipleConnectionFactory2 connectionFactory2; @Resource(mappedName = "java:jboss/Name4") private MultipleAdminObject2 adminObject2; /** * Test configuration * * @throws Throwable Thrown if case of an error */ @Test public void testConfiguration() throws Throwable { assertNotNull("CF1 not found", connectionFactory1); assertNotNull("AO1 not found", adminObject1); assertNotNull("CF2 not found", connectionFactory2); assertNotNull("AO2 not found", adminObject2); } }
4,659
38.82906
136
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/tests/configproperty/ConfigPropertyTestCase.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.smoke.deployment.rar.tests.configproperty; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import javax.naming.Context; import javax.naming.InitialContext; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.base.AbstractMgmtServerSetupTask; import org.jboss.as.test.integration.management.base.AbstractMgmtTestBase; import org.jboss.as.test.smoke.deployment.rar.configproperty.ConfigPropertyAdminObjectInterface; import org.jboss.as.test.smoke.deployment.rar.configproperty.ConfigPropertyConnection; import org.jboss.as.test.smoke.deployment.rar.configproperty.ConfigPropertyConnectionFactory; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="vrastsel@redhat.com">Vladimir Rastseluev</a> * @author <a href="stefano.maestri@redhat.com">Stefano Maestri</a> * Test case for AS7-1452: Resource Adapter config-property value passed incorrectly */ @RunWith(Arquillian.class) @ServerSetup(ConfigPropertyTestCase.ConfigPropertyTestClassSetup.class) public class ConfigPropertyTestCase { /** * Class that performs setup before the deployment is deployed */ static class ConfigPropertyTestClassSetup extends AbstractMgmtServerSetupTask { @Override public void doSetup(final ManagementClient managementClient) throws Exception { final ModelNode address = new ModelNode(); address.add("subsystem", "resource-adapters"); address.add("resource-adapter", "as7_1452.rar"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("add"); operation.get(OP_ADDR).set(address); operation.get("archive").set("as7_1452.rar"); operation.get("transaction-support").set("NoTransaction"); executeOperation(operation); final ModelNode addressConfigRes = address.clone(); addressConfigRes.add("config-properties", "Property"); addressConfigRes.protect(); final ModelNode operationConfigRes = new ModelNode(); operationConfigRes.get(OP).set("add"); operationConfigRes.get(OP_ADDR).set(addressConfigRes); operationConfigRes.get("value").set("A"); executeOperation(operationConfigRes); final ModelNode addressAdmin = address.clone(); addressAdmin.add("admin-objects", "java:jboss/ConfigPropertyAdminObjectInterface1"); addressAdmin.protect(); final ModelNode operationAdmin = new ModelNode(); operationAdmin.get(OP).set("add"); operationAdmin.get(OP_ADDR).set(addressAdmin); operationAdmin.get("class-name").set("org.jboss.as.test.smoke.deployment.rar.configproperty.ConfigPropertyAdminObjectImpl"); operationAdmin.get("jndi-name").set(AO_JNDI_NAME); executeOperation(operationAdmin); final ModelNode addressConfigAdm = addressAdmin.clone(); addressConfigAdm.add("config-properties", "Property"); addressConfigAdm.protect(); final ModelNode operationConfigAdm = new ModelNode(); operationConfigAdm.get(OP).set("add"); operationConfigAdm.get(OP_ADDR).set(addressConfigAdm); operationConfigAdm.get("value").set("C"); executeOperation(operationConfigAdm); final ModelNode addressConn = address.clone(); addressConn.add("connection-definitions", "java:jboss/ConfigPropertyConnectionFactory1"); addressConn.protect(); final ModelNode operationConn = new ModelNode(); operationConn.get(OP).set("add"); operationConn.get(OP_ADDR).set(addressConn); operationConn.get("class-name").set("org.jboss.as.test.smoke.deployment.rar.configproperty.ConfigPropertyManagedConnectionFactory"); operationConn.get("jndi-name").set(CF_JNDI_NAME); operationConn.get("pool-name").set("ConfigPropertyConnectionFactory"); executeOperation(operationConn); final ModelNode addressConfigConn = addressConn.clone(); addressConfigConn.add("config-properties", "Property"); addressConfigConn.protect(); final ModelNode operationConfigConn = new ModelNode(); operationConfigConn.get(OP).set("add"); operationConfigConn.get(OP_ADDR).set(addressConfigConn); operationConfigConn.get("value").set("B"); executeOperation(operationConfigConn); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { final ModelNode address = new ModelNode(); address.add("subsystem", "resource-adapters"); address.add("resource-adapter", "as7_1452.rar"); address.protect(); remove(address); } } /** * Define the deployment * * @return The deployment archive */ @Deployment public static ResourceAdapterArchive createDeployment() throws Exception { String deploymentName = "as7_1452.rar"; ResourceAdapterArchive raa = ShrinkWrap.create(ResourceAdapterArchive.class, deploymentName); JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "as7_1452.jar"); ja.addPackage("org.jboss.as.test.smoke.deployment.rar.configproperty") .addClasses(ConfigPropertyTestCase.class); ja.addPackage(AbstractMgmtTestBase.class.getPackage()); // needed to process the @ServerSetup annotation on the server side raa.addAsLibrary(ja); raa.addAsManifestResource(ConfigPropertyTestCase.class.getPackage(), "ra.xml", "ra.xml"); return raa; } /** * CF */ private static final String CF_JNDI_NAME = "java:jboss/ConfigPropertyConnectionFactory1"; /** * AO */ private static final String AO_JNDI_NAME = "java:jboss/ConfigPropertyAdminObjectInterface1"; /** * Test config properties * * @throws Throwable Thrown if case of an error */ @Test public void testConfigProperties() throws Throwable { Context ctx = new InitialContext(); ConfigPropertyConnectionFactory connectionFactory = (ConfigPropertyConnectionFactory) ctx.lookup(CF_JNDI_NAME); assertNotNull(connectionFactory); ConfigPropertyAdminObjectInterface adminObject = (ConfigPropertyAdminObjectInterface) ctx.lookup(AO_JNDI_NAME); assertNotNull(adminObject); ConfigPropertyConnection connection = connectionFactory.getConnection(); assertNotNull(connection); assertEquals("A", connection.getResourceAdapterProperty()); assertEquals("B", connection.getManagedConnectionFactoryProperty()); assertEquals("C", adminObject.getProperty()); connection.close(); } }
8,587
40.487923
144
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/inflow/PureInflowActivationSpec.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar.inflow; import jakarta.resource.spi.ActivationSpec; import jakarta.resource.spi.InvalidPropertyException; import jakarta.resource.spi.ResourceAdapter; import org.jboss.logging.Logger; /** * PureInflowActivationSpec * * @version $Revision: $ */ public class PureInflowActivationSpec implements ActivationSpec { /** * The logger */ private static Logger log = Logger.getLogger(PureInflowActivationSpec.class); /** * The resource adapter */ private ResourceAdapter ra; /** * Default constructor */ public PureInflowActivationSpec() { } /** * This method may be called by a deployment tool to validate the overall * activation configuration information provided by the endpoint deployer. * * @throws InvalidPropertyException indicates invalid onfiguration property settings. */ public void validate() throws InvalidPropertyException { log.trace("validate()"); } /** * Get the resource adapter * * @return The handle */ public ResourceAdapter getResourceAdapter() { log.trace("getResourceAdapter()"); return ra; } /** * Set the resource adapter * * @param ra The handle */ public void setResourceAdapter(ResourceAdapter ra) { log.trace("setResourceAdapter()"); this.ra = ra; } }
2,465
28.710843
89
java
null
wildfly-main/testsuite/integration/smoke/src/test/java/org/jboss/as/test/smoke/deployment/rar/inflow/PureInflowActivation.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.smoke.deployment.rar.inflow; import jakarta.resource.ResourceException; import jakarta.resource.spi.endpoint.MessageEndpointFactory; /** * PureInflowActivation */ public class PureInflowActivation { /** * The resource adapter */ private PureInflowResourceAdapter ra; /** * Activation spec */ private PureInflowActivationSpec spec; /** * The message endpoint factory */ private MessageEndpointFactory endpointFactory; /** * Default constructor * * @throws ResourceException Thrown if an error occurs */ public PureInflowActivation() throws ResourceException { this(null, null, null); } /** * Constructor * * @param ra PureInflowResourceAdapter * @param endpointFactory MessageEndpointFactory * @param spec PureInflowActivationSpec * @throws ResourceException Thrown if an error occurs */ public PureInflowActivation(PureInflowResourceAdapter ra, MessageEndpointFactory endpointFactory, PureInflowActivationSpec spec) throws ResourceException { this.ra = ra; this.endpointFactory = endpointFactory; this.spec = spec; } /** * Get activation spec class * * @return Activation spec */ public PureInflowActivationSpec getActivationSpec() { return spec; } /** * Get message endpoint factory * * @return Message endpoint factory */ public MessageEndpointFactory getMessageEndpointFactory() { return endpointFactory; } /** * Start the activation * * @throws ResourceException Thrown if an error occurs */ public void start() throws ResourceException { } /** * Stop the activation */ public void stop() { } }
2,971
26.775701
71
java