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/ejb/interceptor/serverside/SubstituteSampleBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ejb.interceptor.serverside;
import jakarta.ejb.Stateless;
@Stateless
public class SubstituteSampleBean implements SubstituteSampleBeanRemote {
public String getSimpleName() {
return SubstituteSampleBean.class.getSimpleName();
}
}
| 1,308 | 39.90625 | 73 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/interceptor/serverside/SubstituteInterceptor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ejb.interceptor.serverside;
import jakarta.interceptor.AroundInvoke;
import jakarta.interceptor.InvocationContext;
/**
* A simple interceptor that adds string prefix to the intercepted method return value.
*/
public class SubstituteInterceptor {
static final String PREFIX = "Intercepted:";
@AroundInvoke
public Object aroundInvoke(final InvocationContext invocationContext) throws Exception {
return PREFIX + invocationContext.proceed();
}
}
| 1,533 | 38.333333 | 92 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/IndependentBean.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.ejb.client.outbound.connection;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateless;
/**
* @author Jaikiran Pai
*/
@Stateless
@Remote(RemoteEcho.class)
public class IndependentBean implements RemoteEcho {
@Override
public String echo(String msg) {
return msg;
}
}
| 1,353 | 33.717949 | 70 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/RemoteEcho.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.ejb.client.outbound.connection;
/**
* @author Jaikiran Pai
*/
public interface RemoteEcho {
String echo(String msg);
}
| 1,187 | 37.322581 | 70 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/RemoteOutboundConnectionReconnectTestCase.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.ejb.client.outbound.connection;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.io.File;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingException;
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.test.manualmode.ejb.Util;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests that an Jakarta Enterprise Beans client context containing a reference to a remote outbound connection, has the ability to
* reconnect a failed connection
*
* @author Jaikiran Pai
* @see https://issues.jboss.org/browse/AS7-3820 for details
*/
@RunWith(Arquillian.class)
@RunAsClient
public class RemoteOutboundConnectionReconnectTestCase {
private static final Logger logger = Logger.getLogger(RemoteOutboundConnectionReconnectTestCase.class);
private static final String SERVER_ONE_MODULE_NAME = "server-one-module";
private static final String SERVER_TWO_MODULE_NAME = "server-two-module";
private static final String JBOSSAS_NON_CLUSTERED = "jbossas-non-clustered";
private static final String JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION_NON_CLUSTERED = "jbossas-with-remote-outbound-connection-non-clustered";
private static final String DEFAULT_AS_DEPLOYMENT = "default-jbossas-deployment";
private static final String DEPLOYMENT_WITH_JBOSS_EJB_CLIENT_XML = "other-deployment";
@ArquillianResource
private ContainerController container;
@ArquillianResource
private Deployer deployer;
private Context context;
@Before
public void before() throws Exception {
final Properties ejbClientProperties = setupEJBClientProperties();
this.context = Util.createNamingContext(ejbClientProperties);
}
@After
public void after() throws NamingException {
this.context.close();
}
@Deployment(name = DEFAULT_AS_DEPLOYMENT, managed = false, testable = false)
@TargetsContainer(JBOSSAS_NON_CLUSTERED)
public static Archive<?> createContainer1Deployment() {
final JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, SERVER_TWO_MODULE_NAME + ".jar");
ejbJar.addClasses(EchoOnServerTwo.class, RemoteEcho.class);
return ejbJar;
}
@Deployment(name = DEPLOYMENT_WITH_JBOSS_EJB_CLIENT_XML, managed = false, testable = false)
@TargetsContainer(JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION_NON_CLUSTERED)
public static Archive<?> createContainer2Deployment() {
final JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, SERVER_ONE_MODULE_NAME + ".jar");
ejbJar.addClasses(EchoOnServerOne.class, RemoteEcho.class, IndependentBean.class);
ejbJar.addAsManifestResource(EchoOnServerOne.class.getPackage(), "jboss-ejb-client.xml", "jboss-ejb-client.xml");
ejbJar.addAsManifestResource(
createPermissionsXmlAsset(
new FilePermission(System.getProperty("jboss.home") + File.separatorChar + "standalone" + File.separatorChar + "tmp" + File.separatorChar + "auth" + File.separatorChar + "-", "read")),
"permissions.xml");
return ejbJar;
}
/**
* Start a server (A) which has a remote outbound connection to another server (B). Server (B) is down.
* Deploy (X) to server A. X contains a jboss-ejb-client.xml pointing to server B (which is down). The deployment
* must succeed. However invocations on beans which depend on server B should fail.
* Then start server B and deploy Y to it. Invoke again on server A beans which depend on server B and this time
* they should pass
*
* @throws Exception
*/
@Test
public void testRemoteServerStartsLate() throws Exception {
// First start the server which has a remote-outbound-connection
this.container.start(JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION_NON_CLUSTERED);
boolean defaultContainerStarted = false;
try {
// deploy a deployment which contains jboss-ejb-client.xml that contains an Jakarta Enterprise Beans receiver pointing
// to a server which hasn't yet started. Should succeed without throwing deployment error
this.deployer.deploy(DEPLOYMENT_WITH_JBOSS_EJB_CLIENT_XML);
// To make sure deployment succeeded and invocations are possible, call an independent bean
final RemoteEcho independentBean = (RemoteEcho) context.lookup("ejb:/" + SERVER_ONE_MODULE_NAME + "//" + IndependentBean.class.getSimpleName() + "!" + RemoteEcho.class.getName());
final String msg = "Hellooooo!";
final String echoFromIndependentBean = independentBean.echo(msg);
Assert.assertEquals("Unexpected echo from independent bean", msg, echoFromIndependentBean);
// now try invoking the Jakarta Enterprise Beans (which calls a delegate bean on other server) on this server.
// should fail with no Jakarta Enterprise Beans receivers, since the other server
// which can handle the delegate bean invocation hasn't yet started.
try {
final RemoteEcho dependentBean = (RemoteEcho) context.lookup("ejb:/" + SERVER_ONE_MODULE_NAME + "//" + EchoOnServerOne.class.getSimpleName() + "!" + RemoteEcho.class.getName());
final String echoBeforeOtherServerStart = dependentBean.echo(msg);
Assert.fail("Invocation on bean when was expected to fail due to other server being down");
} catch (Exception e) {
// expected
logger.trace("Got the expected exception on invoking a bean when other server was down", e);
}
// now start the main server
this.container.start(JBOSSAS_NON_CLUSTERED);
defaultContainerStarted = true;
// deploy to this container
this.deployer.deploy(DEFAULT_AS_DEPLOYMENT);
// now invoke the Jakarta Enterprise Beans (which had failed earlier)
final RemoteEcho dependentBean = (RemoteEcho) context.lookup("ejb:/" + SERVER_ONE_MODULE_NAME + "//" + EchoOnServerOne.class.getSimpleName() + "!" + RemoteEcho.class.getName());
final String echoAfterOtherServerStarted = dependentBean.echo(msg);
Assert.assertEquals("Unexpected echo from bean", EchoOnServerTwo.ECHO_PREFIX + msg, echoAfterOtherServerStarted);
} finally {
try {
this.deployer.undeploy(DEPLOYMENT_WITH_JBOSS_EJB_CLIENT_XML);
this.container.stop(JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION_NON_CLUSTERED);
} catch (Exception e) {
logger.debug("Exception during container shutdown", e);
}
if (defaultContainerStarted) {
try {
this.deployer.undeploy(DEFAULT_AS_DEPLOYMENT);
this.container.stop(JBOSSAS_NON_CLUSTERED);
} catch (Exception e) {
logger.debug("Exception during container shutdown", e);
}
}
}
}
/**
* Start a server (A) which has a remote outbound connection to another server (B). Also start Server (B).
* Deploy (X) to server A. X contains a jboss-ejb-client.xml pointing to server B. The deployment and invocations
* must succeed.
* Now stop server (B). Invoke again on the bean. Invocation should fail since server B is down. Now
* restart server B and invoke again on the bean. Invocation should pass since the Jakarta Enterprise Beans client context is
* expected to reconnect to the restarted server B.
*
* @throws Exception
*/
@Test
public void testRemoteServerRestarts() throws Exception {
// Start the main server
this.container.start(JBOSSAS_NON_CLUSTERED);
// deploy to this container
this.deployer.deploy(DEFAULT_AS_DEPLOYMENT);
// Now start the server which has a remote-outbound-connection
this.container.start(JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION_NON_CLUSTERED);
this.deployer.deploy(DEPLOYMENT_WITH_JBOSS_EJB_CLIENT_XML);
boolean defaultContainerStarted = true;
try {
// To make sure deployment succeeded and invocations are possible, call an independent bean
final RemoteEcho independentBean = (RemoteEcho) context.lookup("ejb:/" + SERVER_ONE_MODULE_NAME + "//" + IndependentBean.class.getSimpleName() + "!" + RemoteEcho.class.getName());
final String msg = "Hellooooo!";
final String echoFromIndependentBean = independentBean.echo(msg);
Assert.assertEquals("Unexpected echo from independent bean", msg, echoFromIndependentBean);
// now try invoking the Jakarta Enterprise Beans (which calls a delegate bean on other server) on this server.
// should fail with no Jakarta Enterprise Beans receivers, since the other server
// which can handle the delegate bean invocation hasn't yet started.
final RemoteEcho dependentBean = (RemoteEcho) context.lookup("ejb:/" + SERVER_ONE_MODULE_NAME + "//" + EchoOnServerOne.class.getSimpleName() + "!" + RemoteEcho.class.getName());
final String echoBeforeShuttingDownServer = dependentBean.echo(msg);
Assert.assertEquals("Unexpected echo from bean", EchoOnServerTwo.ECHO_PREFIX + msg, echoBeforeShuttingDownServer);
// now stop the main server
this.container.stop(JBOSSAS_NON_CLUSTERED);
defaultContainerStarted = false;
try {
final String echoAfterServerShutdown = dependentBean.echo(msg);
Assert.fail("Invocation on bean when was expected to fail due to other server being down");
} catch (Exception e) {
// expected
logger.trace("Got the expected exception on invoking a bean when other server was down", e);
}
// now restart the main server
this.container.start(JBOSSAS_NON_CLUSTERED);
defaultContainerStarted = true;
final String echoAfterServerRestart = dependentBean.echo(msg);
Assert.assertEquals("Unexpected echo from bean after server restart", EchoOnServerTwo.ECHO_PREFIX + msg, echoAfterServerRestart);
} finally {
try {
this.deployer.undeploy(DEPLOYMENT_WITH_JBOSS_EJB_CLIENT_XML);
this.container.stop(JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION_NON_CLUSTERED);
} catch (Exception e) {
logger.debug("Exception during container shutdown", e);
}
if (defaultContainerStarted) {
try {
this.deployer.undeploy(DEFAULT_AS_DEPLOYMENT);
this.container.stop(JBOSSAS_NON_CLUSTERED);
} catch (Exception e) {
logger.debug("Exception during container shutdown", e);
}
}
}
}
/**
* Sets up the Jakarta Enterprise Beans client properties based on this testcase specific jboss-ejb-client.properties file
*
* @return
* @throws java.io.IOException
*/
private static Properties setupEJBClientProperties() throws IOException {
// setup the properties
final String clientPropertiesFile = "org/jboss/as/test/manualmode/ejb/client/outbound/connection/jboss-ejb-client.properties";
final InputStream inputStream = RemoteOutboundConnectionReconnectTestCase.class.getClassLoader().getResourceAsStream(clientPropertiesFile);
if (inputStream == null) {
throw new IllegalStateException("Could not find " + clientPropertiesFile + " in classpath");
}
final Properties properties = new Properties();
properties.load(inputStream);
return properties;
}
}
| 13,685 | 49.131868 | 208 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/EchoOnServerTwo.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.ejb.client.outbound.connection;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateless;
/**
* @author Jaikiran Pai
*/
@Stateless
@Remote(RemoteEcho.class)
public class EchoOnServerTwo implements RemoteEcho {
public static final String ECHO_PREFIX = "ServerTwo ";
@Override
public String echo(String msg) {
return ECHO_PREFIX + msg;
}
}
| 1,427 | 33.829268 | 70 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/EchoOnServerOne.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.ejb.client.outbound.connection;
import jakarta.ejb.EJB;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateless;
/**
* @author Jaikiran Pai
*/
@Stateless
@Remote(RemoteEcho.class)
public class EchoOnServerOne implements RemoteEcho {
@EJB (lookup = "ejb:/server-two-module//EchoOnServerTwo!org.jboss.as.test.manualmode.ejb.client.outbound.connection.RemoteEcho")
private RemoteEcho echoOnServerTwo;
@Override
public String echo(String msg) {
return this.echoOnServerTwo.echo(msg);
}
}
| 1,578 | 35.72093 | 132 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/security/ServerWhoAmI.java
|
package org.jboss.as.test.manualmode.ejb.client.outbound.connection.security;
import org.jboss.ejb3.annotation.SecurityDomain;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Stateless;
/**
* @author <a href="mailto:[email protected]">Michal Jurc</a> (c) 2017 Red Hat, Inc.
*/
@Stateless
@SecurityDomain("ejb-remote-tests")
@PermitAll
public class ServerWhoAmI implements WhoAmI {
@Resource
private SessionContext ctx;
public String whoAmI() {
return ctx.getCallerPrincipal().getName();
}
@RolesAllowed("admin")
public String whoAmIRestricted() {
return ctx.getCallerPrincipal().getName();
}
}
| 783 | 23.5 | 83 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/security/ElytronRemoteOutboundConnectionTestCase.java
|
package org.jboss.as.test.manualmode.ejb.client.outbound.connection.security;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST;
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.OPERATION_HEADERS;
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.PLAIN_TEXT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PORT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REALM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOTE_DESTINATION_OUTBOUND_SOCKET_BINDING;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SASL_AUTHENTICATION_FACTORY;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SECURITY_REALM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SSL_CONTEXT;
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 java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.security.Provider;
import java.util.Properties;
import jakarta.ejb.NoSuchEJBException;
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.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.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
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.ejb.client.EJBClientConnection;
import org.jboss.ejb.client.EJBClientContext;
import org.jboss.ejb.protocol.remote.RemoteTransportProvider;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.naming.client.WildFlyInitialContextFactory;
import org.wildfly.security.WildFlyElytronProvider;
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.sasl.SaslMechanismSelector;
import org.wildfly.test.api.Authentication;
/**
* Test case pertaining to remote outbound connection authentication between two server instances using remote-outbound-connection
* management resource with Elytron authentication context.
*
* @author <a href="mailto:[email protected]">Michal Jurc</a> (c) 2017 Red Hat, Inc.
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ElytronRemoteOutboundConnectionTestCase {
private static final Logger log = Logger.getLogger(ElytronRemoteOutboundConnectionTestCase.class);
private static final String INBOUND_CONNECTION_MODULE_NAME = "inbound-module";
private static final String OUTBOUND_CONNECTION_MODULE_NAME = "outbound-module";
private static final String INBOUND_CONNECTION_SERVER = "inbound-server";
private static final String OUTBOUND_CONNECTION_SERVER = "outbound-server";
private static final String EJB_SERVER_DEPLOYMENT = "ejb-server-deployment";
private static final String EJB_CLIENT_DEPLOYMENT = "ejb-client-deployment";
private static final String RESOURCE_PREFIX = "ejb-remote-tests";
private static final String PROPERTIES_REALM = RESOURCE_PREFIX + "-properties-realm";
private static final String SECURITY_DOMAIN = RESOURCE_PREFIX + "-security-domain";
private static final String AUTHENTICATION_FACTORY = RESOURCE_PREFIX + "-sasl-authentication";
private static final String APPLICATION_SECURITY_DOMAIN = RESOURCE_PREFIX;
private static final String INBOUND_SOCKET_BINDING = RESOURCE_PREFIX + "-socket-binding";
private static final String CONNECTOR = RESOURCE_PREFIX + "-connector";
private static final String OUTBOUND_SOCKET_BINDING = RESOURCE_PREFIX + "-outbound-socket-binding";
private static final String DEFAULT_AUTH_CONFIG = RESOURCE_PREFIX + "-default-auth-config";
private static final String DEFAULT_AUTH_CONTEXT = RESOURCE_PREFIX + "-default-auth-context";
private static final String OVERRIDING_AUTH_CONFIG = RESOURCE_PREFIX + "-overriding-auth-config";
private static final String OVERRIDING_AUTH_CONTEXT = RESOURCE_PREFIX + "-overriding-auth-context";
private static final String REMOTE_OUTBOUND_CONNECTION = RESOURCE_PREFIX + "-remote-outbound-connection";
private static final String SERVER_KEY_STORE = RESOURCE_PREFIX + "-server-key-store";
private static final String SERVER_KEY_MANAGER = RESOURCE_PREFIX + "-server-key-manager";
private static final String SERVER_TRUST_STORE = RESOURCE_PREFIX + "-server-trust-store";
private static final String SERVER_TRUST_MANAGER = RESOURCE_PREFIX + "-server-trust-manager";
private static final String SERVER_SSL_CONTEXT = RESOURCE_PREFIX + "-server-ssl-context";
private static final String DEFAULT_KEY_STORE = RESOURCE_PREFIX + "-default-key-store";
private static final String DEFAULT_KEY_MANAGER = RESOURCE_PREFIX + "-default-key-manager";
private static final String DEFAULT_TRUST_STORE = RESOURCE_PREFIX + "-default-trust-store";
private static final String DEFAULT_TRUST_MANAGER = RESOURCE_PREFIX + "-default-trust-manager";
private static final String DEFAULT_SERVER_SSL_CONTEXT = RESOURCE_PREFIX + "-default-server-ssl-context";
private static final String OVERRIDING_KEY_STORE = RESOURCE_PREFIX + "-overriding-key-store";
private static final String OVERRIDING_KEY_MANAGER = RESOURCE_PREFIX + "-overriding-key-manager";
private static final String OVERRIDING_TRUST_STORE = RESOURCE_PREFIX + "-overriding-trust-store";
private static final String OVERRIDING_TRUST_MANAGER = RESOURCE_PREFIX + "-overriding-trust-manager";
private static final String OVERRIDING_SERVER_SSL_CONTEXT = RESOURCE_PREFIX + "-overriding-server-ssl-context";
private static final String DEFAULT_USERNAME = "ejbRemoteTests";
private static final String DEFAULT_PASSWORD = "ejbRemoteTestsPassword";
private static final String OVERRIDING_USERNAME = "ejbRemoteTestsOverriding";
private static final String OVERRIDING_PASSWORD = "ejbRemoteTestsPasswordOverriding";
private static final String AGGREGATE_ROLE_DECODER = "aggregateRoleDecoder";
private static final String DECODER_1 = "decoder1";
private static final String DECODER_2 = "decoder2";
private static final String IP_PERMISSION_MAPPER = "ipPermissionMapper";
private static final String KEY_STORE_KEYPASS = SecurityTestConstants.KEYSTORE_PASSWORD;
private static final File WORKDIR = new File(new File("").getAbsoluteFile().getAbsolutePath() + File.separatorChar + "target"
+ File.separatorChar + RESOURCE_PREFIX);
private static final String SERVER_KEY_STORE_PATH = new File(WORKDIR.getAbsoluteFile(), SecurityTestConstants.SERVER_KEYSTORE)
.getAbsolutePath();
private static final String SERVER_TRUST_STORE_PATH = new File(WORKDIR.getAbsoluteFile(), SecurityTestConstants.SERVER_TRUSTSTORE)
.getAbsolutePath();
private static final String CLIENT_KEY_STORE_PATH = new File(WORKDIR.getAbsoluteFile(), SecurityTestConstants.CLIENT_KEYSTORE)
.getAbsolutePath();
private static final String CLIENT_TRUST_STORE_PATH = new File(WORKDIR.getAbsoluteFile(), SecurityTestConstants.CLIENT_TRUSTSTORE)
.getAbsolutePath();
private static final String UNTRUSTED_KEY_STORE_PATH = new File(WORKDIR.getAbsoluteFile(), SecurityTestConstants.UNTRUSTED_KEYSTORE)
.getAbsolutePath();
private static final String USERS_PATH = new File(ElytronRemoteOutboundConnectionTestCase.class.getResource("users.properties").
getFile()).getAbsolutePath();
private static final String ROLES_PATH = new File(ElytronRemoteOutboundConnectionTestCase.class.getResource("roles.properties").
getFile()).getAbsolutePath();
private static final int BARE_REMOTING_PORT = 54447;
private static final String BARE_REMOTING_PROTOCOL = "remote";
private static final int SSL_REMOTING_PORT = 54448;
private static final String SSL_REMOTING_PROTOCOL = "remote";
private static final int HTTP_REMOTING_PORT = 8080;
private static final String HTTP_REMOTING_PROTOCOL = "http-remoting";
private static final int HTTPS_REMOTING_PORT = 8443;
private static final String HTTPS_REMOTING_PROTOCOL = "https-remoting";
@ArquillianResource
private static ContainerController containerController;
private static ModelControllerClient serverSideMCC;
private static ModelControllerClient clientSideMCC;
@ArquillianResource
private Deployer deployer;
@Deployment(name = EJB_SERVER_DEPLOYMENT, managed = false, testable = false)
@TargetsContainer(INBOUND_CONNECTION_SERVER)
public static Archive<?> createEjbServerDeployment() {
final JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, INBOUND_CONNECTION_MODULE_NAME + ".jar");
ejbJar.addClass(WhoAmI.class)
.addClass(ServerWhoAmI.class);
return ejbJar;
}
@Deployment(name = EJB_CLIENT_DEPLOYMENT, managed = false, testable = false)
@TargetsContainer(OUTBOUND_CONNECTION_SERVER)
public static Archive<?> createEjbClientDeployment() {
final JavaArchive ejbClientJar = ShrinkWrap.create(JavaArchive.class, OUTBOUND_CONNECTION_MODULE_NAME + ".jar");
ejbClientJar.addClass(WhoAmI.class)
.addClass(IntermediateWhoAmI.class)
.addAsManifestResource(IntermediateWhoAmI.class.getPackage(), "jboss-ejb-client.xml", "jboss-ejb-client.xml");
return ejbClientJar;
}
@BeforeClass
public static void prepareSSLFiles() {
WORKDIR.mkdirs();
try {
Utils.createKeyMaterial(WORKDIR);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Before
public void startContainers() {
if (!containerController.isStarted(INBOUND_CONNECTION_SERVER)){
containerController.start(INBOUND_CONNECTION_SERVER);
}
if (!containerController.isStarted(OUTBOUND_CONNECTION_SERVER)){
containerController.start(OUTBOUND_CONNECTION_SERVER);
}
serverSideMCC = getInboundConnectionServerMCC();
clientSideMCC = getOutboundConnectionServerMCC();
}
@After
public void cleanResources()throws Exception {
deployer.undeploy(EJB_CLIENT_DEPLOYMENT);
deployer.undeploy(EJB_SERVER_DEPLOYMENT);
//==================================
// Client-side server tear down
//==================================
boolean clientReloadRequired = false;
ModelNode result;
try {
result = clientSideMCC.execute(Util.getReadAttributeOperation(PathAddress.pathAddress(SUBSYSTEM, "elytron"),
"default-authentication-context"));
} catch (IOException e) {
throw new RuntimeException(e);
}
if (result != null && result.hasDefined(RESULT)) {
applyUpdate(clientSideMCC, Util.getUndefineAttributeOperation(PathAddress.pathAddress(SUBSYSTEM, "elytron"),
"default-authentication-context"));
clientReloadRequired = true;
}
applyUpdate(clientSideMCC, getEjbConnectorOp("list-remove", CONNECTOR));
executeBlockingReloadClientServer(clientSideMCC);
removeIfExists(clientSideMCC, getConnectionAddress(REMOTE_OUTBOUND_CONNECTION), !clientReloadRequired);
removeIfExists(clientSideMCC, getAuthenticationContextAddress(DEFAULT_AUTH_CONTEXT), !clientReloadRequired);
removeIfExists(clientSideMCC, getServerSSLContextAddress(DEFAULT_SERVER_SSL_CONTEXT), !clientReloadRequired);
removeIfExists(clientSideMCC, getTrustManagerAddress(DEFAULT_TRUST_MANAGER), !clientReloadRequired);
removeIfExists(clientSideMCC, getKeyStoreAddress(DEFAULT_TRUST_STORE), !clientReloadRequired);
removeIfExists(clientSideMCC, getKeyManagerAddress(DEFAULT_KEY_MANAGER), !clientReloadRequired);
removeIfExists(clientSideMCC, getKeyStoreAddress(DEFAULT_KEY_STORE), !clientReloadRequired);
removeIfExists(clientSideMCC, getAuthenticationConfigurationAddress(DEFAULT_AUTH_CONFIG), !clientReloadRequired);
removeIfExists(clientSideMCC, getAuthenticationContextAddress(OVERRIDING_AUTH_CONTEXT), !clientReloadRequired);
removeIfExists(clientSideMCC, getServerSSLContextAddress(OVERRIDING_SERVER_SSL_CONTEXT), !clientReloadRequired);
removeIfExists(clientSideMCC, getTrustManagerAddress(OVERRIDING_TRUST_MANAGER), !clientReloadRequired);
removeIfExists(clientSideMCC, getKeyStoreAddress(OVERRIDING_TRUST_STORE), !clientReloadRequired);
removeIfExists(clientSideMCC, getKeyManagerAddress(OVERRIDING_KEY_MANAGER), !clientReloadRequired);
removeIfExists(clientSideMCC, getKeyStoreAddress(OVERRIDING_KEY_STORE), !clientReloadRequired);
removeIfExists(clientSideMCC, getAuthenticationConfigurationAddress(OVERRIDING_AUTH_CONFIG), !clientReloadRequired);
removeIfExists(clientSideMCC, getOutboundSocketBindingAddress(OUTBOUND_SOCKET_BINDING), !clientReloadRequired);
if (clientReloadRequired) {
executeBlockingReloadClientServer(clientSideMCC);
}
//==================================
// Server-side server tear down
//==================================
if (!executeReadAttributeOpReturnResult(serverSideMCC, getHttpConnectorAddress("http-remoting-connector"), SASL_AUTHENTICATION_FACTORY)
.equals("application-sasl-authentication")) {
applyUpdate(serverSideMCC, Util.getWriteAttributeOperation(getHttpConnectorAddress("http-remoting-connector"),
SASL_AUTHENTICATION_FACTORY, "application-sasl-authentication"));
}
Operations.CompositeOperationBuilder compositeBuilder = Operations.CompositeOperationBuilder.create();
String defaultHttpsListenerSSLContext = executeReadAttributeOpReturnResult(serverSideMCC, getDefaultHttpsListenerAddress(), SSL_CONTEXT);
if (!(defaultHttpsListenerSSLContext == null) && !defaultHttpsListenerSSLContext.isEmpty()) {
ModelNode update = Util.getUndefineAttributeOperation(getDefaultHttpsListenerAddress(), SSL_CONTEXT);
update.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
compositeBuilder.addStep(update);
}
ModelNode update = Util.getWriteAttributeOperation(getDefaultHttpsListenerAddress(), "ssl-context", "applicationSSC");
update.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
compositeBuilder.addStep(update);
applyUpdate(serverSideMCC, compositeBuilder.build().getOperation());
applyUpdate(serverSideMCC, getEjbConnectorOp("list-remove", CONNECTOR));
ServerReload.reloadIfRequired(serverSideMCC); // this use is ok; the server is on the standard address/port
removeIfExists(serverSideMCC, getConnectorAddress(CONNECTOR));
removeIfExists(serverSideMCC, getHttpConnectorAddress(CONNECTOR));
removeIfExists(serverSideMCC, getServerSSLContextAddress(SERVER_SSL_CONTEXT), false);
removeIfExists(serverSideMCC, getTrustManagerAddress(SERVER_TRUST_MANAGER));
removeIfExists(serverSideMCC, getKeyStoreAddress(SERVER_TRUST_STORE));
removeIfExists(serverSideMCC, getKeyManagerAddress(SERVER_KEY_MANAGER));
removeIfExists(serverSideMCC, getKeyStoreAddress(SERVER_KEY_STORE));
removeIfExists(serverSideMCC, getSocketBindingAddress(INBOUND_SOCKET_BINDING));
removeIfExists(serverSideMCC, getEjbApplicationSecurityDomainAddress(APPLICATION_SECURITY_DOMAIN));
removeIfExists(serverSideMCC, getSaslAuthenticationFactoryAddress(AUTHENTICATION_FACTORY));
removeIfExists(serverSideMCC, getElytronSecurityDomainAddress(SECURITY_DOMAIN));
removeIfExists(serverSideMCC, getPropertiesRealmAddress(PROPERTIES_REALM));
removeIfExists(serverSideMCC, getElytronAggregateRoleDecoderAddress(AGGREGATE_ROLE_DECODER));
removeIfExists(serverSideMCC, getElytronSourceAddressRoleDecoderAddress(DECODER_1));
removeIfExists(serverSideMCC, getElytronSourceAddressRoleDecoderAddress(DECODER_2));
removeIfExists(serverSideMCC, getElytronPermissionMapperAddress(IP_PERMISSION_MAPPER));
//noinspection deprecation
ServerReload.reloadIfRequired(serverSideMCC); // this use is ok; the server is on the standard address/port
try {
clientSideMCC.close();
serverSideMCC.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@AfterClass
public static void shutdownContainers() {
if (containerController.isStarted(INBOUND_CONNECTION_SERVER)) {
containerController.stop(INBOUND_CONNECTION_SERVER);
}
if (containerController.isStarted(OUTBOUND_CONNECTION_SERVER)) {
containerController.stop(OUTBOUND_CONNECTION_SERVER);
}
cleanFile(WORKDIR);
}
private static String getIPAddress() throws IllegalStateException {
try {
return InetAddress.getByName(TestSuiteEnvironment.getServerAddress()).getHostAddress();
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
}
/**
* Test verifying that the authentication context host configuration overwrites host configuration in socket binding in remote
* outbound connection referenced from deployment.
*
* The test uses remoting protocol.
*/
@Test
public void testAuthenticationHostConfigWithBareRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundBareRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddressNode1(),
54321));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, BARE_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, DEFAULT_PASSWORD, TestSuiteEnvironment.getServerAddress(), BARE_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, ""));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(DEFAULT_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that if no legacy security is used in remoting outbound connection referenced from deployment and no Elytron
* authentication context is used, the connection will fall back to using Elytron default authentication context.
*
* The test uses remoting protocol.
*/
@Test
public void testElytronDefaultContextWithBareRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundBareRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
BARE_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, BARE_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, DEFAULT_PASSWORD));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, ""));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(DEFAULT_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that the authentication context defined in remote outbound connection referenced from deployment overrides the
* Elytron default authentication context.
*
* The test uses remoting protocol.
*/
@Test
public void testOverridingElytronDefaultContextWithBareRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundBareRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
BARE_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, BARE_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, DEFAULT_PASSWORD));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(OVERRIDING_AUTH_CONFIG, BARE_REMOTING_PROTOCOL, PROPERTIES_REALM,
OVERRIDING_USERNAME, OVERRIDING_PASSWORD));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(OVERRIDING_AUTH_CONTEXT, OVERRIDING_AUTH_CONFIG));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, OVERRIDING_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(OVERRIDING_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that authentication context defined in remote outbound connection referenced from deployment is sufficient and
* no Elytron default authentication context is required.
*
* The test uses remoting protocol.
*/
@Test
public void testConnectionContextWithBareRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundBareRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
BARE_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(OVERRIDING_AUTH_CONFIG, BARE_REMOTING_PROTOCOL, PROPERTIES_REALM,
OVERRIDING_USERNAME, OVERRIDING_PASSWORD));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(OVERRIDING_AUTH_CONTEXT, OVERRIDING_AUTH_CONFIG));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, OVERRIDING_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(OVERRIDING_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that the authentication context host configuration overwrites host configuration in socket binding in remote
* outbound connection referenced from deployment.
*
* The test uses remoting protocol with two-side SSL authentication being enforced.
*/
@Test
public void testAuthenticationHostConfigWithSSLRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundSSLRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddressNode1(),
54321));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, SSL_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, DEFAULT_PASSWORD, TestSuiteEnvironment.getServerAddress(), SSL_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddKeyStoreOp(DEFAULT_KEY_STORE, CLIENT_KEY_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyManagerOp(DEFAULT_KEY_MANAGER, DEFAULT_KEY_STORE, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyStoreOp(DEFAULT_TRUST_STORE, CLIENT_TRUST_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddTrustManagerOp(DEFAULT_TRUST_MANAGER, DEFAULT_TRUST_STORE));
applyUpdate(clientSideMCC, getAddServerSSLContextOp(DEFAULT_SERVER_SSL_CONTEXT, DEFAULT_KEY_MANAGER, DEFAULT_TRUST_MANAGER));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG, DEFAULT_SERVER_SSL_CONTEXT));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, ""));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(DEFAULT_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that if no legacy security is used in remoting outbound connection referenced from deployment and no Elytron
* authentication context is used, the connection will fall back to using Elytron default authentication context.
*
* The test uses remoting protocol with two-side SSL authentication being enforced.
*/
@Test
public void testElytronDefaultContextWithSSLRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundSSLRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
SSL_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, SSL_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, DEFAULT_PASSWORD, TestSuiteEnvironment.getServerAddress(), SSL_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddKeyStoreOp(DEFAULT_KEY_STORE, CLIENT_KEY_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyManagerOp(DEFAULT_KEY_MANAGER, DEFAULT_KEY_STORE, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyStoreOp(DEFAULT_TRUST_STORE, CLIENT_TRUST_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddTrustManagerOp(DEFAULT_TRUST_MANAGER, DEFAULT_TRUST_STORE));
applyUpdate(clientSideMCC, getAddServerSSLContextOp(DEFAULT_SERVER_SSL_CONTEXT, DEFAULT_KEY_MANAGER, DEFAULT_TRUST_MANAGER));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG, DEFAULT_SERVER_SSL_CONTEXT));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, ""));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(DEFAULT_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that the authentication context defined in remote outbound connection referenced from deployment overrides the
* Elytron default authentication context.
*
* The test uses remoting protocol with two-side SSL authentication being enforced.
*/
@Test
public void testOverridingElytronDefaultContextWithSSLRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundSSLRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
SSL_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, SSL_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, DEFAULT_PASSWORD, TestSuiteEnvironment.getServerAddress(), SSL_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddKeyStoreOp(DEFAULT_KEY_STORE, UNTRUSTED_KEY_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyManagerOp(DEFAULT_KEY_MANAGER, DEFAULT_KEY_STORE, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyStoreOp(DEFAULT_TRUST_STORE, UNTRUSTED_KEY_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddTrustManagerOp(DEFAULT_TRUST_MANAGER, DEFAULT_TRUST_STORE));
applyUpdate(clientSideMCC, getAddServerSSLContextOp(DEFAULT_SERVER_SSL_CONTEXT, DEFAULT_KEY_MANAGER, DEFAULT_TRUST_MANAGER));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG, DEFAULT_SERVER_SSL_CONTEXT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(OVERRIDING_AUTH_CONFIG, SSL_REMOTING_PROTOCOL, PROPERTIES_REALM,
OVERRIDING_USERNAME, OVERRIDING_PASSWORD, TestSuiteEnvironment.getServerAddress(), SSL_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddKeyStoreOp(OVERRIDING_KEY_STORE, CLIENT_KEY_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyManagerOp(OVERRIDING_KEY_MANAGER, OVERRIDING_KEY_STORE, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyStoreOp(OVERRIDING_TRUST_STORE, CLIENT_TRUST_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddTrustManagerOp(OVERRIDING_TRUST_MANAGER, OVERRIDING_TRUST_STORE));
applyUpdate(clientSideMCC, getAddServerSSLContextOp(OVERRIDING_SERVER_SSL_CONTEXT, OVERRIDING_KEY_MANAGER, OVERRIDING_TRUST_MANAGER));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(OVERRIDING_AUTH_CONTEXT, OVERRIDING_AUTH_CONFIG, OVERRIDING_SERVER_SSL_CONTEXT));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, OVERRIDING_AUTH_CONTEXT));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(OVERRIDING_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that authentication context defined in remote outbound connection referenced from deployment is sufficient and
* no Elytron default authentication context is required.
*
* The test uses remoting protocol with two-side SSL authentication being enforced.
*/
@Test
public void testConnectionContextWithSSLRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundSSLRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
SSL_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(OVERRIDING_AUTH_CONFIG, SSL_REMOTING_PROTOCOL, PROPERTIES_REALM,
OVERRIDING_USERNAME, OVERRIDING_PASSWORD, TestSuiteEnvironment.getServerAddress(), SSL_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddKeyStoreOp(OVERRIDING_KEY_STORE, CLIENT_KEY_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyManagerOp(OVERRIDING_KEY_MANAGER, OVERRIDING_KEY_STORE, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyStoreOp(OVERRIDING_TRUST_STORE, CLIENT_TRUST_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddTrustManagerOp(OVERRIDING_TRUST_MANAGER, OVERRIDING_TRUST_STORE));
applyUpdate(clientSideMCC, getAddServerSSLContextOp(OVERRIDING_SERVER_SSL_CONTEXT, OVERRIDING_KEY_MANAGER, OVERRIDING_TRUST_MANAGER));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(OVERRIDING_AUTH_CONTEXT, OVERRIDING_AUTH_CONFIG, OVERRIDING_SERVER_SSL_CONTEXT));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, OVERRIDING_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(OVERRIDING_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that the authentication context host configuration overwrites host configuration in socket binding in remote
* outbound connection referenced from deployment.
*
* The test uses http-remoting protocol.
*/
@Test
public void testAuthenticationHostConfigWithHttpRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundHttpRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddressNode1(),
54321));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, HTTP_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, DEFAULT_PASSWORD, TestSuiteEnvironment.getServerAddress(), HTTP_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, ""));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(DEFAULT_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that if no legacy security is used in remoting outbound connection referenced from deployment and no Elytron
* authentication context is used, the connection will fall back to using Elytron default authentication context.
*
* The test uses http-remoting protocol.
*/
@Test
public void testElytronDefaultContextWithHttpRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundHttpRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
HTTP_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, HTTP_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, DEFAULT_PASSWORD));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, ""));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(DEFAULT_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that the authentication context defined in remote outbound connection referenced from deployment overrides the
* Elytron default authentication context.
*
* The test uses http-remoting protocol.
*/
@Test
public void testOverridingElytronDefaultContextWithHttpRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundHttpRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
HTTP_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, HTTP_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, DEFAULT_PASSWORD));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(OVERRIDING_AUTH_CONFIG, HTTP_REMOTING_PROTOCOL, PROPERTIES_REALM,
OVERRIDING_USERNAME, OVERRIDING_PASSWORD));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(OVERRIDING_AUTH_CONTEXT, OVERRIDING_AUTH_CONFIG));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, OVERRIDING_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(OVERRIDING_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that authentication context defined in remote outbound connection referenced from deployment is sufficient and
* no Elytron default authentication context is required.
*
* The test uses http-remoting protocol.
*/
@Test
public void testConnectionContextWithHttpRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundHttpRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
HTTP_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(OVERRIDING_AUTH_CONFIG, HTTP_REMOTING_PROTOCOL, PROPERTIES_REALM,
OVERRIDING_USERNAME, OVERRIDING_PASSWORD));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(OVERRIDING_AUTH_CONTEXT, OVERRIDING_AUTH_CONFIG));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, OVERRIDING_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(OVERRIDING_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that the authentication context host configuration overwrites host configuration in socket binding in remote
* outbound connection referenced from deployment.
*
* The test uses https-remoting protocol with two-side SSL authentication being enforced.
*/
@Test
public void testAuthenticationHostConfigWithHttpsRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundHttpsRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddressNode1(),
54321));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, HTTPS_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, DEFAULT_PASSWORD, TestSuiteEnvironment.getServerAddress(), HTTPS_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddKeyStoreOp(DEFAULT_KEY_STORE, CLIENT_KEY_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyManagerOp(DEFAULT_KEY_MANAGER, DEFAULT_KEY_STORE, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyStoreOp(DEFAULT_TRUST_STORE, CLIENT_TRUST_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddTrustManagerOp(DEFAULT_TRUST_MANAGER, DEFAULT_TRUST_STORE));
applyUpdate(clientSideMCC, getAddServerSSLContextOp(DEFAULT_SERVER_SSL_CONTEXT, DEFAULT_KEY_MANAGER, DEFAULT_TRUST_MANAGER));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG, DEFAULT_SERVER_SSL_CONTEXT));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, ""));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(DEFAULT_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that if no legacy security is used in remoting outbound connection referenced from deployment and no Elytron
* authentication context is used, the connection will fall back to using Elytron default authentication context.
*
* The test uses https-remoting protocol with two-side SSL authentication being enforced.
*/
@Test
public void testElytronDefaultContextWithHttpsRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundHttpsRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
SSL_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, HTTPS_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, DEFAULT_PASSWORD, TestSuiteEnvironment.getServerAddress(), HTTPS_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddKeyStoreOp(DEFAULT_KEY_STORE, CLIENT_KEY_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyManagerOp(DEFAULT_KEY_MANAGER, DEFAULT_KEY_STORE, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyStoreOp(DEFAULT_TRUST_STORE, CLIENT_TRUST_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddTrustManagerOp(DEFAULT_TRUST_MANAGER, DEFAULT_TRUST_STORE));
applyUpdate(clientSideMCC, getAddServerSSLContextOp(DEFAULT_SERVER_SSL_CONTEXT, DEFAULT_KEY_MANAGER, DEFAULT_TRUST_MANAGER));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG, DEFAULT_SERVER_SSL_CONTEXT));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, ""));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(DEFAULT_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that the authentication context defined in remote outbound connection referenced from deployment overrides the
* Elytron default authentication context.
*
* The test uses https-remoting protocol with two-side SSL authentication being enforced.
*/
@Test
public void testOverridingElytronDefaultContextWithHttpsRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundHttpsRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
HTTPS_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, HTTPS_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, DEFAULT_PASSWORD, TestSuiteEnvironment.getServerAddress(), HTTPS_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddKeyStoreOp(DEFAULT_KEY_STORE, UNTRUSTED_KEY_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyManagerOp(DEFAULT_KEY_MANAGER, DEFAULT_KEY_STORE, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyStoreOp(DEFAULT_TRUST_STORE, UNTRUSTED_KEY_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddTrustManagerOp(DEFAULT_TRUST_MANAGER, DEFAULT_TRUST_STORE));
applyUpdate(clientSideMCC, getAddServerSSLContextOp(DEFAULT_SERVER_SSL_CONTEXT, DEFAULT_KEY_MANAGER, DEFAULT_TRUST_MANAGER));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG, DEFAULT_SERVER_SSL_CONTEXT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(OVERRIDING_AUTH_CONFIG, HTTPS_REMOTING_PROTOCOL, PROPERTIES_REALM,
OVERRIDING_USERNAME, OVERRIDING_PASSWORD, TestSuiteEnvironment.getServerAddress(), HTTPS_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddKeyStoreOp(OVERRIDING_KEY_STORE, CLIENT_KEY_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyManagerOp(OVERRIDING_KEY_MANAGER, OVERRIDING_KEY_STORE, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyStoreOp(OVERRIDING_TRUST_STORE, CLIENT_TRUST_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddTrustManagerOp(OVERRIDING_TRUST_MANAGER, OVERRIDING_TRUST_STORE));
applyUpdate(clientSideMCC, getAddServerSSLContextOp(OVERRIDING_SERVER_SSL_CONTEXT, OVERRIDING_KEY_MANAGER, OVERRIDING_TRUST_MANAGER));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(OVERRIDING_AUTH_CONTEXT, OVERRIDING_AUTH_CONFIG, OVERRIDING_SERVER_SSL_CONTEXT));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, OVERRIDING_AUTH_CONTEXT));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(OVERRIDING_USERNAME, callIntermediateWhoAmI());
}
/**
* Test verifying that authentication context defined in remote outbound connection referenced from deployment is sufficient and
* no Elytron default authentication context is required.
*
* The test uses https-remoting protocol with two-side SSL authentication being enforced.
*/
@Test
public void testConnectionContextWithHttpsRemoting() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundHttpsRemoting(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
HTTPS_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(OVERRIDING_AUTH_CONFIG, HTTPS_REMOTING_PROTOCOL, PROPERTIES_REALM,
OVERRIDING_USERNAME, OVERRIDING_PASSWORD, TestSuiteEnvironment.getServerAddress(), HTTPS_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddKeyStoreOp(OVERRIDING_KEY_STORE, CLIENT_KEY_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyManagerOp(OVERRIDING_KEY_MANAGER, OVERRIDING_KEY_STORE, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddKeyStoreOp(OVERRIDING_TRUST_STORE, CLIENT_TRUST_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(clientSideMCC, getAddTrustManagerOp(OVERRIDING_TRUST_MANAGER, OVERRIDING_TRUST_STORE));
applyUpdate(clientSideMCC, getAddServerSSLContextOp(OVERRIDING_SERVER_SSL_CONTEXT, OVERRIDING_KEY_MANAGER, OVERRIDING_TRUST_MANAGER));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(OVERRIDING_AUTH_CONTEXT, OVERRIDING_AUTH_CONFIG, OVERRIDING_SERVER_SSL_CONTEXT));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, OVERRIDING_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(OVERRIDING_USERNAME, callIntermediateWhoAmI());
}
/**
* Test a remote outbound connection with a source address role decoder configured on the
* server-side server where the IP address configured on the role decoder matches the
* IP address of the client-side server.
*/
@Test
public void testElytronWithBareRemotingWithSourceAddressRoleDecoderMatch() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundBareRemotingWithSourceAddressRoleDecoder(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
BARE_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, BARE_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, DEFAULT_PASSWORD));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, ""));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(DEFAULT_USERNAME, callIntermediateWhoAmI(true));
}
/**
* Test a remote outbound connection with a source address role decoder configured on the
* server-side server where the IP address configured on the role decoder matches the
* IP address of the client-side server but the permission mapper does not match.
*/
@Test
public void testElytronWithBareRemotingWithSourceAddressRoleDecoderMatchAndPermissionMapperMismatch() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundBareRemotingWithSourceAddressRoleDecoder(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
BARE_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, BARE_REMOTING_PROTOCOL, PROPERTIES_REALM,
"alice", "password1"));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, ""));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
try {
callIntermediateWhoAmI(true);
Assert.fail("Expected NoSuchEJBException not thrown");
} catch (NoSuchEJBException expected) {
}
}
/**
* Test a remote outbound connection with a source address role decoder configured on the
* server-side server where the IP address configured on the role decoder does not match the
* IP address of the client-side server.
*/
@Test
public void testElytronWithBareRemotingWithSourceAddressRoleDecoderMismatch() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundBareRemotingWithSourceAddressRoleDecoder(serverSideMCC, "999.999.999.999");
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
BARE_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, BARE_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, DEFAULT_PASSWORD));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, ""));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
try {
callIntermediateWhoAmI(true);
Assert.fail("Expected NoSuchEJBException not thrown");
} catch (NoSuchEJBException expected) {
}
}
/**
* Test a remote outbound connection with a source address role decoder configured on the
* server-side server where the IP address configured on the role decoder does not match the
* IP address of the client-side server but the user already has "admin" permission based
* on the security realm.
*/
@Test
public void testElytronWithBareRemotingWithSecurityRealmRole() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundBareRemotingWithSourceAddressRoleDecoder(serverSideMCC, "999.999.999.999");
//==================================
// Client-side server setup
//==================================
String username = "bob"; // has "admin" role based on the security realm
String password = "password2";
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
BARE_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, BARE_REMOTING_PROTOCOL, PROPERTIES_REALM,
username, password));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, ""));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
Assert.assertEquals(username, callIntermediateWhoAmI(true));
}
/**
* Test a remote outbound connection with a source address role decoder configured on the
* server-side server where the IP address configured on the role decoder does match the
* IP address of the client-side server but the client credentials are invalid.
*/
@Test
public void testElytronWithBareRemotingWithSourceAddressRoleDecoderInvalidCredentials() {
//==================================
// Server-side server setup
//==================================
configureServerSideForInboundBareRemotingWithSourceAddressRoleDecoder(serverSideMCC);
//==================================
// Client-side server setup
//==================================
applyUpdate(clientSideMCC, getAddOutboundSocketBindingOp(OUTBOUND_SOCKET_BINDING, TestSuiteEnvironment.getServerAddress(),
BARE_REMOTING_PORT));
applyUpdate(clientSideMCC, getAddAuthenticationConfigurationOp(DEFAULT_AUTH_CONFIG, BARE_REMOTING_PROTOCOL, PROPERTIES_REALM,
DEFAULT_USERNAME, "badpassword"));
applyUpdate(clientSideMCC, getAddAuthenticationContextOp(DEFAULT_AUTH_CONTEXT, DEFAULT_AUTH_CONFIG));
applyUpdate(clientSideMCC, getAddConnectionOp(REMOTE_OUTBOUND_CONNECTION, OUTBOUND_SOCKET_BINDING, ""));
applyUpdate(clientSideMCC, getWriteElytronDefaultAuthenticationContextOp(DEFAULT_AUTH_CONTEXT));
executeBlockingReloadClientServer(clientSideMCC);
deployer.deploy(EJB_SERVER_DEPLOYMENT);
deployer.deploy(EJB_CLIENT_DEPLOYMENT);
try {
callIntermediateWhoAmI(true);
Assert.fail("Expected NoSuchEJBException not thrown");
} catch (NoSuchEJBException expected) {
}
}
private static PathAddress getSocketBindingAddress(String socketBindingName) {
return PathAddress.pathAddress()
.append(SOCKET_BINDING_GROUP, "standard-sockets")
.append(SOCKET_BINDING, socketBindingName);
}
private static ModelNode getAddSocketBindingOp(String socketBindingName, int port) {
ModelNode addSocketBindingOp = Util.createAddOperation(getSocketBindingAddress(socketBindingName));
addSocketBindingOp.get(PORT).set(port);
return addSocketBindingOp;
}
private static PathAddress getPropertiesRealmAddress(String realmName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "elytron")
.append("properties-realm", realmName);
}
private static ModelNode getAddPropertiesRealmOp(String realmName, String groupsPropertiesPath, String usersPropertiesPath,
boolean plainText) {
ModelNode op = Util.createAddOperation(getPropertiesRealmAddress(realmName));
op.get("groups-properties", PATH).set(groupsPropertiesPath);
op.get("users-properties", PATH).set(usersPropertiesPath);
op.get("users-properties", PLAIN_TEXT).set(plainText);
return op;
}
private static PathAddress getElytronSecurityDomainAddress(String domainName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "elytron")
.append("security-domain", domainName);
}
private static ModelNode getAddElytronSecurityDomainOp(String domainName, String realmName) {
ModelNode op = Util.createAddOperation(getElytronSecurityDomainAddress(domainName));
ModelNode realm = new ModelNode();
realm.get(REALM).set(realmName);
realm.get("role-decoder").set("groups-to-roles");
op.get("realms").setEmptyList().add(realm);
op.get("default-realm").set(realmName);
op.get("permission-mapper").set("default-permission-mapper");
return op;
}
private static PathAddress getElytronSourceAddressRoleDecoderAddress(String decoderName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "elytron")
.append("source-address-role-decoder", decoderName);
}
private static ModelNode getAddElytronSourceAddressRoleDecoder(String decoderName, String ipAddress, String role) {
ModelNode op = Util.createAddOperation(getElytronSourceAddressRoleDecoderAddress(decoderName));
op.get("source-address").set(ipAddress);
op.get("roles").add("admin");
return op;
}
private static PathAddress getElytronAggregateRoleDecoderAddress(String aggregateDecoderName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "elytron")
.append("aggregate-role-decoder", aggregateDecoderName);
}
private static ModelNode getAddElytronAggregateRoleDecoder(String aggregateDecoderName, String decoderName1, String decoderName2) {
ModelNode op = Util.createAddOperation(getElytronAggregateRoleDecoderAddress(aggregateDecoderName));
op.get("role-decoders").add(decoderName1);
op.get("role-decoders").add(decoderName2);
return op;
}
private static ModelNode getAddElytronSecurityDomainWithSourceAddressRoleDecoderOp(String domainName, String realmName, String roleDecoderName, String permissionMapperName) {
ModelNode op = Util.createAddOperation(getElytronSecurityDomainAddress(domainName));
op.get("permission-mapper").set(permissionMapperName);
op.get("role-decoder").set(roleDecoderName);
ModelNode realm = new ModelNode();
realm.get(REALM).set(realmName);
realm.get("role-decoder").set("groups-to-roles");
op.get("realms").setEmptyList().add(realm);
op.get("default-realm").set(realmName);
return op;
}
private static PathAddress getElytronPermissionMapperAddress(String permissionMapperName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "elytron")
.append("simple-permission-mapper", permissionMapperName);
}
private static ModelNode getAddElytronPermissionMapperOp(String permissionMapperName) {
ModelNode op = Util.createAddOperation(getElytronPermissionMapperAddress(permissionMapperName));
ModelNode permissionMapping1 = new ModelNode();
permissionMapping1.get("roles").add("admin");
ModelNode permissionSet1 = new ModelNode();
permissionSet1.get("permission-set").set("login-permission");
permissionMapping1.get("permission-sets").add(permissionSet1);
ModelNode permissionSet2 = new ModelNode();
permissionSet2.get("permission-set").set("default-permissions");
permissionMapping1.get("permission-sets").add(permissionSet2);
op.get("permission-mappings").add(permissionMapping1);
ModelNode permissionMapping2 = new ModelNode();
permissionMapping2.get("principals").add("alice");
op.get("permission-mappings").add(permissionMapping2);
op.get("mapping-mode").set("and");
return op;
}
private static PathAddress getEjbApplicationSecurityDomainAddress(String ejbDomainName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "ejb3")
.append("application-security-domain", ejbDomainName);
}
private static ModelNode getAddEjbApplicationSecurityDomainOp(String ejbDomainName, String securityDomainName) {
ModelNode op = Util.createAddOperation(getEjbApplicationSecurityDomainAddress(ejbDomainName));
op.get("security-domain").set(securityDomainName);
return op;
}
private static PathAddress getSaslAuthenticationFactoryAddress(String factoryName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "elytron")
.append("sasl-authentication-factory", factoryName);
}
private static ModelNode getAddSaslAuthenticationFactoryOp(String factoryName, String securityDomainName,
String securityRealmName) {
ModelNode op = Util.createAddOperation(getSaslAuthenticationFactoryAddress(factoryName));
op.get("sasl-server-factory").set("configured");
op.get("security-domain").set(securityDomainName);
ModelNode realmConfig = new ModelNode();
realmConfig.get("realm-name").set(securityRealmName);
ModelNode digestMechanism = new ModelNode();
digestMechanism.get("mechanism-name").set("DIGEST-MD5");
digestMechanism.get("mechanism-realm-configurations").setEmptyList().add(realmConfig);
op.get("mechanism-configurations").setEmptyList().add(digestMechanism);
return op;
}
private static PathAddress getConnectorAddress(String connectorName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "remoting")
.append("connector", connectorName);
}
private static ModelNode getAddConnectorOp(String connectorName, String socketBindingName, String factoryName,
String serverSSLContextName) {
ModelNode addConnectorOp = Util.createAddOperation(getConnectorAddress(connectorName));
addConnectorOp.get(SOCKET_BINDING).set(socketBindingName);
addConnectorOp.get(SASL_AUTHENTICATION_FACTORY).set(factoryName);
if (serverSSLContextName != null && !serverSSLContextName.isEmpty()) {
addConnectorOp.get(SSL_CONTEXT).set(serverSSLContextName);
}
return Operations.CompositeOperationBuilder.create()
.addStep(addConnectorOp)
.addStep(getEjbConnectorOp("list-add", connectorName))
.build().getOperation();
}
private static ModelNode getAddConnectorOp(String connectorName, String socketBindingName, String factoryName) {
return getAddConnectorOp(connectorName, socketBindingName, factoryName, "");
}
private static ModelNode getEjbConnectorOp(String operationName, String connectorName) {
ModelNode operation = Util.createOperation(operationName, PathAddress.pathAddress(
PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, "ejb3"),
PathElement.pathElement(ModelDescriptionConstants.SERVICE, ModelDescriptionConstants.REMOTE)
));
operation.get(ModelDescriptionConstants.NAME).set("connectors");
operation.get(ModelDescriptionConstants.VALUE).set(connectorName);
return operation;
}
private static PathAddress getOutboundSocketBindingAddress(String socketBindingName) {
return PathAddress.pathAddress()
.append(SOCKET_BINDING_GROUP, "standard-sockets")
.append(REMOTE_DESTINATION_OUTBOUND_SOCKET_BINDING, socketBindingName);
}
private static PathAddress getHttpConnectorAddress(String connectorName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "remoting")
.append("http-connector", connectorName);
}
private static ModelNode getAddHttpConnectorOp(String connectorName, String connectorRef, String factoryName) {
ModelNode addHttpConnectorOp = Util.createAddOperation(getHttpConnectorAddress(connectorName));
addHttpConnectorOp.get("connector-ref").set(connectorRef);
addHttpConnectorOp.get(SASL_AUTHENTICATION_FACTORY).set(factoryName);
return Operations.CompositeOperationBuilder.create()
.addStep(addHttpConnectorOp)
.addStep(getEjbConnectorOp("list-add", connectorName))
.build().getOperation();
}
private static ModelNode getAddOutboundSocketBindingOp(String socketBindingName, String host, int port) {
ModelNode addOutboundSocketBindingOp = Util.createAddOperation(getOutboundSocketBindingAddress(socketBindingName));
addOutboundSocketBindingOp.get(PORT).set(port);
addOutboundSocketBindingOp.get(HOST).set(host);
return addOutboundSocketBindingOp;
}
private static PathAddress getAuthenticationConfigurationAddress(String configurationName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "elytron")
.append("authentication-configuration", configurationName);
}
private static ModelNode getAddAuthenticationConfigurationOp(String configurationName, String protocol, String realm,
String username, String password, String host, int port) {
ModelNode addAuthenticationConfigurationOp = Util.createAddOperation(getAuthenticationConfigurationAddress(configurationName));
addAuthenticationConfigurationOp.get("protocol").set(protocol);
if (port != 0) {
addAuthenticationConfigurationOp.get("port").set(port);
}
addAuthenticationConfigurationOp.get("authentication-name").set(username);
if (host != null && !host.isEmpty()) {
addAuthenticationConfigurationOp.get("host").set(host);
}
addAuthenticationConfigurationOp.get("sasl-mechanism-selector").set("DIGEST-MD5");
addAuthenticationConfigurationOp.get(REALM).set(realm);
ModelNode credentialReference = new ModelNode();
credentialReference.get("clear-text").set(password);
addAuthenticationConfigurationOp.get("credential-reference").set(credentialReference);
return addAuthenticationConfigurationOp;
}
private static ModelNode getAddAuthenticationConfigurationOp(String configurationName, String protocol, String realm,
String username, String password) {
return getAddAuthenticationConfigurationOp(configurationName, protocol, realm, username, password, "", 0);
}
private static PathAddress getAuthenticationContextAddress(String contextName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "elytron")
.append("authentication-context", contextName);
}
private static ModelNode getAddAuthenticationContextOp(String contextName, String configurationName, String serverSSLContextName) {
ModelNode addAuthenticationContextOp = Util.createAddOperation(getAuthenticationContextAddress(contextName));
ModelNode matchRule = new ModelNode();
matchRule.get("authentication-configuration").set(configurationName);
if (serverSSLContextName != null && !serverSSLContextName.isEmpty()) {
matchRule.get(SSL_CONTEXT).set(serverSSLContextName);
}
addAuthenticationContextOp.get("match-rules").setEmptyList()
.add(matchRule);
return addAuthenticationContextOp;
}
private static ModelNode getAddAuthenticationContextOp(String contextName, String configurationName) {
return getAddAuthenticationContextOp(contextName, configurationName, "");
}
private static ModelNode getWriteElytronDefaultAuthenticationContextOp(String authenticationContextName) {
ModelNode op = new ModelNode();
op.get(OP_ADDR).setEmptyList()
.add(SUBSYSTEM, "elytron");
op.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
op.get(NAME).set("default-authentication-context");
op.get(VALUE).set(authenticationContextName);
return op;
}
private static PathAddress getConnectionAddress(String connectionName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "remoting")
.append("remote-outbound-connection", connectionName);
}
private static ModelNode getAddConnectionOp(String connectionName, String outboundSocketBindingName,
String authenticationContextName) {
ModelNode addConnectionOp = Util.createAddOperation(getConnectionAddress(connectionName));
addConnectionOp.get("outbound-socket-binding-ref").set(outboundSocketBindingName);
if (authenticationContextName != null && !authenticationContextName.isEmpty()) {
addConnectionOp.get("authentication-context").set(authenticationContextName);
}
return addConnectionOp;
}
private static PathAddress getKeyStoreAddress(String keyStoreName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "elytron")
.append("key-store", keyStoreName);
}
private static ModelNode getAddKeyStoreOp(String keyStoreName, String path, String keyPass) {
ModelNode addKeyStoreOp = Util.createAddOperation(getKeyStoreAddress(keyStoreName));
addKeyStoreOp.get(PATH).set(path);
ModelNode credentialReference = new ModelNode();
credentialReference.get("clear-text").set(keyPass);
addKeyStoreOp.get("credential-reference").set(credentialReference);
addKeyStoreOp.get("type").set("JKS");
return addKeyStoreOp;
}
private static PathAddress getKeyManagerAddress(String keyManagerName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "elytron")
.append("key-manager", keyManagerName);
}
private static ModelNode getAddKeyManagerOp(String keyManagerName, String keyStoreName, String keyPass) {
ModelNode addKeyStoreOp = Util.createAddOperation(getKeyManagerAddress(keyManagerName));
addKeyStoreOp.get("key-store").set(keyStoreName);
ModelNode credentialReference = new ModelNode();
credentialReference.get("clear-text").set(keyPass);
addKeyStoreOp.get("credential-reference").set(credentialReference);
return addKeyStoreOp;
}
private static PathAddress getTrustManagerAddress(String trustManagerName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "elytron")
.append("trust-manager", trustManagerName);
}
private static ModelNode getAddTrustManagerOp(String trustManagerName, String keyStoreName) {
ModelNode addKeyStoreOp = Util.createAddOperation(getTrustManagerAddress(trustManagerName));
addKeyStoreOp.get("key-store").set(keyStoreName);
return addKeyStoreOp;
}
private static PathAddress getServerSSLContextAddress(String serverSSLContextName) {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "elytron")
.append("server-ssl-context", serverSSLContextName);
}
private static ModelNode getAddServerSSLContextOp(String serverSSLContextName, String keyManagerName, String trustManagerName) {
ModelNode addServerSSLContextOp = Util.createAddOperation(getServerSSLContextAddress(serverSSLContextName));
addServerSSLContextOp.get("trust-manager").set(trustManagerName);
addServerSSLContextOp.get("need-client-auth").set(true);
addServerSSLContextOp.get("key-manager").set(keyManagerName);
return addServerSSLContextOp;
}
private static PathAddress getDefaultHttpsListenerAddress() {
return PathAddress.pathAddress()
.append(SUBSYSTEM, "undertow")
.append(SERVER, "default-server")
.append("https-listener", "https");
}
private static void configureServerSideForInboundBareRemoting(ModelControllerClient serverSideMCC) {
applyUpdate(serverSideMCC, getAddPropertiesRealmOp(PROPERTIES_REALM, ROLES_PATH, USERS_PATH, true));
applyUpdate(serverSideMCC, getAddElytronSecurityDomainOp(SECURITY_DOMAIN, PROPERTIES_REALM));
applyUpdate(serverSideMCC, getAddSaslAuthenticationFactoryOp(AUTHENTICATION_FACTORY, SECURITY_DOMAIN, PROPERTIES_REALM));
applyUpdate(serverSideMCC, getAddEjbApplicationSecurityDomainOp(APPLICATION_SECURITY_DOMAIN, SECURITY_DOMAIN));
applyUpdate(serverSideMCC, getAddSocketBindingOp(INBOUND_SOCKET_BINDING, BARE_REMOTING_PORT));
applyUpdate(serverSideMCC, getAddConnectorOp(CONNECTOR, INBOUND_SOCKET_BINDING, AUTHENTICATION_FACTORY));
executeBlockingReloadServerSide(serverSideMCC);
}
private static void configureServerSideForInboundSSLRemoting(ModelControllerClient serverSideMCC) {
applyUpdate(serverSideMCC, getAddPropertiesRealmOp(PROPERTIES_REALM, ROLES_PATH, USERS_PATH, true));
applyUpdate(serverSideMCC, getAddElytronSecurityDomainOp(SECURITY_DOMAIN, PROPERTIES_REALM));
applyUpdate(serverSideMCC, getAddSaslAuthenticationFactoryOp(AUTHENTICATION_FACTORY, SECURITY_DOMAIN, PROPERTIES_REALM));
applyUpdate(serverSideMCC, getAddEjbApplicationSecurityDomainOp(APPLICATION_SECURITY_DOMAIN, SECURITY_DOMAIN));
applyUpdate(serverSideMCC, getAddSocketBindingOp(INBOUND_SOCKET_BINDING, SSL_REMOTING_PORT));
applyUpdate(serverSideMCC, getAddKeyStoreOp(SERVER_KEY_STORE, SERVER_KEY_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(serverSideMCC, getAddKeyManagerOp(SERVER_KEY_MANAGER, SERVER_KEY_STORE, KEY_STORE_KEYPASS));
applyUpdate(serverSideMCC, getAddKeyStoreOp(SERVER_TRUST_STORE, SERVER_TRUST_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(serverSideMCC, getAddTrustManagerOp(SERVER_TRUST_MANAGER, SERVER_TRUST_STORE));
applyUpdate(serverSideMCC, getAddServerSSLContextOp(SERVER_SSL_CONTEXT, SERVER_KEY_MANAGER, SERVER_TRUST_MANAGER));
applyUpdate(serverSideMCC, getAddConnectorOp(CONNECTOR, INBOUND_SOCKET_BINDING, AUTHENTICATION_FACTORY, SERVER_SSL_CONTEXT));
executeBlockingReloadServerSide(serverSideMCC);
}
private static void configureServerSideForInboundHttpRemoting(ModelControllerClient serverSideMCC) {
applyUpdate(serverSideMCC, getAddPropertiesRealmOp(PROPERTIES_REALM, ROLES_PATH, USERS_PATH, true));
applyUpdate(serverSideMCC, getAddElytronSecurityDomainOp(SECURITY_DOMAIN, PROPERTIES_REALM));
applyUpdate(serverSideMCC, getAddSaslAuthenticationFactoryOp(AUTHENTICATION_FACTORY, SECURITY_DOMAIN, PROPERTIES_REALM));
applyUpdate(serverSideMCC, getAddEjbApplicationSecurityDomainOp(APPLICATION_SECURITY_DOMAIN, SECURITY_DOMAIN));
applyUpdate(serverSideMCC, Util.getWriteAttributeOperation(getHttpConnectorAddress("http-remoting-connector"),
SASL_AUTHENTICATION_FACTORY, AUTHENTICATION_FACTORY));
executeBlockingReloadServerSide(serverSideMCC);
}
private static void configureServerSideForInboundHttpsRemoting(ModelControllerClient serverSideMCC) {
applyUpdate(serverSideMCC, getAddPropertiesRealmOp(PROPERTIES_REALM, ROLES_PATH, USERS_PATH, true));
applyUpdate(serverSideMCC, getAddElytronSecurityDomainOp(SECURITY_DOMAIN, PROPERTIES_REALM));
applyUpdate(serverSideMCC, getAddSaslAuthenticationFactoryOp(AUTHENTICATION_FACTORY, SECURITY_DOMAIN, PROPERTIES_REALM));
applyUpdate(serverSideMCC, getAddEjbApplicationSecurityDomainOp(APPLICATION_SECURITY_DOMAIN, SECURITY_DOMAIN));
applyUpdate(serverSideMCC, getAddKeyStoreOp(SERVER_KEY_STORE, SERVER_KEY_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(serverSideMCC, getAddKeyManagerOp(SERVER_KEY_MANAGER, SERVER_KEY_STORE, KEY_STORE_KEYPASS));
applyUpdate(serverSideMCC, getAddKeyStoreOp(SERVER_TRUST_STORE, SERVER_TRUST_STORE_PATH, KEY_STORE_KEYPASS));
applyUpdate(serverSideMCC, getAddTrustManagerOp(SERVER_TRUST_MANAGER, SERVER_TRUST_STORE));
applyUpdate(serverSideMCC, getAddServerSSLContextOp(SERVER_SSL_CONTEXT, SERVER_KEY_MANAGER, SERVER_TRUST_MANAGER));
applyUpdate(serverSideMCC,
Operations.CompositeOperationBuilder.create()
.addStep(Util.getUndefineAttributeOperation(getDefaultHttpsListenerAddress(), SECURITY_REALM))
.addStep(Util.getWriteAttributeOperation(getDefaultHttpsListenerAddress(), SSL_CONTEXT, SERVER_SSL_CONTEXT))
.build().getOperation()
);
applyUpdate(serverSideMCC, getAddHttpConnectorOp(CONNECTOR, "https", AUTHENTICATION_FACTORY));
executeBlockingReloadServerSide(serverSideMCC);
}
private static void configureServerSideForInboundBareRemotingWithSourceAddressRoleDecoder(ModelControllerClient serverSideMCC) {
configureServerSideForInboundBareRemotingWithSourceAddressRoleDecoder(serverSideMCC, getIPAddress());
}
private static void configureServerSideForInboundBareRemotingWithSourceAddressRoleDecoder(ModelControllerClient serverSideMCC, String ipAddress) {
applyUpdate(serverSideMCC, getAddPropertiesRealmOp(PROPERTIES_REALM, ROLES_PATH, USERS_PATH, true));
applyUpdate(serverSideMCC, getAddElytronSourceAddressRoleDecoder(DECODER_1, ipAddress, "admin"));
applyUpdate(serverSideMCC, getAddElytronSourceAddressRoleDecoder(DECODER_2, "99.99.99.99", "employee"));
applyUpdate(serverSideMCC, getAddElytronAggregateRoleDecoder(AGGREGATE_ROLE_DECODER, DECODER_1, DECODER_2));
applyUpdate(serverSideMCC, getAddElytronPermissionMapperOp(IP_PERMISSION_MAPPER));
applyUpdate(serverSideMCC, getAddElytronSecurityDomainWithSourceAddressRoleDecoderOp(SECURITY_DOMAIN, PROPERTIES_REALM, AGGREGATE_ROLE_DECODER, IP_PERMISSION_MAPPER));
applyUpdate(serverSideMCC, getAddSaslAuthenticationFactoryOp(AUTHENTICATION_FACTORY, SECURITY_DOMAIN, PROPERTIES_REALM));
applyUpdate(serverSideMCC, getAddEjbApplicationSecurityDomainOp(APPLICATION_SECURITY_DOMAIN, SECURITY_DOMAIN));
applyUpdate(serverSideMCC, getAddSocketBindingOp(INBOUND_SOCKET_BINDING, BARE_REMOTING_PORT));
applyUpdate(serverSideMCC, getAddConnectorOp(CONNECTOR, INBOUND_SOCKET_BINDING, AUTHENTICATION_FACTORY));
executeBlockingReloadServerSide(serverSideMCC);
}
private static ModelControllerClient getInboundConnectionServerMCC() {
return TestSuiteEnvironment.getModelControllerClient();
}
private static ModelControllerClient getOutboundConnectionServerMCC() {
try {
return ModelControllerClient.Factory.create(
InetAddress.getByName(TestSuiteEnvironment.getServerAddressNode1()),
10090,
Authentication.getCallbackHandler());
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
private static void applyUpdate(final ModelControllerClient client, ModelNode update, boolean allowReload) {
if (allowReload) {
update.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
}
log.trace("Executing operation:\n" + update.toString());
ModelNode result;
try {
result = client.execute(new OperationBuilder(update).build());
} catch (IOException ex) {
throw new RuntimeException(ex);
}
if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) {
log.trace("Operation result:\n" + result.toString());
} else if (result.hasDefined("failure-description")) {
throw new RuntimeException(result.toString());
} else {
throw new RuntimeException("Operation not successful, outcome:\n" + result.get("outcome"));
}
}
private static String executeReadAttributeOpReturnResult(final ModelControllerClient client, PathAddress address,
String attributeName) {
ModelNode op = Util.getReadAttributeOperation(address, attributeName);
ModelNode result;
try {
result = client.execute(new OperationBuilder(op).build());
} catch (IOException ex) {
throw new RuntimeException(ex);
}
if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) {
log.trace("Operation result:\n" + result.toString());
return result.get("result").asString();
} else if (result.hasDefined("failure-description")) {
throw new RuntimeException(result.toString());
} else {
throw new RuntimeException("Operation not successful, outcome:\n" + result.get("outcome"));
}
}
private static void applyUpdate(final ModelControllerClient client, ModelNode update) {
applyUpdate(client, update, false);
}
private static void executeBlockingReloadServerSide(final ModelControllerClient serverSideMCC) {
String state;
try {
state = ServerReload.getContainerRunningState(serverSideMCC);
} catch (IOException e) {
throw new RuntimeException(e);
}
log.trace("Executing reload on client side server with container state: [ " + state + " ]");
ServerReload.executeReloadAndWaitForCompletion(serverSideMCC, ServerReload.TIMEOUT, false,
TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort());
try {
state = ServerReload.getContainerRunningState(serverSideMCC);
} catch (IOException e) {
throw new RuntimeException(e);
}
log.trace("Container state after reload on client side server: [ " + state + " ]");
}
private static void executeBlockingReloadClientServer(final ModelControllerClient clientSideMCC) {
String state;
try {
state = ServerReload.getContainerRunningState(clientSideMCC);
} catch (IOException e) {
throw new RuntimeException(e);
}
log.trace("Executing reload on client side server with container state: [ " + state + " ]");
ServerReload.executeReloadAndWaitForCompletion(clientSideMCC, ServerReload.TIMEOUT, false,
TestSuiteEnvironment.getServerAddressNode1(), 10090);
try {
state = ServerReload.getContainerRunningState(clientSideMCC);
} catch (IOException e) {
throw new RuntimeException(e);
}
log.trace("Container state after reload on client side server: [ " + state + " ]");
}
private String callIntermediateWhoAmI() {
return callIntermediateWhoAmI(false);
}
private String callIntermediateWhoAmI(boolean useRestrictedMethod) {
AuthenticationConfiguration common = AuthenticationConfiguration.empty()
.useProviders(() -> new Provider[] {new WildFlyElytronProvider()})
.setSaslMechanismSelector(SaslMechanismSelector.ALL);
AuthenticationContext authCtxEmpty = AuthenticationContext.empty();
final AuthenticationContext authCtx = authCtxEmpty.with(MatchRule.ALL, common);
final EJBClientContext.Builder ejbClientBuilder = new EJBClientContext.Builder();
ejbClientBuilder.addTransportProvider(new RemoteTransportProvider());
final EJBClientConnection.Builder connBuilder = new EJBClientConnection.Builder();
connBuilder.setDestination(URI.create("remote+http://" + TestSuiteEnvironment.getServerAddressNode1() + ":8180"));
ejbClientBuilder.addClientConnection(connBuilder.build());
final EJBClientContext ejbCtx = ejbClientBuilder.build();
AuthenticationContext.getContextManager().setThreadDefault(authCtx);
EJBClientContext.getContextManager().setThreadDefault(ejbCtx);
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, WildFlyInitialContextFactory.class.getName());
String result;
try {
InitialContext ctx = new InitialContext(props);
String lookupName = "ejb:/outbound-module/IntermediateWhoAmI!org.jboss.as.test.manualmode.ejb.client.outbound.connection.security.WhoAmI";
WhoAmI intermediate = (WhoAmI)ctx.lookup(lookupName);
if (useRestrictedMethod) {
result = intermediate.whoAmIRestricted();
} else {
result = intermediate.whoAmI();
}
ctx.close();
} catch (NamingException e) {
throw new RuntimeException(e);
}
return result;
}
public void removeIfExists(ModelControllerClient client, PathAddress address, boolean allowResourceReload) {
ModelNode rrResult;
try {
rrResult = client.execute(Util.createOperation(READ_RESOURCE_OPERATION, address));
} catch (IOException e) {
throw new RuntimeException(e);
}
if (rrResult != null && Operations.isSuccessfulOutcome(rrResult)) {
applyUpdate(client, Util.createRemoveOperation(address), allowResourceReload);
}
}
public void removeIfExists(ModelControllerClient client, PathAddress address) {
removeIfExists(client, address, false);
}
public static void cleanFile(File toClean) {
if (toClean.exists()) {
if (toClean.isDirectory()) {
for (File child : toClean.listFiles()) {
cleanFile(child);
}
}
toClean.delete();
}
}
}
| 93,216 | 57.260625 | 178 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/security/WhoAmI.java
|
package org.jboss.as.test.manualmode.ejb.client.outbound.connection.security;
import jakarta.ejb.Remote;
/**
* @author <a href="mailto:[email protected]">Michal Jurc</a> (c) 2017 Red Hat, Inc.
*/
@Remote
public interface WhoAmI {
String whoAmI();
String whoAmIRestricted();
}
| 290 | 17.1875 | 83 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/security/IntermediateWhoAmI.java
|
package org.jboss.as.test.manualmode.ejb.client.outbound.connection.security;
import jakarta.ejb.EJB;
import jakarta.ejb.Stateless;
/**
* @author <a href="mailto:[email protected]">Michal Jurc</a> (c) 2017 Red Hat, Inc.
*/
@Stateless
public class IntermediateWhoAmI implements WhoAmI {
@EJB(lookup = "ejb:/inbound-module/ServerWhoAmI!org.jboss.as.test.manualmode.ejb.client.outbound.connection.security.WhoAmI")
private WhoAmI whoAmIBean;
public String whoAmI() {
return whoAmIBean.whoAmI();
}
public String whoAmIRestricted() {
return whoAmIBean.whoAmIRestricted();
}
}
| 618 | 24.791667 | 129 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/transaction/preparehalt/TransactionalBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ejb.client.outbound.connection.transaction.preparehalt;
import org.jboss.as.test.integration.transactions.PersistentTestXAResource;
import org.jboss.as.test.integration.transactions.TransactionCheckerSingleton;
import org.jboss.logging.Logger;
import jakarta.annotation.Resource;
import jakarta.ejb.EJB;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionAttribute;
import jakarta.ejb.TransactionAttributeType;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
/**
* Bean expected to be called by {@link ClientBean}.
* Working with {@link javax.transaction.xa.XAResource}s to force the transaction manager to process
* two-phase commit after the end of the business method.
*/
@Stateless
public class TransactionalBean implements TransactionalRemote {
private static final Logger log = Logger.getLogger(TransactionalBean.class);
@EJB
private TransactionCheckerSingleton transactionCheckerSingleton;
@Resource(lookup = "java:/TransactionManager")
private TransactionManager tm;
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void enlistOnePersistentXAResource() {
try {
log.debugf("Invocation to #enlistOnePersistentXAResource with transaction", tm.getTransaction());
tm.getTransaction().enlistResource(new PersistentTestXAResource(transactionCheckerSingleton));
} catch (Exception e) {
throw new IllegalStateException("Cannot enlist single " + PersistentTestXAResource.class.getSimpleName()
+ " to transaction", e);
}
}
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void intermittentCommitFailure() {
try {
Transaction txn = tm.getTransaction();
log.debugf("Invocation to #intermittentCommitFailure with the transaction: %s", txn);
txn.enlistResource(new TestCommitFailureXAResource(transactionCheckerSingleton));
} catch (Exception e) {
throw new IllegalStateException("Cannot enlist single " + TestCommitFailureXAResource.class.getSimpleName()
+ " to the transaction", e);
}
}
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void intermittentCommitFailureTwoPhase() {
try {
Transaction txn = tm.getTransaction();
log.debugf("Invocation to #intermittentCommitFailure with transaction: %s", txn);
txn.enlistResource(new TestCommitFailureXAResource(transactionCheckerSingleton));
txn.enlistResource(new PersistentTestXAResource(transactionCheckerSingleton));
} catch (Exception e) {
throw new IllegalStateException("Cannot enlist one of the XAResources " + TestCommitFailureXAResource.class.getSimpleName()
+ " or " + PersistentTestXAResource.class.getSimpleName() + " to the transaction", e);
}
}
}
| 4,004 | 44.511364 | 135 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/transaction/preparehalt/TransactionalRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ejb.client.outbound.connection.transaction.preparehalt;
import jakarta.ejb.Remote;
@Remote
public interface TransactionalRemote {
void enlistOnePersistentXAResource();
void intermittentCommitFailure();
void intermittentCommitFailureTwoPhase();
}
| 1,321 | 39.060606 | 92 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/transaction/preparehalt/TestCommitFailureXAResource.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ejb.client.outbound.connection.transaction.preparehalt;
import org.jboss.as.test.integration.transactions.PersistentTestXAResource;
import org.jboss.as.test.integration.transactions.TransactionCheckerSingleton;
import javax.transaction.xa.XAException;
import javax.transaction.xa.Xid;
public class TestCommitFailureXAResource extends PersistentTestXAResource {
private volatile boolean wasCommitted = false;
public TestCommitFailureXAResource(TransactionCheckerSingleton checker) {
super(checker);
}
/**
* On first attemp to commit throwing {@link XAException#XAER_RMFAIL}
* which represents an intermittent failure which the system could be recovered from later.
* The transaction manager is expected to retry the commit.
*/
@Override
public void commit(Xid xid, boolean onePhase) throws XAException {
if(!wasCommitted) {
wasCommitted = true;
throw new XAException(XAException.XAER_RMFAIL);
} else {
super.commit(xid, onePhase);
}
}
}
| 2,118 | 38.981132 | 95 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/transaction/preparehalt/TransactionPropagationFailureTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ejb.client.outbound.connection.transaction.preparehalt;
import org.jboss.arquillian.container.test.api.ContainerController;
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.api.ContainerResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.integration.transactions.RecoveryExecutor;
import org.jboss.as.test.integration.transactions.RemoteLookups;
import org.jboss.as.test.integration.transactions.TestXAResource;
import org.jboss.as.test.integration.transactions.TransactionCheckerSingleton;
import org.jboss.as.test.integration.transactions.TransactionCheckerSingletonRemote;
import org.jboss.as.test.manualmode.ejb.client.outbound.connection.EchoOnServerOne;
import org.jboss.as.test.shared.CLIServerSetupTask;
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.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import jakarta.ejb.EJBException;
import javax.naming.NamingException;
import jakarta.transaction.HeuristicMixedException;
import java.io.File;
import java.io.FilePermission;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.PropertyPermission;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createFilePermission;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
/**
* Testing transaction recovery on cases where WildFly calls remote Jakarta Enterprise Beans on the other WildFly instance.
* The transaction context is propagated along this remote call and then some failure or JVM crash happens.
* When the failure (e.g. simulation of intermittent erroneous state) or when servers are restarted
* (in case the JVM had been crashed) then the transaction recovery must make the system data consistent again.
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(TransactionPropagationFailureTestCase.TransactionStatusManagerSetup.class)
public class TransactionPropagationFailureTestCase {
private static final Logger log = Logger.getLogger(TransactionPropagationFailureTestCase.class);
private static final String CLIENT_SERVER_NAME = "jbossas-with-remote-outbound-connection-non-clustered";
private static final String SERVER_SERVER_NAME = "jbossas-non-clustered";
private static final String CLIENT_DEPLOYMENT = "txn-prepare-halt-client";
private static final String SERVER_DEPLOYMENT = "txn-prepare-halt-server";
private static final String CLIENT_SERVER_JBOSS_HOME = "jbossas-with-remote-outbound-connection";
private static final String WFTC_DATA_DIRECTORY_NAME = "ejb-xa-recovery";
@Deployment(name = CLIENT_DEPLOYMENT, testable = false)
@TargetsContainer(CLIENT_SERVER_NAME)
public static Archive<?> clientDeployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, CLIENT_DEPLOYMENT + ".jar")
.addClasses(TransactionalRemote.class, ClientBean.class, ClientBeanRemote.class)
.addPackage(TestXAResource.class.getPackage())
.addAsManifestResource(EchoOnServerOne.class.getPackage(), "jboss-ejb-client.xml", "jboss-ejb-client.xml")
.addAsManifestResource(createPermissionsXmlAsset(
new RuntimePermission("exitVM", "none"),
createFilePermission("read,write", "basedir",
Arrays.asList("target", CLIENT_SERVER_JBOSS_HOME, "standalone", "data", WFTC_DATA_DIRECTORY_NAME)),
createFilePermission("read,write", "basedir",
Arrays.asList("target", CLIENT_SERVER_JBOSS_HOME, "standalone", "data", WFTC_DATA_DIRECTORY_NAME, "-")),
new FilePermission(System.getProperty("jboss.home") + File.separatorChar + "standalone" + File.separatorChar + "tmp" + File.separatorChar + "auth" + File.separatorChar + "-", "read")
), "permissions.xml")
.addAsManifestResource(new StringAsset("Dependencies: org.jboss.jts\n"), "MANIFEST.MF");
return jar;
}
@Deployment(name = SERVER_DEPLOYMENT, testable = false)
@TargetsContainer(SERVER_SERVER_NAME)
public static Archive<?> deployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, SERVER_DEPLOYMENT + ".jar")
.addClasses(TransactionalBean.class, TransactionalRemote.class, TestCommitFailureXAResource.class)
.addPackages(true, TestXAResource.class.getPackage())
.addAsManifestResource(createPermissionsXmlAsset(
new PropertyPermission("jboss.server.data.dir", "read"),
// PersistentTestXAResource requires the following permissions
createFilePermission("read", "basedir", Arrays.asList("target", "wildfly", "standalone", "data")),
createFilePermission("read,write", "basedir", Arrays.asList("target", "wildfly", "standalone", "data", "PersistentTestXAResource"))
), "permissions.xml")
.addAsManifestResource(new StringAsset("Dependencies: org.jboss.jts\n"), "MANIFEST.MF");
return jar;
}
static class TransactionStatusManagerSetup extends CLIServerSetupTask {
public TransactionStatusManagerSetup() {
this.builder
.node(CLIENT_SERVER_NAME)
.setup("/subsystem=transactions:write-attribute(name=recovery-listener, value=true)")
.reloadOnSetup(true);
}
}
@ArquillianResource
private ContainerController container;
@ContainerResource(CLIENT_SERVER_NAME)
private ManagementClient managementClientClient;
@ContainerResource(SERVER_SERVER_NAME)
private ManagementClient managementClientServer;
@Before
public void setUp() throws URISyntaxException, NamingException {
this.container.start(SERVER_SERVER_NAME);
this.container.start(CLIENT_SERVER_NAME);
// clean the singleton bean which stores TestXAResource calls
RemoteLookups.lookupEjbStateless(managementClientServer, SERVER_DEPLOYMENT,
TransactionCheckerSingleton.class, TransactionCheckerSingletonRemote.class).resetAll();
}
@After
public void tearDown() {
try {
container.stop(CLIENT_SERVER_NAME);
} finally {
container.stop(SERVER_SERVER_NAME);
}
}
/**
* <p>Reproducer for JBEAP-19408</p>
* <p>
* Test scenario:
* <ol>
* <li>client WildFly starts the transactions and calls remote Jakarta Enterprise Beans bean at server WildFly</li>
* <li>{@link ClientBean} method finishes and transaction manager starts 2PC</li>
* <li>client WildFly asks the server WildFly to <code>prepare</code> as part of the 2PC procesing</li>
* <li>server WildFly prepares but after the call is returned the client WildFly JVM crashes</li>
* <li>client WildFly restarts</li>
* <li>client WildFly runs transaction recovery which uses orphan detection
* to rollback the prepared data at server WildFly</li>
* </ol>
* </p>
*/
@Test
public void prepareCrashOnClient() throws Exception {
try {
ClientBeanRemote bean = RemoteLookups.lookupEjbStateless(managementClientClient, CLIENT_DEPLOYMENT,
ClientBean.class, ClientBeanRemote.class);
bean.twoPhaseCommitCrashAtClient(SERVER_DEPLOYMENT);
Assert.fail("Test expects transaction rollback outcome instead of commit");
} catch (Throwable expected) {
log.debugf(expected,"Exception expected as the client server '%s' should be crashed", CLIENT_SERVER_NAME);
}
try {
// container was JVM crashed by the test, this call let the arquillian know that the container is not running
container.kill(CLIENT_SERVER_NAME);
} catch (Exception ignore) {
// ignoring the kill issue as the server process will be killed at the end (Arquillian uses Process.destroyForcibly)
// at this time the Arquillian container inner state could be 'KILLED_FAILED' which is still fine to restart the app server
log.debugf("Arquillian kill of " + CLIENT_SERVER_NAME + " failed, but the process is killed and we can ignore it", ignore);
}
// starting the container (JVM crashed by call Runtime.getRuntime().halt), test will be running transaction recovery on restarted server
container.start(CLIENT_SERVER_NAME);
RecoveryExecutor recoveryExecutor = new RecoveryExecutor(managementClientClient);
TransactionCheckerSingletonRemote serverSingletonChecker = RemoteLookups.lookupEjbStateless(managementClientServer,
SERVER_DEPLOYMENT, TransactionCheckerSingleton.class, TransactionCheckerSingletonRemote.class);
Assert.assertEquals("Expecting the transaction was interrupted and no rollback was called yet",
0, serverSingletonChecker.getRolledback());
Assert.assertTrue("Expecting recovery #1 being run without any issue", recoveryExecutor.runTransactionRecovery());
Assert.assertTrue("Expecting recovery #2 being run without any issue", recoveryExecutor.runTransactionRecovery());
Assert.assertEquals("Expecting the rollback to be called on the server during recovery",
1, serverSingletonChecker.getRolledback());
assertEmptyClientWftcDataDirectory();
}
/**
* <p>Reproducer for JBEAP-19435</p>
* <p>
* Test scenario:
* <ol>
* <li>client WildFly starts the transactions and calls remote Jakarta Enterprise Beans bean at server WildFly,
* there are two resources enlisted on the client side and one resource is enlisted on the other server</li>
* <li>{@link ClientBean} method finishes and transaction manager starts 2PC</li>
* <li>client WildFly asks the server WildFly to <code>prepare</code> and <code>commit</code></li>
* <li>server WildFly prepares but the <code>commit</code> of XAResource fails with intermittent failure on the server</li>
* <li>client WildFly runs transaction recovery and expects the unfinished commit is finished with success
* and just after the commit is processed the WFTC registry is empty</li>
* </ol>
* </p>
*/
@Test
public void recoveryCommitRetryOnFailure() throws Exception {
ClientBeanRemote bean = RemoteLookups.lookupEjbStateless(managementClientClient, CLIENT_DEPLOYMENT,
ClientBean.class, ClientBeanRemote.class);
// ClientBean#twoPhaseIntermittentCommitFailureOnServer -> TransactionalBean#intermittentCommitFailure
bean.twoPhaseIntermittentCommitFailureOnServer(SERVER_DEPLOYMENT);
RecoveryExecutor recoveryExecutor = new RecoveryExecutor(managementClientClient);
TransactionCheckerSingletonRemote serverSingletonChecker = RemoteLookups.lookupEjbStateless(managementClientServer,
SERVER_DEPLOYMENT, TransactionCheckerSingleton.class, TransactionCheckerSingletonRemote.class);
Assert.assertEquals("Expecting the transaction was interrupted and commit was called on resources at the server yet",
0, serverSingletonChecker.getCommitted());
// the second call of the recovery execution is needed to manage the race condition
// if the recovery scan is already in progress started by periodic transaction recovery
// the test needs to ensure that recovery cycle was finished as whole but we need to check the state
// after the first recovery cycle the test checks that the WFTC data is deleted immediately after the transaction is committed.
Assert.assertTrue("Expecting recovery being run without any issue", recoveryExecutor.runTransactionRecovery());
if(serverSingletonChecker.getCommitted() == 0) {
Assert.assertTrue("Expecting recovery #2 being run without any issue", recoveryExecutor.runTransactionRecovery());
}
Assert.assertEquals("Expecting the commit to be called on the server during recovery",
1, serverSingletonChecker.getCommitted());
assertEmptyClientWftcDataDirectory();
}
/**
* <p>
* Test scenario:
* <ol>
* <li>client WildFly starts the transactions and calls remote Jakarta Enterprise Beans bean at server WildFly,
* there is one resource enlisted on the client side but two resources are enlisted on the other server</li>
* <li>{@link ClientBean} method finishes and transaction manager starts 1PC as only one resource was enslited
* on the client side which is the owner of the transaction</li>
* <li>client WildFly asks the server WildFly to <code>commit</code> as 1PC is used</li>
* <li>server WildFly <code>commit</code> of XAResource fails with intermittent failure on the server
* which for 1PC emits the heuristic exceptions, as an exception which requires manual fixing</li>
* <li>the test pretend an administrator to call ':recover' JBoss CLI call on transaction participants
* and the transaction is moved from 'heuristic' state to 'prepared' state</li>
* <li>the transaction recovery should be able to fix the transaction in the 'prepared' state state and commit it</li>
* </ol>
* </p>
*/
@Test
public void recoveryOnePhaseCommitRetryOnFailure() throws Exception {
ClientBeanRemote bean = RemoteLookups.lookupEjbStateless(managementClientClient, CLIENT_DEPLOYMENT,
ClientBean.class, ClientBeanRemote.class);
try {
// ClientBean#onePhaseIntermittentCommitFailureOnServer -> TransactionalBean#intermittentCommitFailureTwoPhase
bean.onePhaseIntermittentCommitFailureOnServer(SERVER_DEPLOYMENT);
Assert.fail("Test expects the method call to fail with EJBException but no exception was thrown.");
} catch (EJBException ejbe) {
if (!(ejbe.getCausedByException() instanceof HeuristicMixedException)) {
log.errorf(ejbe,"Wrong exception type was obtained on 1PC remote Jakarta Enterprise Beans call. Expected %s to be caught..",
HeuristicMixedException.class.getName());
Assert.fail("Expecting the remote 1PC Jakarta Enterprise Beans call fails with HeuristicMixedException but it did not happen" +
" and the " + ejbe + " was caught instead.");
}
}
RecoveryExecutor recoveryExecutor = new RecoveryExecutor(managementClientClient);
TransactionCheckerSingletonRemote serverSingletonChecker = RemoteLookups.lookupEjbStateless(managementClientServer,
SERVER_DEPLOYMENT, TransactionCheckerSingleton.class, TransactionCheckerSingletonRemote.class);
Assert.assertEquals("Expecting the transaction was interrupted on one resource but the second " +
"should be still committed at the server", 1, serverSingletonChecker.getCommitted());
// running recovery on heuristic transaction should not recover it
Assert.assertTrue("Expecting recovery being run without any issue", recoveryExecutor.runTransactionRecovery());
Assert.assertEquals("Expecting no other resource to be committed when recovery is run as the transaction" +
" finished with heuristics and manual intervention is needed", 1, serverSingletonChecker.getCommitted());
// running WFLY :recover operation on all participants of the transactions in the Narayana object store
recoveryExecutor.cliRecoverAllTransactions();
// after :recover is executed the heuristic state is changed to 'prepared'. The recovery should commit it later
Assert.assertTrue("Expecting the recovery after cli :recover operation to be run without any issue",
recoveryExecutor.runTransactionRecovery());
if(serverSingletonChecker.getCommitted() == 1) { // ensuring one whole recovery cycle to be executed before the final check
Assert.assertTrue("Expecting the #2 recovery after cli :recover operation to be run without any issue",
recoveryExecutor.runTransactionRecovery());
}
Assert.assertEquals("Expecting both resources on the server were committed",
2, serverSingletonChecker.getCommitted());
assertEmptyClientWftcDataDirectory();
}
private void assertEmptyClientWftcDataDirectory() {
Path wftcDataDirectory = Paths.get("target", CLIENT_SERVER_JBOSS_HOME, "standalone", "data", WFTC_DATA_DIRECTORY_NAME);
Assert.assertTrue("Expecting existence of WFTC data directory at " + wftcDataDirectory,
wftcDataDirectory.toFile().isDirectory());
String[] wftcFiles = wftcDataDirectory.toFile().list();
Assert.assertEquals("WFTC data directory at " + wftcDataDirectory
+ " is not empty but it should be. There are files: " + Arrays.asList(wftcFiles), 0, wftcFiles.length);
}
}
| 18,754 | 57.065015 | 198 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/transaction/preparehalt/ClientBeanRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ejb.client.outbound.connection.transaction.preparehalt;
import jakarta.ejb.Remote;
@Remote
public interface ClientBeanRemote {
void twoPhaseCommitCrashAtClient(String remoteDeploymentName);
void twoPhaseIntermittentCommitFailureOnServer(String remoteDeploymentName);
void onePhaseIntermittentCommitFailureOnServer(String remoteDeploymentName);
}
| 1,421 | 42.090909 | 92 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/outbound/connection/transaction/preparehalt/ClientBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ejb.client.outbound.connection.transaction.preparehalt;
import org.jboss.as.test.integration.transactions.TestXAResource;
import jakarta.annotation.Resource;
import jakarta.ejb.Stateless;
import javax.naming.Context;
import javax.naming.NamingException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import jakarta.transaction.TransactionManager;
import java.util.Hashtable;
/**
* A bean which uses remote outbound connection configured
* for calling the second instance of the app server via Jakarta Enterprise Beans remoting.
*/
@Stateless
public class ClientBean implements ClientBeanRemote {
@Resource(lookup = "java:/TransactionManager")
private TransactionManager tm;
public void twoPhaseCommitCrashAtClient(String remoteDeploymentName) {
TransactionalRemote bean = getRemote(remoteDeploymentName);
bean.enlistOnePersistentXAResource();
try {
// Enlisting resource for having the 2PC started (the second resource is the Jakarta Enterprise Beans remote call)
// the resource crashes the VM at start of the XAResource.prepare method
// We depend on the transaction manager strict ordering - the order of resource enlistment
// matches the order during 2PC processing
tm.getTransaction().enlistResource(new TestXAResource(TestXAResource.TestAction.PREPARE_CRASH_VM));
} catch (SystemException | RollbackException e) {
throw new RuntimeException("Cannot enlist " + TestXAResource.class.getSimpleName() + " to the current transaction", e);
}
}
public void twoPhaseIntermittentCommitFailureOnServer(String remoteDeploymentName) {
TransactionalRemote bean = getRemote(remoteDeploymentName);
bean.intermittentCommitFailure();
try {
// Enlisting second resource to force 2PC being processed
tm.getTransaction().enlistResource(new TestXAResource());
} catch (SystemException | RollbackException e) {
throw new RuntimeException("Cannot enlist " + TestXAResource.class.getSimpleName() + " to the current transaction", e);
}
}
public void onePhaseIntermittentCommitFailureOnServer(String remoteDeploymentName) {
TransactionalRemote bean = getRemote(remoteDeploymentName);
// Enlisting only remote Jakarta Enterprise Beans bean by the remote call and no other resource to process with 1PC
// but the remote Jakarta Enterprise Beans works with two resources and on 1PC commit it triggers the 2PC
bean.intermittentCommitFailureTwoPhase();
}
private TransactionalRemote getRemote(String remoteDeployment) {
String lookupBean = "ejb:/" + remoteDeployment + "/"
+ "" + "/" + "TransactionalBean" + "!" + TransactionalRemote.class.getName();
try {
final Hashtable props = new Hashtable();
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
final Context context = new javax.naming.InitialContext(props);
final TransactionalRemote remote = (TransactionalRemote) context.lookup(lookupBean);
return remote;
} catch (NamingException ne) {
throw new RuntimeException("Cannot get bean " + lookupBean, ne);
}
}
}
| 4,404 | 46.880435 | 131 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/reconnect/SimpleCrashBean.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.jboss.as.test.manualmode.ejb.client.reconnect;
import jakarta.ejb.Stateless;
/**
* Simple SLSB test bean.
*
* @author <a href="mailto:[email protected]">Ivo Studensky</a>
*/
@Stateless
public class SimpleCrashBean implements SimpleCrashBeanRemote {
public String echo(String message) {
return message;
}
}
| 1,371 | 34.179487 | 70 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/reconnect/SimpleCrashBeanRemote.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.jboss.as.test.manualmode.ejb.client.reconnect;
import jakarta.ejb.Remote;
@Remote
public interface SimpleCrashBeanRemote {
String echo(String message);
}
| 1,199 | 39 | 70 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/reconnect/EJBClientReconnectionTestCase.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.jboss.as.test.manualmode.ejb.client.reconnect;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingException;
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.test.manualmode.ejb.Util;
import org.jboss.ejb.client.EJBClient;
import org.jboss.ejb.client.StatelessEJBLocator;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Simple Jakarta Enterprise Beans client reconnection test case.
* See AS7-3215.
*
* @author <a href="mailto:[email protected]">Ivo Studensky</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
public class EJBClientReconnectionTestCase {
private static final Logger log = Logger.getLogger(EJBClientReconnectionTestCase.class);
private static final String DEPLOYMENT = "ejbclientreconnection";
private static final String CONTAINER = "jbossas-non-clustered";
@ArquillianResource
private ContainerController controller;
@ArquillianResource
private Deployer deployer;
private Context context;
@Deployment(name = DEPLOYMENT, managed = false, testable = false)
@TargetsContainer(CONTAINER)
public static Archive<?> deploy() {
return ShrinkWrap.create(JavaArchive.class, DEPLOYMENT + ".jar")
.addClasses(SimpleCrashBean.class, SimpleCrashBeanRemote.class);
}
@Before
public void before() throws Exception {
final Properties ejbClientProperties = setupEJBClientProperties();
this.context = Util.createNamingContext(ejbClientProperties);
controller.start(CONTAINER);
log.trace("===appserver started===");
deployer.deploy(DEPLOYMENT);
log.trace("===deployment deployed===");
}
@After
public void after() throws Exception {
this.context.close();
try {
if (!controller.isStarted(CONTAINER)) {
controller.start(CONTAINER);
}
deployer.undeploy(DEPLOYMENT);
log.trace("===deployment undeployed===");
} finally {
controller.stop(CONTAINER);
log.trace("===appserver stopped===");
}
}
@Test
public void testReconnection() throws Throwable {
SimpleCrashBeanRemote bean = lookup(SimpleCrashBeanRemote.class, SimpleCrashBean.class, DEPLOYMENT);
assertNotNull(bean);
String echo = bean.echo("Hello!");
assertEquals("Hello!", echo);
controller.stop(CONTAINER);
log.trace("===appserver stopped===");
controller.start(CONTAINER);
log.trace("===appserver started again===");
SimpleCrashBeanRemote bean2 = lookup(SimpleCrashBeanRemote.class, SimpleCrashBean.class, DEPLOYMENT);
assertNotNull(bean2);
echo = bean2.echo("Bye!");
assertEquals("Bye!", echo);
}
@Test
public void testReconnectionWithClientAPI() throws Throwable {
// TODO Elytron: Determine how this should be adapted once the transaction client changes are in
//final EJBClientTransactionContext localUserTxContext = EJBClientTransactionContext.createLocal();
//EJBClientTransactionContext.setGlobalContext(localUserTxContext);
final StatelessEJBLocator<SimpleCrashBeanRemote> locator = new StatelessEJBLocator(SimpleCrashBeanRemote.class, "", DEPLOYMENT, SimpleCrashBean.class.getSimpleName(), "");
final SimpleCrashBeanRemote proxy = EJBClient.createProxy(locator);
assertNotNull(proxy);
String echo = proxy.echo("Hello!");
assertEquals("Hello!", echo);
controller.stop(CONTAINER);
log.trace("===appserver stopped===");
controller.start(CONTAINER);
log.trace("===appserver started again===");
final StatelessEJBLocator<SimpleCrashBeanRemote> locator2 = new StatelessEJBLocator(SimpleCrashBeanRemote.class, "", DEPLOYMENT, SimpleCrashBean.class.getSimpleName(), "");
final SimpleCrashBeanRemote proxy2 = EJBClient.createProxy(locator2);
assertNotNull(proxy2);
echo = proxy2.echo("Bye!");
assertEquals("Bye!", echo);
}
private <T> T lookup(final Class<T> remoteClass, final Class<?> beanClass, final String archiveName) throws NamingException {
String myContext = Util.createRemoteEjbJndiContext(
"",
archiveName,
"",
beanClass.getSimpleName(),
remoteClass.getName(),
false);
return remoteClass.cast(context.lookup(myContext));
}
/**
* Sets up the Jakarta Enterprise Beans client properties based on this testcase specific jboss-ejb-client.properties file
*
* @return
* @throws java.io.IOException
*/
private static Properties setupEJBClientProperties() throws IOException {
// setup the properties
final String clientPropertiesFile = "jboss-ejb-client.properties";
final InputStream inputStream = EJBClientReconnectionTestCase.class.getResourceAsStream(clientPropertiesFile);
if (inputStream == null) {
throw new IllegalStateException("Could not find " + clientPropertiesFile + " in classpath");
}
final Properties properties = new Properties();
properties.load(inputStream);
return properties;
}
}
| 7,075 | 36.638298 | 180 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/cluster/NonClusteredStatefulNodeNameEcho.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.ejb.client.cluster;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateful;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;
/**
* @author Jaikiran Pai
*/
@Stateful
@Remote(NodeNameEcho.class)
public class NonClusteredStatefulNodeNameEcho implements NodeNameEcho {
private NodeNameEcho clusteredDelegate;
@Override
public String getNodeName(final boolean preferOtherNode) {
final String me = System.getProperty("jboss.node.name");
if (this.clusteredDelegate == null) {
this.lookupClusteredBean();
}
String nodeName = this.clusteredDelegate.getNodeName(false);
if (preferOtherNode && me.equals(nodeName)) {
for (int i = 0; i < 10; i++) {
// do another lookup to try creating a SFSB instance on a different node
this.lookupClusteredBean();
nodeName = this.clusteredDelegate.getNodeName(false);
if (!me.equals(nodeName)) {
return nodeName;
}
}
throw new RuntimeException("Invocation on clustered bean always (10 times) ended up picking current node " + me);
}
return nodeName;
}
private void lookupClusteredBean() {
final Properties props = new Properties();
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
try {
final Context context = new InitialContext(props);
try {
this.clusteredDelegate = (NodeNameEcho) context.lookup("ejb:/server-to-server-clustered-ejb-invocation//ClusteredStatefulNodeNameEcho!org.jboss.as.test.manualmode.ejb.client.cluster.NodeNameEcho?stateful");
} finally {
context.close();
}
} catch (NamingException ne) {
throw new RuntimeException(ne);
}
}
}
| 3,004 | 38.025974 | 222 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/cluster/ClusteredStatefulNodeNameEcho.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.ejb.client.cluster;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateful;
/**
* @author Jaikiran Pai
*/
@Stateful
@Remote(NodeNameEcho.class)
public class ClusteredStatefulNodeNameEcho implements NodeNameEcho {
@Override
public String getNodeName(boolean preferOtherNode) {
return System.getProperty("jboss.node.name");
}
}
| 1,411 | 35.205128 | 70 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/cluster/ApplicationSpecificClusterNodeSelector.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.ejb.client.cluster;
import org.jboss.ejb.client.ClusterNodeSelector;
import java.util.Random;
/**
* @author Jaikiran Pai
*/
public class ApplicationSpecificClusterNodeSelector implements ClusterNodeSelector {
@Override
public String selectNode(final String clusterName, final String[] connectedNodes, final String[] availableNodes) {
final Random random = new Random();
// check if there are any connected nodes. If there are then just reuse them
if (connectedNodes.length > 0) {
if (connectedNodes.length == 1) {
return connectedNodes[0];
}
final int randomConnectedNode = random.nextInt(connectedNodes.length);
return connectedNodes[randomConnectedNode];
}
// there are no connected nodes. so use the available nodes and let the cluster context
// establish a connection for the selected node
if (availableNodes.length == 1) {
return availableNodes[0];
}
final int randomSelection = random.nextInt(availableNodes.length);
return availableNodes[randomSelection];
}
}
| 2,202 | 40.566038 | 118 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/cluster/EJBClientClusterConfigurationTestCase.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.ejb.client.cluster;
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.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.manualmode.ejb.Util;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.api.Authentication;
import javax.naming.Context;
import javax.naming.NamingException;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
/**
* Tests that clustered Jakarta Enterprise Beans remote invocations between the server and client, where the client itself
* is another server instance, work correctly and the clustering failover capabilities are available. This
* further tests that the cluster configurations in the jboss-ejb-client.xml are honoured.
*
* @author Jaikiran Pai
* @see https://issues.jboss.org/browse/AS7-4099
*/
@RunWith(Arquillian.class)
@RunAsClient
@Ignore("WFLY-4421")
public class EJBClientClusterConfigurationTestCase {
private static final Logger logger = Logger.getLogger(EJBClientClusterConfigurationTestCase.class);
private static final String MODULE_NAME = "server-to-server-clustered-ejb-invocation";
private static final String DEFAULT_JBOSSAS = "default-jbossas";
private static final String JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION = "jbossas-with-remote-outbound-connection";
private static final String DEFAULT_AS_DEPLOYMENT = "default-jbossas-deployment";
private static final String DEPLOYMENT_WITH_JBOSS_EJB_CLIENT_XML = "other-deployment";
// These should match what's configured in arquillian.xml for -Djboss.node.name of each server instance
private static final String DEFAULT_JBOSSAS_NODE_NAME = "default-jbossas";
private static final String JBOSSAS_WITH_OUTBOUND_CONNECTION_NODE_NAME = "jbossas-with-remote-outbound-connection";
@ArquillianResource
private ContainerController container;
@ArquillianResource
private Deployer deployer;
private Context context;
@Before
public void before() throws Exception {
final Properties ejbClientProperties = setupEJBClientProperties();
this.context = Util.createNamingContext(ejbClientProperties);
}
@After
public void after() throws NamingException {
this.context.close();
}
@Deployment(name = DEFAULT_AS_DEPLOYMENT, managed = false, testable = false)
@TargetsContainer(DEFAULT_JBOSSAS)
public static Archive createContainer1Deployment() {
final JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, MODULE_NAME + ".jar");
ejbJar.addClasses(ClusteredStatefulNodeNameEcho.class, NodeNameEcho.class);
return ejbJar;
}
@Deployment(name = DEPLOYMENT_WITH_JBOSS_EJB_CLIENT_XML, managed = false, testable = false)
@TargetsContainer(JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION)
public static Archive createContainer2Deployment() {
final JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, MODULE_NAME + ".jar");
ejbJar.addClasses(ClusteredStatefulNodeNameEcho.class, CustomDeploymentNodeSelector.class, NonClusteredStatefulNodeNameEcho.class, NodeNameEcho.class, ApplicationSpecificClusterNodeSelector.class);
ejbJar.addAsManifestResource(NonClusteredStatefulNodeNameEcho.class.getPackage(), "jboss-ejb-client.xml", "jboss-ejb-client.xml");
return ejbJar;
}
/**
* 1) Start a server (A) which has a remote outbound connection to another server (B).
* 2) Both server A and B have clustering capability and have a deployment containing a clustered SFSB.
* 3) Server A furthermore has a non-clustered SFSB too.
* 4) This test invokes on the non-clustered SFSB on server A which inturn invokes on the clustered
* SFSB on server B (this is done by disabling local ejb receiver in the jboss-ejb-client.xml).
* 5) Invocation works fine and at the same time (asynchronously) server B sends back a cluster topology
* to server A containing, both server A and B and the nodes.
* 6) The test then stops server B and invokes on the same non-clustered SFSB instance of server A, which inturn
* invokes on the stateful clustered SFSB which it had injected earlier. This time since server B (which owns the session)
* is down the invocation is expected to end up on server A itself (since server A is part of the cluster too)
*
* @throws Exception
*/
@Test
public void testServerToServerClusterFormation() throws Exception {
// First start the default server
this.container.start(DEFAULT_JBOSSAS);
// remove local authentication for applications at the server B
final ModelControllerClient serverBClient = createModelControllerClient(DEFAULT_JBOSSAS);
ModelControllerClient serverAClient = null;
try {
// deploy a deployment which contains a clustered Jakarta Enterprise Beans
this.deployer.deploy(DEFAULT_AS_DEPLOYMENT);
// start the other server
this.container.start(JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION);
// setup system properties for jboss-ejb-client.xml before the deployment
serverAClient = createModelControllerClient(JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION);
SystemPropertySetup.INSTANCE.setup(createManagementClient(serverAClient, JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION), JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION);
// deploy the deployment containing a non-clustered EJB
this.deployer.deploy(DEPLOYMENT_WITH_JBOSS_EJB_CLIENT_XML);
// invoke on the non-clustered bean which internally calls the clustered bean on a remote server
final NodeNameEcho nonClusteredBean = (NodeNameEcho) this.context.lookup("ejb:/" + MODULE_NAME + "//" + NonClusteredStatefulNodeNameEcho.class.getSimpleName() + "!" + NodeNameEcho.class.getName() + "?stateful");
final String nodeNameBeforeShutdown = nonClusteredBean.getNodeName(true);
Assert.assertEquals("Jakarta Enterprise Beans invocation ended up on unexpected node", DEFAULT_JBOSSAS_NODE_NAME, nodeNameBeforeShutdown);
// now shutdown the default server
this.container.stop(DEFAULT_JBOSSAS);
// now invoke again. this time the internal invocation on the clustered bean should end up on
// one of the cluster nodes instead of the default server, since it was shutdown
final String nodeNameAfterShutdown = nonClusteredBean.getNodeName(false);
Assert.assertEquals("Jakarta Enterprise Beans invocation ended up on unexpected node after shutdown", JBOSSAS_WITH_OUTBOUND_CONNECTION_NODE_NAME, nodeNameAfterShutdown);
} finally {
try {
this.deployer.undeploy(DEPLOYMENT_WITH_JBOSS_EJB_CLIENT_XML);
SystemPropertySetup.INSTANCE.tearDown(createManagementClient(serverAClient, JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION), JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION);
} catch (Exception e) {
logger.trace("Exception during container shutdown", e);
} finally {
this.container.stop(JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION);
}
try {
if (!this.container.isStarted(DEFAULT_JBOSSAS)) {
//start the default server again so that we can clean up the deployment first
this.container.start(DEFAULT_JBOSSAS);
}
this.deployer.undeploy(DEFAULT_AS_DEPLOYMENT);
} catch (Exception e) {
logger.trace("Exception during container shutdown", e);
} finally {
this.container.stop(DEFAULT_JBOSSAS);
}
if (serverAClient != null) {
serverAClient.close();
}
serverBClient.close();
}
}
/**
* Sets up the Jakarta Enterprise Beans client properties based on this testcase specific jboss-ejb-client.properties file
*
* @return
* @throws java.io.IOException
*/
private static Properties setupEJBClientProperties() throws IOException {
// setup the properties
final String clientPropertiesFile = "jboss-ejb-client.properties";
final InputStream inputStream = EJBClientClusterConfigurationTestCase.class.getResourceAsStream(clientPropertiesFile);
if (inputStream == null) {
throw new IllegalStateException("Could not find " + clientPropertiesFile + " in classpath");
}
final Properties properties = new Properties();
properties.load(inputStream);
return properties;
}
private static ModelControllerClient createModelControllerClient(final String container) throws UnknownHostException {
if (container == null) {
throw new IllegalArgumentException("container cannot be null");
}
final int portOffset = getContainerPortOffset(container);
final int managementPort = TestSuiteEnvironment.getServerPort() + portOffset;
final String managementAddress = getServerAddress(container);
return ModelControllerClient.Factory.create(InetAddress.getByName(managementAddress),
managementPort,
Authentication.getCallbackHandler());
}
private static ManagementClient createManagementClient(final ModelControllerClient client, final String container) throws UnknownHostException {
if (container == null) {
throw new IllegalArgumentException("container cannot be null");
}
final int portOffset = getContainerPortOffset(container);
final int managementPort = TestSuiteEnvironment.getServerPort() + portOffset;
final String managementAddress = getServerAddress(container);
return new ManagementClient(client, managementAddress, managementPort, "remote+http");
}
private static int getContainerPortOffset(final String container) {
final int portOffset;
if (JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION.equals(container)) {
portOffset = 100;
} else {
portOffset = 0;
}
return portOffset;
}
private static String getServerAddress(final String container) {
if (JBOSSAS_WITH_REMOTE_OUTBOUND_CONNECTION.equals(container)) {
return TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddressNode1());
}
return TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddress());
}
static class SystemPropertySetup implements ServerSetupTask {
public static final SystemPropertySetup INSTANCE = new SystemPropertySetup();
@Override
public void setup(final ManagementClient managementClient, final String containerId) throws Exception {
final ModelControllerClient client = managementClient.getControllerClient();
ModelNode operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.outbound-connection-ref", ModelDescriptionConstants.ADD);
operation.get("value").set("remote-ejb-connection");
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.exclude-local-receiver", ModelDescriptionConstants.ADD);
operation.get("value").set("true");
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.cluster-name", ModelDescriptionConstants.ADD);
operation.get("value").set("ejb");
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.max-allowed-connected-nodes", ModelDescriptionConstants.ADD);
operation.get("value").set("20");
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.cluster-node-selector", ModelDescriptionConstants.ADD);
operation.get("value").set("org.jboss.as.test.manualmode.ejb.client.cluster.ApplicationSpecificClusterNodeSelector");
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.connect-timeout", ModelDescriptionConstants.ADD);
operation.get("value").set("15000");
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.username", ModelDescriptionConstants.ADD);
operation.get("value").set("user1");
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.security-realm", ModelDescriptionConstants.ADD);
operation.get("value").set("PasswordRealm");
Utils.applyUpdate(operation, client);
}
@Override
public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception {
final ModelControllerClient client = managementClient.getControllerClient();
ModelNode operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.outbound-connection-ref", ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.exclude-local-receiver", ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.cluster-name", ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.max-allowed-connected-nodes", ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.cluster-node-selector", ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.connect-timeout", ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.username", ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
operation = createOpNode("system-property=EJBClientClusterConfigurationTestCase.security-realm", ModelDescriptionConstants.REMOVE);
Utils.applyUpdate(operation, client);
}
}
}
| 17,058 | 48.880117 | 223 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/cluster/NodeNameEcho.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.ejb.client.cluster;
/**
* @author Jaikiran Pai
*/
public interface NodeNameEcho {
String getNodeName(boolean preferOtherNode);
}
| 1,197 | 37.645161 | 70 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/client/cluster/CustomDeploymentNodeSelector.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.ejb.client.cluster;
import org.jboss.ejb.client.DeploymentNodeSelector;
/**
* @author Jaikiran Pai
*/
public class CustomDeploymentNodeSelector implements DeploymentNodeSelector {
private volatile String previouslySelectedNode;
@Override
public String selectNode(String[] eligibleNodes, String appName, String moduleName, String distinctName) {
if (eligibleNodes.length == 1) {
return eligibleNodes[0];
}
for (String node : eligibleNodes) {
if (!node.equals(previouslySelectedNode)) {
this.previouslySelectedNode = node;
return node;
}
}
return eligibleNodes[0];
}
}
| 1,758 | 35.645833 | 110 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/ssl/SSLRealmSetupTool.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.ejb.ssl;
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.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS;
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.PROTOCOL;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION;
import java.net.URL;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.test.integration.security.common.SecurityTestConstants;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.junit.Assert;
import org.wildfly.test.security.common.AbstractElytronSetupTask;
import org.wildfly.test.security.common.elytron.ConfigurableElement;
import org.wildfly.test.security.common.elytron.CredentialReference;
import org.wildfly.test.security.common.elytron.Path;
import org.wildfly.test.security.common.elytron.SimpleKeyManager;
import org.wildfly.test.security.common.elytron.SimpleKeyStore;
import org.wildfly.test.security.common.elytron.SimpleServerSslContext;
import org.wildfly.test.security.common.elytron.SimpleTrustManager;
/**
* Setup for ssl Jakarta Enterprise Beans remote connection.
* Keystore created on basis of tutorial at https://community.jboss.org/wiki/SSLSetup.
*
* @author Ondrej Chaloupka
* @author Jan Martiska
*/
public class SSLRealmSetupTool {
private static final Logger log = Logger.getLogger(SSLRealmSetupTool.class);
// server config stuff
public static final String SSL_CONTEXT_NAME = "SSLEJBContext";
// server SSL stuff
public static final String SERVER_KEYSTORE_PASSWORD = "JBossPassword";
public static final String SERVER_KEYSTORE_FILENAME = "jbossServer.keystore";
// SSL stuff for both
public static final String KEYSTORES_RELATIVE_PATH = "ejb3/ssl";
/* ----------------- GETTING ModelNode addresses ----------------- */
public static ModelNode getRemotingConnectorAddress() {
ModelNode address = new ModelNode();
address.add(SUBSYSTEM, "remoting");
address.add("http-connector", "https-remoting-connector");
address.protect();
return address;
}
public static ModelNode getRemoteAddress() {
ModelNode address = new ModelNode();
address.add(SUBSYSTEM, "ejb3");
address.add("service", "remote");
address.protect();
return address;
}
/* ----------------- SetupTask methods ----------------- */
/**
* <security-realm name="SSLRealm">
* <server-identities>
* <ssl>
* <keystore path="$resources/ejb3/ssl/jbossServer.keystore" keystore-password="JBossPassword"/>
* </ssl>
* </server-identities>
* <authentication>
* <truststore path="$resources/ejb3/ssl/jbossServer.keystore" keystore-password="JBossPassword"/>
* </authentication>
* </security-realm>
*/
public static void setup(final ManagementClient managementClient) throws Exception {
new SslContextSetup().setup(managementClient.getControllerClient());
// make the https connector use our SSL realm
ModelNode operation = new ModelNode();
operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
operation.get(OP_ADDR).add(SUBSYSTEM, "undertow");
operation.get(OP_ADDR).add("server", "default-server");
operation.get(OP_ADDR).add("https-listener", "https");
operation.get(NAME).set("ssl-context");
operation.get(VALUE).set(SSL_CONTEXT_NAME);
ModelNode result = managementClient.getControllerClient().execute(operation);
Assert.assertEquals(result.toString(), SUCCESS, result.get(OUTCOME).asString());
//add remoting connector
operation = new ModelNode();
operation.get(OP_ADDR).set(SSLRealmSetupTool.getRemotingConnectorAddress());
operation.get(OP).set(ADD);
operation.get("sasl-authentication-factory").set("application-sasl-authentication");
operation.get(PROTOCOL).set("https-remoting");
operation.get("connector-ref").set("https");
operation.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
result = managementClient.getControllerClient().execute(operation);
log.debugf("Adding HTTPS connector", result);
Assert.assertEquals(result.toString(), SUCCESS, result.get(OUTCOME).asString());
// add remoting connector to connectors list <remote connectors="..."/>
operation = new ModelNode();
operation.get(OP_ADDR).set(SSLRealmSetupTool.getRemoteAddress());
operation.get(OP).set("list-add");
operation.get(NAME).set("connectors");
operation.get(VALUE).set("https-remoting-connector");
operation.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
result = managementClient.getControllerClient().execute(operation);
log.debugf("Adding connector to remote connectors list", result);
Assert.assertEquals(result.toString(), SUCCESS, result.get(OUTCOME).asString());
}
public static void tearDown(final ManagementClient managementClient, ContainerController controller) throws Exception {
// remove remoting connector from connectors list <remote connectors="..."/>
ModelNode operation = new ModelNode();
operation.get(OP_ADDR).set(SSLRealmSetupTool.getRemoteAddress());
operation.get(OP).set("list-remove");
operation.get(NAME).set("connectors");
operation.get(VALUE).set("https-remoting-connector");
operation.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
ModelNode result = managementClient.getControllerClient().execute(operation);
log.debugf("remove connector from remote connectors", result);
Assert.assertEquals(result.toString(), SUCCESS, result.get(OUTCOME).asString());
ServerReload.executeReloadAndWaitForCompletion(managementClient);
operation = new ModelNode();
operation.get(OP_ADDR).set(SSLRealmSetupTool.getRemotingConnectorAddress());
operation.get(OP).set(REMOVE);
operation.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
result = managementClient.getControllerClient().execute(operation);
log.debugf("remove HTTPS connector", result);
Assert.assertEquals(result.toString(), SUCCESS, result.get(OUTCOME).asString());
ServerReload.executeReloadAndWaitForCompletion(managementClient);
// restore https connector to previous state
operation = new ModelNode();
operation.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
operation.get(OP_ADDR).add(SUBSYSTEM, "undertow");
operation.get(OP_ADDR).add("server", "default-server");
operation.get(OP_ADDR).add("https-listener", "https");
operation.get(NAME).set("ssl-context");
operation.get(VALUE).set("applicationSSC");
operation.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
result = managementClient.getControllerClient().execute(operation);
Assert.assertEquals(result.toString(), SUCCESS, result.get(OUTCOME).asString());
ServerReload.executeReloadAndWaitForCompletion(managementClient);
new SslContextSetup().tearDown(managementClient.getControllerClient());
controller.stop(SSLEJBRemoteClientTestCase.DEFAULT_JBOSSAS);
}
private static class SslContextSetup extends AbstractElytronSetupTask {
@Override
protected void setup(ModelControllerClient modelControllerClient) throws Exception {
super.setup(modelControllerClient);
}
@Override
protected void tearDown(ModelControllerClient modelControllerClient) throws Exception {
super.tearDown(modelControllerClient);
}
@Override
protected ConfigurableElement[] getConfigurableElements() {
URL keystoreResource = Thread.currentThread().getContextClassLoader().getResource(KEYSTORES_RELATIVE_PATH + "/" + SERVER_KEYSTORE_FILENAME);
return new ConfigurableElement[] {
SimpleKeyStore.builder().withName(SSL_CONTEXT_NAME + SecurityTestConstants.SERVER_KEYSTORE)
.withPath(Path.builder().withPath(keystoreResource.getPath()).build())
.withCredentialReference(CredentialReference.builder().withClearText(SERVER_KEYSTORE_PASSWORD).build())
.build(),
SimpleKeyStore.builder().withName(SSL_CONTEXT_NAME + SecurityTestConstants.SERVER_TRUSTSTORE)
.withPath(Path.builder().withPath(keystoreResource.getPath()).build())
.withCredentialReference(CredentialReference.builder().withClearText(SERVER_KEYSTORE_PASSWORD).build())
.build(),
SimpleKeyManager.builder().withName(SSL_CONTEXT_NAME)
.withKeyStore(SSL_CONTEXT_NAME + SecurityTestConstants.SERVER_KEYSTORE)
.withCredentialReference(CredentialReference.builder().withClearText(SERVER_KEYSTORE_PASSWORD).build())
.build(),
SimpleTrustManager.builder().withName(SSL_CONTEXT_NAME)
.withKeyStore(SSL_CONTEXT_NAME + SecurityTestConstants.SERVER_TRUSTSTORE)
.build(),
SimpleServerSslContext.builder().withName(SSL_CONTEXT_NAME)
.withKeyManagers(SSL_CONTEXT_NAME)
.withTrustManagers(SSL_CONTEXT_NAME)
.withProtocols("TLSv1.2")
.withNeedClientAuth(true)
.build()
};
}
}
}
| 11,887 | 50.021459 | 152 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/ssl/GenerateJBossStores.java
|
/*
* JBoss, Home of Professional Open Source
*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* 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.ejb.ssl;
import java.io.File;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import javax.security.auth.x500.X500Principal;
import org.wildfly.security.x500.cert.SelfSignedX509CertificateAndSigningKey;
/**
* Generates the keystores and truststore needed for the manualmode tests
* @author <a href="mailto:[email protected]">Justin Cook</a>
*/
public class GenerateJBossStores {
private static final String SERVER_KEYSTORE_ALIAS = "jbossalias";
private static final String SERVER_KEYSTORE_PASSWORD = "JBossPassword";
private static final String SERVER_KEYSTORE_FILENAME = "jbossServer.keystore";
private static final String CLIENT_KEYSTORE_FILENAME = "jbossClient.keystore";
private static final String CLIENT_TRUSTSTORE_FILENAME = "jbossClient.truststore";
private static final String CLIENT_KEYSTORE_ALIAS = "clientalias";
private static final String CLIENT_KEYSTORE_PASSWORD = "clientPassword";
private static final String CLIENT_ALIAS_DN = "CN=localhost, OU=Client Unit, O=JBoss, L=Pune, ST=Maharashtra, C=IN";
private static final String JBOSS_ALIAS_DN = "CN=localhost, OU=JBoss Unit, O=JBoss, L=Pune, ST=Maharashtra, C=IN";
private static final String WORKING_DIRECTORY_LOCATION = GenerateJBossStores.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "ejb3/ssl";
private static final File SERVER_KEY_STORE_FILE = new File(WORKING_DIRECTORY_LOCATION, SERVER_KEYSTORE_FILENAME);
private static final File CLIENT_KEY_STORE_FILE = new File(WORKING_DIRECTORY_LOCATION, CLIENT_KEYSTORE_FILENAME);
private static final File TRUST_STORE_FILE = new File(WORKING_DIRECTORY_LOCATION, CLIENT_TRUSTSTORE_FILENAME);
private static final String SHA_1_RSA = "SHA1withRSA";
private static KeyStore loadKeyStore() throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
return ks;
}
private static SelfSignedX509CertificateAndSigningKey createSelfSigned(String DN) {
return SelfSignedX509CertificateAndSigningKey.builder()
.setDn(new X500Principal(DN))
.setKeyAlgorithmName("RSA")
.setSignatureAlgorithmName(SHA_1_RSA)
.setKeySize(1024)
.build();
}
private static KeyStore createKeyStore(SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey, String alias, char[] password) throws Exception {
KeyStore keyStore = loadKeyStore();
X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();
keyStore.setKeyEntry(alias, selfSignedX509CertificateAndSigningKey.getSigningKey(), password, new X509Certificate[]{certificate});
return keyStore;
}
private static void addCertEntry(SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey, KeyStore trustStore, String alias) throws Exception {
X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();
trustStore.setCertificateEntry(alias, certificate);
}
private static void createTemporaryKeyStoreFile(KeyStore keyStore, File outputFile, char[] password) throws Exception {
try (FileOutputStream fos = new FileOutputStream(outputFile)){
keyStore.store(fos, password);
}
}
private static void setUpKeyStores() throws Exception {
File workingDir = new File(WORKING_DIRECTORY_LOCATION);
if (workingDir.exists() == false) {
workingDir.mkdirs();
}
SelfSignedX509CertificateAndSigningKey clientAliasSelfSignedX509CertificateAndSigningKey = createSelfSigned(CLIENT_ALIAS_DN);
SelfSignedX509CertificateAndSigningKey jbossAliasSelfSignedX509CertificateAndSigningKey = createSelfSigned(JBOSS_ALIAS_DN);
KeyStore serverKeyStore = createKeyStore(jbossAliasSelfSignedX509CertificateAndSigningKey, SERVER_KEYSTORE_ALIAS, SERVER_KEYSTORE_PASSWORD.toCharArray());
addCertEntry(clientAliasSelfSignedX509CertificateAndSigningKey, serverKeyStore, CLIENT_KEYSTORE_ALIAS);
KeyStore clientKeyStore = createKeyStore(clientAliasSelfSignedX509CertificateAndSigningKey, CLIENT_KEYSTORE_ALIAS, CLIENT_KEYSTORE_PASSWORD.toCharArray());
KeyStore trustStore = createKeyStore(clientAliasSelfSignedX509CertificateAndSigningKey, CLIENT_KEYSTORE_ALIAS, CLIENT_KEYSTORE_PASSWORD.toCharArray());
addCertEntry(jbossAliasSelfSignedX509CertificateAndSigningKey, trustStore, SERVER_KEYSTORE_ALIAS);
createTemporaryKeyStoreFile(serverKeyStore, SERVER_KEY_STORE_FILE, SERVER_KEYSTORE_PASSWORD.toCharArray());
createTemporaryKeyStoreFile(clientKeyStore, CLIENT_KEY_STORE_FILE, CLIENT_KEYSTORE_PASSWORD.toCharArray());
createTemporaryKeyStoreFile(trustStore, TRUST_STORE_FILE, CLIENT_KEYSTORE_PASSWORD.toCharArray());
}
public static void main(String[] args) throws Exception {
setUpKeyStores();
}
}
| 5,764 | 50.017699 | 171 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/ssl/SSLEJBRemoteClientTestCase.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.ejb.ssl;
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.ModelControllerClient;
import org.jboss.as.test.manualmode.ejb.ssl.beans.StatefulBean;
import org.jboss.as.test.manualmode.ejb.ssl.beans.StatefulBeanRemote;
import org.jboss.as.test.manualmode.ejb.ssl.beans.StatelessBean;
import org.jboss.as.test.manualmode.ejb.ssl.beans.StatelessBeanRemote;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.logging.Logger;
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.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.Future;
/**
* Testing ssl connection of remote Jakarta Enterprise Beans client.
*
* @author Ondrej Chaloupka
* @author Jan Martiska
*/
@RunWith(Arquillian.class)
@RunAsClient
public class SSLEJBRemoteClientTestCase {
private static final Logger log = Logger.getLogger(SSLEJBRemoteClientTestCase.class);
private static final String MODULE_NAME_STATELESS = "ssl-remote-ejb-client-test";
private static final String MODULE_NAME_STATEFUL = "ssl-remote-ejb-client-test-stateful";
public static final String DEPLOYMENT_STATELESS = "dep_stateless";
public static final String DEPLOYMENT_STATEFUL = "dep_stateful";
private static boolean serverConfigDone = false;
@ArquillianResource
private static ContainerController container;
@ArquillianResource
private Deployer deployer;
public static final String DEFAULT_JBOSSAS = "default-jbossas";
@Deployment(name = DEPLOYMENT_STATELESS, managed = false)
@TargetsContainer(DEFAULT_JBOSSAS)
public static Archive<?> deployStateless() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, MODULE_NAME_STATELESS + ".jar");
jar.addClasses(StatelessBeanRemote.class, StatelessBean.class);
return jar;
}
@Deployment(name = DEPLOYMENT_STATEFUL, managed = false)
@TargetsContainer(DEFAULT_JBOSSAS)
public static Archive<?> deployStateful() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, MODULE_NAME_STATEFUL + ".jar");
jar.addClasses(StatefulBeanRemote.class, StatefulBean.class);
return jar;
}
@BeforeClass
public static void prepare() throws Exception {
log.trace("*** javax.net.ssl.trustStore="+System.getProperty("javax.net.ssl.trustStore"));
log.trace("*** javax.net.ssl.trustStorePassword="+System.getProperty("javax.net.ssl.trustStorePassword"));
log.trace("*** javax.net.ssl.keyStore="+System.getProperty("javax.net.ssl.keyStore"));
log.trace("*** javax.net.ssl.keyStorePassword="+System.getProperty("javax.net.ssl.keyStorePassword"));
System.setProperty("jboss.ejb.client.properties.skip.classloader.scan", "true");
}
private static Properties setupEJBClientProperties() throws IOException {
log.trace("*** reading EJBClientContextSelector properties");
// setup the properties
final String clientPropertiesFile = "org/jboss/as/test/manualmode/ejb/ssl/jboss-ejb-client.properties";
final InputStream inputStream = SSLEJBRemoteClientTestCase.class.getClassLoader().getResourceAsStream(clientPropertiesFile);
if (inputStream == null) {
throw new IllegalStateException("Could not find " + clientPropertiesFile + " in classpath");
}
final Properties properties = new Properties();
properties.load(inputStream);
return properties;
}
@Before
public void prepareServerOnce() throws Exception {
if(!serverConfigDone) {
// prepare server config and then restart
log.trace("*** preparing server configuration");
ManagementClient managementClient;
log.trace("*** starting server");
container.start(DEFAULT_JBOSSAS);
final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient();
managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http");
log.trace("*** will configure server now");
SSLRealmSetupTool.setup(managementClient);
log.trace("*** restarting server");
container.stop(DEFAULT_JBOSSAS);
container.start(DEFAULT_JBOSSAS);
serverConfigDone = true;
} else {
log.trace("*** Server already prepared, skipping config procedure");
}
}
@AfterClass
public static void tearDown() throws Exception {
final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient();
final ManagementClient mClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http");
SSLRealmSetupTool.tearDown(mClient, container);
}
private Properties getEjbClientContextProperties() throws IOException {
Properties env = new Properties();
env.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
env.put("jboss.naming.client.ejb.context", true);
env.putAll(setupEJBClientProperties());
return env;
}
@Test
public void testStatelessBean() throws Exception {
log.trace("**** deploying deployment with stateless beans");
deployer.deploy(DEPLOYMENT_STATELESS);
log.trace("**** creating InitialContext");
InitialContext ctx = new InitialContext(getEjbClientContextProperties());
try {
log.trace("**** looking up StatelessBean through JNDI");
StatelessBeanRemote bean = (StatelessBeanRemote)
ctx.lookup("ejb:/" + MODULE_NAME_STATELESS + "/" + StatelessBean.class.getSimpleName() + "!" + StatelessBeanRemote.class.getCanonicalName());
log.trace("**** About to perform synchronous call on stateless bean");
String response = bean.sayHello();
log.trace("**** The answer is: " + response);
Assert.assertEquals("Remote invocation of Jakarta Enterprise Beans were not successful", StatelessBeanRemote.ANSWER, response);
deployer.undeploy(DEPLOYMENT_STATELESS);
} finally {
ctx.close();
}
}
@Test
public void testStatelessBeanAsync() throws Exception {
log.trace("**** deploying deployment with stateless beans");
deployer.deploy(DEPLOYMENT_STATELESS);
log.trace("**** creating InitialContext");
InitialContext ctx = new InitialContext(getEjbClientContextProperties());
try {
log.trace("**** looking up StatelessBean through JNDI");
StatelessBeanRemote bean = (StatelessBeanRemote)
ctx.lookup("ejb:/" + MODULE_NAME_STATELESS + "/" + StatelessBean.class.getSimpleName() + "!" + StatelessBeanRemote.class.getCanonicalName());
log.trace("**** About to perform asynchronous call on stateless bean");
Future<String> futureResponse = bean.sayHelloAsync();
String response = futureResponse.get();
log.trace("**** The answer is: " + response);
Assert.assertEquals("Remote asynchronous invocation of Jakarta Enterprise Beans were not successful", StatelessBeanRemote.ANSWER, response);
deployer.undeploy(DEPLOYMENT_STATELESS);
} finally {
ctx.close();
}
}
@Test
public void testStatefulBean() throws Exception {
log.trace("**** deploying deployment with stateful beans");
deployer.deploy(DEPLOYMENT_STATEFUL);
log.trace("**** creating InitialContext");
InitialContext ctx = new InitialContext(getEjbClientContextProperties());
try {
log.trace("**** looking up StatefulBean through JNDI");
StatefulBeanRemote bean = (StatefulBeanRemote)
ctx.lookup("ejb:/" + MODULE_NAME_STATEFUL + "/" + StatefulBean.class.getSimpleName() + "!" + StatefulBeanRemote.class.getCanonicalName()+"?stateful");
log.trace("**** About to perform synchronous call on stateful bean");
String response = bean.sayHello();
log.trace("**** The answer is: " + response);
Assert.assertEquals("Remote invocation of Jakarta Enterprise Beans were not successful", StatefulBeanRemote.ANSWER, response);
deployer.undeploy(DEPLOYMENT_STATEFUL);
} finally {
ctx.close();
}
}
@Test
public void testStatefulBeanAsync() throws Exception {
log.trace("**** deploying deployment with stateful beans");
deployer.deploy(DEPLOYMENT_STATEFUL);
log.trace("**** creating InitialContext");
InitialContext ctx = new InitialContext(getEjbClientContextProperties());
try {
log.trace("**** looking up StatefulBean through JNDI");
StatefulBeanRemote bean = (StatefulBeanRemote)
ctx.lookup("ejb:/" + MODULE_NAME_STATEFUL + "/" + StatefulBean.class.getSimpleName() + "!" + StatefulBeanRemote.class.getCanonicalName()+"?stateful");
log.trace("**** About to perform asynchronous call on stateful bean");
Future<String> futureResponse = bean.sayHelloAsync();
String response = futureResponse.get();
log.trace("**** The answer is: " + response);
Assert.assertEquals("Remote asynchronous invocation of Jakarta Enterprise Beans were not successful", StatefulBeanRemote.ANSWER, response);
deployer.undeploy(DEPLOYMENT_STATEFUL);
} finally {
ctx.close();
}
}
}
| 11,460 | 46.754167 | 170 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/ssl/beans/StatefulBean.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.ejb.ssl.beans;
import jakarta.ejb.Stateful;
import java.util.concurrent.Future;
import jakarta.ejb.AsyncResult;
import jakarta.ejb.Asynchronous;
/**
* @author Jan Martiska
*/
@Stateful
public class StatefulBean implements StatefulBeanRemote {
@Override
public String sayHello() {
return ANSWER;
}
@Override
@Asynchronous
public Future<String> sayHelloAsync() {
return new AsyncResult<String>(ANSWER);
}
}
| 1,498 | 30.229167 | 69 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/ssl/beans/StatefulBeanRemote.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.ejb.ssl.beans;
import jakarta.ejb.Remote;
import java.util.concurrent.Future;
/**
* @author Jan Martiska
*/
@Remote
public interface StatefulBeanRemote {
String ANSWER = "Hello";
String sayHello();
Future<String> sayHelloAsync();
}
| 1,291 | 32.128205 | 69 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/ssl/beans/StatelessBeanRemote.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.ejb.ssl.beans;
import jakarta.ejb.Remote;
import java.util.concurrent.Future;
/**
* @author Ondrej Chaloupka
* @author Jan Martiska
*/
@Remote
public interface StatelessBeanRemote {
String ANSWER = "Hello";
String sayHello();
Future<String> sayHelloAsync();
}
| 1,321 | 31.243902 | 69 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ejb/ssl/beans/StatelessBean.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.ejb.ssl.beans;
import jakarta.ejb.AsyncResult;
import jakarta.ejb.Asynchronous;
import jakarta.ejb.Stateless;
import java.util.concurrent.Future;
/**
* @author Ondrej Chaloupka
* @author Jan Martiska
*/
@Stateless
public class StatelessBean implements StatelessBeanRemote {
@Override
public String sayHello() {
return ANSWER;
}
@Override
@Asynchronous
public Future<String> sayHelloAsync() {
return new AsyncResult<String>(ANSWER);
}
}
| 1,528 | 30.854167 | 69 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/connectionlistener/ConnectionListenerTestCase.java
|
package org.jboss.as.test.manualmode.jca.connectionlistener;
import static org.junit.Assert.assertNotNull;
import java.sql.SQLException;
import javax.naming.NamingException;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.manualmode.ejb.Util;
import org.jboss.jca.adapters.jdbc.spi.listener.ConnectionListener;
import org.jboss.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Simple connection listener {@link ConnectionListener} test case.
*
* @author <a href="mailto:[email protected]">Hynek Svabek</a>
*/
@RunWith(Arquillian.class)
@ServerSetup(value = {AbstractTestsuite.TestCaseSetup.class})
public class ConnectionListenerTestCase extends AbstractTestsuite {
private static final Logger log = Logger.getLogger(ConnectionListenerTestCase.class);
@ArquillianResource
private ContainerController controller;
@ArquillianResource
private Deployer deployer;
@Before
public void init() throws Exception {
this.context = Util.createNamingContext();
}
@After
public void after() throws Exception {
this.context.close();
}
/**
* Test: insert record in transaction and then rollback
*
* @throws Exception
*/
@Test
public void testConnListenerWithRollback() throws Exception {
testConnListenerTest(DEP_1, false);
}
/**
* Test: insert record in transaction and then rollback
*
* @throws Exception
*/
@Test
public void testConnListenerXaWithRollback() throws Exception {
testConnListenerTest(DEP_1_XA, true);
}
/**
* Test: insert record in transaction and then rollback
*
* @throws Exception
*/
@Test
public void testConnListener2WithRollback() throws Exception {
testConnListener2Test(DEP_2, false);
}
/**
* Test: insert record in transaction and then rollback
*
* @throws Exception
*/
@Test
public void testConnListener2XaWithRollback() throws Exception {
testConnListener2Test(DEP_2_XA, true);
}
/**
* Test: insert record in transaction
*
* @throws Exception
*/
@Test
public void testConnListener3WithoutRollback() throws Exception {
testConnListener3Test(DEP_3, false);
}
/**
* Test: insert record in transaction
*
* @throws Exception
*/
@Test
public void testConnListener3XaWithoutRollback() throws Exception {
testConnListener3Test(DEP_3_XA, true);
}
private void testConnListenerTest(String deployment, boolean useXaDatasource) throws NamingException, SQLException {
try {
if (!controller.isStarted(CONTAINER)) {
controller.start(CONTAINER);
}
deployer.deploy(deployment);
JpaTestSlsbRemote bean = lookup(JpaTestSlsbRemote.class, JpaTestSlsb.class, deployment);
assertNotNull(bean);
bean.initDataSource(useXaDatasource);
bean.assertRecords(0);
bean.insertRecord();
bean.insertRecord();
bean.insertRecord();
bean.insertRecord();
bean.insertRecord();
bean.assertRecords(5);
bean.insertRecord();
bean.insertRecord(true);
bean.insertRecord(true);
bean.assertRecords(6);
bean.assertRecords(6);
/*
* Activated count - Every new connection creates new activated record, rollback -> remove this record..
* Passivated count - After connection.close() is invoked passivatedConnectionListener, rollback doesn't remove passivated record -> it is created after rollback
*/
bean.assertExactCountOfRecords(6, 11, 12);
} finally {
close(deployment);
}
}
private void testConnListener2Test(String deployment, boolean useXaDatasource) throws SQLException, NamingException {
try {
if (!controller.isStarted(CONTAINER)) {
controller.start(CONTAINER);
}
deployer.deploy(deployment);
JpaTestSlsbRemote bean = lookup(JpaTestSlsbRemote.class, JpaTestSlsb.class, deployment);
assertNotNull(bean);
bean.initDataSource(useXaDatasource);
bean.insertRecord();
bean.insertRecord();
bean.insertRecord(true);
/*
* Activated count - we need open connection for select (in assertExactCountOfRecords...) 1 extra activated record is inserted... -> 3
* Passivated count - rollback remove Activated record, but not passivated -> it is created after rollback
*/
bean.assertExactCountOfRecords(2, 3, 3);
} finally {
close(deployment);
}
}
private void testConnListener3Test(String deployment, boolean useXaDatasource) throws Exception {
try {
if (!controller.isStarted(CONTAINER)) {
controller.start(CONTAINER);
}
deployer.deploy(deployment);
JpaTestSlsbRemote bean = lookup(JpaTestSlsbRemote.class, JpaTestSlsb.class, deployment);
assertNotNull(bean);
bean.insertRecord();
bean.insertRecord();
bean.insertRecord();
bean.insertRecord();
bean.insertRecord();
/*
* Activated count - we need open connection for select (in assertExactCountOfRecords...) -> 1 extra activated record is inserted... -> 6
*/
bean.assertExactCountOfRecords(5, 6, 5);
} finally {
close(deployment);
}
}
private void close(String deploymentName) {
try {
if (!controller.isStarted(CONTAINER)) {
controller.start(CONTAINER);
}
} catch (Exception e) {
log.warn(e.getMessage());
}
try {
deployer.undeploy(deploymentName);
} catch (Exception e) {
log.warn(e.getMessage());
}
try {
if (controller.isStarted(CONTAINER)) {
controller.stop(CONTAINER);
}
} catch (Exception e) {
log.warn(e.getMessage());
}
}
}
| 6,635 | 28.891892 | 173 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/connectionlistener/JpaTestSlsbRemote.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.jboss.as.test.manualmode.jca.connectionlistener;
import java.sql.SQLException;
import jakarta.ejb.Remote;
/**
* @author <a href="mailto:[email protected]">Hynek Svabek</a>
*/
@Remote
public interface JpaTestSlsbRemote {
void initDataSource(boolean useXaDs);
void insertRecord() throws SQLException;
void insertRecord(boolean doRollback) throws SQLException;
void assertRecords(int expectedRecords) throws SQLException;
void assertExactCountOfRecords(int expectedRecords, int expectedActivated, int expectedPassivated) throws SQLException;
}
| 1,611 | 35.636364 | 123 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/connectionlistener/AbstractTestsuite.java
|
package org.jboss.as.test.manualmode.jca.connectionlistener;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import javax.naming.Context;
import javax.naming.NamingException;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase;
import org.jboss.as.test.integration.management.util.CLIWrapper;
import org.jboss.as.test.integration.management.util.MgmtOperationException;
import org.jboss.as.test.manualmode.ejb.Util;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
/**
* @author <a href="mailto:[email protected]">Hynek Svabek</a>
*/
public abstract class AbstractTestsuite {
private static final Logger log = Logger.getLogger(AbstractTestsuite.class);
protected static final String MODULE_NAME = "connlistener";
protected static final String CONTAINER = "default-jbossas";
protected static final String DEP_1 = "connlist_1";
protected static final String DEP_1_XA = "connlist_1_xa";
protected static final String DEP_2 = "connlist_2";
protected static final String DEP_2_XA = "connlist_2_xa";
protected static final String DEP_3 = "connlist_3";
protected static final String DEP_3_XA = "connlist_3_xa";
private static final String CONNECTION_LISTENER_CLASS_IMPL = TestConnectionListener.class.getName();
static final String jndiDs = "java:jboss/datasources/StatDS";
static final String jndiXaDs = "java:jboss/datasources/StatXaDS";
protected Context context;
@Deployment(name = DEP_1, managed = false)
public static JavaArchive createDeployment1() throws Exception {
return createDeployment(DEP_1);
}
@Deployment(name = DEP_1_XA, managed = false)
public static JavaArchive createDeployment1Xa() throws Exception {
return createDeployment(DEP_1_XA);
}
@Deployment(name = DEP_2, managed = false)
public static JavaArchive createDeployment2() throws Exception {
return createDeployment(DEP_2);
}
@Deployment(name = DEP_2_XA, managed = false)
public static JavaArchive createDeployment2Xa() throws Exception {
return createDeployment(DEP_2_XA);
}
@Deployment(name = DEP_3, managed = false)
public static JavaArchive createDeployment3() throws Exception {
return createDeployment(DEP_3);
}
@Deployment(name = DEP_3_XA, managed = false)
public static JavaArchive createDeployment3Xa() throws Exception {
return createDeployment(DEP_3_XA);
}
public static JavaArchive createDeployment(String name) throws Exception {
JavaArchive ja = ShrinkWrap.create(JavaArchive.class, name + ".jar");
ja.addClasses(ConnectionListenerTestCase.class, AbstractTestsuite.class, JpaTestSlsb.class, JpaTestSlsbRemote.class, MgmtOperationException.class, ContainerResourceMgmtTestBase.class)
.addAsManifestResource(
new StringAsset("Dependencies: org.jboss.dmr \n"), "MANIFEST.MF");
return ja;
}
protected static class TestCaseSetup extends ContainerResourceMgmtTestBase implements ServerSetupTask {
public static final TestCaseSetup INSTANCE = new TestCaseSetup();
ModelNode dsAddress;
ModelNode dsXaAddress;
@Override
public void setup(final ManagementClient managementClient, String containerId) throws Exception {
setManagementClient(managementClient);
try {
tryRemoveConnListenerModule();//before test, in tearDown we cannot connect to CLI....
addConnListenerModule();
dsAddress = createDataSource(false, jndiDs);
dsXaAddress = createDataSource(true, jndiXaDs);
} catch (Throwable e) {
removeDss();
throw new Exception(e);
}
}
@Override
public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception {
removeDss();
}
public void removeDss() {
try {
remove(dsAddress);
} catch (Throwable e) {
log.warn(e.getMessage());
}
try {
remove(dsXaAddress);
} catch (Throwable e) {
log.warn(e.getMessage());
}
}
/**
* Creates data source and return its node address
*
* @param xa - should be data source XA?
* @param jndiName of data source
* @return ModelNode - address of data source node
* @throws Exception
*/
private ModelNode createDataSource(boolean xa, String jndiName) throws Exception {
ModelNode address = new ModelNode();
address.add(SUBSYSTEM, "datasources");
address.add((xa ? "xa-" : "") + "data-source", jndiName);
address.protect();
ModelNode operation = new ModelNode();
operation.get(OP).set(ADD);
operation.get(OP_ADDR).set(address);
operation.get("jndi-name").set(jndiName);
operation.get("driver-name").set("h2");
operation.get("prepared-statements-cache-size").set(3);
operation.get("user-name").set("sa");
operation.get("password").set("sa");
if (!xa) {
operation.get("connection-url").set("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
}
operation.get("connection-listener-class").set(CONNECTION_LISTENER_CLASS_IMPL);
operation.get("connection-listener-property").set("testString", "MyTest");
/**
* Uncomment after finishing task https://issues.jboss.org/browse/WFLY-2492
*/
// operation.get("connection-listener-module-name").set(MODULE_NAME);
// operation.get("connection-listener-slot").set("main");
operation.get("enabled").set("false");
executeOperation(operation);
if (xa) {
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);
}
operation = new ModelNode();
operation.get(OP).set(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION);
operation.get(OP_ADDR).set(address);
operation.get("name").set("enabled");
operation.get("value").set("true");
executeOperation(operation);
ServerReload.executeReloadAndWaitForCompletion(getManagementClient(), 50000);
return address;
}
protected void addConnListenerModule() throws Exception {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class);
jar.addClasses(TestConnectionListener.class)
.addPackage(Logger.class.getPackage());
File moduleJar = File.createTempFile(MODULE_NAME, ".jar");
copyModuleFile(moduleJar, jar.as(ZipExporter.class).exportAsInputStream());
CLIWrapper cli = new CLIWrapper(true);
cli.sendLine("module add --name=" + MODULE_NAME + " --slot=main --dependencies=org.jboss.ironjacamar.jdbcadapters --resources=" + moduleJar.getAbsolutePath());
/*
* Delete global module after finishing this task
* https://issues.jboss.org/browse/WFLY-2492
*/
cli.sendLine("/subsystem=ee:write-attribute(name=global-modules,value=[{name => " + MODULE_NAME + ",slot => main}]");
cli.quit();
}
protected void tryRemoveConnListenerModule() throws Exception {
try {
CLIWrapper cli = new CLIWrapper(true);
cli.sendLine("module remove --name=" + MODULE_NAME + " --slot=main");
cli.quit();
} catch (Throwable e) {
log.warn(e.getMessage());
}
}
}
protected static void copyModuleFile(File target, InputStream src) throws IOException {
Files.copy(src, target.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
protected <T> T lookup(final Class<T> remoteClass, final Class<?> beanClass, final String archiveName) throws NamingException {
String myContext = Util.createRemoteEjbJndiContext(
"",
archiveName,
"",
beanClass.getSimpleName(),
remoteClass.getName(),
false);
return remoteClass.cast(context.lookup(myContext));
}
}
| 9,998 | 40.83682 | 191 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/connectionlistener/TestConnectionListener.java
|
package org.jboss.as.test.manualmode.jca.connectionlistener;
import java.sql.Connection;
import java.sql.SQLException;
import org.jboss.jca.adapters.jdbc.spi.listener.ConnectionListener;
import org.jboss.logging.Logger;
/**
* @author <a href="mailto:[email protected]">Hynek Svabek</a>
*/
public class TestConnectionListener implements ConnectionListener {
private static final Logger log = Logger.getLogger(TestConnectionListener.class);
private String testString;
public TestConnectionListener() {
testString = "";
}
public void initialize(ClassLoader cl) throws SQLException {
}
public void activated(Connection c) throws SQLException {
if ("MyTest".equals(testString)) {
c.createStatement().executeUpdate("CREATE TABLE IF NOT EXISTS test_table("
+ "description character varying(255),"
+ "type bigint"
+ ")");
c.createStatement().executeUpdate("INSERT INTO test_table(description, type) VALUES ('activated', '1')");
log.trace("Activated record has been created, " + c);
} else {
log.error("Connection listener property testString was not injected properly. Activated record has not been created.");
}
}
public void passivated(Connection c) throws SQLException {
if ("MyTest".equals(testString)) {
c.createStatement().executeUpdate("INSERT INTO test_table(description, type) VALUES ('passivated', '0')");
log.trace("Passivated record has been created, " + c);
} else {
log.error("Connection listener property testString was not injected properly. Passivated record has not been created.");
}
}
public void setTestString(String testString) {
this.testString = testString;
}
}
| 1,848 | 34.557692 | 132 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/connectionlistener/JpaTestSlsb.java
|
package org.jboss.as.test.manualmode.jca.connectionlistener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionManagement;
import jakarta.ejb.TransactionManagementType;
import jakarta.inject.Inject;
import javax.sql.DataSource;
import jakarta.transaction.SystemException;
import jakarta.transaction.UserTransaction;
import org.jboss.logging.Logger;
import org.junit.Assert;
/**
* @author <a href="mailto:[email protected]">Hynek Svabek</a>
*/
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class JpaTestSlsb implements JpaTestSlsbRemote {
private static final Logger log = Logger.getLogger(JpaTestSlsb.class);
@Resource(mappedName = "java:jboss/datasources/StatDS")
private DataSource ds;
@Resource(mappedName = "java:jboss/datasources/StatXaDS")
private DataSource xads;
private DataSource dataSource;
@Inject
UserTransaction userTransaction;
@PostConstruct
public void postConstruct() {
dataSource = ds;
}
public void initDataSource(boolean useXaDs) {
if (useXaDs) {
dataSource = xads;
} else {
dataSource = ds;
}
}
public void insertRecord() throws SQLException {
insertRecord(false);
}
public void insertRecord(boolean doRollback) throws SQLException {
Connection conn = null;
Statement statement = null;
try {
userTransaction.begin();
Assert.assertNotNull(dataSource);
conn = dataSource.getConnection();
statement = conn.createStatement();
statement.executeUpdate("INSERT INTO test_table(description, type) VALUES ('add in bean', '2')");
if (doRollback) {
throw new IllegalStateException("Rollback!");
}
userTransaction.commit();
} catch (Exception e) {
try {
userTransaction.rollback();
} catch (IllegalStateException | SecurityException | SystemException e1) {
log.warn(e1.getMessage());
}
} finally {
closeStatement(statement);
closeConnection(conn);
}
}
public void assertRecords(int expectedRecords) throws SQLException {
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
try {
conn = dataSource.getConnection();
statement = conn.createStatement();
resultSet = statement.executeQuery("SELECT COUNT(*) FROM test_table WHERE type = '1'");
resultSet.next();
int activatedCount = resultSet.getInt(1);
log.trace("Activated count: " + activatedCount);
closeResultSet(resultSet);
closeStatement(statement);
//Even if we only read from DB, activated listener insert record to DB.
Assert.assertTrue("Count of records created activatedConnectionListener must be > our created records", activatedCount > expectedRecords);
statement = conn.createStatement();
resultSet = statement.executeQuery("SELECT COUNT(*) FROM test_table WHERE type = '0'");
resultSet.next();
int passivatedCount = resultSet.getInt(1);
closeResultSet(resultSet);
closeStatement(statement);
log.trace("Passivated count: " + passivatedCount);
if (expectedRecords > 0) {
Assert.assertTrue("Count of records created passivatedConnectionListener must be > 0", passivatedCount > 0);
} else {
Assert.assertTrue("Count of records created activatedConnectionListener must be >= 0", passivatedCount == 0);
}
statement = conn.createStatement();
resultSet = statement.executeQuery("SELECT COUNT(*) FROM test_table WHERE type = '2'");
resultSet.next();
int ourRecordsCount = resultSet.getInt(1);
closeResultSet(resultSet);
closeStatement(statement);
log.trace("Records count: " + ourRecordsCount);
Assert.assertTrue("Unexpected count of records.", expectedRecords == ourRecordsCount);
} finally {
closeResultSet(resultSet);
closeStatement(statement);
closeConnection(conn);
}
}
public void assertExactCountOfRecords(int expectedRecords, int expectedActivated, int expectedPassivated) throws SQLException {
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
try {
conn = dataSource.getConnection();
statement = conn.createStatement();
resultSet = statement.executeQuery("SELECT COUNT(*) FROM test_table WHERE type = '1'");
resultSet.next();
int activatedCount = resultSet.getInt(1);
closeResultSet(resultSet);
closeStatement(statement);
log.trace("Activated count: " + activatedCount);
//Even if we only read from DB, activated listener insert record to DB.
Assert.assertEquals("Activated count: ", expectedActivated, activatedCount);
statement = conn.createStatement();
resultSet = statement.executeQuery("SELECT COUNT(*) FROM test_table WHERE type = '0'");
resultSet.next();
int passivatedCount = resultSet.getInt(1);
closeResultSet(resultSet);
closeStatement(statement);
log.trace("Passivated count: " + passivatedCount);
Assert.assertEquals("Passivated count: ", expectedPassivated, passivatedCount);
statement = conn.createStatement();
resultSet = statement.executeQuery("SELECT COUNT(*) FROM test_table WHERE type = '2'");
resultSet.next();
int ourRecordsCount = resultSet.getInt(1);
closeResultSet(resultSet);
closeStatement(statement);
log.trace("Records count: " + ourRecordsCount);
Assert.assertEquals("Records count: ", expectedRecords, ourRecordsCount);
} finally {
closeResultSet(resultSet);
closeStatement(statement);
closeConnection(conn);
}
}
private void closeResultSet(ResultSet resultSet) {
try {
if (resultSet != null && !resultSet.isClosed()) {
resultSet.close();
}
} catch (Exception e) {
log.warn(e.getMessage());
}
}
private void closeConnection(Connection conn) {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (Exception e) {
log.warn(e.getMessage());
}
}
private void closeStatement(Statement statement) {
try {
if (statement != null && !statement.isClosed()) {
statement.close();
}
} catch (Exception e) {
log.warn(e.getMessage());
}
}
}
| 7,271 | 32.981308 | 150 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/DwmWatermarkTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.jca.workmanager.distributed;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkException;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.shared.TimeoutUtil;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests distributed work manager and whether it really distributes work over multiple nodes. Test cases use two servers
* both with a deployed resource adapter configured to use the DWM. Tests with WATERMARK policy.
*/
@RunWith(Arquillian.class)
@RunAsClient
public class DwmWatermarkTestCase extends AbstractDwmTestCase {
private static final int WATERMARK_MAX_THREADS = 2;
@Override
protected Policy getPolicy() {
return Policy.WATERMARK;
}
@Override
protected Selector getSelector() {
return Selector.MAX_FREE_THREADS;
}
@Override
protected int getWatermarkPolicyOption() {
return WATERMARK_MAX_THREADS - 1;
}
@Override
protected int getSrtMaxThreads() {
return WATERMARK_MAX_THREADS;
}
@Override
protected int getSrtQueueLength() {
return WATERMARK_MAX_THREADS;
}
/**
* Schedules several (one more than our max threads) long work instances and verifies that
* {@link org.jboss.jca.core.api.workmanager.DistributedWorkManager#scheduleWork(Work)} schedules the work on both
* nodes. Policy.WATERMARK will select the local node once, then we hit the watermark limit, and the other node is
* selected.
*/
@Test
public void testWatermarkPolicy() throws WorkException, InterruptedException {
int scheduleWorkAcceptedServer1 = server1Proxy.getScheduleWorkAccepted();
int scheduleWorkAcceptedServer2 = server2Proxy.getScheduleWorkAccepted();
int distributedScheduleWorkAccepted = server1Proxy.getDistributedScheduleWorkAccepted();
for (int i = 0; i < WATERMARK_MAX_THREADS; i++) {
server1Proxy.scheduleWork(new LongWork());
}
Assert.assertTrue("Work did not finish in the expected time on the expected node",
waitForScheduleWork(server2Proxy, scheduleWorkAcceptedServer2 + 1, TimeoutUtil.adjust(WORK_FINISH_MAX_TIMEOUT)));
Assert.assertTrue("Work did not finish in the expected time on the expected node",
waitForScheduleWork(server1Proxy, scheduleWorkAcceptedServer1 + 1, TimeoutUtil.adjust(WORK_FINISH_MAX_TIMEOUT)));
Assert.assertTrue("Expected distributedScheduleWorkAccepted = " + (distributedScheduleWorkAccepted + WATERMARK_MAX_THREADS)
+ " but was: " + server2Proxy.getDistributedScheduleWorkAccepted(),
server2Proxy.getDistributedScheduleWorkAccepted() == distributedScheduleWorkAccepted + WATERMARK_MAX_THREADS);
}
}
| 3,943 | 40.957447 | 131 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/DwmAdminObjectEjb.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.jca.workmanager.distributed;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkException;
public interface DwmAdminObjectEjb {
int getDoWorkAccepted();
int getDoWorkRejected();
int getStartWorkAccepted();
int getStartWorkRejected();
int getScheduleWorkAccepted();
int getScheduleWorkRejected();
int getDistributedDoWorkAccepted();
int getDistributedDoWorkRejected();
int getDistributedStartWorkAccepted();
int getDistributedStartWorkRejected();
int getDistributedScheduleWorkAccepted();
int getDistributedScheduleWorkRejected();
boolean isDoWorkDistributionEnabled();
void doWork(Work work) throws WorkException;
void startWork(Work work) throws WorkException;
void scheduleWork(Work work) throws WorkException;
}
| 1,881 | 30.366667 | 70 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/DwmAlwaysTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.jca.workmanager.distributed;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkException;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.as.test.shared.TimeoutUtil;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Uses policy = ALWAYS and selector = FIRST_AVAILABLE.
*
* InSequence is necessary since we can't tell whether a work instance has already finished executing and has freed all
* the threads it was occupying (if started via startWork or scheduleWork). The last two test cases could mess with
* each other. The test methods will still run separately without issues.
*/
@RunWith(Arquillian.class)
@RunAsClient
public class DwmAlwaysTestCase extends AbstractDwmTestCase {
@Override
protected Policy getPolicy() {
return Policy.ALWAYS;
}
@Override
protected Selector getSelector() {
return Selector.FIRST_AVAILABLE;
}
/**
* Executes a few short work instances and verifies that they executed on the expected node (the other one since
* we have Policy.ALWAYS)
*/
@Test
@InSequence(1)
public void testDoWork() throws WorkException, InterruptedException {
int doWorkAccepted = server2Proxy.getDoWorkAccepted();
int distributedDoWorkAccepted = server1Proxy.getDistributedDoWorkAccepted();
server1Proxy.doWork(new ShortWork());
server1Proxy.doWork(new ShortWork());
Assert.assertTrue("Work did not finish in the expected time on the expected node",
waitForDoWork(server2Proxy, doWorkAccepted + 2, TimeoutUtil.adjust(WORK_FINISH_MAX_TIMEOUT)));
Assert.assertTrue("Expected distributedDoWorkAccepted = " + (distributedDoWorkAccepted + 2) + " but was: " + server1Proxy.getDistributedDoWorkAccepted(),
server1Proxy.getDistributedDoWorkAccepted() == distributedDoWorkAccepted + 2);
}
/**
* Submits a few (less than our max threads) short work instances and verifies that
* {@link org.jboss.jca.core.api.workmanager.DistributedWorkManager#startWork(Work)} starts the work on the
* expected node (the other one since we have Policy.ALWAYS).
*/
@Test
@InSequence(2)
public void testStartWork() throws WorkException, InterruptedException {
int startWorkAccepted = server2Proxy.getStartWorkAccepted();
int distributedStartWorkAccepted = server1Proxy.getDistributedStartWorkAccepted();
server1Proxy.startWork(new ShortWork());
// the short work was already started and will finish momentarily, however, it still hogs the thread for testScheduleWork
// this will allow it to finish for good (short work takes no time to finish)
Thread.sleep(TimeoutUtil.adjust(1000));
Assert.assertTrue("Work did not finish in the expected time on the expected node",
waitForStartWork(server2Proxy, startWorkAccepted + 1, TimeoutUtil.adjust(WORK_FINISH_MAX_TIMEOUT)));
Assert.assertTrue("Expected distributedStartWorkAccepted = " + (distributedStartWorkAccepted + 1) + " but was: " + server1Proxy.getDistributedStartWorkAccepted(),
server1Proxy.getDistributedStartWorkAccepted() == distributedStartWorkAccepted + 1);
}
/**
* Schedules several (one more than our max threads) long work instances and verifies that
* {@link org.jboss.jca.core.api.workmanager.DistributedWorkManager#scheduleWork(Work)} returns sooner than the time
* needed for the work items to actually finish. Also verifies that work was executed on both nodes (Policy.ALWAYS
* selects the other node first, then the first node is selected because the second one is already full).
*/
@Test
@InSequence(3)
public void testScheduleWork() throws WorkException, InterruptedException {
int scheduleWorkAcceptedServer1 = server1Proxy.getScheduleWorkAccepted();
int scheduleWorkAcceptedServer2 = server2Proxy.getScheduleWorkAccepted();
int distributedScheduleWorkAccepted = server1Proxy.getDistributedScheduleWorkAccepted();
for (int i = 0; i < SRT_MAX_THREADS + 1; i++) {
server1Proxy.scheduleWork(new LongWork());
}
Assert.assertTrue("Work did not finish in the expected time on the expected node",
waitForScheduleWork(server2Proxy, scheduleWorkAcceptedServer2 + SRT_MAX_THREADS, TimeoutUtil.adjust(WORK_FINISH_MAX_TIMEOUT * (SRT_MAX_THREADS + 1))));
Assert.assertTrue("Work was not scheduled on nodes as was expected",
waitForScheduleWork(server1Proxy, scheduleWorkAcceptedServer1 + 1, TimeoutUtil.adjust(WORK_FINISH_MAX_TIMEOUT * (SRT_MAX_THREADS + 1))));
Assert.assertTrue("Expected distributedScheduleWorkAccepted = " + (distributedScheduleWorkAccepted + SRT_MAX_THREADS + 1) + " but was: " + server1Proxy.getDistributedScheduleWorkAccepted(),
server1Proxy.getDistributedScheduleWorkAccepted() == distributedScheduleWorkAccepted + SRT_MAX_THREADS + 1);
}
}
| 6,223 | 49.601626 | 197 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/DwmAdminObjectEjbImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.jca.workmanager.distributed;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateful;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkException;
import org.jboss.as.test.manualmode.jca.workmanager.distributed.ra.DistributedAdminObject1;
import org.jboss.as.test.manualmode.jca.workmanager.distributed.ra.DistributedAdminObject1Impl;
import org.jboss.as.test.manualmode.jca.workmanager.distributed.ra.DistributedResourceAdapter1;
import org.jboss.jca.core.api.workmanager.DistributedWorkManager;
@Stateful(passivationCapable = false) //this is stateful so it maintains affinity, because standalone-ha.xml is used for the tests if a stateless bean is used invocations will go to other nodes
@Remote
public class DwmAdminObjectEjbImpl implements DwmAdminObjectEjb {
@Resource(mappedName = "java:jboss/A1")
private DistributedAdminObject1 dao;
private DistributedWorkManager dwm;
@PostConstruct
public void initialize() {
if (!(dao instanceof DistributedAdminObject1Impl)) {
throw new IllegalStateException("DwmAdminObjectEjbImpl expects that its DistributedAdminObject1 will be of certain implemnetation");
}
DistributedAdminObject1Impl daoi = (DistributedAdminObject1Impl) dao;
if (!(daoi.getResourceAdapter() instanceof DistributedResourceAdapter1)) {
throw new IllegalStateException("DwmAdminObjectEjbImpl expects that its resource adapter will be distributable");
}
DistributedResourceAdapter1 dra = (DistributedResourceAdapter1) daoi.getResourceAdapter();
dwm = dra.getDwm();
}
@Override
public int getDoWorkAccepted() {
return dwm.getStatistics().getDoWorkAccepted();
}
@Override
public int getDoWorkRejected() {
return dwm.getStatistics().getDoWorkRejected();
}
@Override
public int getStartWorkAccepted() {
return dwm.getStatistics().getStartWorkAccepted();
}
@Override
public int getStartWorkRejected() {
return dwm.getStatistics().getStartWorkRejected();
}
@Override
public int getScheduleWorkAccepted() {
return dwm.getStatistics().getScheduleWorkAccepted();
}
@Override
public int getScheduleWorkRejected() {
return dwm.getStatistics().getScheduleWorkRejected();
}
@Override
public int getDistributedDoWorkAccepted() {
return dwm.getDistributedStatistics().getDoWorkAccepted();
}
@Override
public int getDistributedDoWorkRejected() {
return dwm.getDistributedStatistics().getDoWorkRejected();
}
@Override
public int getDistributedStartWorkAccepted() {
return dwm.getDistributedStatistics().getStartWorkAccepted();
}
@Override
public int getDistributedStartWorkRejected() {
return dwm.getDistributedStatistics().getStartWorkRejected();
}
@Override
public int getDistributedScheduleWorkAccepted() {
return dwm.getDistributedStatistics().getScheduleWorkAccepted();
}
@Override
public int getDistributedScheduleWorkRejected() {
return dwm.getDistributedStatistics().getScheduleWorkRejected();
}
@Override
public boolean isDoWorkDistributionEnabled() {
return dwm.isDoWorkDistributionEnabled();
}
@Override
public void doWork(Work work) throws WorkException {
dwm.doWork(work);
}
@Override
public void startWork(Work work) throws WorkException {
dwm.startWork(work);
}
@Override
public void scheduleWork(Work work) throws WorkException {
dwm.scheduleWork(work);
}
}
| 4,781 | 33.402878 | 193 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/LongWork.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.jca.workmanager.distributed;
import jakarta.resource.spi.work.DistributableWork;
import java.io.Serializable;
public class LongWork implements DistributableWork, Serializable {
private boolean quit = false;
/**
* Note that some distributed workmanager threads may depend on the exact time long work takes.
*/
public static final long WORK_TIMEOUT = 1000L; // 1 second
public static final long SLEEP_STEP = 50L; // 0.05 seconds
@Override
public void release() {
quit = true;
}
@Override
public void run() {
long startTime = System.currentTimeMillis();
long finishTime = startTime + WORK_TIMEOUT;
while (!quit) {
try {
Thread.sleep(SLEEP_STEP);
} catch (InterruptedException ignored) {
// ignored
}
if (System.currentTimeMillis() >= finishTime) quit = true;
}
}
}
| 1,999 | 34.087719 | 99 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/ShortWork.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.jca.workmanager.distributed;
import jakarta.resource.spi.work.DistributableWork;
import java.io.Serializable;
public class ShortWork implements DistributableWork, Serializable {
@Override
public void release() {
// do nothing
}
@Override
public void run() {
// just finish quickly
}
}
| 1,389 | 34.641026 | 70 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/DwmNeverTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.jca.workmanager.distributed;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkException;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.as.test.shared.TimeoutUtil;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Uses policy = NEVER and selector = MAX_FREE_THREADS.
*
* InSequence is necessary since testScheduleWork messes with the thread pools for testNeverPolicy. We'd have to wait
* for the work instances to actually finish and free the thread pools otherwise. The test methods will still run
* separately without issues.
*/
@RunWith(Arquillian.class)
@RunAsClient
public class DwmNeverTestCase extends AbstractDwmTestCase {
@Override
protected Policy getPolicy() {
return Policy.NEVER;
}
@Override
protected Selector getSelector() {
return Selector.MAX_FREE_THREADS;
}
/**
* Does a few instances of short work with {@code policy = NEVER} and expects that they will be executed on the node
* where started.
*/
@Test
@InSequence(1)
public void testNeverPolicy() throws WorkException {
int doWorkAccepted = server1Proxy.getDoWorkAccepted();
for (int i = 0; i < 10; i++) {
server1Proxy.doWork(new ShortWork());
}
Assert.assertTrue("Expected doWorkAccepted = " + (doWorkAccepted + 10) + ", actual: " + server1Proxy.getDoWorkAccepted(),
server1Proxy.getDoWorkAccepted() == doWorkAccepted + 10);
}
/**
* Schedules several (one more than our max threads) long work instances and verifies that
* {@link org.jboss.jca.core.api.workmanager.DistributedWorkManager#scheduleWork(Work)} executes work on the local
* node (Policy.NEVER only selects the local node, regardless of the selector).
*/
@Test
@InSequence(2)
public void testScheduleWork() throws WorkException, InterruptedException {
int scheduleWorkAcceptedServer1 = server1Proxy.getScheduleWorkAccepted();
int distributedScheduleWorkAccepted = server2Proxy.getDistributedScheduleWorkAccepted();
for (int i = 0; i < SRT_MAX_THREADS + 1; i++) {
server1Proxy.scheduleWork(new LongWork());
}
Assert.assertTrue("Work did not finish in the expected time on the expected node",
waitForScheduleWork(server1Proxy, scheduleWorkAcceptedServer1 + SRT_MAX_THREADS + 1, TimeoutUtil.adjust(WORK_FINISH_MAX_TIMEOUT)));
Assert.assertTrue("Expected distributedScheduleWorkAccepted = " + (distributedScheduleWorkAccepted + SRT_MAX_THREADS + 1) + " but was: " + server2Proxy.getDistributedScheduleWorkAccepted(),
server2Proxy.getDistributedScheduleWorkAccepted() == distributedScheduleWorkAccepted + SRT_MAX_THREADS + 1);
}
}
| 3,989 | 41.446809 | 197 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/AbstractDwmTestCase.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.jboss.as.test.manualmode.jca.workmanager.distributed;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MAX_THREADS;
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.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION;
import static org.jboss.as.test.shared.ServerReload.executeReloadAndWaitForCompletion;
import static org.junit.Assert.assertTrue;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
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.TargetsContainer;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.test.integration.management.util.ModelUtil;
import org.jboss.as.test.manualmode.jca.workmanager.distributed.ra.DistributedConnection1;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
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.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.wildfly.test.api.Authentication;
/**
* Tests distributed work manager and whether it really distributes work over multiple nodes. Test cases use two servers
* both with a deployed resource adapter configured to use the DWM.
*
* Work is scheduled via a stateless Jakarta Enterprise Beans proxy. This allows us to schedule work from within the test, without the need
* to marshall anything not serializable (such as the resource adapter).
*/
public abstract class AbstractDwmTestCase {
private static Logger log = Logger.getLogger(AbstractDwmTestCase.class.getCanonicalName());
private static final String DEFAULT_DWM_NAME = "newdwm";
private static final String DEFAULT_CONTEXT_NAME = "customContext1";
private static final ModelNode DEFAULT_DWM_ADDRESS = new ModelNode()
.add(SUBSYSTEM, "jca")
.add("distributed-workmanager", DEFAULT_DWM_NAME);
private static final String DEPLOYMENT_0 = "deployment-0";
private static final String DEPLOYMENT_1 = "deployment-1";
private static final String CONTAINER_0 = "dwm-container-manual-0";
private static final String CONTAINER_1 = "dwm-container-manual-1";
// can be used in extending test cases to control test logic
protected static final int SRT_MAX_THREADS = 1;
protected static final int SRT_QUEUE_LENGTH = 1;
protected static final int WORK_FINISH_MAX_TIMEOUT = 10_000;
protected enum Policy {
ALWAYS,
NEVER,
WATERMARK
}
protected enum Selector {
FIRST_AVAILABLE,
MAX_FREE_THREADS,
PING_TIME
}
private String snapshotForServer1;
private String snapshotForServer2;
protected DwmAdminObjectEjb server1Proxy;
protected DwmAdminObjectEjb server2Proxy;
@ArquillianResource
protected static ContainerController containerController;
@ArquillianResource
protected static Deployer deployer;
// --------------------------------------------------------------------------------
// infrastructure preparation
// --------------------------------------------------------------------------------
private static ModelControllerClient createClient1() {
return TestSuiteEnvironment.getModelControllerClient();
}
private static ModelControllerClient createClient2() throws UnknownHostException {
return ModelControllerClient.Factory.create(InetAddress.getByName(TestSuiteEnvironment.getServerAddressNode1()),
TestSuiteEnvironment.getServerPort() + 100,
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);
log.debugf("Snapshot of current configuration taken: %s", result);
return result.asString();
}
private static ModelNode execute(ModelControllerClient client, ModelNode operation) throws Exception {
ModelNode response = client.execute(operation);
boolean success = SUCCESS.equals(response.get(OUTCOME).asString());
if (success) {
return response.get(RESULT);
}
throw new Exception("Operation failed");
}
private void restoreSnapshot(String snapshot) {
File snapshotFile = new File(snapshot);
File configurationDir = snapshotFile.getParentFile().getParentFile().getParentFile();
File standaloneConfiguration = new File(configurationDir, "standalone-ha.xml");
if (standaloneConfiguration.exists()) {
if (!standaloneConfiguration.delete()) {
log.warn("Could not delete file " + standaloneConfiguration.getAbsolutePath());
}
}
if (!snapshotFile.renameTo(standaloneConfiguration)) {
log.warn("File " + snapshotFile.getAbsolutePath() + " could not be renamed to " + standaloneConfiguration.getAbsolutePath());
}
}
private void executeReloadAndWaitForCompletionOfServer1(ModelControllerClient initialClient, boolean adminOnly) throws Exception {
executeReloadAndWaitForCompletion(initialClient, adminOnly);
}
private void executeReloadAndWaitForCompletionOfServer2(ModelControllerClient initialClient, boolean adminOnly) throws Exception {
executeReloadAndWaitForCompletion(initialClient, ServerReload.TIMEOUT,
adminOnly,
TestSuiteEnvironment.getServerAddressNode1(),
TestSuiteEnvironment.getServerPort() + 100);
}
// --------------------------------------------------------------------------------
// server set up and tear down
// --------------------------------------------------------------------------------
@Before
public void setUp() throws Exception {
// start server1 and reload it in admin-only
containerController.start(CONTAINER_0);
ModelControllerClient client1 = createClient1();
snapshotForServer1 = takeSnapshot(client1);
executeReloadAndWaitForCompletionOfServer1(client1, true);
// start server2 and reload it in admin-only
containerController.start(CONTAINER_1);
ModelControllerClient client2 = createClient2();
snapshotForServer2 = takeSnapshot(client2);
executeReloadAndWaitForCompletionOfServer2(client2, true);
// setup both servers
try {
setUpServer(client1, CONTAINER_0);
setUpServer(client2, CONTAINER_1);
} catch (Exception e) {
client1.close();
client2.close();
tearDown();
throw e;
}
// reload servers in normal mode
executeReloadAndWaitForCompletionOfServer1(client1, false);
executeReloadAndWaitForCompletionOfServer2(client2, false);
// both servers are started and configured
assertTrue(containerController.isStarted(CONTAINER_0));
assertTrue(containerController.isStarted(CONTAINER_1));
client1.close();
client2.close();
// now deploy the Jakarta Enterprise Beans
deployer.deploy(DEPLOYMENT_0);
deployer.deploy(DEPLOYMENT_1);
// set up Jakarta Enterprise Beans proxies
try {
server1Proxy = lookupAdminObject(TestSuiteEnvironment.getServerAddress(), "8080");
server2Proxy = lookupAdminObject(TestSuiteEnvironment.getServerAddressNode1(), "8180");
Assert.assertNotNull(server1Proxy);
Assert.assertNotNull(server2Proxy);
} catch (Throwable e) {
tearDown();
throw e;
}
}
@After
public void tearDown() {
server1Proxy = null;
server2Proxy = null;
deployer.undeploy(DEPLOYMENT_0);
deployer.undeploy(DEPLOYMENT_1);
if (containerController.isStarted(CONTAINER_0)) {
containerController.stop(CONTAINER_0);
}
restoreSnapshot(snapshotForServer1);
if (containerController.isStarted(CONTAINER_1)) {
containerController.stop(CONTAINER_1);
}
restoreSnapshot(snapshotForServer2);
}
// --------------------------------------------------------------------------------
// set up helper methods
// --------------------------------------------------------------------------------
private ModelNode addBasicDwm() {
ModelNode setUpDwm = new ModelNode();
setUpDwm.get(OP_ADDR).set(DEFAULT_DWM_ADDRESS);
setUpDwm.get(OP).set(ADD);
setUpDwm.get(NAME).set(DEFAULT_DWM_NAME);
return setUpDwm;
}
private ModelNode setUpShortRunningThreads(int maxThreads, int queueLength) {
ModelNode setUpSrt = new ModelNode();
// the thread pool name must be the same as the DWM it belongs to
setUpSrt.get(OP_ADDR).set(DEFAULT_DWM_ADDRESS.clone().add("short-running-threads", DEFAULT_DWM_NAME));
setUpSrt.get(OP).set(ADD);
setUpSrt.get(MAX_THREADS).set(maxThreads);
setUpSrt.get("queue-length").set(queueLength);
return setUpSrt;
}
private ModelNode setUpCustomContext() {
ModelNode setUpCustomContext = new ModelNode();
setUpCustomContext.get(OP_ADDR).set(new ModelNode()
.add(SUBSYSTEM, "jca")
.add("bootstrap-context", DEFAULT_CONTEXT_NAME));
setUpCustomContext.get(OP).set(ADD);
setUpCustomContext.get(NAME).set(DEFAULT_CONTEXT_NAME);
setUpCustomContext.get("workmanager").set(DEFAULT_DWM_NAME);
return setUpCustomContext;
}
private ModelNode setUpPolicy(Policy policy) {
ModelNode setUpPolicy = new ModelNode();
setUpPolicy.get(OP_ADDR).set(DEFAULT_DWM_ADDRESS);
setUpPolicy.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
setUpPolicy.get(NAME).set("policy");
setUpPolicy.get(VALUE).set(policy.toString());
return setUpPolicy;
}
private ModelNode setUpWatermarkPolicyOption(int waterMarkPolicyOption) {
ModelNode setUpWatermarkPolicyOption = new ModelNode();
setUpWatermarkPolicyOption.get(OP_ADDR).set(DEFAULT_DWM_ADDRESS);
setUpWatermarkPolicyOption.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
setUpWatermarkPolicyOption.get(NAME).set("policy-options");
setUpWatermarkPolicyOption.get(VALUE).set(new ModelNode().add("watermark", waterMarkPolicyOption));
return setUpWatermarkPolicyOption;
}
private ModelNode setUpSelector(Selector selector) {
ModelNode setUpSelector = new ModelNode();
setUpSelector.get(OP_ADDR).set(DEFAULT_DWM_ADDRESS);
setUpSelector.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
setUpSelector.get(NAME).set("selector");
setUpSelector.get(VALUE).set(selector.toString());
return setUpSelector;
}
@SuppressWarnings("unused")
private void setUpServer(ModelControllerClient client ,String containerId) throws IOException {
ModelControllerClient mcc = CONTAINER_0.equals(containerId) ? createClient1() : createClient2();
log.debugf("Setting up Policy/Selector: %s/%s on server %s", getPolicy(), getSelector(), containerId);
ModelNode addBasicDwm = addBasicDwm();
ModelNode setUpPolicy = setUpPolicy(getPolicy());
ModelNode setUpPolicyOptions = setUpWatermarkPolicyOption(getWatermarkPolicyOption());
ModelNode setUpSelector = setUpSelector(getSelector());
ModelNode setUpShortRunningThreads = setUpShortRunningThreads(getSrtMaxThreads(), getSrtQueueLength());
List<ModelNode> operationList = new ArrayList<>(Arrays.asList(addBasicDwm, setUpPolicy, setUpSelector, setUpShortRunningThreads));
if (getPolicy().equals(Policy.WATERMARK)) {
operationList.add(setUpPolicyOptions);
}
ModelNode compositeOp = ModelUtil.createCompositeNode(operationList.toArray(new ModelNode[1]));
ModelNode result = mcc.execute(compositeOp);
log.debugf("Setting up DWM on server %s: %s", containerId, result);
result = mcc.execute(setUpCustomContext());
log.debugf("Setting up CustomContext on server %s: %s", containerId, result);
mcc.close();
}
// --------------------------------------------------------------------------------
// abstract and other to-be-overwritten methods
// --------------------------------------------------------------------------------
protected abstract Policy getPolicy();
protected abstract Selector getSelector();
protected int getWatermarkPolicyOption() {
return 0;
}
protected int getSrtMaxThreads() {
return SRT_MAX_THREADS;
}
protected int getSrtQueueLength() {
return SRT_QUEUE_LENGTH;
}
// --------------------------------------------------------------------------------
// deployment setup
// --------------------------------------------------------------------------------
@Deployment(name = DEPLOYMENT_0, managed = false, testable = false)
@TargetsContainer(CONTAINER_0)
public static Archive<?> deploy0 () {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(CONTAINER_1)
public static Archive<?> deploy1 () {
return createDeployment();
}
private static Archive<?> createDeployment() {
JavaArchive jar = createLibJar();
ResourceAdapterArchive rar = createResourceAdapterArchive();
JavaArchive ejbJar = createEjbJar();
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "dwmtest.ear");
ear.addAsLibrary(jar).addAsModule(rar).addAsModule(ejbJar);
ear.addAsManifestResource(AbstractDwmTestCase.class.getPackage(), "application.xml", "application.xml");
return ear;
}
private static JavaArchive createLibJar() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "lib.jar");
jar.addClass(LongWork.class).addClass(ShortWork.class)
.addPackage(DistributedConnection1.class.getPackage());
jar.addAsManifestResource(new StringAsset("Dependencies: javax.inject.api,org.jboss.as.connector,"
+ "org.jboss.ironjacamar.impl\n"), "MANIFEST.MF");
return jar;
}
private static ResourceAdapterArchive createResourceAdapterArchive() {
ResourceAdapterArchive rar = ShrinkWrap.create(ResourceAdapterArchive.class, "dwm.rar");
rar.addAsManifestResource(AbstractDwmTestCase.class.getPackage(), "ra-distributed.xml", "ra.xml")
.addAsManifestResource(AbstractDwmTestCase.class.getPackage(), "ironjacamar-distributed-1.xml",
"ironjacamar.xml")
.addAsManifestResource(
new StringAsset(
"Dependencies: org.jboss.as.connector \n"),
"MANIFEST.MF");
return rar;
}
private static JavaArchive createEjbJar() {
JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, "ejb.jar");
ejbJar.addClass(DwmAdminObjectEjb.class).addClass(DwmAdminObjectEjbImpl.class);
ejbJar.addAsManifestResource(AbstractDwmTestCase.class.getPackage(), "ejb-jar.xml", "ejb-jar.xml")
.addAsManifestResource(new StringAsset("Dependencies: org.jboss.ironjacamar.api"), "MANIFEST.MF");
return ejbJar;
}
// --------------------------------------------------------------------------------
// test related abstractions
// --------------------------------------------------------------------------------
private DwmAdminObjectEjb lookupAdminObject(String address, String port) throws NamingException {
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.wildfly.naming.client.WildFlyInitialContextFactory");
properties.put(Context.PROVIDER_URL, String.format("%s%s:%s", "http-remoting://", address, port));
Context context = new InitialContext(properties);
String ejbExportedName = String.format("%s/%s/%s!%s", "dwm-ejb-application", "dwm-ejb-module",
DwmAdminObjectEjbImpl.class.getSimpleName(), DwmAdminObjectEjb.class.getCanonicalName());
return (DwmAdminObjectEjb) context.lookup(ejbExportedName);
}
private enum WorkScheduleType {
DO_WORK,
START_WORK,
SCHEDULE_WORK
}
protected boolean waitForDoWork(DwmAdminObjectEjb proxy, int expectedWorkAmount, int timeout) throws InterruptedException {
return waitForWork(proxy, expectedWorkAmount, timeout, WorkScheduleType.DO_WORK);
}
protected boolean waitForStartWork(DwmAdminObjectEjb proxy, int expectedWorkAmount, int timeout) throws InterruptedException {
return waitForWork(proxy, expectedWorkAmount, timeout, WorkScheduleType.START_WORK);
}
protected boolean waitForScheduleWork(DwmAdminObjectEjb proxy, int expectedWorkAmount, int timeout) throws InterruptedException {
return waitForWork(proxy, expectedWorkAmount, timeout, WorkScheduleType.SCHEDULE_WORK);
}
private boolean waitForWork(DwmAdminObjectEjb proxy, int expectedWorkAmount, int timeout, WorkScheduleType wst) throws InterruptedException {
long finish = System.currentTimeMillis() + timeout;
while (System.currentTimeMillis() <= finish) {
if (getCurrentWorkAmount(proxy, wst) == expectedWorkAmount) {
return true;
}
Thread.sleep(100L);
}
return getCurrentWorkAmount(proxy, wst) == expectedWorkAmount;
}
private int getCurrentWorkAmount(DwmAdminObjectEjb proxy, WorkScheduleType wst) {
switch (wst) {
case DO_WORK:
return proxy.getDoWorkAccepted();
case START_WORK:
return proxy.getStartWorkAccepted();
case SCHEDULE_WORK:
return proxy.getScheduleWorkAccepted();
default:
throw new IllegalStateException("Bad work schedule type - test error");
}
}
}
| 20,807 | 42.170124 | 145 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/ra/DistributedManagedConnectionMetadata1.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.jboss.as.test.manualmode.jca.workmanager.distributed.ra;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ManagedConnectionMetaData;
public class DistributedManagedConnectionMetadata1 implements ManagedConnectionMetaData {
public DistributedManagedConnectionMetadata1() {
// empty
}
/**
* 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 {
return "Red Hat Middleware LLC - Test RA";
}
/**
* 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 {
return "0.1";
}
/**
* 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 {
return 100;
}
/**
* 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 {
return "user";
}
}
| 2,710 | 34.207792 | 102 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/ra/DistributedConnection1Impl.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.jboss.as.test.manualmode.jca.workmanager.distributed.ra;
public class DistributedConnection1Impl implements DistributedConnection1 {
private DistributedManagedConnection1 dmc;
private DistributedManagedConnectionFactory1 dmcf;
public DistributedConnection1Impl(DistributedManagedConnection1 dmc, DistributedManagedConnectionFactory1 dmcf) {
this.dmc = dmc;
this.dmcf = dmcf;
}
public String test(String s) {
return null;
}
public void close() {
dmc.closeHandle(this);
}
}
| 1,585 | 36.761905 | 117 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/ra/DistributedManagedConnection1.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.jboss.as.test.manualmode.jca.workmanager.distributed.ra;
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;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class DistributedManagedConnection1 implements ManagedConnection {
private PrintWriter logWriter;
private DistributedManagedConnectionFactory1 dmcf;
private List<ConnectionEventListener> listeners;
private Object connection;
public DistributedManagedConnection1(DistributedManagedConnectionFactory1 dmcf) {
this.dmcf = dmcf;
this.logWriter = null;
this.listeners = new ArrayList<>(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 {
connection = new DistributedConnection1Impl(this, dmcf);
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 {
}
/**
* 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 {
}
/**
* Destroys the physical connection to the underlying resource manager.
*
* @throws ResourceException generic exception if operation fails
*/
public void destroy() throws ResourceException {
}
/**
* Adds a connection event listener to the ManagedConnection instance.
*
* @param listener A new ConnectionEventListener to be registered
*/
public void addConnectionEventListener(ConnectionEventListener listener) {
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) {
if (listener == null) { throw new IllegalArgumentException("Listener is null"); }
listeners.remove(listener);
}
public void closeHandle(DistributedConnection1 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 {
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 {
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 {
return new DistributedManagedConnectionMetadata1();
}
}
| 6,545 | 37.05814 | 100 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/ra/DistributedResourceAdapter1.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.jboss.as.test.manualmode.jca.workmanager.distributed.ra;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ActivationSpec;
import jakarta.resource.spi.BootstrapContext;
import jakarta.resource.spi.ResourceAdapter;
import jakarta.resource.spi.ResourceAdapterInternalException;
import jakarta.resource.spi.endpoint.MessageEndpointFactory;
import jakarta.resource.spi.work.WorkManager;
import javax.transaction.xa.XAResource;
import org.jboss.jca.core.workmanager.DistributedWorkManagerImpl;
/**
* DistributedResourceAdapter1 for use with DistributableWorkManager.
*
* In conjunction with {@link DistributedAdminObject1}, this class allows the tester to create workloads on
* the servers as well as obtain statistics on where that workload was executed.
*/
public class DistributedResourceAdapter1 implements ResourceAdapter {
private DistributedWorkManagerImpl dwm;
public DistributedResourceAdapter1() {
// empty
}
public void setDwm(DistributedWorkManagerImpl dwm) {
this.dwm = dwm;
}
public DistributedWorkManagerImpl getDwm() {
return dwm;
}
/**
* 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 {
}
/**
* 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) {
}
/**
* 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 {
WorkManager wm = ctx.getWorkManager();
if (wm instanceof DistributedWorkManagerImpl) {
DistributedWorkManagerImpl dwm = (DistributedWorkManagerImpl) wm;
setDwm(dwm);
}
}
/**
* This is called when a resource adapter instance is undeployed or during application server shutdown.
*/
public void 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 {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return 17;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object other) {
if (other == null) { return false; }
if (other == this) { return true; }
if (!(other instanceof DistributedResourceAdapter1)) { return false; }
DistributedResourceAdapter1 obj = (DistributedResourceAdapter1) other;
boolean result;
if (dwm == null) { result = obj.getDwm() == null; } else { result = dwm.equals(obj.getDwm()); }
return result;
}
}
| 4,582 | 34.253846 | 122 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/ra/DistributedAdminObject1Impl.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.jboss.as.test.manualmode.jca.workmanager.distributed.ra;
import javax.naming.NamingException;
import javax.naming.Reference;
import jakarta.resource.Referenceable;
import jakarta.resource.spi.ResourceAdapter;
import jakarta.resource.spi.ResourceAdapterAssociation;
import java.io.Serializable;
import org.jboss.logging.Logger;
/**
* Note that since the implementation contains a {@link ResourceAdapter} field, and that field is
* not serializable, the admin object can only be injected via {@link jakarta.annotation.Resource}.
*
* That means that the tests that you write can't use
* {@link org.jboss.arquillian.container.test.api.RunAsClient} and look up the object remotely.
*
* What you can do, is deploy an Jakarta Enterprise Beans, that will report the statistics via its admin object. You
* should be able to lookup that Jakarta Enterprise Beans and use it as a proxy to the resource adapter below. However,
* the Jakarta Enterprise Beans has to be {@link jakarta.ejb.Stateless}, otherwise, once started in a cluster, a session is
* going to be created for it which has to be serializable.
*/
public class DistributedAdminObject1Impl implements DistributedAdminObject1,
ResourceAdapterAssociation, Referenceable, Serializable {
private static final Logger log = Logger.getLogger(DistributedAdminObject1Impl.class.getSimpleName());
private static final long serialVersionUID = 466880381773994922L;
static {
log.trace("Initializing DistributedAdminObject1Impl");
}
private ResourceAdapter ra;
private Reference reference;
private String name;
public DistributedAdminObject1Impl() {
setName("DistributedAdminObject1Impl");
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public ResourceAdapter getResourceAdapter() {
return ra;
}
public void setResourceAdapter(ResourceAdapter ra) {
this.ra = ra;
}
/**
* {@inheritDoc}
*/
@Override
public Reference getReference() throws NamingException {
return reference;
}
/**
* {@inheritDoc}
*/
@Override
public void setReference(Reference reference) {
this.reference = reference;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int result = 17;
if (name != null) { result += 31 * result + 7 * name.hashCode(); } else { result += 31 * result + 7; }
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object other) {
if (other == null) { return false; }
if (other == this) { return true; }
if (!(other instanceof DistributedAdminObject1Impl)) { return false; }
DistributedAdminObject1Impl obj = (DistributedAdminObject1Impl) other;
boolean result = true;
if (result) {
if (name == null) { result = obj.getName() == null; } else { result = name.equals(obj.getName()); }
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return this.getClass().toString() + "name=" + name;
}
}
| 4,274 | 32.139535 | 123 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/ra/DistributedConnection1.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.jboss.as.test.manualmode.jca.workmanager.distributed.ra;
public interface DistributedConnection1 {
String test(String s);
void close();
}
| 1,193 | 38.8 | 70 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/ra/DistributedAdminObject1.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.jboss.as.test.manualmode.jca.workmanager.distributed.ra;
import jakarta.resource.Referenceable;
import java.io.Serializable;
/**
* DistributedAdminObject1 allows the tester to use the resource adapter and workmanager from
* outside EAP.
*/
public interface DistributedAdminObject1 extends Referenceable, Serializable {
void setName(String name);
String getName();
}
| 1,425 | 37.540541 | 93 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/ra/DistributedConnectionFactory1Impl.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.jboss.as.test.manualmode.jca.workmanager.distributed.ra;
import javax.naming.NamingException;
import javax.naming.Reference;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ConnectionManager;
public class DistributedConnectionFactory1Impl implements DistributedConnectionFactory1 {
private static final long serialVersionUID = 812283381273295931L;
private Reference reference;
private DistributedManagedConnectionFactory1 dmcf;
private ConnectionManager connectionManager;
public DistributedConnectionFactory1Impl() {
// empty
}
public DistributedConnectionFactory1Impl(DistributedManagedConnectionFactory1 dmcf, ConnectionManager cxManager) {
this.dmcf = dmcf;
this.connectionManager = cxManager;
}
@Override
public DistributedConnection1 getConnection() throws ResourceException {
return (DistributedConnection1) connectionManager.allocateConnection(dmcf, null);
}
public Reference getReference() throws NamingException {
return reference;
}
/**
* {@inheritDoc}
*/
@Override
public void setReference(Reference reference) {
this.reference = reference;
}
}
| 2,259 | 34.873016 | 118 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/ra/DistributedManagedConnectionFactory1.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.jboss.as.test.manualmode.jca.workmanager.distributed.ra;
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;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Set;
public class DistributedManagedConnectionFactory1 implements ManagedConnectionFactory, ResourceAdapterAssociation {
private static final long serialVersionUID = 112183388263932951L;
private ResourceAdapter ra;
private PrintWriter logwriter;
private String name;
public DistributedManagedConnectionFactory1() {
// empty
}
public void setName(String name) {
this.name = name;
}
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 {
return new DistributedConnectionFactory1Impl(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 {
return new DistributedManagedConnection1(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 {
ManagedConnection result = null;
Iterator it = connectionSet.iterator();
while (result == null && it.hasNext()) {
ManagedConnection mc = (ManagedConnection) it.next();
if (mc instanceof DistributedManagedConnection1) {
result = mc;
}
}
return result;
}
/**
* Get the log writer for this ManagedConnectionFactory instance.
*
* @return PrintWriter
* @throws ResourceException generic exception
*/
public PrintWriter getLogWriter() throws ResourceException {
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 {
logwriter = out;
}
/**
* 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;
}
/**
* 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 DistributedManagedConnectionFactory1)) { return false; }
DistributedManagedConnectionFactory1 obj = (DistributedManagedConnectionFactory1) other;
return name == null ?
obj.getName() == null :
name.equals(obj.getName());
}
}
| 6,508 | 35.161111 | 133 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/jca/workmanager/distributed/ra/DistributedConnectionFactory1.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.jboss.as.test.manualmode.jca.workmanager.distributed.ra;
import jakarta.resource.Referenceable;
import jakarta.resource.ResourceException;
import java.io.Serializable;
public interface DistributedConnectionFactory1 extends Serializable, Referenceable {
DistributedConnection1 getConnection() throws ResourceException;
}
| 1,371 | 41.875 | 84 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/weld/extension/BeforeShutdownExtension.java
|
package org.jboss.as.test.manualmode.weld.extension;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.spi.BeforeShutdown;
import jakarta.enterprise.inject.spi.Extension;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.transaction.TransactionSynchronizationRegistry;
import jakarta.transaction.UserTransaction;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Ryan Emerson
*/
public class BeforeShutdownExtension implements Extension {
private UserTransaction userTx = null;
private TransactionSynchronizationRegistry txSynchRegistry = null;
void lookupBeforeShutdown(@Observes final BeforeShutdown beforeShutdown) throws Exception {
try {
userTx = lookup("java:jboss/UserTransaction");
userTx.getStatus();
txSynchRegistry = lookup("java:jboss/TransactionSynchronizationRegistry");
txSynchRegistry.getTransactionStatus();
} catch (Exception e) {
writeOutput(e);
throw e;
}
writeOutput(null);
}
private <T> T lookup(String jndiName) {
try {
InitialContext initialContext = new InitialContext();
return (T) initialContext.lookup(jndiName);
} catch (NamingException e) {
throw new IllegalArgumentException(e);
}
}
// Necessary so that BeforeShutdownJNDILookupTestCase can see the outcome of the BeforeShutdown JNDI lookups.
private void writeOutput(Exception exception) throws Exception {
List<String> output = new ArrayList<>();
if (exception != null) {
output.add("Exception");
output.add(exception + "," + Arrays.toString(exception.getStackTrace()));
} else {
output.add("UserTransaction");
output.add(userTx.toString());
output.add("TransactionSynchronizationRegistry");
output.add(txSynchRegistry.toString());
}
File parent = new File(BeforeShutdownJNDILookupTestCase.TEST_URL).getParentFile();
if (!parent.exists())
parent.mkdirs();
Files.write(Paths.get("", BeforeShutdownJNDILookupTestCase.TEST_URL), output, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
}
}
| 2,445 | 35.507463 | 139 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/weld/extension/BeforeShutdownJNDILookupTestCase.java
|
package org.jboss.as.test.manualmode.weld.extension;
import org.jboss.arquillian.container.test.api.ContainerController;
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.test.shared.integration.ejb.security.PermissionUtils;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import jakarta.enterprise.inject.spi.Extension;
import java.io.File;
import java.io.FilePermission;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* A test to ensure that the UserTransaction and TransactionSynchronizationRegistry can be retrieved via JNDI when
* an extensions BeforeShutdown method is invoked.
* <p/>
* See WFLY-5232
*
* @author Ryan Emerson
*/
@RunWith(Arquillian.class)
@RunAsClient
public class BeforeShutdownJNDILookupTestCase {
public static final String TEST_URL = "target" + File.separator + "results.txt";
private static final String CONTAINER = "default-jbossas";
private static final String DEPLOYMENT = "test.war";
private static final Path TEST_PATH = Paths.get("", TEST_URL);
@Deployment(name = DEPLOYMENT, managed = true)
@TargetsContainer(CONTAINER)
public static Archive<?> deploy() throws Exception {
return ShrinkWrap
.create(WebArchive.class, DEPLOYMENT)
.addClasses(BeforeShutdownJNDILookupTestCase.class, BeforeShutdownExtension.class)
.add(EmptyAsset.INSTANCE, ArchivePaths.create("WEB-INF/beans.xml"))
.add(new StringAsset(BeforeShutdownExtension.class.getName()), "META-INF/services/" + Extension.class.getName())
.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(
new FilePermission(TEST_PATH.getParent().toString(), "read, write"),
new FilePermission(TEST_PATH.toString(), "read, write, delete")
), "permissions.xml");
}
@ArquillianResource
ContainerController controller;
@Test
public void testTransactionJNDILookupDuringShutdownEvent() throws Exception {
controller.start(CONTAINER);
controller.kill(CONTAINER);
try {
List<String> output = Files.readAllLines(TEST_PATH);
if (output.get(0).equals("Exception")) {
String stacktrace = output.get(1).replaceAll(",", System.getProperty("line.separator"));
String msg = "An exception was thrown by the deployment %s during shutdown. The server stacktrace is shown below: %n%s";
Assert.fail(String.format(msg, DEPLOYMENT, stacktrace));
}
assertEquals("Contents of result.txt is not valid!", "UserTransaction", output.get(0));
} finally {
// start and stop the container to effective remove the managed deployment from the server
controller.start(CONTAINER);
controller.stop(CONTAINER);
}
}
@AfterClass
public static void cleanup() throws Exception {
Files.delete(TEST_PATH);
}
}
| 3,678 | 39.428571 | 137 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/weld/builtinBeans/LegacyCompliantPrincipalPropagationTestCase.java
|
/*
* Copyright 2021 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.manualmode.weld.builtinBeans;
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.junit.InSequence;
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.test.shared.ServerReload;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.security.auth.permission.ChangeRoleMapperPermission;
import org.wildfly.security.permission.ElytronPermission;
import static org.jboss.as.controller.client.helpers.Operations.createWriteAttributeOperation;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
/**
* Functionality tests for legacy-compliant-principal-propagation attribute of Enterprise Beans 3 subsystem.
* See <a href="https://issues.jboss.org/browse/WFLY-11587">WFLY-14074</a>.
*/
@RunWith(Arquillian.class)
public class LegacyCompliantPrincipalPropagationTestCase {
private static final String ANONYMOUS_PRINCIPAL = "anonymous";
private static final String NON_ANONYMOUS_PRINCIPAL = "non-anonymous";
private static final String DEFAULT_FULL_JBOSSAS = "default-full-jbossas";
private static final String LEGACY_COMPLIANT_ATTRIBUTE_TEST_DEPL = "legacy-compliant-test-deployment";
@ArquillianResource
private static Deployer deployer;
@ArquillianResource
private static ContainerController serverController;
@Deployment(name = LEGACY_COMPLIANT_ATTRIBUTE_TEST_DEPL, managed = false)
@TargetsContainer(DEFAULT_FULL_JBOSSAS)
public static Archive<?> createTestArchive() {
return ShrinkWrap.create(WebArchive.class).addPackage(LegacyCompliantPrincipalPropagationTestCase.class.getPackage())
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsWebInfResource(LegacyCompliantPrincipalPropagationTestCase.class.getPackage(), "jboss-ejb3.xml", "jboss-ejb3.xml")
// TODO WFLY-15289 The Elytron permissions need to be checked, should a deployment really need these?
.addAsManifestResource(createPermissionsXmlAsset(
new ElytronPermission("getIdentity"),
new ElytronPermission("createAdHocIdentity"),
new ChangeRoleMapperPermission("ejb")
), "permissions.xml");
}
@Test
@InSequence(1)
@RunAsClient
public void startContainer() throws Exception {
if (!serverController.isStarted(DEFAULT_FULL_JBOSSAS)) {
serverController.start(DEFAULT_FULL_JBOSSAS);
}
ManagementClient managementClient = getManagementClient();
deployer.deploy(LEGACY_COMPLIANT_ATTRIBUTE_TEST_DEPL);
}
@Test
@InSequence(2)
public void testPrincipalUnsecuredLocalEJBInLegacyCompliantMode(CallerWithIdentity callerWithIdentity) {
Assert.assertEquals(NON_ANONYMOUS_PRINCIPAL, callerWithIdentity.getCallerPrincipalFromEJBContext());
}
@Test
@InSequence(3)
@RunAsClient
public void configureLegacyIncompatibleMode() throws Exception {
// deployer needs to redeploy for Arquillian to find config for this class to run test methods
deployer.undeploy(LEGACY_COMPLIANT_ATTRIBUTE_TEST_DEPL);
ManagementClient managementClient = getManagementClient();
ModelNode modelNode = createWriteAttributeOperation(PathAddress.parseCLIStyleAddress(("/subsystem=ejb3/application-security-domain=other")).toModelNode(),
"legacy-compliant-principal-propagation", false);
managementClient.getControllerClient().execute(modelNode);
// must reload after changing attribute's value
ServerReload.reloadIfRequired(managementClient);
deployer.deploy(LEGACY_COMPLIANT_ATTRIBUTE_TEST_DEPL);
}
@Test
@InSequence(4)
public void testPrincipalUnsecuredLocalEJBInElytronMode(CallerWithIdentity callerWithIdentity) {
Assert.assertEquals(ANONYMOUS_PRINCIPAL, callerWithIdentity.getCallerPrincipalFromEJBContext());
}
@Test
@InSequence(5)
@RunAsClient
public void restoreConfigurationAndStopContainer() throws Exception {
deployer.undeploy(LEGACY_COMPLIANT_ATTRIBUTE_TEST_DEPL);
ManagementClient managementClient = getManagementClient();
ModelNode modelNode = createWriteAttributeOperation(PathAddress.parseCLIStyleAddress(("/subsystem=ejb3/application-security-domain=other")).toModelNode(),
"legacy-compliant-principal-propagation", true);
managementClient.getControllerClient().execute(modelNode);
ServerReload.reloadIfRequired(managementClient);
serverController.stop(DEFAULT_FULL_JBOSSAS);
}
private ManagementClient getManagementClient() {
ModelControllerClient modelControllerClient = TestSuiteEnvironment.getModelControllerClient();
return new ManagementClient(modelControllerClient, TestSuiteEnvironment.getServerAddress(), 9990, "remote+http");
}
}
| 6,336 | 45.595588 | 162 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/weld/builtinBeans/CallerWithIdentity.java
|
/*
* Copyright 2021 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.manualmode.weld.builtinBeans;
import org.jboss.ejb3.annotation.RunAsPrincipal;
import jakarta.annotation.security.RunAs;
import jakarta.ejb.Stateless;
import jakarta.inject.Inject;
@Stateless
@RunAs("Admin")
@RunAsPrincipal("non-anonymous")
public class CallerWithIdentity {
@Inject
BeanWithPrincipalFromEJBContext beanB;
public String getCallerPrincipalFromEJBContext() {
return beanB.getPrincipalName();
}
}
| 1,060 | 28.472222 | 75 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/weld/builtinBeans/BeanWithPrincipalFromEJBContext.java
|
/*
* Copyright 2021 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.manualmode.weld.builtinBeans;
import jakarta.annotation.Resource;
import jakarta.ejb.EJBContext;
import jakarta.ejb.Stateless;
@Stateless
public class BeanWithPrincipalFromEJBContext {
@Resource
private EJBContext ctx;
public String getPrincipalName() {
return ctx.getCallerPrincipal().getName();
}
}
| 950 | 28.71875 | 75 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/undertow/CustomHttpHandler.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.undertow;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
/**
* A custom {@link HttpHandler} which sets the response headers {@link #RESPONSE_HEADER_ONE_NAME} and
* {@link #RESPONSE_HEADER_TWO_NAME} with the value {@code true} if this handler was constructed using
* the "right" TCCL in the static and object initialization, respectively. The headers' value is set
* to {@code false} otherwise
*
* @author Jaikiran Pai
*/
public class CustomHttpHandler implements HttpHandler {
static final String RESPONSE_HEADER_ONE_NAME = "correct-tccl-during-handler-static-init";
static final String RESPONSE_HEADER_TWO_NAME = "correct-tccl-during-handler-init";
private final HttpHandler next;
private static final boolean correctTcclInStaticInit;
private final boolean correctTcclInInstanceConstruction;
static {
correctTcclInStaticInit = tryLoadClassInTCCL();
}
public CustomHttpHandler(final HttpHandler next) {
this.next = next;
this.correctTcclInInstanceConstruction = tryLoadClassInTCCL();
}
private static boolean tryLoadClassInTCCL() {
try {
Class.forName("org.jboss.as.test.manualmode.undertow.SomeClassInSameModuleAsCustomHttpHandler", true, Thread.currentThread().getContextClassLoader());
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
exchange.getResponseHeaders().put(new HttpString(RESPONSE_HEADER_ONE_NAME), String.valueOf(correctTcclInStaticInit));
exchange.getResponseHeaders().put(new HttpString(RESPONSE_HEADER_TWO_NAME), String.valueOf(this.correctTcclInInstanceConstruction));
next.handleRequest(exchange);
}
}
| 2,949 | 39.972222 | 162 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/undertow/SomeClassInSameModuleAsCustomHttpHandler.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.undertow;
/**
* A class that's supposed to belong to the same custom (JBoss) module as {@link CustomHttpHandler}
*
* @author Jaikiran Pai
*/
public class SomeClassInSameModuleAsCustomHttpHandler {
}
| 1,269 | 36.352941 | 99 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/undertow/CustomUndertowFilterTestCase.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.undertow;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentHelper;
import org.jboss.as.test.integration.management.ManagementOperations;
import org.jboss.as.test.integration.management.util.ModelUtil;
import org.jboss.as.test.module.util.TestModule;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
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;
import jakarta.inject.Inject;
import java.io.IOException;
import java.io.InputStream;
import static org.junit.Assert.assertEquals;
/**
* Tests custom http handler(s) configured as {@code custom-filter}s in the undertow subsystem
*
* @author Jaikiran Pai
*/
@RunWith(WildflyTestRunner.class)
@ServerControl(manual = true)
public class CustomUndertowFilterTestCase {
private static final Logger logger = Logger.getLogger(CustomUndertowFilterTestCase.class);
private static final String CUSTOM_FILTER_MODULE_NAME = "custom-undertow-filter-module";
private static final String CUSTOM_FILTER_CLASSNAME = CustomHttpHandler.class.getName();
private static final String CUSTOM_FILTER_RESOURCE_NAME = "testcase-added-custom-undertow-filter";
private static final String WAR_DEPLOYMENT_NAME = "test-tccl-in-custom-undertow-handler-construction";
@Inject
private static ServerController serverController;
private static TestModule customHandlerModule;
@BeforeClass
public static void setupServer() throws Exception {
serverController.start();
// setup the server with the necessary Undertow filter configurations
prepareServerConfiguration();
// deploy an web application
deploy();
}
@AfterClass
public static void resetServer() throws Exception {
try {
final ServerDeploymentHelper deploymentHelper = new ServerDeploymentHelper(serverController.getClient().getControllerClient());
deploymentHelper.undeploy(WAR_DEPLOYMENT_NAME + ".war");
} catch (Exception e) {
// ignore
logger.debug("Ignoring exception that occurred during un-deploying", e);
}
try {
// cleanup the undertow configurations we did in this test
resetServerConfiguration();
} finally {
serverController.stop();
}
}
private static void prepareServerConfiguration() throws Exception {
// create a (JBoss) module jar containing the custom http handler and a dummy class that gets used
// by the handler
customHandlerModule = createModule();
// create a custom-filter in the undertow subsystem and use the filter class that's
// present in the module that we just created
final ModelNode addCustomFilter = ModelUtil.createOpNode("subsystem=undertow/configuration=filter" +
"/custom-filter=" + CUSTOM_FILTER_RESOURCE_NAME, "add");
addCustomFilter.get("class-name").set(CUSTOM_FILTER_CLASSNAME);
addCustomFilter.get("module").set(CUSTOM_FILTER_MODULE_NAME);
// add a reference to this custom filter, in the default undertow host, so that it gets used
// for all deployed applications on this host
final ModelNode addFilterRef = ModelUtil.createOpNode("subsystem=undertow/server=default-server/host=default-host" +
"/filter-ref=" + CUSTOM_FILTER_RESOURCE_NAME, "add");
final ModelControllerClient controllerClient = serverController.getClient().getControllerClient();
ManagementOperations.executeOperation(controllerClient,
ModelUtil.createCompositeNode(new ModelNode[]{addCustomFilter, addFilterRef}));
// reload the server for changes to take effect
serverController.reload();
}
private static void resetServerConfiguration() throws Exception {
// remove the filter-ref
final ModelNode removeFilterRef = ModelUtil.createOpNode("subsystem=undertow/server=default-server/host=default-host" +
"/filter-ref=" + CUSTOM_FILTER_RESOURCE_NAME, "remove");
// remove the custom undertow filter
final ModelNode removeCustomFilter = ModelUtil.createOpNode("subsystem=undertow/configuration=filter" +
"/custom-filter=" + CUSTOM_FILTER_RESOURCE_NAME, "remove");
final ModelControllerClient controllerClient = serverController.getClient().getControllerClient();
ManagementOperations.executeOperation(controllerClient,
ModelUtil.createCompositeNode(new ModelNode[]{removeFilterRef, removeCustomFilter}));
// remove the custom module
customHandlerModule.remove();
// reload the server
serverController.reload();
}
private static void deploy() throws Exception {
// create a deployment
final WebArchive war = ShrinkWrap.create(WebArchive.class).addAsWebResource(new StringAsset("Hello world!"), "index.html");
// deploy it
try (InputStream is = war.as(ZipExporter.class).exportAsInputStream()) {
final ServerDeploymentHelper deploymentHelper = new ServerDeploymentHelper(serverController.getClient().getControllerClient());
deploymentHelper.deploy(WAR_DEPLOYMENT_NAME + ".war", is);
}
}
/**
* Tests that the {@link Thread#getContextClassLoader() TCCL} that's set when a
* custom {@link io.undertow.server.HttpHandler}, part of a (JBoss) module, configured in the undertow subsystem
* is initialized/constructed, the classloader is the same as the classloader of the module to which
* the handler belongs
*/
@Test
public void testTCCLInHttpHandlerInitialization() throws Exception {
final String url = "http://" + TestSuiteEnvironment.getHttpAddress()
+ ":" + TestSuiteEnvironment.getHttpPort()
+ "/" + WAR_DEPLOYMENT_NAME + "/index.html";
logger.debug("Invoking request at " + url);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
final HttpGet httpget = new HttpGet(url);
final HttpResponse response = httpClient.execute(httpget);
final StatusLine statusLine = response.getStatusLine();
assertEquals("Unexpected HTTP response status code for request " + url, 200, statusLine.getStatusCode());
// make sure the custom http handler was invoked and it was initialized with the right TCCL
final Header[] headerOneValues = response.getHeaders(CustomHttpHandler.RESPONSE_HEADER_ONE_NAME);
Assert.assertEquals("Unexpected number of response header value for header " + CustomHttpHandler.RESPONSE_HEADER_ONE_NAME, 1, headerOneValues.length);
Assert.assertEquals("Unexpected response header value for header " + CustomHttpHandler.RESPONSE_HEADER_ONE_NAME, true, Boolean.valueOf(headerOneValues[0].getValue()));
final Header[] headerTwoValues = response.getHeaders(CustomHttpHandler.RESPONSE_HEADER_TWO_NAME);
Assert.assertEquals("Unexpected number of response header value for header " + CustomHttpHandler.RESPONSE_HEADER_TWO_NAME, 1, headerTwoValues.length);
Assert.assertEquals("Unexpected response header value for header " + CustomHttpHandler.RESPONSE_HEADER_TWO_NAME, true, Boolean.valueOf(headerTwoValues[0].getValue()));
}
}
private static TestModule createModule() throws IOException {
final TestModule module = new TestModule(CUSTOM_FILTER_MODULE_NAME, "io.undertow.core");
module.addResource("custom-http-handler.jar").addClass(CustomHttpHandler.class)
.addClass(SomeClassInSameModuleAsCustomHttpHandler.class);
module.create(true);
return module;
}
}
| 9,605 | 48.515464 | 179 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/layered/LayeredTestModule.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.layered;
/**
* @author Dominik Pospisil <[email protected]>
*/
public class LayeredTestModule {
}
| 1,164 | 37.833333 | 70 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/layered/LayeredDistributionTestCase.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.layered;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.apache.commons.io.FileUtils;
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.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.as.test.integration.management.ManagementOperations;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
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.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Basic layered distribution integration test.
*
* @author Dominik Pospisil <[email protected]>
*/
@RunWith(Arquillian.class)
public class LayeredDistributionTestCase {
private static final Logger log = Logger.getLogger(LayeredDistributionTestCase.class);
private static final String CONTAINER = "jbossas-layered";
private static final Path AS_PATH = Paths.get("target", CONTAINER);
private final Path layersDir = Paths.get(AS_PATH.toString(), "modules", "system", "layers");
private static final String TEST_LAYER = "test";
private static final String PRODUCT_NAME = "Test-Product";
private static final String PRODUCT_VERSION = "1.0.0-Test";
private static final String DEPLOYMENT = "test-deployment";
private static final String webURI = "http://" + TestSuiteEnvironment.getServerAddress() + ":8080";
@ArquillianResource
private ContainerController controller;
@ArquillianResource
private Deployer deployer;
@Deployment(name = DEPLOYMENT, managed = false, testable = false)
@TargetsContainer(CONTAINER)
public static Archive<?> getDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "test-deployment.war");
// set dependency to the test deployment
war.addClass(LayeredTestServlet.class);
war.setManifest(new StringAsset(
"Manifest-Version: 1.0" + System.getProperty("line.separator")
+ "Dependencies: org.jboss.ldtc, org.jboss.modules" + System.getProperty("line.separator")));
return war;
}
@Test
@InSequence(-1)
public void before() throws Exception {
buildLayer(TEST_LAYER);
buildProductModule(TEST_LAYER);
buildTestModule(TEST_LAYER);
log.trace("===starting server===");
controller.start(CONTAINER);
log.trace("===appserver started===");
//deployer.deploy(DEPLOYMENT);
//log.trace("===deployment deployed===");
}
@Test
@InSequence(1)
public void after() throws Exception {
try {
//deployer.undeploy(DEPLOYMENT);
//log.trace("===deployment undeployed===");
} finally {
controller.stop(CONTAINER);
log.trace("===appserver stopped===");
}
}
@Test
public void testLayeredProductVersion() throws Throwable {
final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient();
ModelNode readAttrOp = new ModelNode();
readAttrOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION);
readAttrOp.get(ModelDescriptionConstants.NAME).set("product-name");
ModelNode result = ManagementOperations.executeOperation(client, readAttrOp);
Assert.assertEquals(result.asString(), PRODUCT_NAME);
readAttrOp.get(ModelDescriptionConstants.NAME).set("product-version");
result = ManagementOperations.executeOperation(client, readAttrOp);
Assert.assertEquals(result.asString(), PRODUCT_VERSION);
}
@Test
public void testLayeredDeployment() throws Throwable {
deployer.deploy(DEPLOYMENT);
// test that the deployment can access class from a layered module
String response = HttpRequest.get(webURI + "/test-deployment/LayeredTestServlet", 10, TimeUnit.SECONDS);
Assert.assertTrue(response.contains("LayeredTestServlet"));
deployer.undeploy(DEPLOYMENT);
}
private void buildLayer(String layer) throws Exception {
log.trace("AS dir:" + AS_PATH);
Assert.assertTrue(Files.exists(AS_PATH));
Assert.assertTrue(Files.exists(layersDir));
Path layerDir = layersDir.resolve(layer);
File layerDirFile = layerDir.toFile();
if(layerDirFile.exists()) {
FileUtils.deleteDirectory(layerDirFile);
}
// set layers.conf
Path layersConf = AS_PATH.resolve("modules").resolve("layers.conf");
if (layersConf.toFile().exists()) {
for (String line : Files.readAllLines(layersConf)) {
if (line.startsWith("layers=")) {
if (!line.equals("layers=test") && !line.startsWith("layers=test,")) {
Files.write(layersConf, Collections.singleton(line.replace("layers=", "layers=test,")));
} // else we've picked up a file perhaps from a previous test that already is configured; just use it
break;
}
}
} else {
Files.write(layersConf, Collections.singleton("layers=test"));
}
}
private void buildProductModule(String layer) throws Exception {
Path layerDir = layersDir.resolve(layer);
Path moduleDir = Paths.get(layerDir.toString(), "org" ,"jboss" ,"as" , "product" , "test");
Files.createDirectories(moduleDir);
Path moduleXmlFile = moduleDir.resolve("module.xml");
Files.copy(LayeredDistributionTestCase.class.getResourceAsStream("/layered/product-module.xml"),
moduleXmlFile);
Path manifestDir = moduleDir.resolve("classes").resolve("META-INF");
Files.createDirectories(manifestDir);
Path moduleManifestFile = manifestDir.resolve("MANIFEST.MF");
Manifest m = new Manifest();
m.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
m.getMainAttributes().putValue("JBoss-Product-Release-Name", PRODUCT_NAME);
m.getMainAttributes().putValue("JBoss-Product-Release-Version", PRODUCT_VERSION);
OutputStream manifestStream = new BufferedOutputStream(Files.newOutputStream(moduleManifestFile));
m.write(manifestStream);
manifestStream.flush();
manifestStream.close();
// set product.conf
Path binDir = AS_PATH.resolve("bin");
if (Files.notExists(binDir)){
Files.createDirectory(binDir);
}
Path productConf = binDir.resolve("product.conf");
Files.deleteIfExists(productConf);
Files.write(productConf, Collections.singleton("slot=test"), StandardCharsets.UTF_8);
}
private void buildTestModule(String layer) throws Exception {
Path layerDir = layersDir.resolve(layer);
Path moduleDir = Paths.get(layerDir.toString(), "org" , "jboss" , "ldtc" , "main");
Files.createDirectories(moduleDir);
Path moduleXmlFile = moduleDir.resolve("module.xml");
Files.copy(LayeredDistributionTestCase.class.getResourceAsStream("/layered/test-module.xml"),
moduleXmlFile);
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "test-module.jar");
jar.addClass(LayeredTestModule.class);
Path jarFile = moduleDir.resolve("test-module.jar");
jar.as(ZipExporter.class).exportTo(jarFile.toFile());
}
}
| 9,482 | 39.699571 | 121 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/layered/LayeredTestServlet.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.layered;
import java.io.IOException;
import java.io.PrintWriter;
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 Dominik Pospisil <[email protected]>
*/
@WebServlet(urlPatterns = {"/LayeredTestServlet"})
public class LayeredTestServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
LayeredTestModule module = new LayeredTestModule();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>LayeredTestServlet</title></head>");
out.println("<body>Done</body>");
out.println("</html>");
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
| 2,392 | 36.984127 | 91 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/parse/HostParseAndMarshalModelsTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, 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.manualmode.parse;
import java.nio.file.Path;
import java.util.List;
import org.jboss.logging.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/**
* Tests the host configuration files can be parsed and marshalled.
*
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
@RunWith(Parameterized.class)
public class HostParseAndMarshalModelsTestCase extends AbstractParseAndMarshalModelsTestCase {
private static final Logger LOGGER = Logger.getLogger(HostParseAndMarshalModelsTestCase.class);
@Parameterized.Parameters
public static List<Path> data() {
return resolveConfigFiles(p -> p.getFileName()
.toString()
// Cannot test the host-secondary.xml as the system property used for testing cannot be written
.startsWith("host") && !"host-secondary.xml".equals(p.getFileName()
.toString()), "domain", "configuration");
}
@Parameterized.Parameter
public Path configFile;
@Test
public void configFiles() throws Exception {
LOGGER.infof("Testing config file %s", configFile);
hostXmlTest(configFile.toFile());
}
}
| 2,271 | 37.508475 | 111 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/parse/StandaloneParseAndMarshalModelsTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, 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.manualmode.parse;
import java.nio.file.Path;
import java.util.List;
import org.jboss.logging.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/**
* Tests the standalone configuration files can be parsed and marshalled.
*
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
@RunWith(Parameterized.class)
public class StandaloneParseAndMarshalModelsTestCase extends AbstractParseAndMarshalModelsTestCase {
private static final Logger LOGGER = Logger.getLogger(StandaloneParseAndMarshalModelsTestCase.class);
@Parameterized.Parameters
public static List<Path> data() {
return resolveConfigFiles("standalone", "configuration");
}
@Parameterized.Parameter
public Path configFile;
@Test
public void configFiles() throws Exception {
LOGGER.infof("Testing config file %s", configFile);
standaloneXmlTest(configFile.toFile());
}
}
| 2,024 | 35.818182 | 105 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/parse/ExampleParseAndMarshalModelsTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, 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.manualmode.parse;
import java.nio.file.Path;
import java.util.List;
import org.jboss.logging.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/**
* Tests the example configuration files can be parsed and marshalled.
*
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
@RunWith(Parameterized.class)
public class ExampleParseAndMarshalModelsTestCase extends AbstractParseAndMarshalModelsTestCase {
private static final Logger LOGGER = Logger.getLogger(ExampleParseAndMarshalModelsTestCase.class);
@Parameterized.Parameters
public static List<Path> data() {
return resolveConfigFiles(p -> p.getFileName().toString().startsWith("standalone"), "docs", "examples", "configs");
}
@Parameterized.Parameter
public Path configFile;
@Test
public void configFiles() throws Exception {
LOGGER.infof("Testing config file %s", configFile);
standaloneXmlTest(configFile.toFile());
}
}
| 2,073 | 36.709091 | 123 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/parse/LegacyParseAndMarshalModelsTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, 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.manualmode.parse;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import java.io.File;
import java.io.FileNotFoundException;
import org.jboss.as.test.shared.FileUtils;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Ignore;
import org.junit.Test;
/**
* Tests the ability to parse the config files we ship or have shipped in the past, as well as the ability to marshal
* them back to xml in a manner such that reparsing them produces a consistent in-memory configuration model.
*
* @author <a href="[email protected]">Kabir Khan</a>
* @author <a href="mailto:[email protected]">Darran Lofthouse</a>
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
@Ignore("[WFLY-15178] Rework ParseAndMarshalModelsTestCase.")
public class LegacyParseAndMarshalModelsTestCase extends AbstractParseAndMarshalModelsTestCase {
private enum Version {
AS_7_1_3(false, "7-1-3"),
AS_7_2_0(false, "7-2-0"),
EAP_6_0_0(true, "6-0-0"),
EAP_6_1_0(true, "6-1-0"),
EAP_6_2_0(true, "6-2-0"),
EAP_6_3_0(true, "6-3-0"),
EAP_6_4_0(true, "6-4-0"),
EAP_7_0_0(true, "7-0-0"),
EAP_7_1_0(true, "7-1-0"),
EAP_7_2_0(true, "7-2-0"),
EAP_7_3_0(true, "7-3-0"),
EAP_7_4_0(true, "7-4-0");
final boolean eap;
final String versionQualifier;
final int major;
final int minor;
final int micro;
Version(boolean eap, String versionQualifier) {
this.eap = eap;
this.versionQualifier = versionQualifier;
final String[] parts = this.versionQualifier.split("-");
major = Integer.valueOf(parts[0]);
minor = Integer.valueOf(parts[1]);
micro = Integer.valueOf(parts[2]);
}
boolean is6x() {
return major == 6;
}
boolean is7x() {
return major == 7;
}
boolean isLessThan(int major, int minor) {
return (this.major == major && this.minor < minor) || this.major < major;
}
}
private static final Version[] EAP_VERSIONS = {
Version.EAP_6_0_0, Version.EAP_6_1_0, Version.EAP_6_2_0, Version.EAP_6_3_0, Version.EAP_6_4_0,
Version.EAP_7_0_0, Version.EAP_7_1_0, Version.EAP_7_2_0, Version.EAP_7_3_0, Version.EAP_7_4_0};
private static final Version[] AS_VERSIONS = {Version.AS_7_1_3, Version.AS_7_2_0};
private static final boolean altDistTest = "ee-".equals(System.getProperty("testsuite.default.build.project.prefix"));
@Test
public void testJBossASStandaloneXml() throws Exception {
for (Version version : AS_VERSIONS) {
ModelNode model = standaloneXmlTest(getLegacyConfigFile("standalone", version, null));
validateJsfSubsystem(model, version);
}
}
@Test
public void testJBossASStandaloneFullHaXml() throws Exception {
for (Version version : AS_VERSIONS) {
ModelNode model = standaloneXmlTest(getLegacyConfigFile("standalone", version, "full-ha"));
validateJsfSubsystem(model, version);
}
}
@Test
public void testJBossASStandaloneFullXml() throws Exception {
for (Version version : AS_VERSIONS) {
ModelNode model = standaloneXmlTest(getLegacyConfigFile("standalone", version, "full"));
validateJsfSubsystem(model, version);
}
}
@Test
public void testJBossASStandaloneHornetQCollocatedXml() throws Exception {
for (Version version : AS_VERSIONS) {
standaloneXmlTest(getLegacyConfigFile("standalone", version, "hornetq-colocated"));
}
}
@Test
public void testJBossASStandaloneJtsXml() throws Exception {
for (Version version : AS_VERSIONS) {
standaloneXmlTest(getLegacyConfigFile("standalone", version, "jts"));
}
}
@Test
public void testJBossASStandaloneMinimalisticXml() throws Exception {
for (Version version : AS_VERSIONS) {
standaloneXmlTest(getLegacyConfigFile("standalone", version, "minimalistic"));
}
}
@Test
public void testJBossASStandaloneXtsXml() throws Exception {
for (Version version : AS_VERSIONS) {
standaloneXmlTest(getLegacyConfigFile("standalone", version, "xts"));
}
}
@Test
public void testEAPStandaloneFullHaXml() throws Exception {
Assume.assumeFalse(altDistTest);
for (Version version : EAP_VERSIONS) {
ModelNode model = standaloneXmlTest(getLegacyConfigFile("standalone", version, "full-ha"));
validateWebSubsystem(model, version);
validateJsfSubsystem(model, version);
validateCmpSubsystem(model, version);
validateMessagingSubsystem(model, version);
}
}
@Test
public void testEAPStandaloneFullXml() throws Exception {
Assume.assumeFalse(altDistTest);
for (Version version : EAP_VERSIONS) {
ModelNode model = standaloneXmlTest(getLegacyConfigFile("standalone", version, "full"));
validateWebSubsystem(model, version);
validateJsfSubsystem(model, version);
validateCmpSubsystem(model, version);
validateMessagingSubsystem(model, version);
}
}
@Test
public void testEAPStandaloneXml() throws Exception {
Assume.assumeFalse(altDistTest);
for (Version version : EAP_VERSIONS) {
ModelNode model = standaloneXmlTest(getLegacyConfigFile("standalone", version, null));
validateWebSubsystem(model, version);
validateJsfSubsystem(model, version);
}
}
@Test
public void testEAPStandaloneHornetQCollocatedXml() throws Exception {
for (Version version : EAP_VERSIONS) {
if (version.is6x()) {
//Only exists in EAP 6.x
ModelNode model = standaloneXmlTest(getLegacyConfigFile("standalone", version, "hornetq-colocated"));
validateWebSubsystem(model, version);
validateJsfSubsystem(model, version);
validateMessagingSubsystem(model, version);
validateThreadsSubsystem(model, version);
validateJacordSubsystem(model, version);
}
}
}
@Test
public void testEAPStandaloneJtsXml() throws Exception {
Assume.assumeFalse(altDistTest);
for (Version version : EAP_VERSIONS) {
ModelNode model = standaloneXmlTest(getLegacyConfigFile("standalone", version, "jts"));
validateWebSubsystem(model, version);
validateJsfSubsystem(model, version);
validateThreadsSubsystem(model, version);
validateJacordSubsystem(model, version);
}
}
@Test
public void testEAPStandaloneMinimalisticXml() throws Exception {
for (Version version : EAP_VERSIONS) {
standaloneXmlTest(getLegacyConfigFile("standalone", version, "minimalistic"));
}
}
@Test
public void testEAPStandaloneXtsXml() throws Exception {
Assume.assumeFalse(altDistTest);
for (Version version : EAP_VERSIONS) {
ModelNode model = standaloneXmlTest(getLegacyConfigFile("standalone", version, "xts"));
validateCmpSubsystem(model, version);
validateWebSubsystem(model, version);
validateJsfSubsystem(model, version);
validateThreadsSubsystem(model, version);
validateJacordSubsystem(model, version);
validateXtsSubsystem(model, version);
}
}
@Test
public void testEAPStandaloneAzureFullHaXml() throws Exception {
Assume.assumeFalse(altDistTest);
for (Version version : EAP_VERSIONS) {
if (version.is6x()) {
// didn't exist yet
} else {
standaloneXmlTest(getLegacyConfigFile("standalone", version, "azure-full-ha"));
}
}
}
@Test
public void testEAPStandaloneAzureHaXml() throws Exception {
Assume.assumeFalse(altDistTest);
for (Version version : EAP_VERSIONS) {
if (version.is6x()) {
// didn't exist yet
} else {
standaloneXmlTest(getLegacyConfigFile("standalone", version, "azure-ha"));
}
}
}
@Test
public void testEAPStandaloneEc2FullHaXml() throws Exception {
Assume.assumeFalse(altDistTest);
for (Version version : EAP_VERSIONS) {
if (version.is6x()) {
// didn't exist yet
} else {
standaloneXmlTest(getLegacyConfigFile("standalone", version, "ec2-full-ha"));
}
}
}
@Test
public void testEAPStandaloneEc2HaXml() throws Exception {
Assume.assumeFalse(altDistTest);
for (Version version : EAP_VERSIONS) {
if (version.is6x()) {
// didn't exist yet
} else {
standaloneXmlTest(getLegacyConfigFile("standalone", version, "ec2-ha"));
}
}
}
@Test
public void testEAPStandaloneGenericJmsXml() throws Exception {
Assume.assumeFalse(altDistTest);
for (Version version : EAP_VERSIONS) {
if (version.is6x()) {
// didn't exist yet
} else {
standaloneXmlTest(getLegacyConfigFile("standalone", version, "genericjms"));
}
}
}
@Test
public void testEAPStandaloneGossipFullHaXml() throws Exception {
Assume.assumeFalse(altDistTest);
for (Version version : EAP_VERSIONS) {
if (version.is6x()) {
// didn't exist yet
} else {
standaloneXmlTest(getLegacyConfigFile("standalone", version, "gossip-full-ha"));
}
}
}
@Test
public void testEAPStandaloneGossipHaXml() throws Exception {
Assume.assumeFalse(altDistTest);
for (Version version : EAP_VERSIONS) {
if (version.is6x()) {
// didn't exist yet
} else {
standaloneXmlTest(getLegacyConfigFile("standalone", version, "gossip-ha"));
}
}
}
@Test
public void testEAPStandaloneLoadBalancerXml() throws Exception {
for (Version version : EAP_VERSIONS) {
if (version.isLessThan(7, 1)) {
// didn't exist yet
} else {
standaloneXmlTest(getLegacyConfigFile("standalone", version, "load-balancer"));
}
}
}
@Test
public void testEAPStandaloneRtsXml() throws Exception {
Assume.assumeFalse(altDistTest);
for (Version version : EAP_VERSIONS) {
if (version.is6x()) {
// didn't exist yet
} else {
standaloneXmlTest(getLegacyConfigFile("standalone", version, "rts"));
}
}
}
@Test
public void testJBossASHostXml() throws Exception {
for (Version version : AS_VERSIONS) {
hostXmlTest(getLegacyConfigFile("host", version, null));
}
}
@Test
public void testEAPHostXml() throws Exception {
for (Version version : EAP_VERSIONS) {
hostXmlTest(getLegacyConfigFile("host", version, null));
}
}
@Test
public void testJBossASDomainXml() throws Exception {
for (Version version : AS_VERSIONS) {
ModelNode model = domainXmlTest(getLegacyConfigFile("domain", version, null));
validateProfiles(model, version);
}
}
@Test
public void testEAPDomainXml() throws Exception {
Assume.assumeFalse(altDistTest);
for (Version version : EAP_VERSIONS) {
ModelNode model = domainXmlTest(getLegacyConfigFile("domain", version, null));
validateProfiles(model, version);
}
}
private static void validateProfiles(ModelNode model, Version version) {
Assert.assertTrue(model.hasDefined(PROFILE));
if (version.is6x()) {
//Only in 6.x
for (Property prop : model.get(PROFILE).asPropertyList()) {
validateWebSubsystem(prop.getValue(), version);
validateJsfSubsystem(prop.getValue(), version);
validateThreadsSubsystem(prop.getValue(), version);
}
} else {
//Don't validate, although we may decide to validate things in the future
}
}
private static void validateWebSubsystem(ModelNode model, Version version) {
if (version.is6x()) {
//Only in 6.x
validateSubsystem(model, "web", version);
Assert.assertTrue(model.hasDefined(SUBSYSTEM, "web", "connector", "http"));
}
}
private static void validateJsfSubsystem(ModelNode model, Version version) {
if (version.is6x()) {
//Only in 6.x
validateSubsystem(model, "jsf", version); //we cannot check for it as web subsystem is not present to add jsf one
}
}
private static void validateCmpSubsystem(ModelNode model, Version version) {
if (version.is6x()) {
//Only in 6.x
validateSubsystem(model, "cmp", version); //we cannot check for it as web subsystem is not present to add jsf one
}
}
private static void validateMessagingSubsystem(ModelNode model, Version version) {
if (version.is6x()) {
//Only in 6.x
validateSubsystem(model, "messaging", version);
Assert.assertTrue(model.hasDefined(SUBSYSTEM, "messaging", "hornetq-server", "default"));
}
}
private static void validateThreadsSubsystem(ModelNode model, Version version) {
if (version.is6x()) {
//Only in 6.x
validateSubsystem(model, "threads", version);
}
}
private static void validateJacordSubsystem(ModelNode model, Version version) {
if (version.is6x()) {
//Only in 6.x
validateSubsystem(model, "jacorb", version);
}
}
private static void validateXtsSubsystem(ModelNode model, Version version) {
validateSubsystem(model, "xts", version);
Assert.assertTrue(model.hasDefined(SUBSYSTEM, "xts", "host"));
}
private static void validateSubsystem(ModelNode model, String subsystem, Version version) {
Assert.assertTrue(model.hasDefined(SUBSYSTEM));
Assert.assertTrue("Missing " + subsystem + " subsystem for " + version.versionQualifier, model.get(SUBSYSTEM)
.hasDefined(subsystem));
}
private File getLegacyConfigFile(String type, Version version, String qualifier) throws FileNotFoundException {
StringBuilder sb = new StringBuilder();
if (version.eap) {
sb.append("eap-");
}
sb.append(version.versionQualifier);
if (qualifier != null) {
sb.append("-");
sb.append(qualifier);
}
sb.append(".xml");
String fileName = sb.toString();
return FileUtils.getFileOrCheckParentsIfNotFound(
System.getProperty("jbossas.ts.submodule.dir"),
"src/test/resources/legacy-configs/" + type + File.separator + fileName
);
}
}
| 16,668 | 33.018367 | 125 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/parse/DomainParseAndMarshalModelsTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, 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.manualmode.parse;
import java.nio.file.Path;
import java.util.List;
import org.jboss.logging.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/**
* Tests the domain configuration files can be parsed and marshalled.
*
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
@RunWith(Parameterized.class)
public class DomainParseAndMarshalModelsTestCase extends AbstractParseAndMarshalModelsTestCase {
private static final Logger LOGGER = Logger.getLogger(DomainParseAndMarshalModelsTestCase.class);
@Parameterized.Parameters
public static List<Path> data() {
return resolveConfigFiles(p -> p.getFileName().toString().startsWith("domain"), "domain", "configuration");
}
@Parameterized.Parameter
public Path configFile;
@Test
public void configFiles() throws Exception {
LOGGER.infof("Testing config file %s", configFile);
domainXmlTest(configFile.toFile());
}
}
| 2,058 | 36.436364 | 115 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/parse/AbstractParseAndMarshalModelsTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, 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.manualmode.parse;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jboss.as.test.shared.ModelParserUtils;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
/**
* Abstract test case for testing the ability to parse configuration files. As well as the ability to marshal them back
* to xml in a manner such that reparsing them produces a consistent in-memory configuration model.
*
* @author <a href="[email protected]">Kabir Khan</a>
* @author <a href="mailto:[email protected]">Darran Lofthouse</a>
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
abstract class AbstractParseAndMarshalModelsTestCase {
private static final File JBOSS_HOME = Paths.get("target", "jbossas-parse-marshal").toFile();
protected ModelNode standaloneXmlTest(File original) throws Exception {
return ModelParserUtils.standaloneXmlTest(original, JBOSS_HOME);
}
protected void hostXmlTest(final File original) throws Exception {
ModelParserUtils.hostXmlTest(original, JBOSS_HOME);
}
protected ModelNode domainXmlTest(final File original) throws Exception {
return ModelParserUtils.domainXmlTest(original, JBOSS_HOME);
}
// Get-config methods
static List<Path> resolveConfigFiles(final String... names) {
return resolveConfigFiles(p -> p.getFileName().toString().endsWith(".xml"), names);
}
static List<Path> resolveConfigFiles(final Predicate<Path> filter, final String... names) {
final String path = System.getProperty("jboss.dist");
Assert.assertNotNull("jboss.dist property was not set", path);
final Path configDir = Path.of(path, names);
Assert.assertTrue(String.format("Directory %s does not exist.", path), Files.exists(configDir));
try (Stream<Path> files = Files.list(configDir)) {
return files.filter(filter)
.collect(Collectors.toUnmodifiableList());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
| 3,341 | 39.756098 | 119 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/model/ReadFullModelTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.manualmode.model;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RECURSIVE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import jakarta.inject.Inject;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.core.testrunner.ManagementClient;
import org.wildfly.core.testrunner.Server;
import org.wildfly.core.testrunner.ServerControl;
import org.wildfly.core.testrunner.ServerController;
import org.wildfly.core.testrunner.WildflyTestRunner;
/**
* Ensures that the full model including runtime resources/attributes can be read in both normal and admin-only mode
* for the fullest server config possible
*
* @author Kabir Khan
* @author Tomaz Cerar
*/
@ServerControl(manual = true)
@RunWith(WildflyTestRunner.class)
public class ReadFullModelTestCase {
//This is the full-ha setup which is the fullest config we have
//Reuse this rather than a setup
private static final String SERVER_CONFIG = "standalone-full-ha.xml";
@Inject
private ServerController container;
@Test
public void test() throws Exception {
container.start(SERVER_CONFIG, Server.StartMode.NORMAL);
try {
ManagementClient client = container.getClient();
ModelNode rr = Util.createEmptyOperation(READ_RESOURCE_OPERATION, PathAddress.EMPTY_ADDRESS);
rr.get(INCLUDE_RUNTIME).set(true);
rr.get(RECURSIVE).set(true);
ModelNode result = client.executeForResult(rr);
//Just a quick sanity test to check that we are full-ha by making sure some of the expected subsystems are there
Assert.assertTrue(result.hasDefined(SUBSYSTEM, "messaging-activemq"));
Assert.assertTrue(result.hasDefined(SUBSYSTEM, "jgroups"));
container.reload();
client.executeForResult(rr);
} finally {
container.stop();
}
}
}
| 3,367 | 39.578313 | 124 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/model/ExpressionSupportSmokeTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.model;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.integration.management.base.AbstractExpressionSupportTestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Smoke test of expression support for default configurations.
*
* @author Ivan Straka (c) 2020 Red Hat Inc.
*/
@RunWith(Arquillian.class)
public class ExpressionSupportSmokeTestCase extends AbstractExpressionSupportTestCase {
private static final String JBOSSAS = "jbossas-custom";
private static final String JBOSSAS_HA = "jbossas-custom-ha";
private static final String JBOSSAS_FULL = "jbossas-custom-full";
private static final String JBOSSAS_FULL_HA = "jbossas-custom-full-ha";
private static final String JBOSSAS_ACTIVEMQ_COLOCATED = "jbossas-custom-activemq-colocated";
private static final String JBOSSAS_GENERICJMS = "jbossas-custom-genericjms";
private static final String JBOSSAS_RTS = "jbossas-custom-rts";
private static final String JBOSSAS_XTS = "jbossas-custom-xts";
private ManagementClient managementClient;
private void setup(String containerName) {
if (!container.isStarted(containerName)) {
container.start(containerName);
}
managementClient = createManagementClient();
}
private void teardown(String containerName) {
container.stop(containerName);
managementClient.close();
}
private void testContainer(String containerName) throws Exception {
try {
setup(containerName);
test(managementClient);
} finally {
teardown(containerName);
}
}
@Test
public void testDefault() throws Exception {
testContainer(JBOSSAS);
}
@Test
public void testHA() throws Exception {
testContainer(JBOSSAS_HA);
}
@Test
public void testFull() throws Exception {
testContainer(JBOSSAS_FULL);
}
@Test
public void testFullHa() throws Exception {
testContainer(JBOSSAS_FULL_HA);
}
@Test
public void testActivemqColocated() throws Exception {
testContainer(JBOSSAS_ACTIVEMQ_COLOCATED);
}
@Test
public void testGenericJMS() throws Exception {
testContainer(JBOSSAS_GENERICJMS);
}
@Test
public void testRTS() throws Exception {
testContainer(JBOSSAS_RTS);
}
@Test
public void testXTS() throws Exception {
testContainer(JBOSSAS_XTS);
}
}
| 3,598 | 31.718182 | 97 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/server/nongraceful/NongracefulStartTestCase.java
|
package org.jboss.as.test.manualmode.server.nongraceful;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.net.SocketPermission;
import java.util.PropertyPermission;
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.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.manualmode.server.nongraceful.deploymenta.TestApplicationA;
import org.jboss.as.test.manualmode.server.nongraceful.deploymentb.TestApplicationB;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* This test will exercise the non-graceful startup feature of WildFly. This test will deploy two applications,
* ApplicationA and ApplicationB. ApplicationB, however, while it is starting, tries to access ApplicationA.
* If the server has started in normal mode, no requests will be allowed until the server has completely
* started, which will cause the deployment of ApplicationB to fail, as it will block indefinitely. We start the
* container, though, with --graceful-startup=false, which will allow requests to be processed or rejected cleanly
* during the server startup process.
*/
@RunWith(Arquillian.class)
public class NongracefulStartTestCase {
private static final String CONTAINER = "non-graceful-server";
private static final String DEPLOYMENTA = "deploymenta";
private static final String DEPLOYMENTB = "deploymentb";
private static final Logger logger = Logger.getLogger(NongracefulStartTestCase.class);
@ArquillianResource
private static ContainerController containerController;
@ArquillianResource
Deployer deployer;
@Deployment(name = DEPLOYMENTA, managed = false, testable = false)
@TargetsContainer(CONTAINER)
public static Archive<?> getDeploymentA() {
return buildBaseArchive(DEPLOYMENTA)
.addPackage(TestApplicationA.class.getPackage());
}
@Deployment(name = DEPLOYMENTB, managed = false, testable = false)
@TargetsContainer(CONTAINER)
public static Archive<?> getDeploymentB() {
return buildBaseArchive(DEPLOYMENTB)
.addPackage(TestApplicationB.class.getPackage());
}
private static WebArchive buildBaseArchive(String name) {
return ShrinkWrap
.create(WebArchive.class, name + ".war")
.add(EmptyAsset.INSTANCE, "WEB-INF/beans.xml")
.addClass(TimeoutUtil.class)
.addAsManifestResource(createPermissionsXmlAsset(
// Required for the TimeoutUtil.adjust call when determining how long DEPLOYMENTB should poll
new PropertyPermission("ts.timeout.factor", "read"),
// Required for the client to connect
new SocketPermission(TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort(), "connect,resolve")
), "permissions.xml");
}
/**
* 1. Start the container
* 2. Deploy the applications
* 3. Stop the container
* 4. Restart the container. If non-graceful mode is working, the container should start successfully.
*/
@Test
public void testNonGracefulDeployment() {
try {
containerController.start(CONTAINER);
deployer.deploy(DEPLOYMENTA);
deployer.deploy(DEPLOYMENTB);
containerController.stop(CONTAINER);
containerController.start(CONTAINER);
} finally {
executeCleanup(() -> deployer.undeploy(DEPLOYMENTA));
executeCleanup(() -> deployer.undeploy(DEPLOYMENTB));
executeCleanup(() -> containerController.stop(CONTAINER));
}
}
private void executeCleanup(Runnable func) {
try {
func.run();
} catch (Exception e) {
logger.trace("Exception during container cleanup and shutdown", e);
}
}
}
| 4,500 | 41.866667 | 145 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/server/nongraceful/deploymentb/TestApplicationB.java
|
package org.jboss.as.test.manualmode.server.nongraceful.deploymentb;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
/**
* @author Paul Ferraro
*/
@ApplicationPath("/testb")
public class TestApplicationB extends Application {
}
| 262 | 19.230769 | 68 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/server/nongraceful/deploymentb/ResourceB.java
|
package org.jboss.as.test.manualmode.server.nongraceful.deploymentb;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.Initialized;
import jakarta.enterprise.event.Observes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.core.Response;
import org.jboss.as.test.shared.TimeoutUtil;
@ApplicationScoped
@Path("/resourceb")
public class ResourceB {
public void postConstruct(@Observes @Initialized(ApplicationScoped.class) Object o) throws InterruptedException {
final Client client = ClientBuilder.newClient();
final int sleepTime = 100;
int tries = 0;
int maxLoopCount = TimeoutUtil.adjust(4500) / sleepTime;
boolean complete = false;
while (!complete && tries < maxLoopCount) {
Response response = client.target("http://localhost:8080/deploymenta/testa/resourcea")
.request()
.get();
int status = response.getStatus();
if (status != 200) {
tries++;
Thread.sleep(sleepTime);
} else {
complete = true;
}
}
}
@GET
public String get() {
return "Hello";
}
}
| 1,332 | 30 | 117 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/server/nongraceful/deploymenta/TestApplicationA.java
|
package org.jboss.as.test.manualmode.server.nongraceful.deploymenta;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
/**
* @author Paul Ferraro
*/
@ApplicationPath("/testa")
public class TestApplicationA extends Application {
}
| 263 | 17.857143 | 68 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/server/nongraceful/deploymenta/ResourceA.java
|
package org.jboss.as.test.manualmode.server.nongraceful.deploymenta;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
@ApplicationScoped
@Path("/resourcea")
public class ResourceA {
@GET
public String get() {
return "Hello";
}
}
| 308 | 19.6 | 68 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ee/globaldirectory/GlobalDirectoryBasicTestCase.java
|
/*
* Copyright 2019 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.manualmode.ee.globaldirectory;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.domain.management.ModelDescriptionConstants.PATH;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.io.FileUtils;
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.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.Operations;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Basic test that ensures that a jar file and a property file added into a global-directory are available in a deployment.
*
* @author Yeray Borges
*/
@RunWith(Arquillian.class)
@RunAsClient
public class GlobalDirectoryBasicTestCase {
private static final PathAddress GLOBAL_DIRECTORY_TEST_APP_LIBS = PathAddress.pathAddress(SUBSYSTEM, "ee").append("global-directory", "test-app-libs");
private static final String DEFAULT_JBOSSAS = "default-jbossas";
private static final String DEPLOYMENT_WAR = "deployment-war";
private static final String DEPLOYMENT_EAR = "deployment-ear";
@ArquillianResource
private static ContainerController controller;
@ArquillianResource
private Deployer deployer;
private ManagementClient managementClient;
private Path globalDirectoryPath;
public void setupServer(ManagementClient managementClient) throws Exception {
final ModelNode op = Operations.createAddOperation(GLOBAL_DIRECTORY_TEST_APP_LIBS.toModelNode());
op.get(PATH).set(globalDirectoryPath.toString());
ModelTestUtils.checkOutcome(managementClient.getControllerClient().execute(op));
}
public void tearDown(ManagementClient managementClient) throws Exception {
final ModelNode op = Operations.createRemoveOperation(GLOBAL_DIRECTORY_TEST_APP_LIBS.toModelNode());
ModelTestUtils.checkOutcome(managementClient.getControllerClient().execute(op));
}
@Deployment(name = DEPLOYMENT_WAR, testable = false, managed = false)
public static Archive<?> deployWr() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "web-app.war");
war.addClasses(EchoServlet.class);
return war;
}
@Deployment(name = DEPLOYMENT_EAR, testable = false, managed = false)
public static Archive<?> deployEar() {
final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "ear-app.ear");
final WebArchive war = ShrinkWrap.create(WebArchive.class, "web-app-in-ear.war");
war.addClasses(EchoServlet.class);
ear.addAsModule(war);
return ear;
}
@Before
public void init() throws Exception {
prepareGlobalDirectory();
controller.start(DEFAULT_JBOSSAS);
final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient();
managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http");
setupServer(managementClient);
deployer.deploy(DEPLOYMENT_WAR);
deployer.deploy(DEPLOYMENT_EAR);
}
@After
public void tearDown() throws Exception {
deployer.undeploy(DEPLOYMENT_WAR);
deployer.undeploy(DEPLOYMENT_EAR);
tearDown(managementClient);
controller.stop(DEFAULT_JBOSSAS);
FileUtils.deleteDirectory(globalDirectoryPath.toFile());
}
@Test
public void testApplications() throws IOException, TimeoutException, ExecutionException {
String address = "http://" + TestSuiteEnvironment.getServerAddress() + ":8080/web-app/echoServlet";
String out = HttpRequest.get(address, 60, TimeUnit.SECONDS);
Assert.assertTrue("Unexpected message from echoServlet in war file", out.contains("echo-library-1 Message from the servlet Key=test, Value=test-value Key=sub-test, Value=sub-test-value"));
address = "http://" + TestSuiteEnvironment.getServerAddress() + ":8080/web-app-in-ear/echoServlet";
out = HttpRequest.get(address, 60, TimeUnit.SECONDS);
Assert.assertTrue("Unexpected message from echoServlet in war file", out.contains("echo-library-1 Message from the servlet Key=test, Value=test-value Key=sub-test, Value=sub-test-value"));
}
private void prepareGlobalDirectory() throws IOException {
final String jbossHome = System.getProperty("jboss.home", null);
if (jbossHome == null) {
throw new IllegalStateException("-Djboss.home not set");
}
globalDirectoryPath = Paths.get(jbossHome, "standalone", "global-directory").toAbsolutePath();
Files.createDirectories(globalDirectoryPath);
prepareLibs();
prepareProperties();
}
private void prepareLibs() {
final JavaArchive lib = ShrinkWrap.create(JavaArchive.class, "lib.jar");
lib.addClasses(EchoUtility.class);
lib.as(ZipExporter.class).exportTo(globalDirectoryPath.resolve("lib.jar").toFile());
}
private void prepareProperties() throws IOException {
Files.createDirectories(globalDirectoryPath.resolve("sub"));
Path testResourcesPath = Paths.get("src","test", "resources");
Path source = testResourcesPath.resolve(GlobalDirectoryBasicTestCase.class.getPackage().getName().replace(".", File.separator))
.resolve("sub")
.resolve("sub-global-directory.properties");
Path target = globalDirectoryPath
.resolve("sub")
.resolve("sub-global-directory.properties");
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
source = testResourcesPath.resolve(GlobalDirectoryBasicTestCase.class.getPackage().getName().replace(".", File.separator))
.resolve("global-directory.properties");
target = globalDirectoryPath
.resolve("global-directory.properties");
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
}
}
| 7,846 | 42.594444 | 196 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ee/globaldirectory/GlobalDirectoryTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ee.globaldirectory;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
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.OUTCOME;
import static org.jboss.as.test.shared.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.PropertyPermission;
import jakarta.ws.rs.core.Response;
import org.apache.commons.io.FileUtils;
import org.hamcrest.MatcherAssert;
import org.jboss.arquillian.container.spi.client.container.DeploymentException;
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.as.test.manualmode.ee.globaldirectory.deployments.GlobalDirectoryDeployment;
import org.jboss.as.test.manualmode.ee.globaldirectory.deployments.GlobalDirectoryDeployment2;
import org.jboss.as.test.manualmode.ee.globaldirectory.deployments.GlobalDirectoryDeployment3;
import org.jboss.as.test.manualmode.ee.globaldirectory.libraries.GlobalDirectoryLibrary;
import org.jboss.as.test.manualmode.ee.globaldirectory.libraries.GlobalDirectoryLibraryImpl;
import org.jboss.as.test.manualmode.ee.globaldirectory.libraries.GlobalDirectoryLibraryImpl2;
import org.jboss.as.test.manualmode.ee.globaldirectory.libraries.GlobalDirectoryLibraryImpl3;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests for global directory
*
* @author Vratislav Marek ([email protected])
* @author Tomas Terem ([email protected])
**/
@RunWith(Arquillian.class)
@RunAsClient
public class GlobalDirectoryTestCase extends GlobalDirectoryBase {
@Before
public void setup() throws Exception {
initCLI(true);
}
@After
public void clean() throws IOException, InterruptedException {
removeGlobalDirectory(GLOBAL_DIRECTORY_NAME);
verifyDoesNotExist(GLOBAL_DIRECTORY_NAME);
reloadServer();
FileUtils.deleteDirectory(GLOBAL_DIRECTORY_PATH.toAbsolutePath().toFile());
FileUtils.deleteDirectory(SECOND_GLOBAL_DIRECTORY_PATH.toAbsolutePath().toFile());
FileUtils.deleteDirectory(TEMP_DIR);
}
@Deployment(name = DEPLOYMENT, managed = false, testable = false)
@TargetsContainer(CONTAINER)
public static WebArchive createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war");
war.addClass(GlobalDirectoryDeployment.class);
war.addAsWebInfResource(new StringAsset("<?xml version=\"1.0\" encoding=\"UTF-8\"?><web-app><servlet-mapping>\n" +
" <servlet-name>jakarta.ws.rs.core.Application</servlet-name>\n" +
" <url-pattern>/*</url-pattern>\n" +
" </servlet-mapping></web-app>"), "web.xml");
return war;
}
@Deployment(name = DEPLOYMENT2, managed = false, testable = false)
@TargetsContainer(CONTAINER)
public static WebArchive createDeployment2() {
WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT2 + ".war");
war.addClass(GlobalDirectoryDeployment2.class);
war.addAsWebInfResource(new StringAsset("<?xml version=\"1.0\" encoding=\"UTF-8\"?><web-app><servlet-mapping>\n" +
" <servlet-name>jakarta.ws.rs.core.Application</servlet-name>\n" +
" <url-pattern>/*</url-pattern>\n" +
" </servlet-mapping></web-app>"), "web.xml");
war.addAsManifestResource(createPermissionsXmlAsset(new RuntimePermission("getClassLoader")), "permissions.xml");
return war;
}
@Deployment(name = DEPLOYMENT3, managed = false, testable = false)
@TargetsContainer(CONTAINER)
public static WebArchive createDeployment3() {
WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT3 + ".war");
war.addClass(GlobalDirectoryDeployment3.class);
war.addAsWebInfResource(new StringAsset("<?xml version=\"1.0\" encoding=\"UTF-8\"?><web-app><servlet-mapping>\n" +
" <servlet-name>jakarta.ws.rs.core.Application</servlet-name>\n" +
" <url-pattern>/*</url-pattern>\n" +
" </servlet-mapping></web-app>"), "web.xml");
war.addAsManifestResource(createPermissionsXmlAsset(new RuntimePermission("getProtectionDomain"), new PropertyPermission("user.dir", "read")), "permissions.xml");
return war;
}
/**
* Test checking if global directory exist
*/
@Test
public void testSmoke() throws IOException, InterruptedException {
registerGlobalDirectory(GLOBAL_DIRECTORY_NAME, GLOBAL_DIRECTORY_PATH.toString(), true);
verifyProperlyRegistered(GLOBAL_DIRECTORY_NAME, GLOBAL_DIRECTORY_PATH.toString());
}
/**
* Test checking rule for only one global directory
*/
@Test
public void testSmokeOnlyOne() throws IOException, InterruptedException {
registerGlobalDirectory(GLOBAL_DIRECTORY_NAME, GLOBAL_DIRECTORY_PATH.toString(), true);
verifyProperlyRegistered(GLOBAL_DIRECTORY_NAME, GLOBAL_DIRECTORY_PATH.toString());
reloadServer();
final ModelNode response = registerGlobalDirectory(SECOND_GLOBAL_DIRECTORY_NAME, SECOND_GLOBAL_DIRECTORY_PATH.toString(), false);
ModelNode outcome = response.get(OUTCOME);
assertThat("Registration of global directory failure!", outcome.asString(), is(FAILED));
final ModelNode failureDescription = response.get(FAILURE_DESCRIPTION);
assertThat("Error message doesn't contains information about duplicate global directory",
failureDescription.asString(), containsString(DUPLICATE_ERROR_GLOBAL_DIRECTORY_CODE));
verifyDoesNotExist(SECOND_GLOBAL_DIRECTORY_NAME);
}
/**
* Test for basic functionality of global directory
* 1. Create libraries and copy them to global directory
* 2. Define global-directory by CLI command
* 3. Check if global-directory is registered properly and verify its attributes
* 4. Reload server
* 5. Deploy test application deployment
* 6. Call some method from global-directory in deployment and verify method output
*/
@Test
public void testBasic() throws IOException, InterruptedException {
createLibrary(GlobalDirectoryLibrary.class.getSimpleName(), GlobalDirectoryLibrary.class);
createLibrary(GlobalDirectoryLibraryImpl.class.getSimpleName(), GlobalDirectoryLibraryImpl.class);
copyLibraryToGlobalDirectory(GlobalDirectoryLibrary.class.getSimpleName());
copyLibraryToGlobalDirectory(GlobalDirectoryLibraryImpl.class.getSimpleName());
registerGlobalDirectory(GLOBAL_DIRECTORY_NAME);
verifyProperlyRegistered(GLOBAL_DIRECTORY_NAME, GLOBAL_DIRECTORY_PATH.toString());
reloadServer();
try {
deployer.deploy(DEPLOYMENT);
Response response = client.target("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/" + DEPLOYMENT + "/global-directory/get").request().get();
String result = response.readEntity(String.class);
Assert.assertEquals("HELLO WORLD", result);
} finally {
deployer.undeploy(DEPLOYMENT);
}
}
/**
* Test reaction to corrupted jar
* 1. Create corrupted jar and copy it to global directory
* 2. Define global-directory by CLI command
* 3. Check if global-directory is registered properly and verify its attributes
* 4. Reload server
* 5. Deploy test application deployment and verify that Exception is thrown
* 6. Check that server log contain information about corrupted jar
*/
@Test
public void testCorruptedJar() throws IOException, InterruptedException {
createCorruptedLibrary("corrupted", Arrays.asList("hello world"));
copyLibraryToGlobalDirectory("corrupted");
registerGlobalDirectory(GLOBAL_DIRECTORY_NAME);
verifyProperlyRegistered(GLOBAL_DIRECTORY_NAME, GLOBAL_DIRECTORY_PATH.toString());
reloadServer();
try {
deployer.deploy(DEPLOYMENT);
fail("Exception should have been thrown.");
} catch (Exception e) {
Assert.assertEquals(DeploymentException.class, e.getClass());
}
logContains("WFLYSRV0276: There is an error in opening zip file " + new File(GLOBAL_DIRECTORY_FILE, "corrupted.jar").getAbsolutePath());
}
/**
* Test loading order of libraries in global directory
* 1. Create multiple jars and copy them to global directory into various folders
* 2. Define global-directory by CLI command
* 3. Check if global-directory is registered properly and verify its attributes
* 4. Reload server
* 5. Set logging level to DEBUG
* 6. Deploy test application deployment
* 7. Call some method from global-directory in deployment
* 8. Verify that class from jar which is first in alphabetical order was used
* 9. Check if server log file contains all jars in alphabetical order
*/
@Test
public void testLoadOrder() throws Exception {
createLibrary(GlobalDirectoryLibrary.class.getSimpleName(), GlobalDirectoryLibrary.class);
createLibrary(GlobalDirectoryLibraryImpl.class.getSimpleName(), GlobalDirectoryLibraryImpl.class);
createLibrary(GlobalDirectoryLibraryImpl2.class.getSimpleName(), GlobalDirectoryLibraryImpl2.class);
createLibrary(GlobalDirectoryLibraryImpl3.class.getSimpleName(), GlobalDirectoryLibraryImpl3.class);
GLOBAL_DIRECTORY_PATH.toFile().mkdirs();
File subDirectoryA = new File(GLOBAL_DIRECTORY_PATH.toFile(), "A");
File subDirectoryAB = new File(GLOBAL_DIRECTORY_PATH.toFile(), "AB");
File subDirectoryC = new File(GLOBAL_DIRECTORY_PATH.toFile(), "C");
File subDirectoryC_D = new File(subDirectoryC, "D");
File subDirectoryC_E = new File(subDirectoryC, "E");
File subDirectoryC_D_F = new File(subDirectoryC_D, "F");
copyLibraryToGlobalDirectory(GlobalDirectoryLibrary.class.getSimpleName());
copyLibraryToDirectory(GlobalDirectoryLibrary.class.getSimpleName(), subDirectoryA.toString());
copyLibraryToDirectory(GlobalDirectoryLibraryImpl.class.getSimpleName(), subDirectoryA.toString());
copyLibraryToDirectory(GlobalDirectoryLibraryImpl.class.getSimpleName(), subDirectoryAB.toString());
copyLibraryToDirectory(GlobalDirectoryLibraryImpl3.class.getSimpleName(), subDirectoryC_D_F.toString());
copyLibraryToDirectory(GlobalDirectoryLibraryImpl2.class.getSimpleName(), subDirectoryC_E.toString());
copyLibraryToDirectory(GlobalDirectoryLibraryImpl3.class.getSimpleName(), subDirectoryC_E.toString());
registerGlobalDirectory(GLOBAL_DIRECTORY_NAME);
verifyProperlyRegistered(GLOBAL_DIRECTORY_NAME, GLOBAL_DIRECTORY_PATH.toString());
reloadServer();
initCLI(true);
cli.sendLine("/subsystem=logging/logger=org.jboss.as.server.moduleservice:add(level=DEBUG)");
try {
deployer.deploy(DEPLOYMENT3);
Response response = client.target("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/" + DEPLOYMENT3 + "/global-directory/get").request().get();
String result = response.readEntity(String.class);
MatcherAssert.assertThat("C/D/F/GlobalDirectoryLibraryImpl3.jar should be used instead of C/E/GlobalDirectoryLibraryImpl3.jar.",
result, not(containsString(new File(subDirectoryC_E, "GlobalDirectoryLibraryImpl3.jar").toString())));
MatcherAssert.assertThat(result, containsString(new File(subDirectoryC_D_F, "GlobalDirectoryLibraryImpl3.jar").toString()));
checkJarLoadingOrder(new String[]{
"Added " + GLOBAL_DIRECTORY_FILE.getAbsolutePath() + " directory as resource root",
"Added " + new File(GLOBAL_DIRECTORY_FILE, "GlobalDirectoryLibrary.jar").getAbsolutePath() + " jar file",
"Added " + new File(subDirectoryA, "GlobalDirectoryLibrary.jar").getAbsolutePath() + " jar file",
"Added " + new File(subDirectoryA, "GlobalDirectoryLibraryImpl.jar").getAbsolutePath() + " jar file",
"Added " + new File(subDirectoryAB, "GlobalDirectoryLibraryImpl.jar").getAbsolutePath() + " jar file",
"Added " + new File(subDirectoryC_D_F, "GlobalDirectoryLibraryImpl3.jar").getAbsolutePath() + " jar file",
"Added " + new File(subDirectoryC_E, "GlobalDirectoryLibraryImpl2.jar").getAbsolutePath() + " jar file",
"Added " + new File(subDirectoryC_E, "GlobalDirectoryLibraryImpl3.jar").getAbsolutePath() + " jar file"
});
} finally {
cli.sendLine("/subsystem=logging/logger=org.jboss.as.server.moduleservice:remove()");
deployer.undeploy(DEPLOYMENT3);
}
}
/**
* Test for loading property files
* 1. Create text file and copy it to global directory
* 2. Define global-directory by CLI command
* 3. Check if global-directory are registered properly and verify its attributes
* 4. Reload server
* 5. Deploy test application deployment
* 6. Call some method (such that its result depend on content of the property file) from global-directory in deployment
* 7. Verify that result contains an expected output
*/
@Test
public void testPropertyFile() throws IOException, InterruptedException {
createLibrary(GlobalDirectoryLibrary.class.getSimpleName(), GlobalDirectoryLibrary.class);
createLibrary(GlobalDirectoryLibraryImpl2.class.getSimpleName(), GlobalDirectoryLibraryImpl2.class);
String propertyFileName = "properties";
String propertyFileString = "PROPERTY FILE";
createTextFile(propertyFileName, Arrays.asList(propertyFileString));
copyLibraryToGlobalDirectory(GlobalDirectoryLibrary.class.getSimpleName());
copyLibraryToGlobalDirectory(GlobalDirectoryLibraryImpl2.class.getSimpleName());
copyTextFileToGlobalDirectory(propertyFileName);
registerGlobalDirectory(GLOBAL_DIRECTORY_NAME);
verifyProperlyRegistered(GLOBAL_DIRECTORY_NAME, GLOBAL_DIRECTORY_PATH.toString());
reloadServer();
try {
deployer.deploy(DEPLOYMENT2);
Response response = client.target("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/" + DEPLOYMENT2 + "/global-directory/get").request().get();
String result = response.readEntity(String.class);
Assert.assertEquals(propertyFileString, result);
} finally {
deployer.undeploy(DEPLOYMENT2);
}
}
}
| 16,585 | 50.033846 | 170 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ee/globaldirectory/EchoUtility.java
|
/*
* Copyright 2019 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.manualmode.ee.globaldirectory;
public class EchoUtility {
public String echo(String msg) {
return "echo-library-1 " + msg;
}
}
| 766 | 30.958333 | 75 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ee/globaldirectory/GlobalDirectoryBase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ee.globaldirectory;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
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.OUTCOME;
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.controller.descriptions.ModelDescriptionConstants.REMOVE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.container.test.api.Deployer;
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.base.AbstractCliTestBase;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.Before;
/**
* Base class for global directory tests. This class contains mostly util methods that are used in tests.
*
* @author Vratislav Marek ([email protected])
* @author Tomas Terem ([email protected])
**/
public class GlobalDirectoryBase extends AbstractCliTestBase {
protected static final String SUBSYSTEM_EE = "ee";
protected static final Path GLOBAL_DIRECTORY_PATH = Paths.get(TestSuiteEnvironment.getTmpDir(), "global-directory");
protected static final File GLOBAL_DIRECTORY_FILE = GLOBAL_DIRECTORY_PATH.toFile();
protected static final String GLOBAL_DIRECTORY_NAME = "global-directory";
protected static final Path SECOND_GLOBAL_DIRECTORY_PATH = Paths.get(TestSuiteEnvironment.getTmpDir(),"global-directory-2");
protected static final String SECOND_GLOBAL_DIRECTORY_NAME = "global-directory-2";
protected static final String DUPLICATE_ERROR_GLOBAL_DIRECTORY_CODE = "WFLYEE0123";
protected static final File TEMP_DIR = new File(TestSuiteEnvironment.getTmpDir(), "jars");
protected static final String CONTAINER = "default-jbossas";
protected static final String DEPLOYMENT = "deployment";
protected static final String DEPLOYMENT2 = "deployment2";
protected static final String DEPLOYMENT3 = "deployment3";
protected static final Logger LOGGER = Logger.getLogger(GlobalDirectoryBase.class);
protected ClientHolder clientHolder;
protected Client client = ClientBuilder.newClient();
@ArquillianResource
protected static ContainerController containerController;
@ArquillianResource
protected static Deployer deployer;
protected void createGlobalDirectoryFolder() {
if (Files.notExists(GLOBAL_DIRECTORY_PATH)) {
GLOBAL_DIRECTORY_PATH.toFile().mkdirs();
}
if (Files.notExists(SECOND_GLOBAL_DIRECTORY_PATH)) {
SECOND_GLOBAL_DIRECTORY_PATH.toFile().mkdirs();
}
}
protected static void createLibrary(String name, Class library) {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, name + ".jar").addClasses(library);
if (Files.notExists(Paths.get(TEMP_DIR.toString()))) {
TEMP_DIR.mkdirs();
}
jar.as(ZipExporter.class).exportTo(new File(TEMP_DIR, name + ".jar"), true);
}
protected static void createTextFile(String name, List<String> content) throws IOException {
if (Files.notExists(Paths.get(TEMP_DIR.toString()))) {
TEMP_DIR.mkdirs();
}
Path file = new File(TEMP_DIR, name + ".txt").toPath();
Files.write(file, content, StandardCharsets.UTF_8);
}
protected static void createCorruptedLibrary(String name, List<String> content) throws IOException {
if (Files.notExists(Paths.get(TEMP_DIR.toString()))) {
TEMP_DIR.mkdirs();
}
Path file = new File(TEMP_DIR, name + ".jar").toPath();
Files.write(file, content, StandardCharsets.UTF_8);
}
protected void copyTextFileToGlobalDirectory(String name) throws IOException {
if (Files.notExists(GLOBAL_DIRECTORY_PATH)) {
GLOBAL_DIRECTORY_PATH.toFile().mkdirs();
}
Path filePath = new File(TEMP_DIR, name + ".txt").toPath();
Files.copy(filePath, new File(GLOBAL_DIRECTORY_FILE, name + ".txt").toPath(), StandardCopyOption.REPLACE_EXISTING);
}
protected void copyLibraryToGlobalDirectory(String name) throws IOException {
if (Files.notExists(GLOBAL_DIRECTORY_PATH)) {
GLOBAL_DIRECTORY_PATH.toFile().mkdirs();
}
Path jarPath = new File(TEMP_DIR, name + ".jar").toPath();
Files.copy(jarPath, new File(GLOBAL_DIRECTORY_FILE, name + ".jar").toPath(), StandardCopyOption.REPLACE_EXISTING);
}
protected void copyLibraryToDirectory(String name, String path) throws IOException {
if (Files.notExists(Paths.get(path))) {
Paths.get(path).toFile().mkdirs();
}
Path jarPath = new File(TEMP_DIR, name + ".jar").toPath();
Files.copy(jarPath, new File(path, name + ".jar").toPath(), StandardCopyOption.REPLACE_EXISTING);
}
protected void logContains(String expectedMessage) throws IOException {
String serverLog = String.join("\n", Files.readAllLines(getServerLogFile().toPath()));
assertTrue("Log doesn't contain '" + expectedMessage + "'", serverLog.contains(expectedMessage));
}
@Before
public void before() throws IOException {
if (!containerController.isStarted(CONTAINER)) {
containerController.start(CONTAINER);
}
createGlobalDirectoryFolder();
connect();
}
@After
public void after() {
if (containerController.isStarted(CONTAINER)) {
containerController.stop(CONTAINER);
}
client.close();
disconnect();
}
protected void connect() {
if (clientHolder == null) {
clientHolder = ClientHolder.init();
}
}
protected void disconnect() {
clientHolder = null;
}
protected void reloadServer() {
ServerReload.executeReloadAndWaitForCompletion(clientHolder.mgmtClient);
}
/**
* @param expectedJars Expected Jars, the order matter, it will compare order of jars in the log
*/
protected void checkJarLoadingOrder(String[] expectedJars) throws IOException {
String[] logs = Files.readAllLines(getServerLogFile().toPath()).toArray(new String[]{});
int i = 0;
while (!logs[i].contains(expectedJars[0])) {
i++;
}
for (int j = 0; j < expectedJars.length; j++) {
assertThat("Jars were not loaded in correct order!", logs[i], containsString(expectedJars[j]));
i++;
}
}
/**
* Register global directory
* Verify the response for success
*
* @param name Name of new global directory
*/
protected ModelNode registerGlobalDirectory(String name) throws IOException {
return registerGlobalDirectory(name, GLOBAL_DIRECTORY_PATH.toString(), true);
}
/**
* Register global directory
*
* @param name Name of new global directory
* @param path
* @param expectSuccess If is true verify the response for success, if false only return operation result
*/
protected ModelNode registerGlobalDirectory(String name, String path, boolean expectSuccess) throws IOException {
// /subsystem=ee/global-directory=<<name>>:add(path=<<path>>)
final ModelNode address = new ModelNode();
address.add(SUBSYSTEM, SUBSYSTEM_EE)
.add(GLOBAL_DIRECTORY_NAME, name)
.protect();
final ModelNode operation = new ModelNode();
operation.get(OP).set(ADD);
operation.get(INCLUDE_RUNTIME).set(true);
operation.get(OP_ADDR).set(address);
operation.get(PATH).set(path);
ModelNode response = clientHolder.execute(operation);
ModelNode outcome = response.get(OUTCOME);
if (expectSuccess) {
assertThat("Registration of global directory " + name + " failure!", outcome.asString(), is(SUCCESS));
}
return response;
}
/**
* Remove global directory
*
* @param name Name of global directory for removing
*/
protected ModelNode removeGlobalDirectory(String name) throws IOException {
// /subsystem=ee/global-directory=<<name>>:remove
final ModelNode address = new ModelNode();
address.add(SUBSYSTEM, SUBSYSTEM_EE)
.add(GLOBAL_DIRECTORY_NAME, name)
.protect();
final ModelNode operation = new ModelNode();
operation.get(OP).set(REMOVE);
operation.get(INCLUDE_RUNTIME).set(true);
operation.get(OP_ADDR).set(address);
ModelNode response = clientHolder.execute(operation);
ModelNode outcome = response.get(OUTCOME);
assertThat("Remove of global directory " + name + " failure!", outcome.asString(), is(SUCCESS));
return response;
}
/**
* Verify if global directory is registered and contains correct path
*
* @param name Name of global directory
* @param path Expected path for current global directory
*/
protected ModelNode verifyProperlyRegistered(String name, String path) throws IOException {
ModelNode response = readGlobalDirectory(name);
ModelNode outcome = response.get(OUTCOME);
assertThat("Read resource of global directory " + name + " failure!", outcome.asString(), is(SUCCESS));
final ModelNode result = response.get(RESULT);
assertThat("Global directory " + name + " have set wrong path!", result.get(PATH).asString(), is(path));
return response;
}
/**
* Verify that global directory doesn't exist
*
* @param name Name of global directory
*/
protected ModelNode verifyDoesNotExist(String name) throws IOException {
ModelNode response = readGlobalDirectory(name);
ModelNode outcome = response.get(OUTCOME);
assertThat("Global directory " + name + " still exist!", outcome.asString(), not(SUCCESS));
return response;
}
/**
* Read resource command for global directory
*
* @param name Name of global directory
*/
private ModelNode readGlobalDirectory(String name) throws IOException {
// /subsystem=ee/global-directory=<<name>>:read-resource
final ModelNode address = new ModelNode();
address.add(SUBSYSTEM, SUBSYSTEM_EE)
.add(GLOBAL_DIRECTORY_NAME, name)
.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);
return clientHolder.execute(operation);
}
private static class ClientHolder {
private final ManagementClient mgmtClient;
private ClientHolder(ManagementClient mgmtClient) {
this.mgmtClient = mgmtClient;
}
protected static ClientHolder init() {
final ModelControllerClient clientHolder = TestSuiteEnvironment.getModelControllerClient();
ManagementClient mgmtClient = new ManagementClient(clientHolder, TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddress()),
TestSuiteEnvironment.getServerPort(), "http-remoting");
return new ClientHolder(mgmtClient);
}
/**
* Execute operation in wildfly
*
* @param operation Cli command represent in ModelNode interpretation
*/
protected ModelNode execute(final ModelNode operation) throws
IOException {
return mgmtClient.getControllerClient().execute(operation);
}
}
protected File getServerLogFile() {
String JBOSS_HOME = System.getProperty("jboss.home", "jboss-as");
String SERVER_MODE = Boolean.parseBoolean(System.getProperty("domain", "false")) ? "domain" : "standalone";
return Paths.get(JBOSS_HOME, SERVER_MODE, "log", "server.log").toFile();
}
}
| 14,582 | 40.428977 | 165 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ee/globaldirectory/EchoServlet.java
|
/*
* Copyright 2019 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.manualmode.ee.globaldirectory;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Properties;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet(name = "EchoServlet", urlPatterns = "/echoServlet")
public class EchoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String propertiesName = request.getParameter("prop");
EchoUtility echoUtil = new EchoUtility();
out.print(echoUtil.echo("Message from the servlet"));
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
for (String s : Arrays.asList("global-directory.properties", "sub/sub-global-directory.properties")) {
try (InputStream is = classLoader.getResourceAsStream(s)) {
if (is == null) {
out.println(propertiesName + " not found.");
} else {
Properties prop = new Properties();
prop.load(is);
prop.forEach((key, value) -> out.print(" Key=" + key + ", Value=" + value));
}
} catch (Exception e) {
throw new ServletException(e);
}
}
out.flush();
out.close();
}
}
| 2,396 | 34.776119 | 122 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ee/globaldirectory/libraries/GlobalDirectoryLibrary.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ee.globaldirectory.libraries;
/**
* @author Tomas Terem ([email protected])
**/
public interface GlobalDirectoryLibrary {
String get();
}
| 1,206 | 36.71875 | 70 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ee/globaldirectory/libraries/GlobalDirectoryLibraryImpl3.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ee.globaldirectory.libraries;
import java.io.File;
/**
* @author Tomas Terem ([email protected])
**/
public class GlobalDirectoryLibraryImpl3 implements GlobalDirectoryLibrary {
public String get() {
return new File(GlobalDirectoryLibraryImpl3.class.getProtectionDomain().getCodeSource().getLocation().getFile()).getAbsolutePath();
}
}
| 1,417 | 39.514286 | 139 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ee/globaldirectory/libraries/GlobalDirectoryLibraryImpl2.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ee.globaldirectory.libraries;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* @author Tomas Terem ([email protected])
**/
public class GlobalDirectoryLibraryImpl2 implements GlobalDirectoryLibrary {
public String get() {
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
String res = null;
try (InputStream is = classloader.getResourceAsStream("properties.txt")) {
try(BufferedReader in = new BufferedReader(new InputStreamReader(is))) {
res = in.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
}
| 1,802 | 37.361702 | 84 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ee/globaldirectory/libraries/GlobalDirectoryLibraryImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ee.globaldirectory.libraries;
/**
* @author Tomas Terem ([email protected])
**/
public class GlobalDirectoryLibraryImpl implements GlobalDirectoryLibrary {
private String s1 = "HELLO WORLD";
public String get() {
return s1;
}
}
| 1,308 | 36.4 | 75 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ee/globaldirectory/deployments/GlobalDirectoryDeployment2.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ee.globaldirectory.deployments;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import org.jboss.as.test.manualmode.ee.globaldirectory.libraries.GlobalDirectoryLibrary;
import org.jboss.as.test.manualmode.ee.globaldirectory.libraries.GlobalDirectoryLibraryImpl2;
/**
* @author Tomas Terem ([email protected])
**/
@Path("global-directory")
public class GlobalDirectoryDeployment2 {
@Path("/get")
@GET
@Produces("text/plain")
public String get() {
GlobalDirectoryLibrary globalDirectoryLibrary = new GlobalDirectoryLibraryImpl2();
return globalDirectoryLibrary.get();
}
}
| 1,708 | 36.977778 | 93 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ee/globaldirectory/deployments/GlobalDirectoryDeployment.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ee.globaldirectory.deployments;
import org.jboss.as.test.manualmode.ee.globaldirectory.libraries.GlobalDirectoryLibrary;
import org.jboss.as.test.manualmode.ee.globaldirectory.libraries.GlobalDirectoryLibraryImpl;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
/**
* @author Tomas Terem ([email protected])
**/
@Path("global-directory")
public class GlobalDirectoryDeployment {
@Path("/get")
@GET
@Produces("text/plain")
public String get() {
GlobalDirectoryLibrary globalDirectoryLibrary = new GlobalDirectoryLibraryImpl();
return globalDirectoryLibrary.get();
}
}
| 1,696 | 36.711111 | 92 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ee/globaldirectory/deployments/GlobalDirectoryDeployment3.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.manualmode.ee.globaldirectory.deployments;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import org.jboss.as.test.manualmode.ee.globaldirectory.libraries.GlobalDirectoryLibrary;
import org.jboss.as.test.manualmode.ee.globaldirectory.libraries.GlobalDirectoryLibraryImpl3;
/**
* @author Tomas Terem ([email protected])
**/
@Path("global-directory")
public class GlobalDirectoryDeployment3 {
@Path("/get")
@GET
@Produces("text/plain")
public String get() {
GlobalDirectoryLibrary globalDirectoryLibrary = new GlobalDirectoryLibraryImpl3();
return globalDirectoryLibrary.get();
}
}
| 1,708 | 36.977778 | 93 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ws/WSAttributesChangesTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, 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.manualmode.ws;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADDRESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_REQUIRES_RELOAD;
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_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RECURSIVE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESPONSE_HEADERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION;
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.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
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.junit.Arquillian;
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.controller.client.OperationBuilder;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Some tests on changes to the model that are applied immediately to the runtime
* when there's no WS deployment on the server.
*
* @author <a href="mailto:[email protected]">Alessio Soldano</a>
* @author <a href="mailto:[email protected]">Jim Ma</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
public class WSAttributesChangesTestCase {
private static final String DEFAULT_JBOSSAS = "default-jbossas";
private static final String DEP_1 = "jaxws-manual-pojo-1";
private static final String DEP_2 = "jaxws-manual-pojo-2";
@ArquillianResource
ContainerController containerController;
@ArquillianResource
Deployer deployer;
@Deployment(name = DEP_1, testable = false, managed = false)
public static WebArchive deployment1() {
WebArchive pojoWar = ShrinkWrap.create(WebArchive.class, DEP_1 + ".war").addClasses(
EndpointIface.class, PojoEndpoint.class);
return pojoWar;
}
@Deployment(name = DEP_2, testable = false, managed = false)
public static WebArchive deployment2() {
WebArchive pojoWar = ShrinkWrap.create(WebArchive.class, DEP_2 + ".war").addClasses(
EndpointIface.class, PojoEndpoint.class);
return pojoWar;
}
@Before
public void startContainer() throws Exception {
containerController.start(DEFAULT_JBOSSAS);
}
@Test
public void testWsdlHostChanges() throws Exception {
performWsdlHostAttributeTest(false);
performWsdlHostAttributeTest(true);
}
private void performWsdlHostAttributeTest(boolean checkUpdateWithDeployedEndpoint) throws Exception {
Assert.assertTrue(containerController.isStarted(DEFAULT_JBOSSAS));
ManagementClient managementClient = new ManagementClient(TestSuiteEnvironment.getModelControllerClient(),
TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http");
ModelControllerClient client = managementClient.getControllerClient();
String initialWsdlHost = null;
try {
initialWsdlHost = getAttribute("wsdl-host", client);
final String hostnameA = "foo-host-a";
ModelNode op = createOpNode("subsystem=webservices/", WRITE_ATTRIBUTE_OPERATION);
op.get(NAME).set("wsdl-host");
op.get(VALUE).set(hostnameA);
applyUpdate(client, op, false); //update successful, no need to reload
//now we deploy an endpoint...
deployer.deploy(DEP_1);
//verify the updated wsdl host is used...
URL wsdlURL = new URL(managementClient.getWebUri().toURL(), '/' + DEP_1 + "/POJOService?wsdl");
checkWsdl(wsdlURL, hostnameA);
if (checkUpdateWithDeployedEndpoint) {
final String hostnameB = "foo-host-b";
ModelNode opB = createOpNode("subsystem=webservices/", WRITE_ATTRIBUTE_OPERATION);
opB.get(NAME).set("wsdl-host");
opB.get(VALUE).set(hostnameB);
applyUpdate(client, opB, true); //update again, but we'll need to reload, as there's an active deployment
//check the wsdl host is still the one we updated to before
checkWsdl(wsdlURL, hostnameA);
//and check that still applies even if we undeploy and redeploy the endpoint
deployer.undeploy(DEP_1);
deployer.deploy(DEP_1);
checkWsdl(wsdlURL, hostnameA);
}
} finally {
try {
deployer.undeploy(DEP_1);
} catch (Throwable t) {
//ignore
}
try {
if (initialWsdlHost != null) {
ModelNode op = createOpNode("subsystem=webservices/", WRITE_ATTRIBUTE_OPERATION);
op.get(NAME).set("wsdl-host");
op.get(VALUE).set(initialWsdlHost);
applyUpdate(client, op, checkUpdateWithDeployedEndpoint);
}
} finally {
managementClient.close();
}
}
}
@Test
public void testWsdlPortChanges() throws Exception {
performWsdlPortAttributeTest(false);
performWsdlPortAttributeTest(true);
}
private void performWsdlPortAttributeTest(boolean checkUpdateWithDeployedEndpoint) throws Exception {
Assert.assertTrue(containerController.isStarted(DEFAULT_JBOSSAS));
ManagementClient managementClient = new ManagementClient(TestSuiteEnvironment.getModelControllerClient(),
TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http");
ModelControllerClient client = managementClient.getControllerClient();
try {
final String portA = "55667";
ModelNode op = createOpNode("subsystem=webservices/", WRITE_ATTRIBUTE_OPERATION);
op.get(NAME).set("wsdl-port");
op.get(VALUE).set(portA);
applyUpdate(client, op, false); //update successful, no need to reload
//now we deploy an endpoint...
deployer.deploy(DEP_2);
//verify the updated wsdl port is used...
URL wsdlURL = new URL(managementClient.getWebUri().toURL(), '/' + DEP_2 + "/POJOService?wsdl");
checkWsdl(wsdlURL, portA);
if (checkUpdateWithDeployedEndpoint) {
final String portB = "55668";
ModelNode opB = createOpNode("subsystem=webservices/", WRITE_ATTRIBUTE_OPERATION);
opB.get(NAME).set("wsdl-port");
opB.get(VALUE).set(portB);
applyUpdate(client, opB, true); //update again, but we'll need to reload, as there's an active deployment
//check the wsdl port is still the one we updated to before
checkWsdl(wsdlURL, portA);
//and check that still applies even if we undeploy and redeploy the endpoint
deployer.undeploy(DEP_2);
deployer.deploy(DEP_2);
checkWsdl(wsdlURL, portA);
}
} finally {
try {
deployer.undeploy(DEP_2);
} catch (Throwable t) {
//ignore
}
try {
ModelNode op = createOpNode("subsystem=webservices/", UNDEFINE_ATTRIBUTE_OPERATION);
op.get(NAME).set("wsdl-port");
applyUpdate(client, op, checkUpdateWithDeployedEndpoint);
} finally {
managementClient.close();
}
}
}
@Test
public void testWsdlUriSchemeChanges() throws Exception {
performWsdlUriSchemeAttributeTest(false);
performWsdlUriSchemeAttributeTest(true);
}
private void performWsdlUriSchemeAttributeTest(boolean checkUpdateWithDeployedEndpoint) throws Exception {
Assert.assertTrue(containerController.isStarted(DEFAULT_JBOSSAS));
ManagementClient managementClient = new ManagementClient(TestSuiteEnvironment.getModelControllerClient(),
TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http");
ModelControllerClient client = managementClient.getControllerClient();
String initialWsdlUriScheme = null;
try {
//save initial wsdl-uri-schema value to restore later
initialWsdlUriScheme = getAttribute("wsdl-uri-scheme", client, false);
//set wsdl-uri-scheme value to https
ModelNode op = createOpNode("subsystem=webservices/", WRITE_ATTRIBUTE_OPERATION);
op.get(NAME).set("wsdl-uri-scheme");
op.get(VALUE).set("https");
applyUpdate(client, op, false);
deployer.deploy(DEP_1);
//check if it works for the deployed endpoint url
checkWSDLUriScheme(client, DEP_1 + ".war", "https");
deployer.undeploy(DEP_1);
//set wsdl-uri-scheme value to http
ModelNode op2 = createOpNode("subsystem=webservices/", WRITE_ATTRIBUTE_OPERATION);
op2.get(NAME).set("wsdl-uri-scheme");
op2.get(VALUE).set("http");
applyUpdate(client, op2, false);
deployer.deploy(DEP_1);
//check if the uri scheme of soap address is modified to http
checkWSDLUriScheme(client, DEP_1 + ".war", "http");
if (checkUpdateWithDeployedEndpoint) {
//set wsdl-uri-schema value to http
ModelNode opB = createOpNode("subsystem=webservices/", WRITE_ATTRIBUTE_OPERATION);
opB.get(NAME).set("wsdl-uri-scheme");
opB.get(VALUE).set("https");
applyUpdate(client, opB, true);
//check this doesn't apply to endpointed which are deployed before this change
checkWSDLUriScheme(client, DEP_1 + ".war", "http");
deployer.undeploy(DEP_1);
deployer.deploy(DEP_1);
//check this will take effect to redeployed endpoint
checkWSDLUriScheme(client, DEP_1 + ".war", "http");
}
} finally {
try {
deployer.undeploy(DEP_1);
} catch (Throwable t) {
//ignore
}
try {
//restore the value of wsdl-uri-scheme attribute
ModelNode op = null;
if ("undefined".equals(initialWsdlUriScheme)) {
op = createOpNode("subsystem=webservices/", UNDEFINE_ATTRIBUTE_OPERATION);
op.get(NAME).set("wsdl-uri-scheme");
} else {
op = createOpNode("subsystem=webservices/", WRITE_ATTRIBUTE_OPERATION);
op.get(NAME).set("wsdl-uri-scheme");
op.get(VALUE).set(initialWsdlUriScheme);
}
applyUpdate(client, op, checkUpdateWithDeployedEndpoint);
} finally {
managementClient.close();
}
}
}
@Test
public void testWsdlPathRewriteRuleChanges() throws Exception {
performWsdlPathRewriteRuleAttributeTest(false);
performWsdlPathRewriteRuleAttributeTest(true);
}
private void performWsdlPathRewriteRuleAttributeTest(boolean checkUpdateWithDeployedEndpoint) throws Exception {
Assert.assertTrue(containerController.isStarted(DEFAULT_JBOSSAS));
ManagementClient managementClient = new ManagementClient(TestSuiteEnvironment.getModelControllerClient(),
TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http");
ModelControllerClient client = managementClient.getControllerClient();
try {
final String expectedContext = "xx/jaxws-manual-pojo-1";
final String sedCmdA = "s/jaxws-manual-pojo-1/xx\\/jaxws-manual-pojo-1/g";
ModelNode op = createOpNode("subsystem=webservices/", WRITE_ATTRIBUTE_OPERATION);
op.get(NAME).set("wsdl-path-rewrite-rule");
op.get(VALUE).set(sedCmdA);
applyUpdate(client, op, false); //update successful, no need to reload
//now we deploy an endpoint...
deployer.deploy(DEP_1);
//verify the updated wsdl host is used...
URL wsdlURL = new URL(managementClient.getWebUri().toURL(), '/' + DEP_1 + "/POJOService?wsdl");
checkWsdl(wsdlURL, expectedContext);
if (checkUpdateWithDeployedEndpoint) {
//final String hostnameB = "foo-host-b";
final String sedCmdB = "s/jaxws-manual-pojo-1/FOO\\/jaxws-manual-pojo-1/g";
ModelNode opB = createOpNode("subsystem=webservices/", WRITE_ATTRIBUTE_OPERATION);
opB.get(NAME).set("wsdl-path-rewrite-rule");
opB.get(VALUE).set(sedCmdB);
applyUpdate(client, opB, true); //update again, but we'll need to reload, as there's an active deployment
//check the wsdl host is still the one we updated to before
checkWsdl(wsdlURL, expectedContext);
//and check that still applies even if we undeploy and redeploy the endpoint
deployer.undeploy(DEP_1);
deployer.deploy(DEP_1);
checkWsdl(wsdlURL, expectedContext);
}
} finally {
try {
deployer.undeploy(DEP_1);
} catch (Throwable t) {
//ignore
}
try {
ModelNode op = createOpNode("subsystem=webservices/", UNDEFINE_ATTRIBUTE_OPERATION);
op.get(NAME).set("wsdl-path-rewrite-rule");
applyUpdate(client, op, checkUpdateWithDeployedEndpoint);
} finally {
managementClient.close();
}
}
}
@After
public void stopContainer() {
if (containerController.isStarted(DEFAULT_JBOSSAS)) {
containerController.stop(DEFAULT_JBOSSAS);
}
}
private String getAttribute(final String attribute, final ModelControllerClient client) throws Exception {
return getAttribute(attribute, client, true);
}
private String getAttribute(final String attribute, final ModelControllerClient client, final boolean checkDefined) throws Exception {
ModelNode op = createOpNode("subsystem=webservices/", READ_ATTRIBUTE_OPERATION);
op.get(NAME).set(attribute);
final ModelNode result = client.execute(new OperationBuilder(op).build());
if (result.hasDefined(OUTCOME) && SUCCESS.equals(result.get(OUTCOME).asString())) {
if (checkDefined) {
Assert.assertTrue(result.hasDefined(RESULT));
}
return result.get(RESULT).asString();
} else if (result.hasDefined(FAILURE_DESCRIPTION)) {
throw new Exception(result.get(FAILURE_DESCRIPTION).toString());
} else {
throw new Exception("Operation not successful; outcome = " + result.get(OUTCOME));
}
}
private static ModelNode createOpNode(String address, String operation) {
ModelNode op = new ModelNode();
// set address
ModelNode list = op.get(ADDRESS).setEmptyList();
if (address != null) {
String[] pathSegments = address.split("/");
for (String segment : pathSegments) {
String[] elements = segment.split("=");
list.add(elements[0], elements[1]);
}
}
op.get("operation").set(operation);
return op;
}
private static ModelNode applyUpdate(final ModelControllerClient client, final ModelNode update, final boolean expectReloadRequired) throws Exception {
final ModelNode result = client.execute(new OperationBuilder(update).build());
if (result.hasDefined(OUTCOME) && SUCCESS.equals(result.get(OUTCOME).asString())) {
if (expectReloadRequired) {
Assert.assertTrue(result.hasDefined(RESPONSE_HEADERS));
ModelNode responseHeaders = result.get(RESPONSE_HEADERS);
Assert.assertTrue(responseHeaders.hasDefined(OPERATION_REQUIRES_RELOAD));
Assert.assertEquals("true", responseHeaders.get(OPERATION_REQUIRES_RELOAD).asString());
} else {
Assert.assertFalse(result.hasDefined(RESPONSE_HEADERS));
}
return result;
} else if (result.hasDefined(FAILURE_DESCRIPTION)) {
throw new Exception(result.get(FAILURE_DESCRIPTION).toString());
} else {
throw new Exception("Operation not successful; outcome = " + result.get(OUTCOME));
}
}
private void checkWsdl(URL wsdlURL, String hostOrPort) throws IOException {
HttpURLConnection connection = (HttpURLConnection) wsdlURL.openConnection();
try {
connection.connect();
Assert.assertEquals(200, connection.getResponseCode());
connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
if (line.contains("address location")) {
Assert.assertTrue(line.contains(hostOrPort));
return;
}
}
fail("Could not check soap:address!");
} finally {
connection.disconnect();
}
}
private void checkWSDLUriScheme(final ModelControllerClient managementClient, String deploymentName, String expectedScheme) throws Exception {
final ModelNode address = new ModelNode();
address.add(DEPLOYMENT, deploymentName);
address.add(SUBSYSTEM, "webservices");
address.add("endpoint", "*"); // get all endpoints
final ModelNode operation = new ModelNode();
operation.get(OP).set(READ_RESOURCE_OPERATION);
operation.get(OP_ADDR).set(address);
operation.get(INCLUDE_RUNTIME).set(true);
operation.get(RECURSIVE).set(true);
ModelNode result = managementClient.execute(operation);
Assert.assertEquals(SUCCESS, result.get(OUTCOME).asString());
for (final ModelNode endpointResult : result.get("result").asList()) {
final ModelNode endpoint = endpointResult.get("result");
final URL wsdlURL = new URL(endpoint.get("wsdl-url").asString());
HttpURLConnection connection = (HttpURLConnection) wsdlURL.openConnection();
try {
connection.connect();
Assert.assertEquals(200, connection.getResponseCode());
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
if (line.contains("address location")) {
if ("https".equals(expectedScheme)) {
Assert.assertTrue(line, line.contains("https"));
return;
} else {
Assert.assertTrue(line, line.contains("http") && !line.contains("https"));
return;
}
}
}
fail(line + " Could not check soap:address!");
} finally {
connection.disconnect();
}
}
}
}
| 22,582 | 44.714575 | 155 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ws/EndpointIface.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, 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.manualmode.ws;
import jakarta.jws.WebService;
/**
*
* @author <a href="mailto:[email protected]">Emmanuel Hugonnet</a>
*/
@WebService
public interface EndpointIface {
String helloString(String input);
}
| 1,273 | 35.4 | 70 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ws/PojoEndpoint.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, 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.manualmode.ws;
import jakarta.jws.WebService;
import jakarta.xml.ws.BindingType;
/**
* Simple POJO endpoint
*
* @author <a href="mailto:[email protected]">Emmanuel Hugonnet</a>
*/
@WebService(
serviceName = "POJOService",
targetNamespace = "http://jbossws.org/basic",
endpointInterface = "org.jboss.as.test.manualmode.ws.EndpointIface"
)
@BindingType(jakarta.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING)
public class PojoEndpoint implements EndpointIface {
public String helloString(String input) {
return "Hello " + input + "!";
}
}
| 1,648 | 36.477273 | 75 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ws/ReloadWSDLPublisherTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, 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.manualmode.ws;
import static org.jboss.as.test.shared.ServerReload.executeReloadAndWaitForCompletion;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import org.jboss.logging.Logger;
import jakarta.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;
import jakarta.xml.ws.Service;
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.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*
* @author <a href="mailto:[email protected]">Emmanuel Hugonnet</a> (c) 2013 Red Hat, inc.
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ReloadWSDLPublisherTestCase {
private static final String DEFAULT_JBOSSAS = "default-jbossas";
private static final String DEPLOYMENT = "jaxws-manual-pojo";
private static final String keepAlive = System.getProperty("http.keepAlive") == null ? "true" : System.getProperty("http.keepAlive");
private static final String maxConnections = System.getProperty("http.maxConnections") == null ? "5" : System.getProperty("http.maxConnections");
@ArquillianResource
ContainerController containerController;
@ArquillianResource
Deployer deployer;
@Deployment(name = DEPLOYMENT, testable = false, managed = false)
public static WebArchive deployment() {
WebArchive pojoWar = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war").addClasses(
EndpointIface.class, PojoEndpoint.class);
return pojoWar;
}
@Before
public void endpointLookup() throws Exception {
containerController.start(DEFAULT_JBOSSAS);
if (containerController.isStarted(DEFAULT_JBOSSAS)) {
deployer.deploy(DEPLOYMENT);
}
System.setProperty("http.keepAlive", "false");
System.setProperty("http.maxConnections", "1");
}
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testHelloStringAfterReload() throws Exception {
Assert.assertTrue(containerController.isStarted(DEFAULT_JBOSSAS));
ManagementClient managementClient = new ManagementClient(TestSuiteEnvironment.getModelControllerClient(),
TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http");
QName serviceName = new QName("http://jbossws.org/basic", "POJOService");
URL wsdlURL = new URL(managementClient.getWebUri().toURL(), '/' + DEPLOYMENT + "/POJOService?wsdl");
checkWsdl(wsdlURL);
Service service = Service.create(wsdlURL, serviceName);
EndpointIface proxy = service.getPort(EndpointIface.class);
Assert.assertEquals("Hello World!", proxy.helloString("World"));
executeReloadAndWaitForCompletion(managementClient, 100000);
checkWsdl(wsdlURL);
serviceName = new QName("http://jbossws.org/basic", "POJOService");
service = Service.create(wsdlURL, serviceName);
proxy = service.getPort(EndpointIface.class);
Assert.assertEquals("Hello World!", proxy.helloString("World"));
Assert.assertTrue(containerController.isStarted(DEFAULT_JBOSSAS));
}
@After
public void stopContainer() {
System.setProperty("http.keepAlive", keepAlive);
System.setProperty("http.maxConnections", maxConnections);
if (containerController.isStarted(DEFAULT_JBOSSAS)) {
deployer.undeploy(DEPLOYMENT);
}
if (containerController.isStarted(DEFAULT_JBOSSAS)) {
containerController.stop(DEFAULT_JBOSSAS);
}
}
private void checkWsdl(URL wsdlURL) throws IOException {
StringBuilder proxyUsed = new StringBuilder();
try {
List<Proxy> proxies = ProxySelector.getDefault().select(wsdlURL.toURI());
for(Proxy proxy : proxies) {
//System.out.println("To connect to " + wsdlURL + " we are using proxy " + proxy);
proxyUsed.append("To connect to ").append(wsdlURL).append(" we are using proxy ").append(proxy).append("\r\n");
}
} catch (URISyntaxException ex) {
Logger.getLogger(ReloadWSDLPublisherTestCase.class.getName()).error(ex);
}
HttpURLConnection connection = (HttpURLConnection) wsdlURL.openConnection();
try {
connection.connect();
Assert.assertEquals(proxyUsed.toString(), HttpServletResponse.SC_OK, connection.getResponseCode());
} finally {
connection.disconnect();
}
}
}
| 6,284 | 42.344828 | 149 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/ws/ReloadRequiringChangesTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, 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.manualmode.ws;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADDRESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_REQUIRES_RELOAD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESPONSE_HEADERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION;
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.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
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.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Some tests on changes to the model requiring reload
*
* @author <a href="mailto:[email protected]">Alessio Soldano</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ReloadRequiringChangesTestCase {
private static final String DEFAULT_JBOSSAS = "default-jbossas";
private static final String DEPLOYMENT = "jaxws-manual-pojo";
@ArquillianResource
ContainerController containerController;
@ArquillianResource
Deployer deployer;
@Deployment(name = DEPLOYMENT, testable = false, managed = false)
public static WebArchive deployment() {
WebArchive pojoWar = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war").addClasses(
EndpointIface.class, PojoEndpoint.class);
return pojoWar;
}
@Before
public void startContainer() throws Exception {
containerController.start(DEFAULT_JBOSSAS);
if (containerController.isStarted(DEFAULT_JBOSSAS)) {
deployer.deploy(DEPLOYMENT);
}
}
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testWSDLHostChangeRequiresReloadAndDoesNotAffectRuntime() throws Exception {
Assert.assertTrue(containerController.isStarted(DEFAULT_JBOSSAS));
ManagementClient managementClient = new ManagementClient(TestSuiteEnvironment.getModelControllerClient(),
TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http");
ModelControllerClient client = managementClient.getControllerClient();
String initialWsdlHost = null;
try {
initialWsdlHost = getWsdlHost(client);
//change wsdl-host to "foo-host" and reload
final String hostname = "foo-host";
setWsdlHost(client, hostname);
ServerReload.executeReloadAndWaitForCompletion(managementClient);
//change wsdl-host to "bar-host" and verify deployment still uses "foo-host"
setWsdlHost(client, "bar-host");
URL wsdlURL = new URL(managementClient.getWebUri().toURL(), '/' + DEPLOYMENT + "/POJOService?wsdl");
checkWsdl(wsdlURL, hostname);
} finally {
try {
if (initialWsdlHost != null) {
setWsdlHost(client, initialWsdlHost);
}
} finally {
managementClient.close();
}
}
}
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testWSDLHostUndefineRequiresReloadAndDoesNotAffectRuntime() throws Exception {
Assert.assertTrue(containerController.isStarted(DEFAULT_JBOSSAS));
ManagementClient managementClient = new ManagementClient(TestSuiteEnvironment.getModelControllerClient(),
TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http");
ModelControllerClient client = managementClient.getControllerClient();
String initialWsdlHost = null;
try {
initialWsdlHost = getWsdlHost(client);
//change wsdl-host to "my-host" and reload
final String hostname = "my-host";
setWsdlHost(client, hostname);
ServerReload.executeReloadAndWaitForCompletion(managementClient);
//undefine wsdl-host and verify deployment still uses "foo-host"
setWsdlHost(client, null);
URL wsdlURL = new URL(managementClient.getWebUri().toURL(), '/' + DEPLOYMENT + "/POJOService?wsdl");
checkWsdl(wsdlURL, hostname);
} finally {
try {
if (initialWsdlHost != null) {
setWsdlHost(client, initialWsdlHost);
}
} finally {
managementClient.close();
}
}
}
@After
public void stopContainer() {
if (containerController.isStarted(DEFAULT_JBOSSAS)) {
deployer.undeploy(DEPLOYMENT);
}
if (containerController.isStarted(DEFAULT_JBOSSAS)) {
containerController.stop(DEFAULT_JBOSSAS);
}
}
private String getWsdlHost(final ModelControllerClient client) throws Exception {
ModelNode op = createOpNode("subsystem=webservices/", READ_ATTRIBUTE_OPERATION);
op.get(NAME).set("wsdl-host");
final ModelNode result = client.execute(new OperationBuilder(op).build());
if (result.hasDefined(OUTCOME) && SUCCESS.equals(result.get(OUTCOME).asString())) {
Assert.assertTrue(result.hasDefined(RESULT));
return result.get(RESULT).asString();
} else if (result.hasDefined(FAILURE_DESCRIPTION)) {
throw new Exception(result.get(FAILURE_DESCRIPTION).toString());
} else {
throw new Exception("Operation not successful; outcome = " + result.get(OUTCOME));
}
}
private void setWsdlHost(final ModelControllerClient client, final String wsdlHost) throws Exception {
ModelNode op;
if (wsdlHost != null) {
op = createOpNode("subsystem=webservices/", WRITE_ATTRIBUTE_OPERATION);
op.get(NAME).set("wsdl-host");
op.get(VALUE).set(wsdlHost);
} else {
op = createOpNode("subsystem=webservices/", UNDEFINE_ATTRIBUTE_OPERATION);
op.get(NAME).set("wsdl-host");
}
applyUpdate(client, op);
}
private static ModelNode createOpNode(String address, String operation) {
ModelNode op = new ModelNode();
// set address
ModelNode list = op.get(ADDRESS).setEmptyList();
if (address != null) {
String[] pathSegments = address.split("/");
for (String segment : pathSegments) {
String[] elements = segment.split("=");
list.add(elements[0], elements[1]);
}
}
op.get("operation").set(operation);
return op;
}
private static ModelNode applyUpdate(final ModelControllerClient client, final ModelNode update) throws Exception {
final ModelNode result = client.execute(new OperationBuilder(update).build());
if (result.hasDefined(OUTCOME) && SUCCESS.equals(result.get(OUTCOME).asString())) {
Assert.assertTrue(result.hasDefined(RESPONSE_HEADERS));
ModelNode responseHeaders = result.get(RESPONSE_HEADERS);
Assert.assertTrue(responseHeaders.hasDefined(OPERATION_REQUIRES_RELOAD));
Assert.assertEquals("true", responseHeaders.get(OPERATION_REQUIRES_RELOAD).asString());
return result;
} else if (result.hasDefined(FAILURE_DESCRIPTION)) {
throw new Exception(result.get(FAILURE_DESCRIPTION).toString());
} else {
throw new Exception("Operation not successful; outcome = " + result.get(OUTCOME));
}
}
private void checkWsdl(URL wsdlURL, String host) throws IOException {
HttpURLConnection connection = (HttpURLConnection) wsdlURL.openConnection();
try {
connection.connect();
Assert.assertEquals(200, connection.getResponseCode());
connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
if (line.contains("address location")) {
Assert.assertTrue(line.contains(host));
return;
}
}
fail("Could not check soap:address!");
} finally {
connection.disconnect();
}
}
}
| 11,033 | 42.785714 | 127 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/OrderedLoadBalancingPolicy.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 org.apache.activemq.artemis.api.core.client.loadbalance.ConnectionLoadBalancingPolicy;
/**
* Simple add-on for Activemq Artemis.
* @author Emmanuel Hugonnet (c) 2022 Red Hat, Inc.
*/
public class OrderedLoadBalancingPolicy implements ConnectionLoadBalancingPolicy {
private int pos = -1;
@Override
public int select(final int max) {
pos++;
if (pos >= max) {
pos = 0;
}
return pos;
}
}
| 1,109 | 29 | 93 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/NetworkHealthTestCase.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 static org.jboss.as.controller.client.helpers.Operations.isSuccessfulOutcome;
import java.io.IOException;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.cli.Util;
import org.jboss.as.controller.client.helpers.Operations;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import org.apache.activemq.artemis.core.server.NetworkHealthCheck;
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.test.integration.common.jms.JMSOperations;
import org.jboss.as.test.integration.common.jms.JMSOperationsProvider;
import org.jboss.as.test.integration.management.util.MgmtOperationException;
import org.jboss.as.test.shared.TestLogHandlerSetupTask;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.as.test.shared.util.LoggingUtil;
import org.jboss.dmr.ModelNode;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*
* @author Emmanuel Hugonnet (c) 2020 Red Hat, Inc.
*/
@RunAsClient()
@RunWith(Arquillian.class)
public class NetworkHealthTestCase {
private static final String DEFAULT_FULL_JBOSSAS = "default-full-jbossas";
private static final String IP_ADDRESS = "192.0.2.0";
@ArquillianResource
protected static ContainerController container;
private LoggerSetup loggerSetup;
private ManagementClient managementClient;
@Before
public void setup() throws Exception {
if (!container.isStarted(DEFAULT_FULL_JBOSSAS)) {
container.start(DEFAULT_FULL_JBOSSAS);
}
loggerSetup = new LoggerSetup();
managementClient = createManagementClient();
loggerSetup.setup(managementClient, DEFAULT_FULL_JBOSSAS);
}
@After
public void tearDown() throws Exception {
loggerSetup.tearDown(managementClient, DEFAULT_FULL_JBOSSAS);
managementClient.close();
container.stop(DEFAULT_FULL_JBOSSAS);
}
/**
* Defines a test IP to ping so that it fails and ensure that the logs contains the error message.
* Re-defines the IP to be pinged to the current server address and checks that no such error message occurs.
* @throws Exception.
*/
@Test
public void testNetworkUnHealthyNetwork() throws Exception {
JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient());
ModelNode op;
if(TestSuiteEnvironment.isWindows()) {
// The default ping commands in the AttributeDefinitions are meant for *nix based OSs and don't work,
// on Windows, so on Windows use the default *Artemis* values (from their NetworkHealthCheck class).
// The values of the Artemis defaults vary at runtime based on the OS, so we'll get the ones they think are best for Windows.
// Doing this also serves to test their current values (vs us hard coding something here).
op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-ping-command", NetworkHealthCheck.IPV4_DEFAULT_COMMAND);
executeOperationForSuccess(managementClient, op);
op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-ping6-command", NetworkHealthCheck.IPV6_DEFAULT_COMMAND);
executeOperationForSuccess(managementClient, op);
} // else .... for non-Windows for the ping commands we leave the config as-is and test the default AD values
op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-list", IP_ADDRESS);
executeOperationForSuccess(managementClient, op);
op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-period", 1000);
executeOperationForSuccess(managementClient, op);
op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-timeout", 200);
executeOperationForSuccess(managementClient, op);
Path logFile = LoggingUtil.getLogPath(managementClient, "file-handler", "artemis-log");
managementClient.close();
container.stop(DEFAULT_FULL_JBOSSAS);
container.start(DEFAULT_FULL_JBOSSAS);
managementClient = createManagementClient();
Thread.sleep(TimeoutUtil.adjust(2000));
if(TestSuiteEnvironment.isWindows()) {
// Until Artemis is upgraded to 2.22.0 which contains the fix.
// @see ARTEMIS-3803 / ARTEMIS-3799
Assert.assertTrue("Log should contains ActiveMQ ping error log message: [AMQ201001]", LoggingUtil.hasLogMessage(managementClient, "artemis-log", "AMQ201001", (line) -> line.contains("name=default")));
} else {
Assert.assertTrue("Log should contains ActiveMQ ping error log message: [AMQ202002]", LoggingUtil.hasLogMessage(managementClient, "artemis-log", "AMQ202002", (line) -> line.contains(IP_ADDRESS)));
}
Assert.assertFalse("Broker should be stopped", isBrokerActive(jmsOperations, managementClient));
String ipAddress = TestSuiteEnvironment.getServerAddress();
if(ipAddress.charAt(0) == '[') {
ipAddress = ipAddress.substring(1, ipAddress.lastIndexOf(']'));
}
op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-list", ipAddress);
executeOperationForSuccess(managementClient, op);
managementClient.close();
container.stop(DEFAULT_FULL_JBOSSAS);
long restartLine = LoggingUtil.countLines(logFile);
container.start(DEFAULT_FULL_JBOSSAS);
managementClient = createManagementClient();
Thread.sleep(TimeoutUtil.adjust(2000));
LoggingUtil.dumpTestLog(managementClient, "artemis-log");
Assert.assertFalse("Log contains ActiveMQ ping error log message: [AMQ202002]",
LoggingUtil.hasLogMessage(managementClient, "artemis-log", "AMQ202002", restartLine, (line) -> line.contains(IP_ADDRESS)));
Assert.assertTrue("Broker should be running", isBrokerActive(jmsOperations, managementClient));
op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-list");
executeOperationForSuccess(managementClient, op);
op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-period");
executeOperationForSuccess(managementClient, op);
op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-timeout");
executeOperationForSuccess(managementClient, op);
op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-ping-command");
executeOperationForSuccess(managementClient, op);
op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-ping6-command");
executeOperationForSuccess(managementClient, op);
}
/**
* Defines an unexisting ping command to check that this creates a proper error message.
* @throws Exception.
*/
@Test
public void testPingCommandError() throws Exception {
JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient());
ModelNode op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-ping-command", "not_existing_command");
executeOperationForSuccess(managementClient, op);
op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-ping6-command", "not_existing_command");
executeOperationForSuccess(managementClient, op);
op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-list", IP_ADDRESS);
executeOperationForSuccess(managementClient, op);
op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-period", 1000);
executeOperationForSuccess(managementClient, op);
op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-timeout", 200);
executeOperationForSuccess(managementClient, op);
managementClient.close();
container.stop(DEFAULT_FULL_JBOSSAS);
container.start(DEFAULT_FULL_JBOSSAS);
managementClient = createManagementClient();
Thread.sleep(TimeoutUtil.adjust(2000));
Assert.assertTrue("Log should contains ActiveMQ ping error log message: [AMQ202007]",
LoggingUtil.hasLogMessage(managementClient, "artemis-log", "",
(line) -> (line.contains(" AMQ202007") && line.contains(IP_ADDRESS) && line.contains("java.io.IOException")) || line.contains("AMQ201001")));
Assert.assertFalse("Broker should be stopped", isBrokerActive(jmsOperations, managementClient));
op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-list");
executeOperationForSuccess(managementClient, op);
op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-period");
executeOperationForSuccess(managementClient, op);
op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-timeout");
executeOperationForSuccess(managementClient, op);
op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-ping-command");
executeOperationForSuccess(managementClient, op);
op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-ping6-command");
executeOperationForSuccess(managementClient, op);
}
private static ManagementClient createManagementClient() throws UnknownHostException {
return new ManagementClient(
TestSuiteEnvironment.getModelControllerClient(),
TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddress()),
TestSuiteEnvironment.getServerPort(),
"remote+http");
}
private Path getLogFile(ManagementClient managementClient) throws IOException {
final ModelNode address = Operations.createAddress("subsystem", "logging", "periodic-rotating-file-handler", "FILE");
final ModelNode op = Operations.createOperation("resolve-path", address);
final ModelNode result = managementClient.getControllerClient().execute(op);
if (!Operations.isSuccessfulOutcome(result)) {
Assert.fail("Failed to locate the log file: " + Operations.getFailureDescription(result).asString());
}
return Paths.get(Operations.readResult(result).asString());
}
private void executeOperationForSuccess(ManagementClient managementClient, ModelNode operation) throws IOException, MgmtOperationException {
ModelNode response = managementClient.getControllerClient().execute(operation);
Assert.assertTrue(Util.getFailureDescription(response), isSuccessfulOutcome(response));
}
private boolean isBrokerActive(JMSOperations jmsOperations, ManagementClient managementClient) throws IOException, MgmtOperationException {
ModelNode operation = Operations.createReadAttributeOperation(jmsOperations.getServerAddress(), "active");
ModelNode response = managementClient.getControllerClient().execute(operation);
Assert.assertTrue(Util.getFailureDescription(response), isSuccessfulOutcome(response));
return response.get("result").asBoolean();
}
class LoggerSetup extends TestLogHandlerSetupTask {
@Override
public Collection<String> getCategories() {
return Arrays.asList("org.apache.activemq.artemis");
}
@Override
public String getLevel() {
return "TRACE";
}
@Override
public String getHandlerName() {
return "artemis-log";
}
@Override
public String getLogFileName() {
return "artemis.log";
}
}
}
| 13,649 | 52.320313 | 212 |
java
|
null |
wildfly-main/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/messaging/CriticalAnalyzerTestCase.java
|
/*
* Copyright 2021 JBoss by Red Hat.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.manualmode.messaging;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Properties;
import jakarta.jms.ConnectionFactory;
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.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.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.TestLogHandlerSetupTask;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.as.test.shared.util.LoggingUtil;
import org.jboss.byteman.agent.submit.Submit;
import org.jboss.dmr.ModelNode;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*
* @author Emmanuel Hugonnet (c) 2020 Red Hat, Inc.
*/
@RunWith(Arquillian.class)
@RunAsClient
public class CriticalAnalyzerTestCase {
private static final String DEFAULT_FULL_JBOSSAS = "default-full-jbossas-byteman";
private static final String EXPORTED_PREFIX = "java:jboss/exported/";
@ArquillianResource
protected static ContainerController container;
private LoggerSetup loggerSetup;
private ManagementClient managementClient;
private final Submit bytemanSubmit = new Submit(
System.getProperty("byteman.server.ipaddress", Submit.DEFAULT_ADDRESS),
Integer.getInteger("byteman.server.port", Submit.DEFAULT_PORT));
private void deployRules() throws Exception {
bytemanSubmit.addRulesFromResources(Collections.singletonList(
CriticalAnalyzerTestCase.class.getClassLoader().getResourceAsStream("byteman/CriticalAnalyzerTestCase.btm")));
}
private void removeRules() {
try {
bytemanSubmit.deleteAllRules();
} catch (Exception ex) {
}
}
@Before
public void setup() throws Exception {
if (!container.isStarted(DEFAULT_FULL_JBOSSAS)) {
container.start(DEFAULT_FULL_JBOSSAS);
}
loggerSetup = new LoggerSetup();
managementClient = createManagementClient();
loggerSetup.setup(managementClient, DEFAULT_FULL_JBOSSAS);
JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient());
managementClient.getControllerClient().execute(Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-policy", "SHUTDOWN"));
managementClient.getControllerClient().execute(Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-enabled", ModelNode.TRUE));
managementClient.getControllerClient().execute(Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-check-period", new ModelNode(100L)));
managementClient.getControllerClient().execute(Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-timeout", new ModelNode(1000L)));
try {
jmsOperations.removeJmsQueue("critical");
} catch(RuntimeException ex) {
}
jmsOperations.createJmsQueue("critical", EXPORTED_PREFIX + "queue/critical");
jmsOperations.close();
managementClient.close();
container.stop(DEFAULT_FULL_JBOSSAS);
container.start(DEFAULT_FULL_JBOSSAS);
managementClient = createManagementClient();
}
@After
public void cleanAll() throws Exception {
if (!container.isStarted(DEFAULT_FULL_JBOSSAS)) {
container.start(DEFAULT_FULL_JBOSSAS);
}
removeRules();
loggerSetup.tearDown(managementClient, DEFAULT_FULL_JBOSSAS);
JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient());
managementClient.getControllerClient().execute(Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-policy"));
managementClient.getControllerClient().execute(Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-enabled"));
managementClient.getControllerClient().execute(Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-check-period"));
managementClient.getControllerClient().execute(Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-timeout"));
if (isBrokerRunning()) {
jmsOperations.removeJmsQueue("critical");
}
jmsOperations.close();
managementClient.close();
container.stop(DEFAULT_FULL_JBOSSAS);
}
private static ManagementClient createManagementClient() throws UnknownHostException {
return new ManagementClient(
TestSuiteEnvironment.getModelControllerClient(),
TestSuiteEnvironment.formatPossibleIpv6Address(TestSuiteEnvironment.getServerAddress()),
TestSuiteEnvironment.getServerPort(),
"remote+http");
}
/**
* Set the critical analyzer to SHUTDOWN strategy.
* Use the byteman script to simulate a slow journal that would make the critical analyzer to activate.
* Check that the critical analyzer was started and created the expected log traces.
* Check that the broker has been stopped.
* @throws Exception
*/
@Test
public void testCriticalAnalyzer() throws Exception {
if (!container.isStarted(DEFAULT_FULL_JBOSSAS)) {
container.start(DEFAULT_FULL_JBOSSAS);
}
InitialContext remoteContext = createJNDIContext();
managementClient = createManagementClient();
ConnectionFactory cf = (ConnectionFactory) remoteContext.lookup("jms/RemoteConnectionFactory");
Queue queue = (Queue) remoteContext.lookup("queue/critical");
deployRules();
try (JMSContext context = cf.createContext("guest", "guest", JMSContext.AUTO_ACKNOWLEDGE)) {
JMSProducer producer = context.createProducer();
for (int i = 0; i < 20; i++) {
TextMessage message = context.createTextMessage(RandomStringUtils.randomAlphabetic(10));
producer.send(queue, message);
}
Assert.fail("Critical analyzer should have kicked in");
} catch (jakarta.jms.JMSRuntimeException ex) {
Assert.assertTrue("Log should contains ActiveMQ connection failure error log message: [AMQ219016]", ex.getMessage().contains("AMQ219016"));
Assert.assertTrue("Log should contains ActiveMQ critical measure ", LoggingUtil.hasLogMessage(managementClient, "artemis-log", "",
(line) -> (line.contains("[org.apache.activemq.artemis.utils.critical.CriticalMeasure]"))));
Assert.assertTrue("Log should contains ActiveMQ AMQ224080 : critical analyzer is stopping the broker", LoggingUtil.hasLogMessage(managementClient, "artemis-log", "",
(line) -> (line.contains("AMQ224080"))));
Assert.assertTrue("Log should contains ActiveMQ AMQ222199 : Thread dump ", LoggingUtil.hasLogMessage(managementClient, "artemis-log", "",
(line) -> (line.contains("AMQ222199"))));
}
remoteContext.close();
assertFalse(isBrokerRunning());
}
/**
* Disable the critical analyzer.
* Use the byteman script to simulate a slow journal that would make the critical analyzer to activate.
* Check that there is nothing in the logs and that the broker is still running.
* @throws Exception
*/
@Test
public void testCriticalAnalyzerDisabled() throws Exception {
if (!container.isStarted(DEFAULT_FULL_JBOSSAS)) {
container.start(DEFAULT_FULL_JBOSSAS);
}
JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient());
managementClient.getControllerClient().execute(Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-enabled", ModelNode.FALSE));
jmsOperations.close();
managementClient.close();
container.stop(DEFAULT_FULL_JBOSSAS);
container.start(DEFAULT_FULL_JBOSSAS);
InitialContext remoteContext = createJNDIContext();
managementClient = createManagementClient();
ConnectionFactory cf = (ConnectionFactory) remoteContext.lookup("jms/RemoteConnectionFactory");
Queue queue = (Queue) remoteContext.lookup("queue/critical");
deployRules();
try (JMSContext context = cf.createContext("guest", "guest", JMSContext.AUTO_ACKNOWLEDGE)) {
JMSProducer producer = context.createProducer();
for (int i = 0; i < 20; i++) {
TextMessage message = context.createTextMessage(RandomStringUtils.randomAlphabetic(10));
producer.send(queue, message);
}
}
remoteContext.close();
assertTrue(isBrokerRunning());
}
private boolean isBrokerRunning() throws IOException {
JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient());
ModelNode response = managementClient.getControllerClient().execute(Operations.createReadAttributeOperation(jmsOperations.getServerAddress(), "started"));
jmsOperations.close();
assertTrue(response.toJSONString(true), Operations.isSuccessfulOutcome(response));
return Operations.readResult(response).asBoolean();
}
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);
}
class LoggerSetup extends TestLogHandlerSetupTask {
@Override
public Collection<String> getCategories() {
return Arrays.asList("org.apache.activemq.artemis.core.server", "org.apache.activemq.artemis.utils");
}
@Override
public String getLevel() {
return "INFO";
}
@Override
public String getHandlerName() {
return "artemis-log";
}
@Override
public String getLogFileName() {
return "artemis.log";
}
}
}
| 12,077 | 46.928571 | 186 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.