repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/security/securitycontext/SecurityContextImplLoginTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.securitycontext; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.controller.client.helpers.ClientConstants; import org.apache.http.client.methods.HttpGet; import org.apache.http.HttpResponse; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.cli.CommandContext; import org.jboss.as.cli.CommandContextFactory; import org.jboss.as.cli.impl.CommandContextConfiguration; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; 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.Assert; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.jboss.as.test.integration.web.security.SecuredServlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import java.util.List; import static org.jboss.as.controller.client.helpers.ClientConstants.FAILURE_DESCRIPTION; import static org.jboss.as.controller.client.helpers.ClientConstants.RESULT; /** * SecurityContextImplLoginTestCase * For more information visit <a href="https://issues.redhat.com/browse/ELYWEB-133">https://issues.redhat.com/browse/ELYWEB-133</a> * @author Petr Adamec */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({SnapshotRestoreSetupTask.class, SecurityContextImplLoginTestCase.SecurityContextImplLoginTestCaseServerSetup.class}) public class SecurityContextImplLoginTestCase { @ArquillianResource(SecuredServlet.class) URL deploymentURL; private static CommandContext ctx; @ClassRule public static final TemporaryFolder temporaryUserHome = new TemporaryFolder(); private static final ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); private static final String DEPLOYMENT = "simple-webapp"; private static final String MY_FS_REALM = "MyFsRealm"; private static final String MY_SECURITY_DOMAIN = "MySecurityDomain"; private static final String MY_HTTP_AUTH_FACTORY = "MyHttpAuthFactory"; private static final String MY_APP_SECURITY_DOMAIN = "my_app_security_domain"; private static final String MY_CACHING_REALM = "MyCachingRealm"; private static final String MY_REALM_MAPPER = "MyRealmMapper"; private static final String FROM_ROLES_ATTRIBUTE_DECODER = "FromRolesAttributeDecoder"; private static final String TEST_USER = "testuser"; @ContainerResource private ManagementClient managementClient; @Deployment(name = DEPLOYMENT) public static WebArchive createDeployment() throws Exception{ WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war"); war.addClass(MyDummyTokenHandler.class); war.addClass(MyServletExtension.class); war.addClass(SecuredServlet.class); war.addAsResource(new StringAsset("org.jboss.as.test.integration.security.securitycontext.MyServletExtension"), "META-INF/services/io.undertow.servlet.ServletExtension"); war.addAsWebResource(SecurityContextImplLoginTestCase.class.getPackage(), "pub/login.html", "pub/login.html"); war.addAsWebResource(SecurityContextImplLoginTestCase.class.getPackage(), "pub/login-error.html", "pub/login-error.html"); war.addAsWebResource(SecurityContextImplLoginTestCase.class.getPackage(), "index.html", "index.html"); war.addAsWebResource(SecurityContextImplLoginTestCase.class.getPackage(), "main/index.html", "main/index.html"); war.addAsWebInfResource(SecurityContextImplLoginTestCase.class.getPackage(), "web.xml", "web.xml"); war.addAsWebInfResource(SecurityContextImplLoginTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml"); return war; } /** * Access to protected page directly. * The login page should be back so expected status code is 200 * @throws Exception */ @Test public void accessProtectedPageDirectlyTest() throws Exception{ try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(getURL())); Assert.assertEquals("For more info see ELYWEB-133. " ,200, response.getStatusLine().getStatusCode()); } } /** * Access the protected page but the custom http handler will login. * Protected page content should be returned so expected status code is 200 * @throws Exception */ @Test public void accessProtectedPageWithCustomHttpHandlerLoginTest() throws Exception{ try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpResponse response = client.execute(new HttpGet(getURL()+"?login=true")); Assert.assertEquals("For more info see ELYWEB-133. " ,200, response.getStatusLine().getStatusCode()); } } 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 boolean domainExists(String domain) throws Exception { ModelNode realms = createOpNode("subsystem=undertow", "read-children-names"); realms.get("child-type").set("application-security-domain"); List<ModelNode> mn = executeForResult(realms).asList(); for (ModelNode c : mn) { if (c.asString().equals(domain)) { return true; } } return false; } private static ModelNode executeForResult(final ModelNode operation) throws Exception { try { final ModelNode result = ctx.getModelControllerClient().execute(operation); checkSuccessful(result, operation); return result.get(RESULT); } catch (IOException e) { throw new RuntimeException(e); } } private static void checkSuccessful(final ModelNode result, final ModelNode operation) throws Exception { if (!ClientConstants.SUCCESS.equals(result.get(ClientConstants.OUTCOME).asString())) { throw new Exception(result.get( FAILURE_DESCRIPTION).toString()); } } private String getURL() { return deploymentURL.toString() + "main/"; } static class SecurityContextImplLoginTestCaseServerSetup implements ServerSetupTask { @Override public void setup(ManagementClient managementClient, String s) throws Exception { CommandContextConfiguration.Builder configBuilder = new CommandContextConfiguration.Builder(); ctx = CommandContextFactory.getInstance().newCommandContext(configBuilder.build()); ctx.connectController(); ctx.handle("/subsystem=elytron/filesystem-realm=" + MY_FS_REALM + ":add(path=my-realm-users, relative-to=jboss.server.config.dir)"); ctx.handle("/subsystem=elytron/filesystem-realm=" + MY_FS_REALM + ":add-identity(identity=" + TEST_USER ); ctx.handle("/subsystem=elytron/filesystem-realm=" + MY_FS_REALM + ":set-password(identity=" + TEST_USER + ",clear={password=testpassword})"); ctx.handle("/subsystem=elytron/filesystem-realm="+ MY_FS_REALM + ":add-identity-attribute(identity=" + TEST_USER + ", name=Roles, value=[regular_user])"); ctx.handle("/subsystem=elytron/caching-realm=" + MY_CACHING_REALM + ":add(realm=" + MY_FS_REALM +", maximum-age=300000"); ctx.handle("/subsystem=elytron/simple-role-decoder=" + FROM_ROLES_ATTRIBUTE_DECODER + ":add(attribute=Roles)"); ctx.handle("/subsystem=elytron/security-domain="+ MY_SECURITY_DOMAIN +":add(realms=[{realm=" + MY_CACHING_REALM + ", role-decoder=" + FROM_ROLES_ATTRIBUTE_DECODER + "}], default-realm=" + MY_CACHING_REALM + ", permission-mapper=default-permission-mapper)"); ctx.handle("/subsystem=elytron/constant-realm-mapper=" + MY_REALM_MAPPER + ":add(realm-name=" + MY_CACHING_REALM + ")"); ctx.handle("/subsystem=elytron/http-authentication-factory=" + MY_HTTP_AUTH_FACTORY +":add(http-server-mechanism-factory=global, security-domain=" + MY_SECURITY_DOMAIN + ", mechanism-configurations=[{mechanism-name=FORM, realm-mapper=MyRealmMapper, mechanism-realm-configurations=[{realm-name=MyRealm}]}]"); ctx.handle("/subsystem=undertow/application-security-domain=" + MY_APP_SECURITY_DOMAIN + " :add(http-authentication-factory=" + MY_HTTP_AUTH_FACTORY + ")"); ctx.handle("reload"); } @Override public void tearDown(ManagementClient managementClient, String s) throws Exception { Exception e = null; ModelNode op = createOpNode("subsystem=undertow/application-security-domain=" + MY_APP_SECURITY_DOMAIN, "remove"); executeForResult(op); op = createOpNode("subsystem=elytron/http-authentication-factory=" + MY_HTTP_AUTH_FACTORY, "remove"); executeForResult(op); ModelNode removeMapper = createOpNode("subsystem=elytron/constant-realm-mapper=" + MY_REALM_MAPPER, "remove"); executeForResult(removeMapper); op = createOpNode("subsystem=elytron/security-domain=" + MY_SECURITY_DOMAIN, "remove"); executeForResult(op); op = createOpNode("subsystem=elytron/caching-realm=" + MY_CACHING_REALM, "remove"); executeForResult(op); if (ctx != null) { try { ctx.handle("/subsystem=elytron/simple-role-decoder=" + FROM_ROLES_ATTRIBUTE_DECODER + " :remove"); ctx.handle("/subsystem=elytron/filesystem-realm="+ MY_FS_REALM + ":remove-identity(identity=" + TEST_USER + ")"); ctx.handle("/subsystem=elytron/filesystem-realm=" + MY_FS_REALM + " :remove"); } catch (Exception ex) { if (e == null) { e = ex; } } finally { try { ctx.handle("reload"); } finally { ctx.terminateSession(); } } } if (e != null) { throw e; } } } }
12,315
47.488189
319
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/security/securitycontext/MyDummyTokenHandler.java
/* Copyright 2018 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.integration.security.securitycontext; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.servlet.handlers.ServletRequestContext; public class MyDummyTokenHandler implements HttpHandler { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { HttpServletRequest request = (HttpServletRequest) exchange .getAttachment(ServletRequestContext.ATTACHMENT_KEY) .getServletRequest(); HttpServletResponse response = (HttpServletResponse) exchange .getAttachment(ServletRequestContext.ATTACHMENT_KEY) .getServletResponse(); boolean login = false; try { login = Boolean.valueOf(request.getParameter("login")); } catch (Exception e) { //ignore } final String AUTHENTICATED = "authenticated"; HttpSession session = request.getSession(false); if (login && (session == null || session.getAttribute(AUTHENTICATED) == null)) { request.login("testuser", "testpassword"); session = session == null ? request.getSession() : session; session.setAttribute(AUTHENTICATED, AUTHENTICATED); } } }
2,003
34.785714
88
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/security/auditing/SecurityAuditingTestCase.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.integration.security.auditing; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.File; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.integration.ejb.security.AnnSBTest; import org.jboss.as.test.integration.ejb.security.authorization.SingleMethodsAnnOnlyCheckSFSB; import org.jboss.as.test.integration.management.base.AbstractMgmtTestBase; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.ServerSnapshot; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.security.common.elytron.ElytronDomainSetup; import org.wildfly.test.security.common.elytron.ServletElytronDomainSetup; /** * This class tests Security auditing functionality * * @author <a href="mailto:[email protected]">Jan Lanik</a>. */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({SecurityAuditingTestCase.SecurityAuditingTestCaseSetup.class}) public class SecurityAuditingTestCase extends AnnSBTest { private static final Logger log = Logger.getLogger(testClass()); private static File auditLog = new File(System.getProperty("jboss.home", null), "standalone" + File.separator + "log" + File.separator + "audit.log"); static class SecurityAuditingTestCaseSetup extends AbstractMgmtTestBase implements ServerSetupTask { /** * The LOGGING */ private static final String LOGGING = "logging"; private static final String SECURITY_DOMAIN_NAME = "form-auth"; private AutoCloseable snapshot; private ElytronDomainSetup elytronDomainSetup; private ServletElytronDomainSetup servletElytronDomainSetup; private ManagementClient managementClient; protected static String getUsersFile() { return new File(SecurityAuditingTestCase.class.getResource("form-auth/users.properties").getFile()).getAbsolutePath(); } protected static String getGroupsFile() { return new File(SecurityAuditingTestCase.class.getResource("form-auth/roles.properties").getFile()).getAbsolutePath(); } @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { this.managementClient = managementClient; snapshot = ServerSnapshot.takeSnapshot(managementClient); final List<ModelNode> updates = new ArrayList<ModelNode>(); ModelNode op = new ModelNode(); elytronDomainSetup = new ElytronDomainSetup(getUsersFile(), getGroupsFile(), SECURITY_DOMAIN_NAME); servletElytronDomainSetup = new ServletElytronDomainSetup(SECURITY_DOMAIN_NAME, false); elytronDomainSetup.setup(managementClient, containerId); servletElytronDomainSetup.setup(managementClient, containerId); // /subsystem=elytron/security-domain=form-auth:write-attribute(name=security-event-listener, value=local-audit) op = new ModelNode(); op.get(OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(OP_ADDR).add(SUBSYSTEM, "elytron"); op.get(OP_ADDR).add("security-domain", SECURITY_DOMAIN_NAME); op.get("name").set("security-event-listener"); op.get("value").set("local-audit"); updates.add(op); // /subsystem=elytron/security-domain=ApplicationDomain:write-attribute(name=security-event-listener, value=local-audit) op = new ModelNode(); op.get(OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(OP_ADDR).add(SUBSYSTEM, "elytron"); op.get(OP_ADDR).add("security-domain", "ApplicationDomain"); op.get("name").set("security-event-listener"); op.get("value").set("local-audit"); updates.add(op); executeOperations(updates); ServerReload.executeReloadAndWaitForCompletion(managementClient, 50000); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { snapshot.close(); // /subsystem=elytron/security-domain=ApplicationDomain:undefine-attribute(name=security-event-listener) final List<ModelNode> updates = new ArrayList<ModelNode>(); ModelNode op = new ModelNode(); op.get(OP).set(UNDEFINE_ATTRIBUTE_OPERATION); op.get(OP_ADDR).add(SUBSYSTEM, "elytron"); op.get(OP_ADDR).add("security-domain", SECURITY_DOMAIN_NAME); op.get("name").set("security-event-listener"); updates.add(op); executeOperations(updates); elytronDomainSetup.tearDown(managementClient, containerId); servletElytronDomainSetup.tearDown(managementClient, containerId); } @Override protected ModelControllerClient getModelControllerClient() { return managementClient.getControllerClient(); } } @Deployment public static WebArchive deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, "form-auth.war"); war.setWebXML("org/jboss/as/test/integration/security/auditing/form-auth/web.xml"); war.addAsWebInfResource("org/jboss/as/test/integration/security/auditing/form-auth/jboss-web.xml"); war.addAsWebResource("org/jboss/as/test/integration/security/auditing/form-auth/index.jsp"); war.addAsWebResource("org/jboss/as/test/integration/security/auditing/form-auth/login.jsp"); war.addAsWebResource("org/jboss/as/test/integration/security/auditing/form-auth/loginerror.jsp"); war.addAsWebResource("org/jboss/as/test/integration/security/auditing/form-auth/logout.jsp"); war.addAsResource("org/jboss/as/test/integration/security/auditing/form-auth/users.properties", "/users.properties"); war.addAsResource("org/jboss/as/test/integration/security/auditing/form-auth/roles.properties", "/roles.properties"); return war; } private static final String MODULE = "singleMethodsAnnOnlySFSB"; private static Class<?> testClass() { return SecurityAuditingTestCase.class; } private static Class<?> beanClass() { return SingleMethodsAnnOnlyCheckSFSB.class; } @Deployment(name = MODULE + ".jar", order = 1, testable = false) public static Archive<JavaArchive> deployment() { return testAppDeployment(Logger.getLogger(testClass()), MODULE, beanClass()); } /** * Basic test if auditing works in EJB module. * * @throws Exception */ @Test public void testSingleMethodAnnotationsUser1Template() throws Exception { assertTrue("Audit log file has not been created (" + auditLog.getAbsolutePath() + ")", auditLog.exists()); assertTrue("Audit log file is closed for reading (" + auditLog.getAbsolutePath() + ")", auditLog.canRead()); BufferedReader reader = Files.newBufferedReader(auditLog.toPath(), StandardCharsets.UTF_8); while (reader.readLine() != null) { // we need to get trough all old records (if any) } testSingleMethodAnnotationsUser1Template(MODULE, log, beanClass()); checkAuditLog(reader, "SecurityAuthenticationSuccessfulEvent.*\"name\":\"user1\""); } /** * Basic test if auditing works for web module. * * @param url * @throws Exception */ @Test public void test(@ArquillianResource URL url) throws Exception { assertTrue("Audit log file has not been created (" + auditLog.getAbsolutePath() + ")", auditLog.exists()); assertTrue("Audit log file is closed for reading (" + auditLog.getAbsolutePath() + ")", auditLog.canRead()); BufferedReader reader = Files.newBufferedReader(auditLog.toPath(), StandardCharsets.UTF_8); while (reader.readLine() != null) { // we need to get trough all old records (if any) } Utils.makeCall(url.toString(), "anil", "anil", 200); checkAuditLog(reader, "SecurityAuthenticationSuccessfulEvent.*\"name\":\"anil\""); } private void checkAuditLog(BufferedReader reader, String regex) throws Exception { Pattern successPattern = Pattern.compile(regex); // we'll be actively waiting for a given INTERVAL for the record to appear final long INTERVAL = TimeoutUtil.adjust(5000); long startTime = System.currentTimeMillis(); String line; search_for_log: while (true) { // some new lines were added -> go trough those and check whether our record is present while (null != (line = reader.readLine())) { if (successPattern.matcher(line).find()) { break search_for_log; } } // record not written to log yet -> continue checking if the time has not yet expired if (System.currentTimeMillis() > startTime + INTERVAL) { // time expired throw new AssertionError("Login record has not been written into audit log! (time expired). Checked regex=" + regex); } } } }
11,630
43.224335
154
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/OriginalLibraryServlet.java
package org.jboss.as.test.integration.management.cli; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author Stuart Douglas */ @WebServlet(urlPatterns = "/LibraryServlet") public class OriginalLibraryServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("Original Library Servlet"); } }
643
29.666667
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/DeploymentScannerTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.cli; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.URL; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.management.util.CLIOpResult; import org.jboss.as.test.integration.management.util.SimpleServlet; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Dominik Pospisil <[email protected]> */ @RunWith(Arquillian.class) @RunAsClient public class DeploymentScannerTestCase extends AbstractCliTestBase { private static final String tempDir = TestSuiteEnvironment.getTmpDir(); private static File warFile; private static File deployDir; @ArquillianResource URL url; @Deployment public static Archive<?> getDeployment() { JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "dummy.jar"); ja.addClass(DeploymentScannerTestCase.class); return ja; } @BeforeClass public static void before() throws Exception { deployDir = new File(tempDir + File.separator + "tempDeployment"); if (deployDir.exists()) { FileUtils.deleteDirectory(deployDir); } assertTrue("Unable to create deployment scanner directory.", deployDir.mkdir()); AbstractCliTestBase.initCLI(); } @AfterClass public static void after() throws Exception { FileUtils.deleteDirectory(deployDir); AbstractCliTestBase.closeCLI(); } @Test public void testAddRemoveDeploymentScanner() throws Exception { addDeploymentScanner(); removeDeploymentScanner(); } private void addDeploymentScanner() throws Exception { WebArchive war = ShrinkWrap.create(WebArchive.class, "SimpleServlet.war"); war.addClass(SimpleServlet.class); warFile = new File(deployDir.getAbsolutePath() + File.separator + "SimpleServlet.war"); new ZipExporterImpl(war).exportTo(warFile, true); // add deployment scanner String path = deployDir.getAbsolutePath(); path = path.replaceAll("\\\\", "/"); cli.sendLine("/subsystem=deployment-scanner/scanner=testScanner:add(scan-interval=1000,path=\"" + path +"\")"); // wait for deployment Thread.sleep(2000); // check that the app has been deployed File marker = new File(deployDir.getAbsolutePath() + File.separator + "SimpleServlet.war.deployed"); assertTrue(marker.exists()); String response = HttpRequest.get(getBaseURL(url) + "SimpleServlet/SimpleServlet", 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >=0); } private void removeDeploymentScanner() throws Exception { // remove deployment scanner cli.sendLine("/subsystem=deployment-scanner/scanner=testScanner:remove()"); CLIOpResult result = cli.readAllAsOpResult(); assertTrue(result.isIsOutcomeSuccess()); // delete deployment assertTrue("Could not delete deployed file.", warFile.delete()); // wait for deployment Thread.sleep(2000); // check that the deployment is still live String response = HttpRequest.get(getBaseURL(url) + "SimpleServlet/SimpleServlet", 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >=0); // undeploy using CLI cli.sendLine("undeploy SimpleServlet.war"); assertTrue(checkUndeployed(getBaseURL(url) + "SimpleServlet/SimpleServlet")); } }
5,353
36.971631
119
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/ReplacedLibraryServlet.java
package org.jboss.as.test.integration.management.cli; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author Stuart Douglas */ @WebServlet(urlPatterns = "/LibraryServlet") public class ReplacedLibraryServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("Replaced Library Servlet"); } }
643
29.666667
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/DeployURLTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.cli; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.URL; import java.util.concurrent.TimeUnit; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.management.util.SimpleServlet; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Dominik Pospisil <[email protected]> */ @RunWith(Arquillian.class) @RunAsClient public class DeployURLTestCase extends AbstractCliTestBase { private static WebArchive war; private static File warFile; @ArquillianResource URL url; @Deployment public static Archive<?> getDeployment() { JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "dummy.jar"); ja.addClass(DeployURLTestCase.class); return ja; } @BeforeClass public static void before() throws Exception { war = ShrinkWrap.create(WebArchive.class, "SimpleServlet.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(new StringAsset("Version1"), "page.html"); String tempDir = TestSuiteEnvironment.getTmpDir(); warFile = new File(tempDir + File.separator + "SimpleServlet.war"); new ZipExporterImpl(war).exportTo(warFile, true); AbstractCliTestBase.initCLI(); } @AfterClass public static void after() throws Exception { warFile.delete(); AbstractCliTestBase.closeCLI(); } @Test public void testDeployRedeployUndeploy() throws Exception { testDeploy(); testRedeploy(); testUndeploy(); } public void testDeploy() throws Exception { // deploy to server cli.sendLine("deploy --url=" + warFile.toURI().toURL().toExternalForm() + " --name=" + warFile.getName()); // check deployment String response = HttpRequest.get(getBaseURL(url) + "SimpleServlet/SimpleServlet", 1000, 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >=0); } public void testRedeploy() throws Exception { // check we have original deployment String response = HttpRequest.get(getBaseURL(url) + "SimpleServlet/page.html", 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("Version1") >=0); // update the deployment - replace page.html war = ShrinkWrap.create(WebArchive.class, "SimpleServlet.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(new StringAsset("Version2"), "page.html"); new ZipExporterImpl(war).exportTo(warFile, true); // redeploy to server Assert.assertFalse(cli.sendLine("deploy --url=" + warFile.toURI().toURL().toExternalForm() + " --name=" + warFile.getName(), true)); // force redeploy cli.sendLine("deploy --url=" + warFile.toURI().toURL().toExternalForm() + " --name=" + warFile.getName() + " --force"); // check that new version is running final long firstTry = System.currentTimeMillis(); response = HttpRequest.get(getBaseURL(url) + "SimpleServlet/page.html", 1000, 10, TimeUnit.SECONDS); while(response.indexOf("Version2") < 0) { if(System.currentTimeMillis() - firstTry >= 1000) { break; } try { Thread.sleep(500); } catch(InterruptedException e) { break; } finally { response = HttpRequest.get(getBaseURL(url) + "SimpleServlet/page.html", 1000, 10, TimeUnit.SECONDS); } } assertTrue("Invalid response: " + response, response.indexOf("Version2") >=0); } public void testUndeploy() throws Exception { //undeploy cli.sendLine("undeploy " + warFile.getName()); // check undeployment assertTrue(checkUndeployed(getBaseURL(url) + "SimpleServlet/SimpleServlet")); } }
5,740
36.769737
140
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/WildCardReadsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.cli; import java.io.IOException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import org.jboss.as.test.integration.management.util.CLIOpResult; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests related to read ops for wildcard addresses, specifically WFLY-2527. * <p> * Really this test belongs in wildfly-core, but the particularly requirements around the management resource registration * being read are not trivially reproduced, so the test remains in main wildfly where there happens to be an applicable * resource. * </p> * * * @author Brian Stansberry (c) 2013 Red Hat Inc. */ @org.junit.Ignore("WFLY-16418") @RunWith(Arquillian.class) @RunAsClient public class WildCardReadsTestCase extends AbstractCliTestBase { /* * This address meets a particular set of requirements needed to validate the WFLY-2527 fix: * 1) the distributed-cache=dist resource does not actually exist. Therefore eviction=XXX child resources also do not * TBH I'm not certain this aspect is all that critical, but don't blindly remove it. * 2) There is no ManagementResourceRegistration for eviction=* * 3) There are MRR's for eviction=XXX, eviction=YYY, etc * 4) The descriptions for each of those eviction=XXX, eviction=YYY, etc are identical * * TODO add some assertions that validate that 1-4 still hold true, in order to ensure the test continues * to validate the expected behavior */ private static final String OP_PATTERN = "/subsystem=infinispan/cache-container=web/distributed-cache=dist/eviction=%s:%s"; private static final String READ_OP_DESC_OP = ModelDescriptionConstants.READ_OPERATION_DESCRIPTION_OPERATION + "(name=%s)"; private static final String READ_RES_DESC_OP = ModelDescriptionConstants.READ_RESOURCE_DESCRIPTION_OPERATION + "(access-control=combined-descriptions,operations=true,recursive=true)"; private static final String EVICTION = "EVICTION"; @BeforeClass public static void before() throws Exception { initCLI(); } @AfterClass public static void after() throws Exception { closeCLI(); } /** * Tests WFLY-2527 added behavior of supporting read-operation-description for * wildcard addresses where there is no generic resource registration for the type */ @Test public void testLenientReadOperationDescription() throws IOException { cli.sendLine(String.format(OP_PATTERN, EVICTION, ModelDescriptionConstants.READ_OPERATION_NAMES_OPERATION)); CLIOpResult opResult = cli.readAllAsOpResult(); Assert.assertTrue(opResult.isIsOutcomeSuccess()); for (ModelNode node : opResult.getResponseNode().get(ModelDescriptionConstants.RESULT).asList()) { String opPart = String.format(READ_OP_DESC_OP, node.asString()); cli.sendLine(String.format(OP_PATTERN, EVICTION, opPart)); opResult = cli.readAllAsOpResult(); Assert.assertTrue(opResult.isIsOutcomeSuccess()); ModelNode specific = opResult.getResponseNode().get(ModelDescriptionConstants.RESULT); cli.sendLine(String.format(OP_PATTERN, "*", opPart)); opResult = cli.readAllAsOpResult(); Assert.assertTrue(opResult.isIsOutcomeSuccess()); Assert.assertEquals("mismatch for " + node.asString(), specific, opResult.getResponseNode().get(ModelDescriptionConstants.RESULT)); } } /** * Tests WFLY-2527 fix. */ @Test public void testReadResourceDescriptionNoGenericRegistration() throws IOException { cli.sendLine(String.format(OP_PATTERN, EVICTION, READ_RES_DESC_OP)); CLIOpResult opResult = cli.readAllAsOpResult(); Assert.assertTrue(opResult.isIsOutcomeSuccess()); ModelNode specific = opResult.getResponseNode().get(ModelDescriptionConstants.RESULT); cli.sendLine(String.format(OP_PATTERN, "*", READ_RES_DESC_OP)); opResult = cli.readAllAsOpResult(); Assert.assertTrue(opResult.isIsOutcomeSuccess()); ModelNode generic = opResult.getResponseNode().get(ModelDescriptionConstants.RESULT); Assert.assertEquals(ModelType.LIST, generic.getType()); Assert.assertEquals(1, generic.asInt()); Assert.assertEquals(specific, generic.get(0).get(ModelDescriptionConstants.RESULT)); } }
5,786
46.434426
187
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/EarServlet.java
package org.jboss.as.test.integration.management.cli; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; /** * @author Stuart Douglas */ @WebServlet(urlPatterns = "/EarServlet") public class EarServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { InputStream resource = getClass().getClassLoader().getResourceAsStream("jar-info.txt"); try { byte[] data = new byte[100]; int res; while ((res = resource.read(data)) > 0) { resp.getOutputStream().write(data, 0, res); } } finally { resource.close(); } } }
955
29.83871
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/SecurityAuthCommandsTestCase.java
/* Copyright 2018 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.integration.management.cli; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.aesh.complete.AeshCompleteOperation; import org.aesh.readline.completion.Completion; import org.aesh.readline.terminal.formatting.TerminalString; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.cli.CommandContext; import org.jboss.as.cli.CommandContextFactory; import org.jboss.as.cli.Util; import org.jboss.as.cli.impl.CommandContextConfiguration; import org.jboss.as.cli.impl.aesh.cmd.security.model.DefaultResourceNames; import org.jboss.as.cli.impl.aesh.cmd.security.model.ElytronUtil; import org.jboss.as.cli.operation.OperationFormatException; import org.jboss.as.cli.operation.impl.DefaultOperationRequestBuilder; import static org.jboss.as.controller.client.helpers.ClientConstants.FAILURE_DESCRIPTION; import static org.jboss.as.controller.client.helpers.ClientConstants.OUTCOME; import static org.jboss.as.controller.client.helpers.ClientConstants.RESULT; import static org.jboss.as.controller.client.helpers.ClientConstants.SUCCESS; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; /** * * @author [email protected] */ @RunWith(Arquillian.class) public class SecurityAuthCommandsTestCase { private static final ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); private static CommandContext ctx; @ClassRule public static final TemporaryFolder temporaryUserHome = new TemporaryFolder(); private static final String TEST_DOMAIN = "test-domain"; private static final String TEST_HTTP_FACTORY = "test-http-factory"; private static final String TEST_USERS_REALM = "test-users-realm"; private static final String TEST_KS_REALM = "test-ks-realm"; private static final String TEST_FS_REALM = "test-fs-realm"; private static final String TEST_KS = "test-ks"; private static final String TEST_UNDERTOW_DOMAIN = "test-undertow-security-domain"; private static List<ModelNode> originalPropertiesRealms; private static List<ModelNode> originalKSRealms; private static List<ModelNode> originalHttpFactories; private static List<ModelNode> originalSecurityDomains; private static List<ModelNode> originalFSRealms; private static List<ModelNode> originalConstantMappers; private static List<ModelNode> originalConstantRoleMappers; @BeforeClass public static void setup() throws Exception { // Create ctx, used to setup the test and do the final reload. CommandContextConfiguration.Builder configBuilder = new CommandContextConfiguration.Builder(); configBuilder.setConnectionTimeout(TimeoutUtil.adjust(5000)); // default from org.jboss.as.cli.impl.CliConfigImpl configBuilder.setConsoleOutput(consoleOutput).setInitConsole(true). setController("remote+http://" + TestSuiteEnvironment.getServerAddress() + ":" + TestSuiteEnvironment.getServerPort()); ctx = CommandContextFactory.getInstance().newCommandContext(configBuilder.build()); ctx.connectController(); // filesystem realm. addFSRealm(); originalFSRealms = getFileSystemRealms(); originalPropertiesRealms = getPropertiesRealm(); originalHttpFactories = getHttpFactories(); originalSecurityDomains = getSecurityDomains(); originalConstantMappers = getConstantRealmMappers(); originalConstantRoleMappers = getConstantRoleMappers(); originalKSRealms = getKSRealms(); } private static String escapePath(String filePath) { if (Util.isWindows()) { StringBuilder builder = new StringBuilder(); for (char c : filePath.toCharArray()) { if (c == '\\') { builder.append('\\'); } builder.append(c); } return builder.toString(); } else { return filePath; } } private static void addFSRealm() throws Exception { ctx.handle("/subsystem=elytron/filesystem-realm=" + TEST_FS_REALM + ":add(path=" + escapePath(temporaryUserHome.newFolder("identities").getAbsolutePath())); ctx.handle("/subsystem=elytron/filesystem-realm=" + TEST_FS_REALM + ":add-identity(identity=user1"); ctx.handle("/subsystem=elytron/filesystem-realm=" + TEST_FS_REALM + ":set-password(identity=user1,clear={password=mypassword})"); } private static List<ModelNode> getPropertiesRealm() throws Exception { ModelNode props = createOpNode("subsystem=elytron", "read-children-names"); props.get("child-type").set("properties-realm"); List<ModelNode> res = new ArrayList<>(); for (ModelNode mn : executeForResult(props).asList()) { ModelNode prop = createOpNode("subsystem=elytron/properties-realm=" + mn.asString(), "read-resource"); prop.get("recursive").set(Boolean.TRUE); prop.get("recursive-depth").set(100); res.add(executeForResult(prop)); } return res; } private static List<ModelNode> getKSRealms() throws Exception { ModelNode props = createOpNode("subsystem=elytron", "read-children-names"); props.get("child-type").set("key-store-realm"); List<ModelNode> res = new ArrayList<>(); for (ModelNode mn : executeForResult(props).asList()) { ModelNode prop = createOpNode("subsystem=elytron/key-store-realm=" + mn.asString(), "read-resource"); prop.get("recursive").set(Boolean.TRUE); prop.get("recursive-depth").set(100); res.add(executeForResult(prop)); } return res; } private static List<ModelNode> getFileSystemRealms() throws Exception { ModelNode props = createOpNode("subsystem=elytron", "read-children-names"); props.get("child-type").set("filesystem-realm"); List<ModelNode> res = new ArrayList<>(); for (ModelNode mn : executeForResult(props).asList()) { ModelNode prop = createOpNode("subsystem=elytron/filesystem-realm=" + mn.asString(), "read-resource"); prop.get("recursive").set(Boolean.TRUE); prop.get("recursive-depth").set(100); res.add(executeForResult(prop)); } return res; } private static List<String> getNames(String childrenType) throws Exception { ModelNode props = createOpNode("subsystem=elytron", "read-children-names"); props.get("child-type").set(childrenType); List<String> res = new ArrayList<>(); for (ModelNode mn : executeForResult(props).asList()) { res.add(mn.asString()); } return res; } private static List<ModelNode> getHttpFactories() throws Exception { ModelNode props = createOpNode("subsystem=elytron", "read-children-names"); props.get("child-type").set("http-authentication-factory"); List<ModelNode> res = new ArrayList<>(); for (ModelNode mn : executeForResult(props).asList()) { ModelNode prop = createOpNode("subsystem=elytron/http-authentication-factory=" + mn.asString(), "read-resource"); prop.get("recursive").set(Boolean.TRUE); prop.get("recursive-depth").set(100); res.add(executeForResult(prop)); } return res; } private static List<ModelNode> getSecurityDomains() throws Exception { ModelNode props = createOpNode("subsystem=elytron", "read-children-names"); props.get("child-type").set("security-domain"); List<ModelNode> res = new ArrayList<>(); for (ModelNode mn : executeForResult(props).asList()) { ModelNode prop = createOpNode("subsystem=elytron/security-domain=" + mn.asString(), "read-resource"); prop.get("recursive").set(Boolean.TRUE); prop.get("recursive-depth").set(100); res.add(executeForResult(prop)); } return res; } private static List<ModelNode> getConstantRealmMappers() throws Exception { ModelNode props = createOpNode("subsystem=elytron", "read-children-names"); props.get("child-type").set("constant-realm-mapper"); List<ModelNode> res = new ArrayList<>(); for (ModelNode mn : executeForResult(props).asList()) { ModelNode prop = createOpNode("subsystem=elytron/constant-realm-mapper=" + mn.asString(), "read-resource"); prop.get("recursive").set(Boolean.TRUE); prop.get("recursive-depth").set(100); res.add(executeForResult(prop)); } return res; } private static void checkState() throws Exception { Assert.assertEquals(originalConstantMappers, getConstantRealmMappers()); Assert.assertEquals(originalFSRealms, getFileSystemRealms()); Assert.assertEquals(originalHttpFactories, getHttpFactories()); Assert.assertEquals(originalPropertiesRealms, getPropertiesRealm()); Assert.assertEquals(originalKSRealms, getKSRealms()); Assert.assertEquals(originalSecurityDomains, getSecurityDomains()); Assert.assertEquals(originalConstantRoleMappers, getConstantRoleMappers()); } @After public void cleanupTest() throws Exception { try { eraseAllDomains(); eraseAuth(); checkState(); } finally { ctx.handle("reload"); } } private void eraseAuth() throws Exception { try { ModelNode op = createOpNode("subsystem=elytron/http-authentication-factory=" + TEST_HTTP_FACTORY, "remove"); executeForResult(op); } catch (Exception ex) { // OK, } try { ModelNode op = createOpNode("subsystem=elytron/security-domain=" + TEST_DOMAIN, "remove"); executeForResult(op); } catch (Exception ex) { // OK, } try { ModelNode op = createOpNode("subsystem=elytron/properties-realm=" + TEST_USERS_REALM, "remove"); executeForResult(op); } catch (Exception ex) { // OK, } try { ModelNode op = createOpNode("subsystem=elytron/key-store-realm=" + TEST_KS_REALM, "remove"); executeForResult(op); } catch (Exception ex) { // OK, } try { ModelNode removeMapper = createOpNode("subsystem=elytron/constant-realm-mapper=" + TEST_USERS_REALM, "remove"); executeForResult(removeMapper); } catch (Exception ex) { // OK, } try { ModelNode removeMapper = createOpNode("subsystem=elytron/constant-realm-mapper=" + TEST_FS_REALM, "remove"); executeForResult(removeMapper); } catch (Exception ex) { // OK, } try { ModelNode removeMapper = createOpNode("subsystem=elytron/constant-realm-mapper=" + TEST_KS_REALM, "remove"); executeForResult(removeMapper); } catch (Exception ex) { // OK, } try { ModelNode removeMapper = createOpNode("subsystem=elytron/constant-role-mapper=" + DefaultResourceNames.ROLE_MAPPER_NAME, "remove"); executeForResult(removeMapper); } catch (Exception ex) { // OK, } try { ModelNode removeMapper = createOpNode("subsystem=elytron/constant-realm-mapper=ApplicationRealm", "remove"); executeForResult(removeMapper); } catch (Exception ex) { // OK, } try { ModelNode op = createOpNode("subsystem=elytron/key-store=" + TEST_KS, "remove"); executeForResult(op); } catch (Exception ex) { // OK, } } private static void eraseAllDomains() throws Exception { Exception e = null; try { if (domainExists(TEST_UNDERTOW_DOMAIN)) { ModelNode eraseHttp = createOpNode("subsystem=undertow/application-security-domain=" + TEST_UNDERTOW_DOMAIN, "remove"); executeForResult(eraseHttp); } } catch (Exception ex) { if (e == null) { e = ex; } } if (e != null) { throw e; } } @AfterClass public static void cleanup() throws Exception { Exception e = null; if (ctx != null) { try { ctx.handle("/subsystem=elytron/filesystem-realm=" + TEST_FS_REALM + ":remove"); } catch (Exception ex) { if (e == null) { e = ex; } } finally { try { ctx.handle("reload"); } finally { ctx.terminateSession(); } } } if (e != null) { throw e; } } @Test public void testOOBHTTP() throws Exception { ctx.handle("security enable-http-auth-http-server --no-reload --security-domain=" + TEST_UNDERTOW_DOMAIN); Assert.assertEquals(ElytronUtil.OOTB_APPLICATION_DOMAIN, getReferencedSecurityDomain(ctx, TEST_UNDERTOW_DOMAIN)); try { // enabling the same domain using mechanism should fail now ctx.handle("security enable-http-auth-http-server --no-reload --mechanism=BASIC " + "--file-system-realm-name=" + TEST_FS_REALM + " --security-domain=" + TEST_UNDERTOW_DOMAIN); Assert.fail("Enabling using mechanism should have failed"); } catch (Exception e) { MatcherAssert.assertThat(e.getMessage(), CoreMatchers.containsString("Can't mix mechanism and referenced security domain")); } ctx.handle("security disable-http-auth-http-server --no-reload --security-domain=" + TEST_UNDERTOW_DOMAIN); Assert.assertFalse(domainExists(TEST_UNDERTOW_DOMAIN)); } @Test public void testOOBHTTP2() throws Exception { // New factory but reuse OOB ApplicationRealm properties realm. // side effect is to create a constant realm mapper for ApplicationRealm. ctx.handle("security enable-http-auth-http-server --no-reload --mechanism=BASIC " + "--user-properties-file=application-users.properties --group-properties-file=application-roles.properties " + "--relative-to=jboss.server.config.dir --exposed-realm=ApplicationRealm --new-security-domain-name=" + TEST_DOMAIN + " --new-auth-factory-name=" + TEST_HTTP_FACTORY + " --security-domain=" + TEST_UNDERTOW_DOMAIN); Assert.assertEquals(TEST_HTTP_FACTORY, getSecurityDomainAuthFactory(ctx, TEST_UNDERTOW_DOMAIN)); // Check Realm. Assert.assertEquals("ApplicationRealm", getExposedRealmName(TEST_UNDERTOW_DOMAIN, "BASIC")); Assert.assertEquals("ApplicationRealm", getMechanismRealmMapper(TEST_UNDERTOW_DOMAIN, "BASIC")); getNames(Util.CONSTANT_REALM_MAPPER).contains("ApplicationRealm"); // Replace with file system realm. ctx.handle("security enable-http-auth-http-server --no-reload --mechanism=BASIC " + "--file-system-realm-name=" + TEST_FS_REALM + " --security-domain=" + TEST_UNDERTOW_DOMAIN); Assert.assertEquals(TEST_FS_REALM, getMechanismRealmMapper(TEST_UNDERTOW_DOMAIN, "BASIC")); getNames(Util.CONSTANT_REALM_MAPPER).contains(TEST_FS_REALM); // check that domain has both realms. List<String> realms = getDomainRealms(TEST_DOMAIN); Assert.assertTrue(realms.contains("ApplicationRealm")); Assert.assertTrue(realms.contains(TEST_FS_REALM)); try { // enabling the same domain using referenced domain should fail now ctx.handle("security enable-http-auth-http-server --no-reload --security-domain=" + TEST_UNDERTOW_DOMAIN + " --referenced-security-domain=" + ElytronUtil.OOTB_APPLICATION_DOMAIN); Assert.fail("Enabling using referenced domain should have failed"); } catch (Exception e) { MatcherAssert.assertThat(e.getMessage(), CoreMatchers.containsString("Can't mix mechanism and referenced security domain")); } } @Test public void testReferencedSecurityDomainHTTP() throws Exception { ctx.handle("security enable-http-auth-http-server --no-reload --security-domain=" + TEST_UNDERTOW_DOMAIN + " --referenced-security-domain=" + ElytronUtil.OOTB_APPLICATION_DOMAIN); Assert.assertEquals(ElytronUtil.OOTB_APPLICATION_DOMAIN, getReferencedSecurityDomain(ctx, TEST_UNDERTOW_DOMAIN)); ctx.handle("security disable-http-auth-http-server --no-reload --security-domain=" + TEST_UNDERTOW_DOMAIN); Assert.assertFalse(domainExists(TEST_UNDERTOW_DOMAIN)); } @Test public void testCompletion() throws Exception { { String cmd = "security enable-http-auth-http-server "; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); List<String> res = Arrays.asList("--no-reload", "--security-domain="); assertEquals(candidates.toString(), res, candidates); candidates = complete(ctx, cmd, null); assertEquals(candidates.toString(), res, candidates); } { String cmd = "security enable-http-auth-http-server --security-domain=foo "; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); List<String> res = Arrays.asList("--mechanism=", "--no-reload", "--referenced-security-domain="); assertEquals(candidates.toString(), res, candidates); candidates = complete(ctx, cmd, null); assertEquals(candidates.toString(), res, candidates); } { String cmd = "security enable-http-auth-http-server --security-domain=foo " + "--mechanism="; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); List<String> res = Arrays.asList("BASIC", "CLIENT_CERT", "DIGEST", "FORM"); assertTrue(candidates.toString(), candidates.containsAll(res)); candidates = complete(ctx, cmd, null); assertTrue(candidates.toString(), candidates.containsAll(res)); } { String cmd = "security enable-http-auth-http-server --security-domain=foo " + "--mechanism=BASIC "; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); assertFalse(candidates.toString(), candidates.contains("--referenced-security-domain=")); candidates = complete(ctx, cmd, null); assertFalse(candidates.toString(), candidates.contains("--referenced-security-domain=")); } { String cmd = "security enable-http-auth-http-server --security-domain=foo " + "--referenced-security-domain="; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); List<String> res = Arrays.asList("ApplicationDomain"); assertTrue(candidates.toString(), candidates.containsAll(res)); candidates = complete(ctx, cmd, null); assertTrue(candidates.toString(), candidates.containsAll(res)); } { String cmd = "security enable-http-auth-http-server --security-domain=foo " + "--referenced-security-domain=ApplicationDomain "; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); assertFalse(candidates.toString(), candidates.contains("--mechanism=")); candidates = complete(ctx, cmd, null); assertFalse(candidates.toString(), candidates.contains("--mechanism=")); } } @Test public void testHTTP() throws Exception { // Enable and add mechanisms. ctx.handle("security enable-http-auth-http-server --no-reload --mechanism=BASIC" + " --user-properties-file=application-users.properties --group-properties-file=application-roles.properties" + " --relative-to=jboss.server.config.dir --new-security-domain-name=" + TEST_DOMAIN + " --new-auth-factory-name=" + TEST_HTTP_FACTORY + " --new-realm-name=" + TEST_USERS_REALM + " --exposed-realm=ApplicationRealm" + " --security-domain=" + TEST_UNDERTOW_DOMAIN); Assert.assertTrue(getDomainRealms(TEST_DOMAIN).contains(TEST_USERS_REALM)); Assert.assertEquals("ApplicationRealm", getExposedRealmName(TEST_UNDERTOW_DOMAIN, "BASIC")); Assert.assertEquals(TEST_USERS_REALM, getMechanismRealmMapper(TEST_UNDERTOW_DOMAIN, "BASIC")); Assert.assertTrue(getNames(Util.HTTP_AUTHENTICATION_FACTORY).contains(TEST_HTTP_FACTORY)); Assert.assertTrue(getNames(Util.SECURITY_DOMAIN).contains(TEST_DOMAIN)); Assert.assertEquals(Arrays.asList("BASIC"), getMechanisms(TEST_UNDERTOW_DOMAIN)); // Add DIGEST. ctx.handle("security enable-http-auth-http-server --no-reload --mechanism=DIGEST" + " --properties-realm-name=" + TEST_USERS_REALM + " --exposed-realm=ApplicationRealm" + " --security-domain=" + TEST_UNDERTOW_DOMAIN); Assert.assertEquals("ApplicationRealm", getExposedRealmName(TEST_UNDERTOW_DOMAIN, "BASIC")); Assert.assertEquals(TEST_USERS_REALM, getMechanismRealmMapper(TEST_UNDERTOW_DOMAIN, "BASIC")); Assert.assertTrue(getDomainRealms(TEST_DOMAIN).size() == 1); Assert.assertTrue(getDomainRealms(TEST_DOMAIN).contains(TEST_USERS_REALM)); // capture the state. List<ModelNode> factories = getHttpFactories(); List<ModelNode> domains = getSecurityDomains(); List<ModelNode> mappers = getConstantRealmMappers(); List<ModelNode> userRealms = getPropertiesRealm(); List<String> expected1 = Arrays.asList("BASIC", "DIGEST"); Assert.assertEquals(expected1, getMechanisms(TEST_UNDERTOW_DOMAIN)); Assert.assertTrue(getNames(Util.PROPERTIES_REALM).contains(TEST_USERS_REALM)); // Disable digest mechanism ctx.handle("security disable-http-auth-http-server --no-reload --mechanism=DIGEST" + " --security-domain=" + TEST_UNDERTOW_DOMAIN); Assert.assertTrue(getDomainRealms(TEST_DOMAIN).size() == 1); Assert.assertTrue(getDomainRealms(TEST_DOMAIN).contains(TEST_USERS_REALM)); Assert.assertEquals("ApplicationRealm", getExposedRealmName(TEST_UNDERTOW_DOMAIN, "BASIC")); Assert.assertEquals(TEST_USERS_REALM, getMechanismRealmMapper(TEST_UNDERTOW_DOMAIN, "BASIC")); Assert.assertEquals(domains, getSecurityDomains()); //still secured Assert.assertEquals(TEST_HTTP_FACTORY, getSecurityDomainAuthFactory(ctx, TEST_UNDERTOW_DOMAIN)); Assert.assertEquals(Arrays.asList("BASIC"), getMechanisms(TEST_UNDERTOW_DOMAIN)); { // Disable the last mechanism is forbidden boolean failed = false; try { ctx.handle("security disable-http-auth-http-server --no-reload --mechanism=BASIC" + " --security-domain=" + TEST_UNDERTOW_DOMAIN); } catch (Exception ex) { // XXX OK. failed = true; } if (!failed) { throw new Exception("Disabling the last mechanism should have failed"); } } // Re-enable the mechanism ctx.handle("security enable-http-auth-http-server --no-reload --mechanism=DIGEST" + " --properties-realm-name=" + TEST_USERS_REALM + " --exposed-realm=ApplicationRealm" + " --security-domain=" + TEST_UNDERTOW_DOMAIN); Assert.assertEquals("ApplicationRealm", getExposedRealmName(TEST_UNDERTOW_DOMAIN, "BASIC")); Assert.assertEquals(TEST_USERS_REALM, getMechanismRealmMapper(TEST_UNDERTOW_DOMAIN, "BASIC")); Assert.assertEquals("ApplicationRealm", getExposedRealmName(TEST_UNDERTOW_DOMAIN, "DIGEST")); Assert.assertEquals(TEST_USERS_REALM, getMechanismRealmMapper(TEST_UNDERTOW_DOMAIN, "DIGEST")); Assert.assertEquals(expected1, getMechanisms(TEST_UNDERTOW_DOMAIN)); Assert.assertEquals(factories, getHttpFactories()); Assert.assertEquals(domains, getSecurityDomains()); Assert.assertEquals(mappers, getConstantRealmMappers()); Assert.assertEquals(userRealms, getPropertiesRealm()); Assert.assertTrue(getDomainRealms(TEST_DOMAIN).size() == 1); Assert.assertTrue(getDomainRealms(TEST_DOMAIN).contains(TEST_USERS_REALM)); } @Test public void testDisableAuth() throws Exception { boolean failed = false; try { ctx.handle("security disable-http-auth-http-server --no-reload" + " --security-domain=" + TEST_UNDERTOW_DOMAIN); } catch (Exception ex) { // XXX OK. failed = true; } if (!failed) { throw new Exception("Should have fail"); } } @Test public void testHTTPCertificate() throws Exception { ctx.handle("/subsystem=elytron/key-store=" + TEST_KS + ":add(type=JKS, credential-reference={clear-text=pass})"); ctx.handle("security enable-http-auth-http-server --no-reload --mechanism=CLIENT_CERT" + " --key-store-name=" + TEST_KS + " --new-security-domain-name=" + TEST_DOMAIN + " --new-auth-factory-name=" + TEST_HTTP_FACTORY + " --new-realm-name=" + TEST_KS_REALM + " --security-domain=" + TEST_UNDERTOW_DOMAIN); Assert.assertEquals(TEST_KS_REALM, getMechanismRealmMapper(TEST_UNDERTOW_DOMAIN, "CLIENT_CERT")); Assert.assertTrue(getDomainRealms(TEST_DOMAIN).contains(TEST_KS_REALM)); // capture the state. List<ModelNode> factories = getHttpFactories(); List<ModelNode> domains = getSecurityDomains(); List<ModelNode> mappers = getConstantRealmMappers(); List<ModelNode> ksRealms = getKSRealms(); // Re-enable simply by re-using same key-store-realm, no changes expected. ctx.handle("security enable-http-auth-http-server --no-reload --mechanism=CLIENT_CERT" + " --key-store-realm-name=" + TEST_KS_REALM + " --security-domain=" + TEST_UNDERTOW_DOMAIN); Assert.assertEquals(TEST_KS_REALM, getMechanismRealmMapper(TEST_UNDERTOW_DOMAIN, "CLIENT_CERT")); Assert.assertTrue(getDomainRealms(TEST_DOMAIN).contains(TEST_KS_REALM)); Assert.assertEquals(factories, getHttpFactories()); Assert.assertEquals(domains, getSecurityDomains()); Assert.assertEquals(mappers, getConstantRealmMappers()); Assert.assertEquals(ksRealms, getKSRealms()); ctx.handle("security disable-http-auth-http-server --no-reload --security-domain=" + TEST_UNDERTOW_DOMAIN); // Re-enable simply by re-using same key-store-realm with roles, no changes expected other than roles. ctx.handle("security enable-http-auth-http-server --no-reload --mechanism=CLIENT_CERT" + " --key-store-realm-name=" + TEST_KS_REALM + " --roles=FOO,BAR" + " --security-domain=" + TEST_UNDERTOW_DOMAIN); Assert.assertEquals(factories, getHttpFactories()); Assert.assertEquals(mappers, getConstantRealmMappers()); Assert.assertEquals(ksRealms, getKSRealms()); Assert.assertEquals(DefaultResourceNames.ROLE_MAPPER_NAME, getRoleMapper(TEST_KS_REALM, TEST_DOMAIN)); List<String> names = getNames(Util.CONSTANT_ROLE_MAPPER); Assert.assertTrue(names.toString(), names.contains(DefaultResourceNames.ROLE_MAPPER_NAME)); ModelNode roleMapper = getConstantRoleMapper(DefaultResourceNames.ROLE_MAPPER_NAME); List<ModelNode> lst = roleMapper.get(Util.ROLES).asList(); Assert.assertTrue(lst.size() == 2); for (ModelNode r : lst) { if (!r.asString().equals("FOO") && !r.asString().equals("BAR")) { throw new Exception("Invalid roles in " + lst); } } } private static List<String> getMechanisms(String securityDomain) throws Exception { String factory = getSecurityDomainAuthFactory(ctx, securityDomain); ModelNode mecs = createOpNode("subsystem=elytron/http-authentication-factory=" + factory, "read-attribute"); mecs.get("name").set("mechanism-configurations"); List<String> res = new ArrayList<>(); for (ModelNode mn : executeForResult(mecs).asList()) { res.add(mn.get("mechanism-name").asString()); } return res; } private static String getExposedRealmName(String securityDomain, String mec) throws Exception { String factory = getSecurityDomainAuthFactory(ctx, securityDomain); ModelNode mecs = createOpNode("subsystem=elytron/http-authentication-factory=" + factory, "read-attribute"); mecs.get("name").set("mechanism-configurations"); for (ModelNode mn : executeForResult(mecs).asList()) { if (mn.get("mechanism-name").asString().equals(mec)) { return mn.get("mechanism-realm-configurations").asList().get(0).get("realm-name").asString(); } } return null; } private static String getMechanismRealmMapper(String securityDomain, String mec) throws Exception { String factory = getSecurityDomainAuthFactory(ctx, securityDomain); ModelNode mecs = createOpNode("subsystem=elytron/http-authentication-factory=" + factory, "read-attribute"); mecs.get("name").set("mechanism-configurations"); for (ModelNode mn : executeForResult(mecs).asList()) { if (mn.get("mechanism-name").asString().equals(mec)) { return mn.get("realm-mapper").asString(); } } return null; } private static List<String> getDomainRealms(String domain) throws Exception { ModelNode realms = createOpNode("subsystem=elytron/security-domain=" + domain, "read-attribute"); realms.get("name").set("realms"); List<String> lst = new ArrayList<>(); for (ModelNode mn : executeForResult(realms).asList()) { lst.add(mn.get("realm").asString()); } return lst; } private static boolean domainExists(String domain) throws Exception { ModelNode realms = createOpNode("subsystem=undertow", "read-children-names"); realms.get("child-type").set("application-security-domain"); List<ModelNode> mn = executeForResult(realms).asList(); for (ModelNode c : mn) { if (c.asString().equals(domain)) { return true; } } return false; } private static String getSecurityDomainAuthFactory(CommandContext ctx, String domain) throws Exception { return readAttribute(ctx, domain, Util.HTTP_AUTHENTICATION_FACTORY); } private static String getReferencedSecurityDomain(CommandContext ctx, String domain) throws Exception { return readAttribute(ctx, domain, Util.SECURITY_DOMAIN); } private static String readAttribute(CommandContext ctx, String domain, String name) throws Exception { final DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder(); final ModelNode request; try { builder.setOperationName(Util.READ_ATTRIBUTE); builder.addNode(Util.SUBSYSTEM, Util.UNDERTOW); builder.addNode(Util.APPLICATION_SECURITY_DOMAIN, domain); builder.addProperty(Util.NAME, name); request = builder.buildRequest(); } catch (OperationFormatException e) { throw new IllegalStateException("Failed to build operation", e); } final ModelNode outcome = ctx.getModelControllerClient().execute(request); if (Util.isSuccess(outcome)) { boolean hasResult = outcome.has(Util.RESULT); if (hasResult) { if (outcome.get(Util.RESULT).isDefined()) { return outcome.get(Util.RESULT).asString(); } else { return null; } } } throw new Exception("Error retrieving Auth factory " + outcome); } private static String getRoleMapper(String realm, String securityDomain) throws Exception { ModelNode mecs = createOpNode("subsystem=elytron/security-domain=" + securityDomain, "read-attribute"); mecs.get("name").set("realms"); for (ModelNode mn : executeForResult(mecs).asList()) { if (mn.get("realm").asString().equals(realm)) { return mn.get("role-mapper").asString(); } } return null; } private static ModelNode getConstantRoleMapper(String name) throws Exception { ModelNode prop = createOpNode("subsystem=elytron/constant-role-mapper=" + name, "read-resource"); prop.get("recursive").set(Boolean.TRUE); prop.get("recursive-depth").set(100); return executeForResult(prop); } private static List<ModelNode> getConstantRoleMappers() throws Exception { ModelNode props = createOpNode("subsystem=elytron", "read-children-names"); props.get("child-type").set("constant-role-mapper"); List<ModelNode> res = new ArrayList<>(); for (ModelNode mn : executeForResult(props).asList()) { ModelNode prop = createOpNode("subsystem=elytron/constant-role-mapper=" + mn.asString(), "read-resource"); prop.get("recursive").set(Boolean.TRUE); prop.get("recursive-depth").set(100); res.add(executeForResult(prop)); } return res; } private static ModelNode executeForResult(final ModelNode operation) throws Exception { try { final ModelNode result = ctx.getModelControllerClient().execute(operation); checkSuccessful(result, operation); return result.get(RESULT); } catch (IOException e) { throw new RuntimeException(e); } } private static void checkSuccessful(final ModelNode result, final ModelNode operation) throws Exception { if (!SUCCESS.equals(result.get(OUTCOME).asString())) { throw new Exception(result.get( FAILURE_DESCRIPTION).toString()); } } 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; } // This completion is what aesh-readline completion is calling, so more // similar to interactive CLI session private List<String> complete(CommandContext ctx, String cmd, Boolean separator) { Completion<AeshCompleteOperation> completer = (Completion<AeshCompleteOperation>) ctx.getDefaultCommandCompleter(); AeshCompleteOperation op = new AeshCompleteOperation(cmd, cmd.length()); completer.complete(op); if (separator != null) { assertEquals(op.hasAppendSeparator(), separator); } List<String> candidates = new ArrayList<>(); for (TerminalString ts : op.getCompletionCandidates()) { candidates.add(ts.getCharacters()); } // aesh-readline does sort the candidates prior to display. Collections.sort(candidates); return candidates; } }
38,194
44.578759
151
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/DeployWithRuntimeNameTestCase.java
/* * Copyright (C) 2013 Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file * in the distribution for a full listing of individual contributors. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package org.jboss.as.test.integration.management.cli; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; 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.cli.CommandContext; import org.jboss.as.cli.CommandLineException; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import org.jboss.as.test.integration.management.util.CLITestUtil; import org.jboss.as.test.integration.management.util.SimpleHelloWorldServlet; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.junit.After; import org.junit.AfterClass; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.Before; import org.junit.BeforeClass; 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 DeployWithRuntimeNameTestCase { @ArquillianResource URL url; private CommandContext ctx; private File warFile; private String baseUrl; public static final String RUNTIME_NAME = "SimpleServlet.war"; public static final String OTHER_RUNTIME_NAME = "OtherSimpleServlet.war"; private static final String APP_NAME = "simple1"; private static final String OTHER_APP_NAME = "simple2"; @Deployment public static Archive<?> getDeployment() { return ShrinkWrap.create(JavaArchive.class, "dummy.jar").addClass(DeployWithRuntimeNameTestCase.class); } @BeforeClass public static void setupCli() throws Exception { AbstractCliTestBase.initCLI(); } @Before public void setUp() throws Exception { ctx = CLITestUtil.getCommandContext(); ctx.connectController(); baseUrl = getBaseURL(url); } private File createWarFile(String content) throws IOException { WebArchive war = ShrinkWrap.create(WebArchive.class, "HelloServlet.war"); war.addClass(SimpleHelloWorldServlet.class); war.addAsWebInfResource(SimpleHelloWorldServlet.class.getPackage(), "web.xml", "web.xml"); war.addAsWebResource(new StringAsset(content), "page.html"); File tempFile = new File(TestSuiteEnvironment.getTmpDir(), "HelloServlet.war"); new ZipExporterImpl(war).exportTo(tempFile, true); return tempFile; } @AfterClass public static void cleanup() throws Exception { AbstractCliTestBase.closeCLI(); } @After public void undeployAll() { assertThat(warFile.delete(), is(true)); if(ctx != null) { ctx.handleSafe("undeploy " + APP_NAME); ctx.handleSafe("undeploy " +OTHER_APP_NAME); ctx.terminateSession(); } } @Test public void testDeployWithSameRuntimeName() throws Exception { warFile = createWarFile("Version1"); ctx.handle(buildDeployCommand(RUNTIME_NAME, APP_NAME)); checkURL("SimpleServlet/page.html", "Version1", false); checkURL("SimpleServlet/hello", "SimpleHelloWorldServlet", false); warFile = createWarFile("Shouldn't be deployed, as runtime already exist"); try { ctx.handle(buildDeployCommand(RUNTIME_NAME, OTHER_APP_NAME)); } catch(CommandLineException ex) { assertThat(ex.getMessage(), containsString("WFLYSRV0205")); } checkURL("SimpleServlet/hello", "SimpleHelloWorldServlet", false); checkURL("SimpleServlet/page.html", "Version1", false); } @Test public void testDeployWithDifferentRuntimeName() throws Exception { warFile = createWarFile("Version1"); ctx.handle(buildDeployCommand(RUNTIME_NAME, APP_NAME)); checkURL("SimpleServlet/hello", "SimpleHelloWorldServlet", false); checkURL("SimpleServlet/page.html", "Version1", false); warFile = createWarFile("Version2"); ctx.handle(buildDeployCommand(OTHER_RUNTIME_NAME, OTHER_APP_NAME)); checkURL("SimpleServlet/hello", "SimpleHelloWorldServlet", false); checkURL("SimpleServlet/page.html", "Version1", false); checkURL("OtherSimpleServlet/hello", "SimpleHelloWorldServlet", false); checkURL("OtherSimpleServlet/page.html", "Version2",false); } @Test public void testUndeployWithDisabledSameRuntimeName() throws Exception { warFile = createWarFile("Version1"); ctx.handle(buildDeployCommand(RUNTIME_NAME, APP_NAME)); checkURL("SimpleServlet/hello", "SimpleHelloWorldServlet", false); checkURL("SimpleServlet/page.html", "Version1", false); warFile = createWarFile("Version2"); ctx.handle(buildDisabledDeployCommand(RUNTIME_NAME, OTHER_APP_NAME)); checkURL("SimpleServlet/hello", "SimpleHelloWorldServlet", false); checkURL("SimpleServlet/page.html", "Version1", false); ctx.handle(buildUndeployCommand(OTHER_APP_NAME)); checkURL("SimpleServlet/hello", "SimpleHelloWorldServlet", false); checkURL("SimpleServlet/page.html", "Version1", false); } private String buildDeployCommand(String runtimeName, String name) { return "deploy " + warFile.getAbsolutePath() + " --runtime-name=" + runtimeName + " --name=" + name; } private String buildDisabledDeployCommand(String runtimeName, String name) { return "deploy " + warFile.getAbsolutePath() + " --runtime-name=" + runtimeName + " --name=" + name + " --disabled"; } private String buildUndeployCommand(String name) { return "/deployment=" + name + ":undeploy()"; } private void checkURL(String path, String content, boolean shouldFail) throws Exception { boolean failed = false; try { String response = HttpRequest.get(baseUrl + path, 10, TimeUnit.SECONDS); assertThat(response, containsString(content)); } catch (Exception e) { failed = true; if (!shouldFail) { throw new Exception("Http request failed.", e); } } if (shouldFail) { assertThat(baseUrl + path, failed, is(true)); } } private String getBaseURL(URL url) throws MalformedURLException { return new URL(url.getProtocol(), url.getHost(), url.getPort(), "/").toString(); } }
7,976
39.085427
124
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/AddedLibraryServlet.java
package org.jboss.as.test.integration.management.cli; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author Stuart Douglas */ @WebServlet(urlPatterns = "/AddedLibraryServlet") public class AddedLibraryServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("Added Library Servlet"); } }
642
29.619048
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/ArchiveTestCase.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.integration.management.cli; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.cli.CommandContext; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.management.util.CLITestUtil; import org.jboss.as.test.integration.management.util.SimpleServlet; import org.jboss.as.test.shared.TestSuiteEnvironment; 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.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.jboss.shrinkwrap.impl.base.path.BasicPath; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * @author btison * */ @RunWith(Arquillian.class) @RunAsClient public class ArchiveTestCase { private static File cliArchiveFile; @ArquillianResource URL url; @Deployment public static Archive<?> getDeployment() { JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "dummy.jar"); ja.addClass(ArchiveTestCase.class); return ja; } @BeforeClass public static void before() throws Exception { String tempDir = TestSuiteEnvironment.getTmpDir(); WebArchive[] wars = new WebArchive[3]; // deployment1 wars[0] = ShrinkWrap.create(WebArchive.class, "deployment0.war"); wars[0].addClass(SimpleServlet.class); wars[0].addAsWebResource(new StringAsset("Version0"), "page.html"); // deployment2 wars[1] = ShrinkWrap.create(WebArchive.class, "deployment1.war"); wars[1].addClass(SimpleServlet.class); wars[1].addAsWebResource(new StringAsset("Version1"), "page.html"); // deployment3 is included but not deployed wars[2] = ShrinkWrap.create(WebArchive.class, "deployment2.war"); wars[2].addClass(SimpleServlet.class); wars[2].addAsWebResource(new StringAsset("Version2"), "page.html"); //build cli archive EnterpriseArchive cliArchive = ShrinkWrap.create(EnterpriseArchive.class, "archive.cli"); String deploy = "deploy deployment0.war\ndeploy deployment1.war"; String undeploy = "undeploy deployment0.war\nundeploy deployment1.war"; cliArchive.add(new StringAsset(deploy), new BasicPath("/", "install.scr")); // add the default script which shouldn't be picked up cliArchive.add(new StringAsset("deploy deployment0.war\ndeploy deployment1.war\ndeploy deployment2.war"), new BasicPath("/", "deploy.scr")); cliArchive.add(new StringAsset(undeploy), new BasicPath("/", "uninstall.scr")); cliArchive.add(new StringAsset("undeploy deployment0.war\nundeploy deployment1.war\nundeploy deployment2.war"), new BasicPath("/", "undeploy.scr")); for (WebArchive war : wars) { cliArchive.add(war, new BasicPath("/"), ZipExporter.class); } cliArchiveFile = new File(tempDir + File.separator + "archive.cli"); new ZipExporterImpl(cliArchive).exportTo(cliArchiveFile, true); } @Test public void testDeployArchive() throws Exception { final CommandContext ctx = CLITestUtil.getCommandContext(); try { ctx.connectController(); ctx.handle("deploy " + cliArchiveFile.getAbsolutePath() + " --script=install.scr"); // check that now both wars are deployed String response = HttpRequest.get(getBaseURL(url) + "deployment0/SimpleServlet", 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >=0); response = HttpRequest.get(getBaseURL(url) + "deployment1/SimpleServlet", 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >=0); assertTrue(checkUndeployed(getBaseURL(url) + "deployment2/SimpleServlet")); ctx.handle("deploy " + cliArchiveFile.getAbsolutePath() + " --script=uninstall.scr"); // check that both wars are undeployed assertTrue(checkUndeployed(getBaseURL(url) + "deployment0/SimpleServlet")); assertTrue(checkUndeployed(getBaseURL(url) + "deployment1/SimpleServlet")); } finally { ctx.terminateSession(); } } @Test public void testUnDeployArchive() throws Exception { final CommandContext ctx = CLITestUtil.getCommandContext(); try { ctx.connectController(); ctx.handle("deploy " + cliArchiveFile.getAbsolutePath() + " --script=install.scr"); // check that now both wars are deployed String response = HttpRequest.get(getBaseURL(url) + "deployment0/SimpleServlet", 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >=0); response = HttpRequest.get(getBaseURL(url) + "deployment1/SimpleServlet", 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >=0); ctx.handle("undeploy " + "--path=" + cliArchiveFile.getAbsolutePath() + " --script=uninstall.scr"); // check that both wars are undeployed assertTrue(checkUndeployed(getBaseURL(url) + "deployment0/SimpleServlet")); assertTrue(checkUndeployed(getBaseURL(url) + "deployment1/SimpleServlet")); } finally { ctx.terminateSession(); } } @AfterClass public static void after() throws Exception { cliArchiveFile.delete(); } protected final String getBaseURL(URL url) throws MalformedURLException { return new URL(url.getProtocol(), url.getHost(), url.getPort(), "/").toString(); } protected boolean checkUndeployed(String spec) { try { final long firstTry = System.currentTimeMillis(); HttpRequest.get(spec, 10, TimeUnit.SECONDS); while (System.currentTimeMillis() - firstTry <= 1000) { try { Thread.sleep(500); } catch (InterruptedException e) { break; } finally { HttpRequest.get(spec, 10, TimeUnit.SECONDS); } } return false; } catch (Exception e) { } return true; } }
7,986
41.484043
156
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/DeploymentArchiveTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.cli; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.URL; import java.util.concurrent.TimeUnit; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.management.util.SimpleServlet; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.GenericArchive; 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.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * This tests a CLI deployment archive functionality. * See https://community.jboss.org/wiki/CLIDeploymentArchive * * @author Ivo Studensky <[email protected]> */ @RunWith(Arquillian.class) @RunAsClient public class DeploymentArchiveTestCase extends AbstractCliTestBase { private static final String MODULE_NAME = "org.jboss.test.deploymentarchive"; private static final String WEB_ARCHIVE_NAME = "deploymentarchive"; private static final String MODULE_ARCHIVE = "deploymentarchivemodule.jar"; private static final String MODULE_XML_FILE = "module.xml"; private static final String DEPLOY_SCR = "deploy " + WEB_ARCHIVE_NAME + ".war\n" + "module add --name=" + MODULE_NAME + " --resources=" + MODULE_ARCHIVE + " --module-xml=" + MODULE_XML_FILE; private static final String UNDEPLOY_SCR = "undeploy " + WEB_ARCHIVE_NAME + ".war\n" + "module remove --name=" + MODULE_NAME; private static final String MODULE_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<module xmlns=\"urn:jboss:module:1.9\" name=\"" + MODULE_NAME + ">" + " <resources>" + " <resource-root path=\"" + MODULE_ARCHIVE + "\"/>" + " </resources>" + "</module>"; private static File cliFile; @ArquillianResource URL url; @Deployment public static Archive<?> getDeployment() { return ShrinkWrap.create(JavaArchive.class, "dummy.jar") .addClass(DeploymentArchiveTestCase.class); } @BeforeClass public static void before() throws Exception { cliFile = createCliArchive(); AbstractCliTestBase.initCLI(); } @AfterClass public static void after() throws Exception { AbstractCliTestBase.closeCLI(); cliFile.delete(); } @Test public void testDeployUndeploy() throws Exception { testDeploy(); testUndeploy(); } private void testDeploy() throws Exception { // check whether the module is not deployed final File testModuleRoot = new File(getModulePath(), MODULE_NAME.replace('.', File.separatorChar)); assertFalse("Module is already deployed at " + testModuleRoot, testModuleRoot.exists()); // deploy to server cli.sendLine("deploy " + cliFile.getAbsolutePath()); // check war deployment String response = HttpRequest.get(getBaseURL(url) + WEB_ARCHIVE_NAME + "/SimpleServlet", 1000, 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >=0); // check module deployment assertTrue("Module deployment failed! Module dir does not exist: " + testModuleRoot, testModuleRoot.exists()); } private void testUndeploy() throws Exception { //undeploy cli.sendLine("undeploy --path=" + cliFile.getAbsolutePath()); // check undeployment assertTrue(checkUndeployed(getBaseURL(url) + WEB_ARCHIVE_NAME + "/SimpleServlet")); // check module undeployment final File testModuleRoot = new File(getModulePath(), MODULE_NAME.replace('.', File.separatorChar)); assertFalse("Module undeployment failed.", testModuleRoot.exists()); } private static File createCliArchive() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, WEB_ARCHIVE_NAME + ".war"); webArchive.addClass(SimpleServlet.class); final JavaArchive moduleArchive = ShrinkWrap.create(JavaArchive.class, MODULE_ARCHIVE); moduleArchive.addClass(DeploymentArchiveTestCase.class); final GenericArchive cliArchive = ShrinkWrap.create(GenericArchive.class, "deploymentarchive.cli"); cliArchive.add(new StringAsset(DEPLOY_SCR), "deploy.scr"); cliArchive.add(new StringAsset(UNDEPLOY_SCR), "undeploy.scr"); cliArchive.add(webArchive, "/", ZipExporter.class); cliArchive.add(moduleArchive, "/", ZipExporter.class); cliArchive.add(new StringAsset(MODULE_XML), "/", "module.xml"); final String tempDir = TestSuiteEnvironment.getTmpDir(); final File file = new File(tempDir, "deploymentarchive.cli"); cliArchive.as(ZipExporter.class).exportTo(file, true); return file; } private File getModulePath() { String modulePath = TestSuiteEnvironment.getSystemProperty("module.path", null); if (modulePath == null) { String jbossHome = TestSuiteEnvironment.getSystemProperty("jboss.home", null); if (jbossHome == null) { throw new IllegalStateException( "Neither -Dmodule.path nor -Djboss.home were set"); } modulePath = jbossHome + File.separatorChar + "modules"; } else { modulePath = modulePath.split(File.pathSeparator)[0]; } File moduleDir = new File(modulePath); if (!moduleDir.exists()) { throw new IllegalStateException( "Determined module path does not exist"); } if (!moduleDir.isDirectory()) { throw new IllegalStateException( "Determined module path is not a dir"); } return moduleDir; } }
7,508
38.521053
125
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/DataSourceTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.cli; import java.net.URL; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Map; import org.junit.Assert; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.JndiServlet; import org.jboss.as.test.integration.management.util.CLIOpResult; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Dominik Pospisil <[email protected]> */ @RunWith(Arquillian.class) @RunAsClient public class DataSourceTestCase extends AbstractCliTestBase { @ArquillianResource URL url; private static final String[][] DS_PROPS = new String[][] { {"idle-timeout-minutes", "5"} }; @Deployment public static Archive<?> getDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, "DataSourceTestCase.war"); war.addClass(DataSourceTestCase.class); war.addClass(JndiServlet.class); return war; } @BeforeClass public static void before() throws Exception { AbstractCliTestBase.initCLI(); } @AfterClass public static void after() throws Exception { AbstractCliTestBase.closeCLI(); } @Test public void testDataSource() throws Exception { testAddDataSource(); testModifyDataSource(); testRemoveDataSource(); } @Test public void testDataSourceConnectionProperties() throws Exception { testAddDataSourceConnectionProperties(); testModifyDataSource(); testRemoveDataSource(); } @Test public void testXaDataSource() throws Exception { testAddXaDataSource(); testModifyXaDataSource(); testRemoveXaDataSource(); } /** * https://issues.jboss.org/browse/WFLY-12161 */ @Test public void testSharedPreparedStatementsEpxr() throws Exception { cli.sendLine("/system-property=prop:add(value=true)"); testAddDataSourceWithSharedPreparedStatementsEpxr(); testRemoveDataSource(); cli.sendLine("/system-property=prop:remove()"); } /** * https://issues.jboss.org/browse/WFLY-12161 */ @Test public void testXaSharedPreparedStatementsEpxr() throws Exception { cli.sendLine("/system-property=prop:add(value=true)"); testAddXaDataSourceWithSharedPreparedStatementsEpxr(); testRemoveXaDataSource(); cli.sendLine("/system-property=prop:remove()"); } private void testAddDataSource() throws Exception { // add data source cli.sendLine("data-source add --name=TestDS --jndi-name=java:jboss/datasources/TestDS --driver-name=h2 --connection-url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1 --enabled=true"); // check the data source is listed cli.sendLine("cd /subsystem=datasources/data-source"); cli.sendLine("ls"); String ls = cli.readOutput(); assertTrue(ls.contains("TestDS")); // check that it is available through JNDI String jndiClass = JndiServlet.lookup(url.toString(), "java:jboss/datasources/TestDS"); Assert.assertTrue(javax.sql.DataSource.class.isAssignableFrom(Class.forName(jndiClass))); } private void testAddDataSourceConnectionProperties() throws Exception { // add data source cli.sendLine("data-source add --name=TestDS --jndi-name=java:jboss/datasources/TestDS --driver-name=h2 --datasource-class=org.h2.jdbcx.JdbcDataSource --connection-properties={\"url\"=>\"jdbc:h2:mem:test;DB_CLOSE_DELAY=-1\"}"); // check the data source is listed cli.sendLine("cd /subsystem=datasources/data-source"); cli.sendLine("ls"); String ls = cli.readOutput(); assertTrue(ls.contains("TestDS")); // check that it is available through JNDI String jndiClass = JndiServlet.lookup(url.toString(), "java:jboss/datasources/TestDS"); Assert.assertTrue(javax.sql.DataSource.class.isAssignableFrom(Class.forName(jndiClass))); } private void testRemoveDataSource() throws Exception { // remove data source cli.sendLine("data-source remove --name=TestDS"); // cli.sendLine("/subsystem=datasources/data-source=TestDS:remove()"); cli.sendLine("reload"); //check the data source is not listed cli.sendLine("cd /subsystem=datasources/data-source"); cli.sendLine("ls"); String ls = cli.readOutput(); assertFalse(ls.contains("java:jboss/datasources/TestDS")); // check that it is not available through JNDI String jndiClass = JndiServlet.lookup(url.toString(), "java:jboss/datasources/TestDS"); Assert.assertEquals(JndiServlet.NOT_FOUND, jndiClass); } private void testModifyDataSource() throws Exception { StringBuilder cmd = new StringBuilder("data-source --name=TestDS"); for (String[] props : DS_PROPS) { cmd.append(" --"); cmd.append(props[0]); cmd.append("="); cmd.append(props[1]); } cli.sendLine(cmd.toString()); // check that datasource was modified cli.sendLine("/subsystem=datasources/data-source=TestDS:read-resource(recursive=true)"); CLIOpResult result = cli.readAllAsOpResult(); assertTrue(result.getResult().toString(), result.isIsOutcomeSuccess()); assertTrue(result.getResult() instanceof Map); Map dsProps = (Map) result.getResult(); for (String[] props : DS_PROPS) assertTrue(dsProps.get(props[0]).equals(props[1])); } private void testAddXaDataSource() throws Exception { // add data source cli.sendLine("xa-data-source add --name=TestXADS --jndi-name=java:jboss/datasources/TestXADS --driver-name=h2 --xa-datasource-properties={\"url\"=>\"jdbc:h2:mem:test\"}"); //check the data source is listed cli.sendLine("cd /subsystem=datasources/xa-data-source"); cli.sendLine("ls"); String ls = cli.readOutput(); assertTrue(ls.contains("TestXADS")); // check that it is available through JNDI String jndiClass = JndiServlet.lookup(url.toString(), "java:jboss/datasources/TestXADS"); Assert.assertTrue(javax.sql.DataSource.class.isAssignableFrom(Class.forName(jndiClass))); } private void testRemoveXaDataSource() throws Exception { // remove data source cli.sendLine("xa-data-source remove --name=TestXADS"); cli.sendLine("reload"); //check the data source is not listed cli.sendLine("cd /subsystem=datasources/xa-data-source"); cli.sendLine("ls"); String ls = cli.readOutput(); Assert.assertNull(ls); // check that it is no more available through JNDI String jndiClass = JndiServlet.lookup(url.toString(), "java:jboss/datasources/TestXADS"); Assert.assertEquals(JndiServlet.NOT_FOUND, jndiClass); } private void testModifyXaDataSource() throws Exception { StringBuilder cmd = new StringBuilder("xa-data-source --name=TestXADS"); for (String[] props : DS_PROPS) { cmd.append(" --"); cmd.append(props[0]); cmd.append("="); cmd.append(props[1]); } cli.sendLine(cmd.toString()); // check that datasource was modified cli.sendLine("/subsystem=datasources/xa-data-source=TestXADS:read-resource(recursive=true)"); CLIOpResult result = cli.readAllAsOpResult(); assertTrue(result.isIsOutcomeSuccess()); assertTrue(result.getResult() instanceof Map); Map<String,Object> dsProps = (Map<String, Object>) result.getResult(); for (String[] props : DS_PROPS) assertTrue(dsProps.get(props[0]).equals(props[1])); } private void testAddDataSourceWithSharedPreparedStatementsEpxr() throws Exception { // add data source cli.sendLine("data-source add --name=TestDS --jndi-name=java:jboss/datasources/TestDS --driver-name=h2" + " --datasource-class=org.h2.jdbcx.JdbcDataSource --connection-properties={\"url\"=>\"jdbc:h2:mem:test;DB_CLOSE_DELAY=-1\"}"); // check the data source is listed cli.sendLine("cd /subsystem=datasources/data-source"); cli.sendLine("ls"); String ls = cli.readOutput(); assertTrue(ls.contains("TestDS")); } private void testAddXaDataSourceWithSharedPreparedStatementsEpxr() throws Exception { // add data source cli.sendLine("xa-data-source add --name=TestXADS --jndi-name=java:jboss/datasources/TestXADS --driver-name=h2" + " --xa-datasource-properties={\"url\"=>\"jdbc:h2:mem:test\"} --share-prepared-statements=${prop}"); //check the data source is listed cli.sendLine("cd /subsystem=datasources/xa-data-source"); cli.sendLine("ls"); String ls = cli.readOutput(); assertTrue(ls.contains("TestXADS")); } }
10,474
36.544803
234
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/JdbcDriverInfoTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.cli; import java.util.HashMap; import java.util.Map; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Test for high level cli command jdbc-driver-info and jdbc-driver-info [driver-name] */ @RunWith(Arquillian.class) @RunAsClient public class JdbcDriverInfoTestCase extends AbstractCliTestBase { @BeforeClass public static void before() throws Exception { initCLI(); } @AfterClass public static void after() throws Exception { closeCLI(); } @Test public void testJdbcDriverInfo() throws Exception { cli.sendLine("jdbc-driver-info"); String[] lines = cli.readOutput().split("\\n"); Assert.assertEquals(2, lines.length); String[] header = lines[0].split("\\s+"); Assert.assertEquals("NAME", header[0]); Assert.assertEquals("SOURCE", header[1]); String[] driver = lines[1].split("\\s+"); Assert.assertEquals("h2", driver[0]); Assert.assertEquals("com.h2database.h2/main", driver[1]); } @Test public void testJdbcDriverInfoWithDriverParameter() throws Exception { cli.sendLine("jdbc-driver-info h2"); String[] lines = cli.readOutput().split("\\n"); Map<String, String> driverInformation = new HashMap<>(lines.length); for (String line : lines) { String[] info = line.split("\\s+"); driverInformation.put(info[0], info.length == 2 ? info[1] : null); } Assert.assertTrue(driverInformation.containsKey("driver-name")); Assert.assertEquals("h2", driverInformation.get("driver-name")); Assert.assertTrue(driverInformation.containsKey("deployment-name")); Assert.assertTrue(driverInformation.containsKey("driver-module-name")); Assert.assertTrue(driverInformation.containsKey("datasource-class-info")); Assert.assertTrue(driverInformation.containsKey("driver-class-name")); Assert.assertTrue(driverInformation.containsKey("driver-major-version")); Assert.assertTrue(driverInformation.containsKey("driver-minor-version")); } }
3,443
36.846154
86
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/DeploymentOverlayCLITestCase.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.integration.management.cli; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; 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.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.cli.CommandContext; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.management.util.CLITestUtil; import org.jboss.as.test.integration.management.util.SimpleServlet; import org.jboss.as.test.shared.TestSuiteEnvironment; 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.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.ExplodedExporterImpl; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; 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; /** * @author Alexey Loubyansky * * NOTE: References in this file to JavaServer Pages (JSP) refer to the Jakarta Server Pages unless otherwise noted * */ @RunWith(Arquillian.class) @RunAsClient public class DeploymentOverlayCLITestCase { private static File replacedLibrary; private static File addedLibrary; private static File war1; private static File war1_exploded; private static File war2; private static File war2_exploded; private static File war3; private static File ear1; private static File ear1_exploded; private static File ear2; private static File ear2_exploded; private static File webXml; private static File overrideXml; private static File replacedAjsp; @ArquillianResource URL url; private String baseUrl; private CommandContext ctx; @Deployment public static Archive<?> getDeployment() { JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "dummy.jar"); ja.addClass(DeploymentOverlayCLITestCase.class); return ja; } @BeforeClass public static void before() throws Exception { String tempDir = TestSuiteEnvironment.getTmpDir(); WebArchive war; JavaArchive jar; jar = ShrinkWrap.create(JavaArchive.class, "lib.jar"); jar.addClass(ReplacedLibraryServlet.class); jar.add(new StringAsset("replaced library"), "jar-info.txt"); replacedLibrary = new File(tempDir + File.separator + jar.getName()); new ZipExporterImpl(jar).exportTo(replacedLibrary, true); jar = ShrinkWrap.create(JavaArchive.class, "addedlib.jar"); jar.addClass(AddedLibraryServlet.class); addedLibrary = new File(tempDir + File.separator + jar.getName()); new ZipExporterImpl(jar).exportTo(addedLibrary, true); jar = ShrinkWrap.create(JavaArchive.class, "lib.jar"); jar.addClass(OriginalLibraryServlet.class); // deployment1 war = ShrinkWrap.create(WebArchive.class, "deployment0.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(DeploymentOverlayCLITestCase.class.getPackage(), "a.jsp", "a.jsp"); war.addAsWebInfResource(DeploymentOverlayCLITestCase.class.getPackage(), "web.xml", "web.xml"); war.addAsLibraries(jar); File explodedwars_basedir = new File(tempDir + File.separator + "exploded_deployments"); explodedwars_basedir.mkdirs(); war1 = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(war1, true); war1_exploded = new ExplodedExporterImpl(war).exportExploded(explodedwars_basedir); war = ShrinkWrap.create(WebArchive.class, "deployment1.war"); war.addClass(SimpleServlet.class); war.addAsWebInfResource(DeploymentOverlayCLITestCase.class.getPackage(), "web.xml", "web.xml"); war.addAsLibraries(jar); war2 = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(war2, true); war2_exploded = new ExplodedExporterImpl(war).exportExploded(explodedwars_basedir); war = ShrinkWrap.create(WebArchive.class, "another.war"); war.addClass(SimpleServlet.class); war.addAsWebInfResource(DeploymentOverlayCLITestCase.class.getPackage(), "web.xml", "web.xml"); war.addAsLibraries(jar); war3 = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(war3, true); EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "eardeployment1.ear"); ear.addAsModule(war1); ear1 = new File(tempDir + File.separator + ear.getName()); new ZipExporterImpl(ear).exportTo(ear1, true); ear1_exploded = new ExplodedExporterImpl(ear).exportExploded(explodedwars_basedir); war = ShrinkWrap.create(WebArchive.class, "deployment0.war"); war.addClass(SimpleServlet.class); war.addClass(EarServlet.class); war.addAsWebResource(DeploymentOverlayCLITestCase.class.getPackage(), "a.jsp", "a.jsp"); war.addAsWebInfResource(DeploymentOverlayCLITestCase.class.getPackage(), "web.xml", "web.xml"); jar = ShrinkWrap.create(JavaArchive.class, "lib.jar"); jar.add(new StringAsset("original library"), "jar-info.txt"); ear = ShrinkWrap.create(EnterpriseArchive.class, "eardeployment2.ear"); ear.addAsModule(war); ear.addAsLibraries(jar); ear2 = new File(tempDir + File.separator + ear.getName()); new ZipExporterImpl(ear).exportTo(ear2, true); ear2_exploded = new ExplodedExporterImpl(ear).exportExploded(explodedwars_basedir); final URL overrideXmlUrl = DeploymentOverlayCLITestCase.class.getResource("override.xml"); if (overrideXmlUrl == null) { Assert.fail("Failed to locate override.xml"); } overrideXml = new File(overrideXmlUrl.toURI()); if (!overrideXml.exists()) { Assert.fail("Failed to locate override.xml"); } final URL webXmlUrl = DeploymentOverlayCLITestCase.class.getResource("web.xml"); if (webXmlUrl == null) { Assert.fail("Failed to locateweb.xml"); } webXml = new File(webXmlUrl.toURI()); if (!webXml.exists()) { Assert.fail("Failed to locate web.xml"); } final URL ajsp = DeploymentOverlayCLITestCase.class.getResource("a-replaced.jsp"); if (ajsp == null) { Assert.fail("Failed to locate a-replaced.jsp"); } replacedAjsp = new File(ajsp.toURI()); if (!replacedAjsp.exists()) { Assert.fail("Failed to locate a-replaced.jsp"); } } @AfterClass public static void after() throws Exception { war1.delete(); FileUtils.deleteDirectory(war1_exploded); war2.delete(); FileUtils.deleteDirectory(war2_exploded); war3.delete(); ear1.delete(); FileUtils.deleteDirectory(ear1_exploded); ear2.delete(); FileUtils.deleteDirectory(ear2_exploded); replacedLibrary.delete(); // replacedAjsp.delete(); addedLibrary.delete(); } protected final String getBaseURL(URL url) throws MalformedURLException { return new URL(url.getProtocol(), url.getHost(), url.getPort(), "/").toString(); } @Before public void setUp() throws Exception { ctx = CLITestUtil.getCommandContext(); ctx.connectController(); baseUrl = getBaseURL(url); } @After public void tearDown() throws Exception { if (ctx != null) { ctx.handleSafe("undeploy " + war1.getName()); ctx.handleSafe("undeploy " + war2.getName()); ctx.handleSafe("undeploy " + war3.getName()); ctx.handleSafe("undeploy " + ear1.getName()); ctx.handleSafe("undeploy " + ear2.getName()); ctx.handleSafe("deployment-overlay remove --name=overlay-test"); ctx.handleSafe("deployment-overlay remove --name=overlay1"); ctx.handleSafe("deployment-overlay remove --name=overlay2"); ctx.handleSafe("deployment-overlay remove --name=overlay3"); ctx.terminateSession(); } } @Test public void testSimpleOverride() throws Exception { simpleOverrideTest(false); } @Test public void testSimpleOverrideMultipleDeploymentOverlay() throws Exception { simpleOverrideTest(true); } private void simpleOverrideTest(boolean multipleOverlay) throws Exception { ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); if (multipleOverlay) { ctx.handle("deployment-overlay add --name=overlay1 --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + " --deployments=" + war1.getName()); ctx.handle("deployment-overlay add --name=overlay2 --content=WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); ctx.handle("deployment-overlay add --name=overlay3 --content=WEB-INF/lib/addedlib.jar=" + addedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); } else { ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + ",WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + ",WEB-INF/lib/addedlib.jar=" + addedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); } String response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); ctx.handle("/deployment=" + war1.getName() + ":redeploy"); ctx.handle("/deployment=" + war2.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); //now test JSP assertEquals("Replaced JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); //now test Libraries assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); assertEquals("Added Library Servlet", HttpRequest.get(baseUrl + "deployment0/AddedLibraryServlet", 10, TimeUnit.SECONDS).trim()); } @Test public void testSimpleOverrideExploded() throws Exception { simpleOverrideExplodedTest(false); } @Test public void testSimpleOverrideExplodedMultipleDeploymentOverlay() throws Exception { simpleOverrideExplodedTest(true); } private void simpleOverrideExplodedTest(boolean multiple) throws Exception { ctx.handle("/deployment=" + war1_exploded.getName() + ":add(content=[{\"path\"=>\"" + war1_exploded.getAbsolutePath().replace("\\", "\\\\") + "\",\"archive\"=>false}], enabled=true)"); ctx.handle("/deployment=" + war2_exploded.getName() + ":add(content=[{\"path\"=>\"" + war2_exploded.getAbsolutePath().replace("\\", "\\\\") + "\",\"archive\"=>false}], enabled=true)"); if (multiple) { ctx.handle("deployment-overlay add --name=overlay1 --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + " --deployments=" + war1_exploded.getName()); ctx.handle("deployment-overlay add --name=overlay2 --content=WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + war1_exploded.getName()); ctx.handle("deployment-overlay add --name=overlay3 --content=WEB-INF/lib/addedlib.jar=" + addedLibrary.getAbsolutePath() + " --deployments=" + war1_exploded.getName()); } else { ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + ",WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + ",WEB-INF/lib/addedlib.jar=" + addedLibrary.getAbsolutePath() + " --deployments=" + war1_exploded.getName()); } String response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); ctx.handle("/deployment=" + war1_exploded.getName() + ":redeploy"); ctx.handle("/deployment=" + war2_exploded.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); // replacing JSP files in exploded deployments is not supported - see WFLY-2989 for more details // assertEquals("Replaced JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); //now test Libraries assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); assertEquals("Added Library Servlet", HttpRequest.get(baseUrl + "deployment0/AddedLibraryServlet", 10, TimeUnit.SECONDS).trim()); } @Test public void testSimpleOverrideInEarAtWarLevel() throws Exception { simpleOverrideInEarAtWarLevelTest(false); } @Test public void testSimpleOverrideInEarAtWarLevelMultipleDeploymentOverlay() throws Exception { simpleOverrideInEarAtWarLevelTest(true); } private void simpleOverrideInEarAtWarLevelTest(boolean multiple) throws Exception { ctx.handle("deploy " + ear1.getAbsolutePath()); if (multiple) { ctx.handle("deployment-overlay add --name=overlay1 --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + " --deployments=" + war1.getName()); ctx.handle("deployment-overlay add --name=overlay2 --content=WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); } else { ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + ",WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); } String response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); ctx.handle("/deployment=" + ear1.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); //now test JSP assertEquals("Replaced JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); //now test Libraries assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); } @Test public void testSimpleOverrideInEarAtWarLevelExploded() throws Exception { simpleOverrideInEarAtWarLevelExplodedTest(false); } @Test public void testSimpleOverrideInEarAtWarLevelExplodedMultipleDeploymentOverlay() throws Exception { simpleOverrideInEarAtWarLevelExplodedTest(true); } private void simpleOverrideInEarAtWarLevelExplodedTest(boolean multiple) throws Exception { ctx.handle("/deployment=" + ear1_exploded.getName() + ":add(content=[{\"path\"=>\"" + ear1_exploded.getAbsolutePath().replace("\\", "\\\\") + "\",\"archive\"=>false}], enabled=true)"); if (multiple) { ctx.handle("deployment-overlay add --name=overlay1 --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + " --deployments=" + war1.getName()); ctx.handle("deployment-overlay add --name=overlay2 --content=WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); } else { ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + ",WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); } String response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); ctx.handle("/deployment=" + ear1_exploded.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); //now test JSP (it works here, because only the EAR is exploded, the inner WAR is not) assertEquals("Replaced JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); //now test Libraries assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); } @Test public void testSimpleOverrideInEarAtEarLevel() throws Exception { ctx.handle("deploy " + ear2.getAbsolutePath()); ctx.handle("deployment-overlay add --name=overlay-test --content=lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + ear2.getName()); //now test Libraries assertEquals("original library", HttpRequest.get(baseUrl + "deployment0/EarServlet", 10, TimeUnit.SECONDS).trim()); ctx.handle("/deployment=" + ear2.getName() + ":redeploy"); //now test Libraries assertEquals("replaced library", HttpRequest.get(baseUrl + "deployment0/EarServlet", 10, TimeUnit.SECONDS).trim()); } @Test public void testSimpleOverrideInEarAtEarLevelExploded() throws Exception { ctx.handle("/deployment=" + ear2_exploded.getName() + ":add(content=[{\"path\"=>\"" + ear2_exploded.getAbsolutePath().replace("\\", "\\\\") + "\",\"archive\"=>false}], enabled=true)"); ctx.handle("deployment-overlay add --name=overlay-test --content=lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + ear2_exploded.getName()); //now test Libraries assertEquals("original library", HttpRequest.get(baseUrl + "deployment0/EarServlet", 10, TimeUnit.SECONDS).trim()); ctx.handle("/deployment=" + ear2_exploded.getName() + ":redeploy"); //now test Libraries assertEquals("replaced library", HttpRequest.get(baseUrl + "deployment0/EarServlet", 10, TimeUnit.SECONDS).trim()); } @Test public void testSimpleOverrideWithRedeployAffected() throws Exception { simpleOverrideWithRedeployAffectedTest(false); } @Test public void testSimpleOverrideWithRedeployAffectedMultipleDeploymentOverlay() throws Exception { simpleOverrideWithRedeployAffectedTest(true); } private void simpleOverrideWithRedeployAffectedTest(boolean multiple) throws Exception { ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); String response1 = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response1); if (multiple) { ctx.handle("deployment-overlay add --name=overlay1 --content=a.jsp=" + replacedAjsp.getAbsolutePath() + " --deployments=" + war1.getName()); ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=" + war1.getName() + " --redeploy-affected"); } else { ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=" + war1.getName() + " --redeploy-affected"); } String response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); if (multiple) { //now test JSP assertEquals("Replaced JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); } } @Test public void testWildcardOverride() throws Exception { wildcardOverrideTest(false); } @Test public void testWildcardOverrideMultipleDeploymentOverlay() throws Exception { wildcardOverrideTest(true); } private void wildcardOverrideTest(boolean multiple) throws Exception { if (multiple) { ctx.handle("deployment-overlay add --name=overlay1 --content=WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=deployment*.war"); } ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=deployment*.war"); ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); ctx.handle("deploy " + war3.getAbsolutePath()); String response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); if (multiple) { assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment1/LibraryServlet", 10, TimeUnit.SECONDS).trim()); } } @Test public void testWildcardOverrideWithRedeployAffected() throws Exception { wildcardOverrideWithRedeployAffectedTest(false); } @Test public void testWildcardOverrideWithRedeployAffectedMultipleDeploymentOverlay() throws Exception { wildcardOverrideWithRedeployAffectedTest(true); } private void wildcardOverrideWithRedeployAffectedTest(boolean multiple) throws Exception { ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); ctx.handle("deploy " + war3.getAbsolutePath()); if (multiple) { ctx.handle("deployment-overlay add --name=overlay1 --content=WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=deployment*.war"); } ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=deployment*.war --redeploy-affected"); //Thread.sleep(2000); String response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); if (multiple) { assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment1/LibraryServlet", 10, TimeUnit.SECONDS).trim()); } } @Test public void testMultipleLinks() throws Exception { ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=" + war1.getName()); ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); ctx.handle("deploy " + war3.getAbsolutePath()); String response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); ctx.handle("deployment-overlay link --name=overlay-test --deployments=a*.war"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); ctx.handle("/deployment=" + war1.getName() + ":redeploy"); ctx.handle("/deployment=" + war2.getName() + ":redeploy"); ctx.handle("/deployment=" + war3.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("OVERRIDDEN", response); ctx.handle("deployment-overlay link --name=overlay-test --deployments=" + war2.getName() + " --redeploy-affected"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("OVERRIDDEN", response); response = readResponse("another"); assertEquals("OVERRIDDEN", response); ctx.handle("deployment-overlay remove --name=overlay-test --deployments=" + war2.getName() + " --redeploy-affected"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("OVERRIDDEN", response); ctx.handle("deployment-overlay remove --name=overlay-test --deployments=a*.war"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("OVERRIDDEN", response); ctx.handle("/deployment=" + war1.getName() + ":redeploy"); ctx.handle("/deployment=" + war2.getName() + ":redeploy"); ctx.handle("/deployment=" + war3.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); ctx.handle("deployment-overlay remove --name=overlay-test --content=WEB-INF/web.xml --redeploy-affected"); response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); ctx.handle("deployment-overlay upload --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --redeploy-affected"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); } @Test public void testRedeployAffected() throws Exception { ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); ctx.handle("deploy " + war3.getAbsolutePath()); ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath()); ctx.handle("deployment-overlay link --name=overlay-test --deployments=deployment0.war,a*.war"); String response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); ctx.handle("deployment-overlay redeploy-affected --name=overlay-test"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("OVERRIDDEN", response); } @Test public void testSimpleOverrideRemoveOverlay() throws Exception { ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); ctx.handle("deployment-overlay add --name=" + "overlay-test --content=" + "WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + "," + "a.jsp=" + replacedAjsp.getAbsolutePath() + "," + "WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + "," + "WEB-INF/lib/addedlib.jar=" + addedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); String response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); ctx.handle("/deployment=" + war1.getName() + ":redeploy"); ctx.handle("/deployment=" + war2.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); //now test JSP assertEquals("Replaced JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); //now test Libraries assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); assertEquals("Added Library Servlet", HttpRequest.get(baseUrl + "deployment0/AddedLibraryServlet", 10, TimeUnit.SECONDS).trim()); ctx.handleSafe("deployment-overlay remove --name=overlay-test"); ctx.handle("/deployment=" + war1.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); //now test Libraries assertEquals("Original Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); try { // Assert.assertNotEquals("Added Library Servlet", HttpRequest.get(baseUrl + "deployment0/AddedLibraryServlet", 10, TimeUnit.SECONDS).trim()); HttpRequest.get(baseUrl + "deployment0/AddedLibraryServlet", 10, TimeUnit.SECONDS); Assert.fail(); } catch (IOException e) { //ok } //now test JSP assertEquals("Original JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); } @Test public void testSimpleOverrideRemoveOverlay2() throws Exception { ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); ctx.handle("deployment-overlay add --name=" + "overlay-test --content=" + "a.jsp=" + replacedAjsp.getAbsolutePath() + "," + " --deployments=" + war1.getName()); String response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); ctx.handle("/deployment=" + war1.getName() + ":redeploy"); ctx.handle("/deployment=" + war2.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); //now test JSP assertEquals("Replaced JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); ctx.handleSafe("deployment-overlay remove --name=overlay-test"); ctx.handle("/deployment=" + war1.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); //now test JSP assertEquals("Original JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); } protected String readResponse(String warName) throws IOException, ExecutionException, TimeoutException { return HttpRequest.get(baseUrl + warName + "/SimpleServlet?env-entry=overlay-test", 10, TimeUnit.SECONDS).trim(); } }
34,863
42.854088
215
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/ArchiveDefaultScriptNamesTestCase.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.integration.management.cli; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.cli.CommandContext; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.management.util.CLITestUtil; import org.jboss.as.test.integration.management.util.SimpleServlet; import org.jboss.as.test.shared.TestSuiteEnvironment; 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.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.jboss.shrinkwrap.impl.base.path.BasicPath; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * @author btison * */ @RunWith(Arquillian.class) @RunAsClient public class ArchiveDefaultScriptNamesTestCase { private static File cliArchiveFile; @ArquillianResource URL url; @Deployment public static Archive<?> getDeployment() { JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "dummy.jar"); ja.addClass(ArchiveDefaultScriptNamesTestCase.class); return ja; } @BeforeClass public static void before() throws Exception { String tempDir = TestSuiteEnvironment.getTmpDir(); WebArchive[] wars = new WebArchive[3]; // deployment1 wars[0] = ShrinkWrap.create(WebArchive.class, "deployment0.war"); wars[0].addClass(SimpleServlet.class); wars[0].addAsWebResource(new StringAsset("Version0"), "page.html"); // deployment2 wars[1] = ShrinkWrap.create(WebArchive.class, "deployment1.war"); wars[1].addClass(SimpleServlet.class); wars[1].addAsWebResource(new StringAsset("Version1"), "page.html"); // deployment3 is included but not deployed wars[2] = ShrinkWrap.create(WebArchive.class, "deployment2.war"); wars[2].addClass(SimpleServlet.class); wars[2].addAsWebResource(new StringAsset("Version2"), "page.html"); //build cli archive EnterpriseArchive cliArchive = ShrinkWrap.create(EnterpriseArchive.class, "archive.cli"); String deploy = "deploy deployment0.war\ndeploy deployment1.war"; String undeploy = "undeploy deployment0.war\nundeploy deployment1.war"; cliArchive.add(new StringAsset(deploy), new BasicPath("/", "deploy.scr")); cliArchive.add(new StringAsset(undeploy), new BasicPath("/", "undeploy.scr")); for (WebArchive war : wars) { cliArchive.add(war, new BasicPath("/"), ZipExporter.class); } cliArchiveFile = new File(tempDir + File.separator + "archive.cli"); new ZipExporterImpl(cliArchive).exportTo(cliArchiveFile, true); } @Test public void testDeployUndeployArchive() throws Exception { final CommandContext ctx = CLITestUtil.getCommandContext(); try { ctx.connectController(); ctx.handle("deploy " + cliArchiveFile.getAbsolutePath()); // check that now both wars are deployed String response = HttpRequest.get(getBaseURL(url) + "deployment0/SimpleServlet", 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >=0); response = HttpRequest.get(getBaseURL(url) + "deployment1/SimpleServlet", 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >=0); assertTrue(checkUndeployed(getBaseURL(url) + "deployment2/SimpleServlet")); ctx.handle("undeploy " + "--path=" + cliArchiveFile.getAbsolutePath()); // check that both wars are undeployed assertTrue(checkUndeployed(getBaseURL(url) + "deployment0/SimpleServlet")); assertTrue(checkUndeployed(getBaseURL(url) + "deployment1/SimpleServlet")); } finally { ctx.terminateSession(); } } @AfterClass public static void after() throws Exception { cliArchiveFile.delete(); } protected final String getBaseURL(URL url) throws MalformedURLException { return new URL(url.getProtocol(), url.getHost(), url.getPort(), "/").toString(); } protected boolean checkUndeployed(String spec) { try { final long firstTry = System.currentTimeMillis(); HttpRequest.get(spec, 10, TimeUnit.SECONDS); while (System.currentTimeMillis() - firstTry <= 1000) { try { Thread.sleep(500); } catch (InterruptedException e) { break; } finally { HttpRequest.get(spec, 10, TimeUnit.SECONDS); } } return false; } catch (Exception e) { } return true; } }
6,451
39.074534
115
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/UndeployWildcardTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.cli; import static org.junit.Assert.fail; import java.io.File; import java.net.URL; import java.util.HashSet; import java.util.Set; 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.cli.CommandContext; import org.jboss.as.test.integration.management.util.CLITestUtil; import org.jboss.as.test.integration.management.util.SimpleServlet; import org.jboss.as.test.shared.TestSuiteEnvironment; 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.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.jboss.shrinkwrap.impl.base.path.BasicPath; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Alexey Loubyansky */ @RunWith(Arquillian.class) @RunAsClient public class UndeployWildcardTestCase { @ArquillianResource URL url; private static File[] appFiles; private CommandContext ctx; @Deployment public static Archive<?> getDeployment() { JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "dummy.jar"); ja.addClass(UndeployWildcardTestCase.class); return ja; } @BeforeClass public static void before() throws Exception { String tempDir = TestSuiteEnvironment.getSystemProperty("java.io.tmpdir"); appFiles = new File[4]; // deployment1 WebArchive war = ShrinkWrap.create(WebArchive.class, "cli-test-app1.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(new StringAsset("Version0"), "page.html"); appFiles[0] = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(appFiles[0], true); // deployment2 war = ShrinkWrap.create(WebArchive.class, "cli-test-app2.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(new StringAsset("Version1"), "page.html"); appFiles[1] = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(appFiles[1], true); // deployment3 war = ShrinkWrap.create(WebArchive.class, "cli-test-another.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(new StringAsset("Version2"), "page.html"); appFiles[2] = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(appFiles[2], true); // deployment4 war = ShrinkWrap.create(WebArchive.class, "cli-test-app3.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(new StringAsset("Version3"), "page.html"); final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "cli-test-app.ear"); ear.add(war, new BasicPath("/"), ZipExporter.class); appFiles[3] = new File(tempDir + File.separator + ear.getName()); new ZipExporterImpl(ear).exportTo(appFiles[3], true); } @AfterClass public static void after() throws Exception { for(File f : appFiles) { f.delete(); } } private Set<String> afterTestDeployments; @Before public void beforeTest() throws Exception { ctx = CLITestUtil.getCommandContext(); ctx.connectController(); for(File f : appFiles) { ctx.handle("deploy " + f.getAbsolutePath()); } afterTestDeployments = new HashSet<String>(); } @After public void afterTest() throws Exception { StringBuilder buf = null; for(File f : appFiles) { ctx.handleSafe("undeploy " + f.getName()); if(ctx.getExitCode() == 0) { if(!afterTestDeployments.remove(f.getName())) { if(buf == null) { buf = new StringBuilder(); buf.append("Undeployed unexpected content: "); buf.append(f.getName()); } else { buf.append(", ").append(f.getName()); } } } } ctx.terminateSession(); if(buf != null) { fail(buf.toString()); } if(afterTestDeployments.size() > 0) { fail("Expected to undeploy but failed to: " + afterTestDeployments); } } @Test public void testUndeployAllWars() throws Exception { ctx.handle("undeploy *.war"); afterTestDeployments.add(appFiles[3].getName()); } @Test public void testUndeployCliTestApps() throws Exception { ctx.handle("undeploy cli-test-app*"); afterTestDeployments.add(appFiles[2].getName()); } @Test public void testUndeployTestAps() throws Exception { ctx.handle("undeploy *test-ap*"); afterTestDeployments.add(appFiles[2].getName()); } @Test public void testUndeployTestAs() throws Exception { ctx.handle("undeploy *test-a*"); } @Test public void testUndeployTestAWARs() throws Exception { ctx.handle("undeploy *test-a*.war"); afterTestDeployments.add(appFiles[3].getName()); } }
6,688
34.579787
101
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/RemoveEJBSubsystemTestCase.java
/* * JBoss, Home of Professional Open Source * Copyright 2018, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.management.cli; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.security.common.CoreUtils; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE; /** * Test removes EJB subsystem using the CLI command and checks if no error occurred. * * Automated test for [ WFLY-9405 ] * * @author Daniel Cihak */ @RunWith(Arquillian.class) @ServerSetup(SnapshotRestoreSetupTask.class) @RunAsClient public class RemoveEJBSubsystemTestCase { private static final String DEPLOYMENT = "deployment"; @ContainerResource private ManagementClient managementClient; @Deployment(name = DEPLOYMENT) public static WebArchive createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war"); war.addClass(RemoveEJBSubsystemTestCase.class); return war; } @Test public void testRemoveEJBSubsystem() throws Exception { // /subsystem=ejb3/service=remote/channel-creation-options=MAX_OUTBOUND_MESSAGES:remove ModelNode removeOp = new ModelNode(); removeOp.get(OP).set(REMOVE); removeOp.get(OP_ADDR).add("subsystem", "ejb3"); removeOp.get(OP_ADDR).add("service", "remote"); removeOp.get(OP_ADDR).add("channel-creation-options", "MAX_OUTBOUND_MESSAGES"); CoreUtils.applyUpdate(removeOp, managementClient.getControllerClient()); } }
2,945
39.356164
95
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/SecurityCommandsTestCase.java
/* Copyright 2018 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.integration.management.cli; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.aesh.complete.AeshCompleteOperation; import org.aesh.readline.completion.Completion; import org.aesh.readline.terminal.formatting.TerminalString; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.cli.CommandContext; import org.jboss.as.cli.CommandContextFactory; import org.jboss.as.cli.CommandLineException; import org.jboss.as.cli.Util; import org.jboss.as.cli.impl.CommandContextConfiguration; import org.jboss.as.cli.operation.OperationFormatException; import org.jboss.as.cli.operation.impl.DefaultOperationRequestBuilder; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; /** * * @author [email protected] */ @RunWith(Arquillian.class) public class SecurityCommandsTestCase { private static final String TEST_SOCKET_BINDING="foo"; private static final String DEFAULT_SERVER = "default-server"; private static final String DEFAULT_KEY_STORE = "applicationKS"; private static final String DEFAULT_KEY_MANAGER = "applicationKM"; private static final String DEFAULT_SSL_CONTEXT = "applicationSSC"; private static final int DEFAULT_NUM_KEY_STORES = 1; private static final int DEFAULT_NUM_KEY_MANAGERS = 1; private static final int DEFAULT_NUM_TRUST_MANAGERS = 0; private static final int DEFAULT_NUM_SSL_CONTEXTS = 1; private static final ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); private static CommandContext ctx; private static final String GENERATED_KEY_STORE_FILE_NAME = "gen-key-store.keystore"; private static final String GENERATED_PEM_FILE_NAME = "gen-key-store.pem"; private static final String GENERATED_CSR_FILE_NAME = "gen-key-store.csr"; private static final String GENERATED_KEY_STORE_PASSWORD = "mysecret"; private static final String GENERATED_KEY_STORE_ALIAS = "myalias"; private static final String GENERATED_TRUST_STORE_FILE_NAME = "gen-trust-store.truststore"; private static final String SERVER_KEY_STORE_FILE = "cli-security-test-server.keystore"; private static final String CLIENT_KEY_STORE_FILE = "cli-security-test-client.keystore"; private static final String CLIENT_CERTIFICATE_FILE = "cli-security-test-client-certificate.pem"; private static final String KEY_STORE_PASSWORD = "secret"; private static final String KEY_STORE_NAME = "ks1"; private static final String KEY_MANAGER_NAME = "km1"; private static final String TRUST_STORE_NAME = "ts1"; private static final String TRUST_MANAGER_NAME = "tm1"; private static final String SSL_CONTEXT_NAME = "sslCtx1"; private static File serverKeyStore; private static File clientKeyStore; private static File clientCertificate; @ClassRule public static final TemporaryFolder temporaryUserHome = new TemporaryFolder(); @BeforeClass public static void setup() throws Exception { // Create ctx, used to setup the test and do the final reload. CommandContextConfiguration.Builder configBuilder = new CommandContextConfiguration.Builder(); configBuilder.setConnectionTimeout(TimeoutUtil.adjust(5000)); // default from org.jboss.as.cli.impl.CliConfigImpl configBuilder.setConsoleOutput(consoleOutput).setInitConsole(true). setController("remote+http://" + TestSuiteEnvironment.getServerAddress() + ":" + TestSuiteEnvironment.getServerPort()); ctx = CommandContextFactory.getInstance().newCommandContext(configBuilder.build()); ctx.connectController(); // generate key-store file for server. ctx.handle("/subsystem=elytron/key-store=cli-server-key-store:add(path=" + SERVER_KEY_STORE_FILE + " ,type=JKS" + ", relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + ", credential-reference={clear-text=" + KEY_STORE_PASSWORD + "})"); ctx.handle("/subsystem=elytron/key-store=cli-server-key-store:generate-key-pair(distinguished-name=\"CN=CA\", algorithm=RSA, key-size=1024, alias=localhost)"); ctx.handle("/subsystem=elytron/key-store=cli-server-key-store:store()"); // Remove the key-store resource. ctx.handle("/subsystem=elytron/key-store=cli-server-key-store:remove()"); serverKeyStore = new File(TestSuiteEnvironment.getSystemProperty("jboss.home") + File.separator + "standalone" + File.separator + "configuration" + File.separator + SERVER_KEY_STORE_FILE); if (!serverKeyStore.exists()) { throw new Exception("No key-store generated :" + serverKeyStore); } // generate key-store file for client. ctx.handle("/subsystem=elytron/key-store=cli-client-key-store:add(path=" + CLIENT_KEY_STORE_FILE + " ,type=JKS" + ", relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + ", credential-reference={clear-text=" + KEY_STORE_PASSWORD + "})"); ctx.handle("/subsystem=elytron/key-store=cli-client-key-store:generate-key-pair(distinguished-name=\"CN=CA\", algorithm=RSA, key-size=1024, alias=client)"); ctx.handle("/subsystem=elytron/key-store=cli-client-key-store:store()"); // export the client certificate. ctx.handle("/subsystem=elytron/key-store=cli-client-key-store:export-certificate(relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + ",path=" + CLIENT_CERTIFICATE_FILE + ", alias=client, pem=true)"); // Remove the key-store resource. ctx.handle("/subsystem=elytron/key-store=cli-client-key-store:remove()"); clientKeyStore = new File(TestSuiteEnvironment.getSystemProperty("jboss.home") + File.separator + "standalone" + File.separator + "configuration" + File.separator + CLIENT_KEY_STORE_FILE); if (!clientKeyStore.exists()) { throw new Exception("No key-store generated"); } clientCertificate = new File(TestSuiteEnvironment.getSystemProperty("jboss.home") + File.separator + "standalone" + File.separator + "configuration" + File.separator + CLIENT_CERTIFICATE_FILE); if (!clientCertificate.exists()) { throw new Exception("No certificate exported"); } //ctx.handle("/subsystem=undertow/server=default-server/https-listener=https:undefine-attribute(name=ssl-context"); } @After public void cleanupTest() throws Exception { try { removeTLS(); removeCustomHTTPSListeners(); } finally { ctx.handle("reload"); } } @AfterClass public static void cleanup() throws Exception { if (serverKeyStore != null) { serverKeyStore.delete(); } if (clientKeyStore != null) { clientKeyStore.delete(); } if (clientCertificate != null) { clientCertificate.delete(); } if (ctx != null) { try { ctx.handle("/subsystem=undertow/server=default-server/https-listener=https:write-attribute(name=ssl-context, value=applicationSSC"); ctx.handle("reload"); } finally { ctx.terminateSession(); } } } @Test public void testInvalidEnableSSL() throws Exception { assertEmptyModel(null); { boolean failed = false; try { ctx.handle("security enable-ssl-http-server"); } catch (Exception ex) { failed = true; // XXX OK, expected } Assert.assertTrue(failed); assertEmptyModel(null); } { boolean failed = false; try { ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload" + " --server-name=foo"); } catch (Exception ex) { failed = true; // XXX OK, expected } Assert.assertTrue(failed); assertEmptyModel(null); } // Call the command with an invalid key-store-path. { boolean failed = false; try { ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + "foo.bar" + " --key-store-password=" + KEY_STORE_PASSWORD + " --no-reload"); } catch (Exception ex) { failed = true; // XXX OK, expected } Assert.assertTrue(failed); assertEmptyModel(null); } { // Call the command with no password. boolean failed = false; try { ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload"); } catch (Exception ex) { failed = true; // XXX OK, expected } Assert.assertTrue(failed); assertEmptyModel(null); } { // Call the command with an invalid key-store-name. boolean failed = false; try { ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-name=" + "foo.bar" + " --no-reload"); } catch (Exception ex) { failed = true; // XXX OK, expected } Assert.assertTrue(failed); assertEmptyModel(null); } { boolean failed = false; // call the command with both key-store-name and path ctx.handle("/subsystem=elytron/key-store=foo:add(path=foo.bar, type=JKS" + ", relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + ", credential-reference={clear-text=" + KEY_STORE_PASSWORD + "})"); try { try { ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-name=foo" + " --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload"); } catch (Exception ex) { failed = true; // XXX OK, expected } } finally { ctx.handle("/subsystem=elytron/key-store=foo:remove()"); } Assert.assertTrue(failed); assertEmptyModel(null); } { boolean failed = false; // call the command with both trust-store-name and certificate path ctx.handle("/subsystem=elytron/key-store=foo:add(path=foo.bar, type=JKS" + ", relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + ", credential-reference={clear-text=" + KEY_STORE_PASSWORD + "})"); try { try { ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --trusted-certificate-path=" + clientCertificate.getAbsolutePath() + " --trust-store-name=foo" + " --trust-store-file-name=" + GENERATED_TRUST_STORE_FILE_NAME + " --trust-store-file-password=" + GENERATED_KEY_STORE_PASSWORD + " --new-trust-store-name=" + TRUST_STORE_NAME + " --new-trust-manager-name=" + TRUST_MANAGER_NAME + " --new-key-store-name=" + KEY_STORE_NAME + " --new-key-manager-name=" + KEY_MANAGER_NAME + " --new-ssl-context-name=" + SSL_CONTEXT_NAME + " --no-reload"); } catch (Exception ex) { failed = true; // XXX OK, expected } } finally { ctx.handle("/subsystem=elytron/key-store=foo:remove()"); } Assert.assertTrue(failed); assertEmptyModel(null); } { boolean failed = false; try { ctx.handle("security enable-ssl-http-server --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload" + " --https-listener-name=" + "UNKNOWN"); } catch (Exception ex) { failed = true; // XXX OK, expected } Assert.assertTrue(failed); assertEmptyModel(null); } { boolean failed = false; try { ctx.handle("security enable-ssl-http-server --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload" + " --add-https-listener --https-listener-name=bar --https-listener-socket-binding-name=UNKNOWN"); } catch (Exception ex) { failed = true; // XXX OK, expected } Assert.assertTrue(failed); assertEmptyModel(null); } } @Test public void testInvalidDisableSSL() throws Exception { assertEmptyModel(null); { boolean failed = false; try { // We can't disable the default SSL context. ctx.handle("security disable-ssl-http-server"); } catch (Exception ex) { failed = true; // XXX OK, expected } Assert.assertTrue(failed); assertEmptyModel(null); } { boolean failed = false; try { // Invalid default context. ctx.handle("security disable-ssl-http-server --default-server-ssl-context=foo"); } catch (Exception ex) { failed = true; // XXX OK, expected } Assert.assertTrue(failed); assertEmptyModel(null); } { boolean failed = false; try { // Invalid listener name ctx.handle("security disable-ssl-http-server --https-listener-name=foo"); } catch (Exception ex) { failed = true; // XXX OK, expected } Assert.assertTrue(failed); assertEmptyModel(null); } } @Test public void testEnableSSLTwoWay() throws Exception { assertEmptyModel(null); // first validation must fail boolean failed = false; try { ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --trusted-certificate-path=" + clientCertificate.getAbsolutePath() + " --trust-store-file-name=" + GENERATED_TRUST_STORE_FILE_NAME + " --trust-store-file-password=" + GENERATED_KEY_STORE_PASSWORD + " --new-trust-store-name=" + TRUST_STORE_NAME + " --new-trust-manager-name=" + TRUST_MANAGER_NAME + " --new-key-store-name=" + KEY_STORE_NAME + " --new-key-manager-name=" + KEY_MANAGER_NAME + " --new-ssl-context-name=" + SSL_CONTEXT_NAME + " --no-reload"); } catch (Exception ex) { failed = true; } Assert.assertTrue(failed); // Call the command without validation and no-reload. ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --trusted-certificate-path=" + clientCertificate.getAbsolutePath() + " --trust-store-file-name=" + GENERATED_TRUST_STORE_FILE_NAME + " --trust-store-file-password=" + GENERATED_KEY_STORE_PASSWORD + " --new-trust-store-name=" + TRUST_STORE_NAME + " --new-trust-manager-name=" + TRUST_MANAGER_NAME + " --new-key-store-name=" + KEY_STORE_NAME + " --new-key-manager-name=" + KEY_MANAGER_NAME + " --new-ssl-context-name=" + SSL_CONTEXT_NAME + " --no-trusted-certificate-validation" + " --no-reload"); File genTrustStore = null; try { assertTLSNumResources(2, 1, 1, 1); // Check that the trustStore has been generated. genTrustStore = new File(TestSuiteEnvironment.getSystemProperty("jboss.home") + File.separator + "standalone" + File.separator + "configuration" + File.separator + GENERATED_TRUST_STORE_FILE_NAME); Assert.assertTrue(genTrustStore.exists()); // Check the model contains the provided values. checkModel(null, SERVER_KEY_STORE_FILE, Util.JBOSS_SERVER_CONFIG_DIR, KEY_STORE_PASSWORD, GENERATED_TRUST_STORE_FILE_NAME, GENERATED_KEY_STORE_PASSWORD, KEY_STORE_NAME, KEY_MANAGER_NAME, TRUST_STORE_NAME, TRUST_MANAGER_NAME, SSL_CONTEXT_NAME); } finally { if (genTrustStore != null) { genTrustStore.delete(); } } ctx.handle("security disable-ssl-http-server --no-reload"); // Re-use the trust-store generated in previous step. ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --trust-store-name=" + TRUST_STORE_NAME + " --no-reload"); assertTLSNumResources(2, 1, 1, 1); // Check that the model has not been updated. checkModel(null, SERVER_KEY_STORE_FILE, Util.JBOSS_SERVER_CONFIG_DIR, KEY_STORE_PASSWORD, GENERATED_TRUST_STORE_FILE_NAME, GENERATED_KEY_STORE_PASSWORD, KEY_STORE_NAME, KEY_MANAGER_NAME, TRUST_STORE_NAME, TRUST_MANAGER_NAME, SSL_CONTEXT_NAME); ctx.handle("security disable-ssl-http-server --no-reload"); } @Test public void testSSLCustomListener() throws Exception { String listenerName = "foo"; // Need to add a socket binding ctx.handle("/socket-binding-group=standard-sockets/socket-binding=" + TEST_SOCKET_BINDING + ":add(port=0)"); try { ctx.handle("security enable-ssl-http-server --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload" + " --add-https-listener --https-listener-name=" + listenerName + " --https-listener-socket-binding-name=" + TEST_SOCKET_BINDING); Assert.assertNotNull(getSSLContextName(ctx, DEFAULT_SERVER, listenerName)); Assert.assertTrue(getHTTPSListeners().contains(listenerName)); ctx.handle("security disable-ssl-http-server --https-listener-name=" + listenerName); Assert.assertTrue(getHTTPSListeners().contains(listenerName)); Assert.assertTrue(getHTTPSListeners().contains(Util.HTTPS)); Assert.assertEquals(DEFAULT_SSL_CONTEXT, getSSLContextName(ctx, DEFAULT_SERVER, listenerName)); ctx.handle("security disable-ssl-http-server --remove-https-listener --https-listener-name=" + listenerName); Assert.assertFalse(getHTTPSListeners().contains(listenerName)); Assert.assertTrue(getHTTPSListeners().contains(Util.HTTPS)); } finally { ctx.handle("/socket-binding-group=standard-sockets/socket-binding=" + TEST_SOCKET_BINDING + ":remove"); } } @Test public void testAddExistingHTTPSListener() throws Exception { String listenerName = "https"; ctx.handle("security enable-ssl-http-server --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload" + " --override-ssl-context --add-https-listener"); Assert.assertNotNull(getSSLContextName(ctx, DEFAULT_SERVER, listenerName)); Assert.assertNotEquals(DEFAULT_SSL_CONTEXT, getSSLContextName(ctx, DEFAULT_SERVER, listenerName)); ctx.handle("security disable-ssl-http-server --https-listener-name=" + listenerName); Assert.assertTrue(getHTTPSListeners().contains(listenerName)); Assert.assertEquals(DEFAULT_SSL_CONTEXT, getSSLContextName(ctx, DEFAULT_SERVER, listenerName)); } @Test public void testEnableSSLDefaultServer() throws Exception { testEnableSSL(DEFAULT_SERVER); } @Test public void testEnableSSL() throws Exception { testEnableSSL(null); } @Test public void testEnableSSLInteractiveConfirm() throws Exception { testEnableSSLInteractiveConfirm(null); } @Test public void testEnableSSLInteractiveConfirmDefaultServer() throws Exception { testEnableSSLInteractiveConfirm(DEFAULT_SERVER); } @Test public void testEnableSSLInteractiveNoConfirm() throws Exception { assertEmptyModel(null); CliProcessWrapper cli = new CliProcessWrapper(). addJavaOption("-Duser.home=" + temporaryUserHome.getRoot().toPath().toString()). addCliArgument("--controller=remote+http://" + TestSuiteEnvironment.getServerAddress() + ":" + TestSuiteEnvironment.getServerPort()). addCliArgument("--connect"); try { cli.executeInteractive(); cli.clearOutput(); Assert.assertTrue(cli.pushLineAndWaitForResults("security enable-ssl-http-server --override-ssl-context --interactive --no-reload", "Key-store file name")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "Password")); //Loop until DN has been provided. Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is your first and last name? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your organizational unit? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your organization? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your City or Locality? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your State or Province? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the two-letter country code for this unit? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct y/n [y]")); cli.clearOutput(); Assert.assertTrue(cli.pushLineAndWaitForResults("n", "What is your first and last name? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("foo", "What is the name of your organizational unit? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("bar", "What is the name of your organization? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("foofoo", "What is the name of your City or Locality? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("barbar", "What is the name of your State or Province? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("toto", "What is the two-letter country code for this unit? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("TO", "Is CN=foo, OU=bar, O=foofoo, L=barbar, ST=toto, C=TO correct y/n [y]")); //Loop until value is valid. Assert.assertTrue(cli.pushLineAndWaitForResults("y", "Validity")); Assert.assertTrue(cli.pushLineAndWaitForResults("Hello", "Validity")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "Alias")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "Enable SSL Mutual Authentication")); cli.clearOutput(); // Loop until value is y or n. Assert.assertTrue(cli.pushLineAndWaitForResults("TT", "Enable SSL Mutual Authentication")); cli.clearOutput(); Assert.assertTrue(cli.pushLineAndWaitForResults("COCO", "Enable SSL Mutual Authentication")); Assert.assertTrue(cli.pushLineAndWaitForResults("y", "Client certificate (path to pem file)")); cli.clearOutput(); //Loop until certificate file exists Assert.assertTrue(cli.pushLineAndWaitForResults("foo.bar", "Client certificate (path to pem file)")); Assert.assertTrue(cli.pushLineAndWaitForResults(clientCertificate.getAbsolutePath(), "Validate certificate")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "Trust-store file name")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "Password")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "Do you confirm")); cli.clearOutput(); Assert.assertTrue(cli.pushLineAndWaitForResults("PP", "Do you confirm")); cli.clearOutput(); Assert.assertTrue(cli.pushLineAndWaitForResults("COCO", "Do you confirm")); Assert.assertTrue(cli.pushLineAndWaitForResults("n", null)); assertEmptyModel(null); } catch (Throwable ex) { throw new Exception(cli.getOutput(), ex); } finally { cli.destroyProcess(); } } @Test public void testKeyStoreDifferentPassword() throws Exception { assertEmptyModel(null); // Create a credential store and alias ctx.handle("/subsystem=elytron/credential-store=cs:add(credential-reference={clear-text=cs-secret}," + "create,location=cs.store,relative-to=jboss.server.config.dir"); try { ctx.handle("/subsystem=elytron/credential-store=cs:add-alias(alias=xxx,secret-value=secret"); ctx.handle("/subsystem=elytron/key-store=ks1:add(credential-reference={alias=xxx,store=cs},type=JKS,relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + ",path=" + SERVER_KEY_STORE_FILE); assertTLSNumResources(1, 0, 0, 0); // Don't reuse the ks because different credential-reference ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload"); assertTLSNumResources(2, 1, 0, 1); ctx.handle("security disable-ssl-http-server --no-reload"); } finally { File credentialStores = new File(TestSuiteEnvironment.getSystemProperty("jboss.home") + File.separator + "standalone" + File.separator + "configuration" + File.separator + "cs.store"); credentialStores.delete(); } } @Test public void testKeyStoreDifferentAlias() throws Exception { assertEmptyModel(null); // add a key-store with different alias. ctx.handle("/subsystem=elytron/key-store=ks3:add(credential-reference={clear-text=secret}," + "type=JKS,relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + ",path=" + SERVER_KEY_STORE_FILE + ",alias-filter=foo"); assertTLSNumResources(1, 0, 0, 0); //Don't reuse the key-store because different alias-filter ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload"); assertTLSNumResources(2, 1, 0, 1); ctx.handle("security disable-ssl-http-server --no-reload"); } @Test public void testKeyManagerDifferentAlgorithm() throws Exception { assertEmptyModel(null); // add a key-store that will be reused. ctx.handle("/subsystem=elytron/key-store=ks1:add(credential-reference={clear-text=secret}," + "type=JKS,relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + ",path=" + SERVER_KEY_STORE_FILE); // A leymanager that will be not re-used. ctx.handle("/subsystem=elytron/key-manager=km:add(algorithm=PKIX,credential-reference={clear-text=secret},key-store=ks1"); assertTLSNumResources(1, 1, 0, 0); //Reuse the key-store but create a new key-manager ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload"); assertTLSNumResources(1, 2, 0, 1); ctx.handle("security disable-ssl-http-server --no-reload"); } @Test public void testKeyManagerDifferentAlias() throws Exception { assertEmptyModel(null); // add a key-store that will be reused. ctx.handle("/subsystem=elytron/key-store=ks1:add(credential-reference={clear-text=secret}," + "type=JKS,relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + ",path=" + SERVER_KEY_STORE_FILE); // A keymanager that will be not re-used. ctx.handle("/subsystem=elytron/key-manager=km:add(alias-filter=foo,credential-reference={clear-text=secret},key-store=ks1"); assertTLSNumResources(1, 1, 0, 0); //Reuse the key-store but create a new key-manager ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload"); assertTLSNumResources(1, 2, 0, 1); ctx.handle("security disable-ssl-http-server --no-reload"); } @Test public void testSSLContextDifferentNeedWant() throws Exception { assertEmptyModel(null); // add a key-store that will be reused. ctx.handle("/subsystem=elytron/key-store=ks1:add(credential-reference={clear-text=secret}," + "type=JKS,relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + ",path=" + SERVER_KEY_STORE_FILE); // A keymanager that will be reused. ctx.handle("/subsystem=elytron/key-manager=km:add(credential-reference={clear-text=secret},key-store=ks1"); // An SSLContext not reused. ctx.handle("/subsystem=elytron/server-ssl-context=ctx:add(key-manager=km,need-client-auth=true,want-client-auth=true)"); assertTLSNumResources(1, 1, 0, 1); //Reuse the key-store but create a new key-manager ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload"); assertTLSNumResources(1, 1, 0, 2); ctx.handle("security disable-ssl-http-server --no-reload"); } @Test public void testSSLContextDifferentTrustManager() throws Exception { assertEmptyModel(null); // add a key-store that will be reused. ctx.handle("/subsystem=elytron/key-store=ks1:add(credential-reference={clear-text=secret}," + "type=JKS,relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + ",path=" + SERVER_KEY_STORE_FILE); // A keymanager that will be reused. ctx.handle("/subsystem=elytron/key-manager=km:add(credential-reference={clear-text=secret},key-store=ks1"); // A trust manager. ctx.handle("/subsystem=elytron/trust-manager=tm:add(key-store=ks1"); // An SSLContext not reused. ctx.handle("/subsystem=elytron/server-ssl-context=ctx:add(key-manager=km,trust-manager=tm)"); assertTLSNumResources(1, 1, 1, 1); //Reuse the key-store but create a new key-manager ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload"); assertTLSNumResources(1, 1, 1, 2); ctx.handle("security disable-ssl-http-server --no-reload"); } @Test public void testCompletion() throws Exception { { String cmd = "security enable-ssl-http-server "; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); List<String> res = Arrays.asList("--add-https-listener", "--https-listener-name=", "--interactive", "--key-store-name=", "--key-store-path=", "--override-ssl-context", "--server-name="); Assert.assertEquals(candidates.toString(), res, candidates); candidates = complete(ctx, cmd, null); Assert.assertEquals(candidates.toString(), res, candidates); } { String cmd = "security enable-ssl-http-server --add-https-listener "; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); List<String> res = Arrays.asList("--https-listener-name=", "--https-listener-socket-binding-name=", "--interactive", "--key-store-name=", "--key-store-path=", "--override-ssl-context", "--server-name="); Assert.assertEquals(candidates.toString(), res, candidates); candidates = complete(ctx, cmd, null); Assert.assertEquals(candidates.toString(), res, candidates); } { String cmd = "security enable-ssl-http-server --https-listener-name="; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); List<String> res = Arrays.asList("https"); Assert.assertEquals(candidates.toString(), res, candidates); candidates = complete(ctx, cmd, null); Assert.assertEquals(candidates.toString(), res, candidates); } { String cmd = "security enable-ssl-http-server --server-name=foo --https-listener-name="; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); Assert.assertTrue(candidates.isEmpty()); candidates = complete(ctx, cmd, null); Assert.assertTrue(candidates.isEmpty()); } { String cmd = "security enable-ssl-http-server --add-https-listener --https-listener-name="; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); Assert.assertTrue(candidates.isEmpty()); candidates = complete(ctx, cmd, null); Assert.assertTrue(candidates.isEmpty()); } { String cmd = "security enable-ssl-http-server --add-https-listener --https-listener-socket-binding-name="; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); Assert.assertFalse(candidates.isEmpty()); Assert.assertTrue(candidates.contains("https")); candidates = complete(ctx, cmd, null); Assert.assertFalse(candidates.isEmpty()); Assert.assertTrue(candidates.contains("https")); } { String cmd = "security disable-ssl-http-server "; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); List<String> res = Arrays.asList("--default-server-ssl-context=", "--https-listener-name=", "--no-reload", "--remove-https-listener", "--server-name="); Assert.assertEquals(candidates.toString(), res, candidates); candidates = complete(ctx, cmd, null); Assert.assertEquals(candidates.toString(), res, candidates); } { String cmd = "security disable-ssl-http-server --https-listener-name="; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); Assert.assertFalse(candidates.isEmpty()); Assert.assertTrue(candidates.contains("https")); candidates = complete(ctx, cmd, null); Assert.assertFalse(candidates.isEmpty()); Assert.assertTrue(candidates.contains("https")); } { String cmd = "security disable-ssl-http-server --server-name=foo --https-listener-name="; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); Assert.assertTrue(candidates.isEmpty()); candidates = complete(ctx, cmd, null); Assert.assertTrue(candidates.isEmpty()); } { String cmd = "security disable-ssl-http-server --default-server-ssl-context="; List<String> candidates = new ArrayList<>(); ctx.getDefaultCommandCompleter().complete(ctx, cmd, cmd.length(), candidates); Assert.assertEquals(1, candidates.size()); Assert.assertTrue(candidates.contains("applicationSSC")); candidates = complete(ctx, cmd, null); Assert.assertEquals(1, candidates.size()); Assert.assertTrue(candidates.contains("applicationSSC")); } } private void testEnableSSL(String serverName) throws Exception { //assertEmptyModel(serverName); // Call the command but no-reload. ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload" + (serverName == null ? "" : " --server-name=" + serverName)); // A new key-store List<String> ks = getNames(ctx.getModelControllerClient(), Util.KEY_STORE); Assert.assertEquals(DEFAULT_NUM_KEY_STORES + 1, ks.size()); // A new keyManager List<String> km = getNames(ctx.getModelControllerClient(), Util.KEY_MANAGER); Assert.assertEquals(DEFAULT_NUM_KEY_MANAGERS + 1, km.size()); // A new SSLContext List<String> sslCtx = getNames(ctx.getModelControllerClient(), Util.SERVER_SSL_CONTEXT); Assert.assertEquals(DEFAULT_NUM_SSL_CONTEXTS + 1, sslCtx.size()); // Http-interface is secured. String usedSslCtx = getSSLContextName(ctx, serverName); Assert.assertNotNull(usedSslCtx); Assert.assertTrue(sslCtx.contains(usedSslCtx)); // Disable ssl, resources shouldn't be deleted ctx.handle("security disable-ssl-http-server --no-reload" + (serverName == null ? "" : " --server-name=" + serverName)); String usedSslCtx2 = getSSLContextName(ctx, serverName); Assert.assertEquals(DEFAULT_SSL_CONTEXT, usedSslCtx2); List<String> ks2 = getNames(ctx.getModelControllerClient(), Util.KEY_STORE); Assert.assertEquals(ks, ks2); List<String> km2 = getNames(ctx.getModelControllerClient(), Util.KEY_MANAGER); Assert.assertEquals(km, km2); List<String> sslCtx2 = getNames(ctx.getModelControllerClient(), Util.SERVER_SSL_CONTEXT); Assert.assertEquals(sslCtx, sslCtx2); // Re-enable, no new resources should be created. ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload" + (serverName == null ? "" : " --server-name=" + serverName)); String usedSslCtx3 = getSSLContextName(ctx, serverName); Assert.assertNotNull(usedSslCtx3); List<String> ks3 = getNames(ctx.getModelControllerClient(), Util.KEY_STORE); Assert.assertEquals(ks, ks3); List<String> km3 = getNames(ctx.getModelControllerClient(), Util.KEY_MANAGER); Assert.assertEquals(km, km3); List<String> sslCtx3 = getNames(ctx.getModelControllerClient(), Util.SERVER_SSL_CONTEXT); Assert.assertEquals(sslCtx, sslCtx3); // Try to enable again, exception should be thrown. boolean failed = false; try { ctx.handle("security enable-ssl-http-server --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --no-reload" + (serverName == null ? "" : " --server-name=" + serverName)); } catch (Exception ex) { failed = true; // XXX OK, expected } Assert.assertTrue(failed); // Disable ssl ctx.handle("security disable-ssl-http-server --no-reload" + (serverName == null ? "" : " --server-name=" + serverName)); // Enable SSL with key-store-name, no new resources created. ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-name=" + ks.get(1) + " --no-reload" + (serverName == null ? "" : " --server-name=" + serverName)); String usedSslCtx4 = getSSLContextName(ctx, serverName); Assert.assertNotNull(usedSslCtx4); List<String> ks4 = getNames(ctx.getModelControllerClient(), Util.KEY_STORE); Assert.assertEquals(ks, ks4); List<String> km4 = getNames(ctx.getModelControllerClient(), Util.KEY_MANAGER); Assert.assertEquals(km, km4); List<String> sslCtx4 = getNames(ctx.getModelControllerClient(), Util.SERVER_SSL_CONTEXT); Assert.assertEquals(sslCtx, sslCtx4); // Disable ssl ctx.handle("security disable-ssl-http-server --no-reload" + (serverName == null ? "" : " --server-name=" + serverName)); // Enable SSL, provide new key-store, key-manager and ssl-context names; ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --new-key-store-name=" + KEY_STORE_NAME + " --new-key-manager-name=" + KEY_MANAGER_NAME + " --new-ssl-context-name=" + SSL_CONTEXT_NAME + " --no-reload" + (serverName == null ? "" : " --server-name=" + serverName)); String usedSslCtx5 = getSSLContextName(ctx, serverName); Assert.assertEquals(SSL_CONTEXT_NAME, usedSslCtx5); List<String> ks5 = getNames(ctx.getModelControllerClient(), Util.KEY_STORE); Assert.assertEquals(DEFAULT_NUM_KEY_STORES + 2, ks5.size()); Assert.assertTrue(ks5.contains(KEY_STORE_NAME)); List<String> km5 = getNames(ctx.getModelControllerClient(), Util.KEY_MANAGER); Assert.assertEquals(DEFAULT_NUM_KEY_MANAGERS + 2, km5.size()); Assert.assertTrue(km5.contains(KEY_MANAGER_NAME)); List<String> sslCtx5 = getNames(ctx.getModelControllerClient(), Util.SERVER_SSL_CONTEXT); Assert.assertEquals(DEFAULT_NUM_SSL_CONTEXTS + 2, sslCtx5.size()); Assert.assertTrue(sslCtx5.contains(SSL_CONTEXT_NAME)); checkModel(serverName, SERVER_KEY_STORE_FILE, Util.JBOSS_SERVER_CONFIG_DIR, KEY_STORE_PASSWORD, null, null, KEY_STORE_NAME, KEY_MANAGER_NAME, null, null, SSL_CONTEXT_NAME); // Disable ssl ctx.handle("security disable-ssl-http-server --no-reload" + (serverName == null ? "" : " --server-name=" + serverName)); // Enable SSL, provide same new-key-store-name, exception thrown because already exists failed = false; try { ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --new-key-store-name=" + KEY_STORE_NAME + " --no-reload" + (serverName == null ? "" : " --server-name=" + serverName)); } catch (Exception ex) { // XXX OK expected failed = true; } Assert.assertTrue(failed); // Check that it has not been enabled. Assert.assertEquals(DEFAULT_SSL_CONTEXT, getSSLContextName(ctx, serverName)); // Enable SSL, provide same new-key-manager-name, exception thrown because already exists failed = false; try { ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --new-key-manager-name=" + KEY_MANAGER_NAME + " --no-reload" + (serverName == null ? "" : " --server-name=" + serverName)); } catch (Exception ex) { // XXX OK expected failed = true; } Assert.assertTrue(failed); // Check that it has not been enabled. Assert.assertEquals(DEFAULT_SSL_CONTEXT, getSSLContextName(ctx, serverName)); // Enable SSL, provide same new-key-manager-name, exception thrown because already exists failed = false; try { ctx.handle("security enable-ssl-http-server --override-ssl-context --key-store-path=" + SERVER_KEY_STORE_FILE + " --key-store-password=" + KEY_STORE_PASSWORD + " --key-store-path-relative-to=" + Util.JBOSS_SERVER_CONFIG_DIR + " --new-ssl-context-name=" + SSL_CONTEXT_NAME + " --no-reload" + (serverName == null ? "" : " --server-name=" + serverName)); } catch (Exception ex) { // XXX OK expected failed = true; } Assert.assertTrue(failed); // Check that it has not been enabled. Assert.assertEquals(DEFAULT_SSL_CONTEXT, getSSLContextName(ctx, serverName)); } private void testEnableSSLInteractiveConfirm(String mgmtInterface) throws Exception { assertEmptyModel(mgmtInterface); CliProcessWrapper cli = new CliProcessWrapper(). addJavaOption("-Duser.home=" + temporaryUserHome.getRoot().toPath().toString()). addCliArgument("--controller=remote+http://" + TestSuiteEnvironment.getServerAddress() + ":" + TestSuiteEnvironment.getServerPort()). addCliArgument("--connect"); File genKeyStore = null; File genTrustStore = null; File genServerCertificate = null; File genCsr = null; try { cli.executeInteractive(); cli.clearOutput(); Assert.assertTrue(cli.pushLineAndWaitForResults("security enable-ssl-http-server --override-ssl-context --interactive --no-reload" + (mgmtInterface == null ? "" : " --server-name=" + mgmtInterface), "Key-store file name")); Assert.assertTrue(cli.pushLineAndWaitForResults(GENERATED_KEY_STORE_FILE_NAME, "Password")); Assert.assertTrue(cli.pushLineAndWaitForResults(GENERATED_KEY_STORE_PASSWORD, "What is your first and last name? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your organizational unit? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your organization? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your City or Locality? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your State or Province? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the two-letter country code for this unit? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct y/n [y]")); Assert.assertTrue(cli.pushLineAndWaitForResults("y", "Validity")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "Alias")); Assert.assertTrue(cli.pushLineAndWaitForResults(GENERATED_KEY_STORE_ALIAS, "Enable SSL Mutual Authentication")); Assert.assertTrue(cli.pushLineAndWaitForResults("y", "Client certificate (path to pem file)")); Assert.assertTrue(cli.pushLineAndWaitForResults(clientCertificate.getAbsolutePath(), "Validate certificate")); Assert.assertTrue(cli.pushLineAndWaitForResults("n", "Trust-store file name")); Assert.assertTrue(cli.pushLineAndWaitForResults(GENERATED_TRUST_STORE_FILE_NAME, "Password")); Assert.assertTrue(cli.pushLineAndWaitForResults(GENERATED_KEY_STORE_PASSWORD, "Do you confirm")); Assert.assertTrue(cli.pushLineAndWaitForResults("y", null)); assertTLSNumResources(2, 1, 1, 1); // Check that the files have been generated. genKeyStore = new File(TestSuiteEnvironment.getSystemProperty("jboss.home") + File.separator + "standalone" + File.separator + "configuration" + File.separator + GENERATED_KEY_STORE_FILE_NAME); Assert.assertTrue(genKeyStore.exists()); genTrustStore = new File(TestSuiteEnvironment.getSystemProperty("jboss.home") + File.separator + "standalone" + File.separator + "configuration" + File.separator + GENERATED_TRUST_STORE_FILE_NAME); Assert.assertTrue(genTrustStore.exists()); genServerCertificate = new File(TestSuiteEnvironment.getSystemProperty("jboss.home") + File.separator + "standalone" + File.separator + "configuration" + File.separator + GENERATED_PEM_FILE_NAME); Assert.assertTrue(genServerCertificate.exists()); genCsr = new File(TestSuiteEnvironment.getSystemProperty("jboss.home") + File.separator + "standalone" + File.separator + "configuration" + File.separator + GENERATED_CSR_FILE_NAME); Assert.assertTrue(genCsr.exists()); // Check the model contains the provided values. List<String> ksList = getNames(ctx.getModelControllerClient(), Util.KEY_STORE); List<String> kmList = getNames(ctx.getModelControllerClient(), Util.KEY_MANAGER); List<String> tmList = getNames(ctx.getModelControllerClient(), Util.TRUST_MANAGER); List<String> sslContextList = getNames(ctx.getModelControllerClient(), Util.SERVER_SSL_CONTEXT); ModelNode trustManager = getResource(Util.TRUST_MANAGER, tmList.get(0), null); checkModel(mgmtInterface, GENERATED_KEY_STORE_FILE_NAME, Util.JBOSS_SERVER_CONFIG_DIR, GENERATED_KEY_STORE_PASSWORD, GENERATED_TRUST_STORE_FILE_NAME, GENERATED_KEY_STORE_PASSWORD, ksList.get(1), kmList.get(1), trustManager.get(Util.KEY_STORE).asString(), tmList.get(0), sslContextList.get(1)); ctx.handle("security disable-ssl-http-server --no-reload" + (mgmtInterface == null ? "" : " --server-name=" + mgmtInterface)); // Test that existing key-store file makes the command to abort. Assert.assertTrue(cli.pushLineAndWaitForResults("security enable-ssl-http-server --override-ssl-context --interactive --no-reload" + (mgmtInterface == null ? "" : " --server-name=" + mgmtInterface), "Key-store file name")); Assert.assertTrue(cli.pushLineAndWaitForResults(GENERATED_KEY_STORE_FILE_NAME, null)); //Test that existing trust-store file makes command to abort Assert.assertTrue(cli.pushLineAndWaitForResults("security enable-ssl-http-server --override-ssl-context --interactive --no-reload" + (mgmtInterface == null ? "" : " --server-name=" + mgmtInterface), "Key-store file name")); Assert.assertTrue(cli.pushLineAndWaitForResults("foo", "Password")); Assert.assertTrue(cli.pushLineAndWaitForResults(GENERATED_KEY_STORE_PASSWORD, "What is your first and last name? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your organizational unit? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your organization? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your City or Locality? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the name of your State or Province? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "What is the two-letter country code for this unit? [Unknown]")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct y/n [y]")); Assert.assertTrue(cli.pushLineAndWaitForResults("y", "Validity")); Assert.assertTrue(cli.pushLineAndWaitForResults("", "Alias")); Assert.assertTrue(cli.pushLineAndWaitForResults(GENERATED_KEY_STORE_ALIAS, "Enable SSL Mutual Authentication")); Assert.assertTrue(cli.pushLineAndWaitForResults("y", "Client certificate (path to pem file)")); Assert.assertTrue(cli.pushLineAndWaitForResults(clientCertificate.getAbsolutePath(), "Validate certificate")); Assert.assertTrue(cli.pushLineAndWaitForResults("n", "Trust-store file name")); Assert.assertTrue(cli.pushLineAndWaitForResults(GENERATED_TRUST_STORE_FILE_NAME, null)); } catch (Throwable ex) { throw new Exception(cli.getOutput(), ex); } finally { if (genKeyStore != null) { genKeyStore.delete(); } if (genTrustStore != null) { genTrustStore.delete(); } if (genServerCertificate != null) { genServerCertificate.delete(); } if (genCsr != null) { genCsr.delete(); } cli.destroyProcess(); } } private static String getSSLContextName(CommandContext ctx, String serverName) throws IOException, OperationFormatException { return getSSLContextName(ctx, serverName, Util.HTTPS); } private static String getSSLContextName(CommandContext ctx, String serverName, String httpsListener) throws IOException, OperationFormatException { final DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder(); final ModelNode request; try { builder.setOperationName(Util.READ_ATTRIBUTE); builder.addNode(Util.SUBSYSTEM, Util.UNDERTOW); builder.addNode(Util.SERVER, serverName == null ? DEFAULT_SERVER : serverName); builder.addNode(Util.HTTPS_LISTENER, httpsListener); builder.addProperty(Util.NAME, Util.SSL_CONTEXT); request = builder.buildRequest(); } catch (OperationFormatException e) { throw new IllegalStateException("Failed to build operation", e); } try { final ModelNode outcome = ctx.getModelControllerClient().execute(request); if (Util.isSuccess(outcome)) { ModelNode mn = outcome.get(Util.RESULT); if (mn.isDefined()) { return outcome.get(Util.RESULT).asString(); } else { return null; } } } catch (Exception e) { } return null; } private static List<String> getNames(ModelControllerClient client, String type) { final DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder(); final ModelNode request; try { builder.setOperationName(Util.READ_CHILDREN_NAMES); builder.addNode(Util.SUBSYSTEM, Util.ELYTRON); builder.addProperty(Util.CHILD_TYPE, type); request = builder.buildRequest(); } catch (OperationFormatException e) { throw new IllegalStateException("Failed to build operation", e); } try { final ModelNode outcome = client.execute(request); if (Util.isSuccess(outcome)) { return Util.getList(outcome); } } catch (Exception e) { } return Collections.emptyList(); } private List<String> getHTTPSListeners() { final DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder(); final ModelNode request; try { builder.setOperationName(Util.READ_CHILDREN_NAMES); builder.addNode(Util.SUBSYSTEM, Util.UNDERTOW); builder.addNode(Util.SERVER, DEFAULT_SERVER); builder.addProperty(Util.CHILD_TYPE, Util.HTTPS_LISTENER); request = builder.buildRequest(); } catch (OperationFormatException e) { throw new IllegalStateException("Failed to build operation", e); } try { final ModelNode outcome = ctx.getModelControllerClient().execute(request); if (Util.isSuccess(outcome)) { return Util.getList(outcome); } } catch (Exception e) { } return Collections.emptyList(); } private void removeCustomHTTPSListeners() throws CommandLineException { for (String listener : getHTTPSListeners()) { if (!Util.HTTPS.equals(listener)) { ctx.handle("/subsystem=undertow/server=" + DEFAULT_SERVER + "/https-listener=" + listener + ":remove"); } } } private static void removeTLS() throws CommandLineException { List<String> sslContextList = getNames(ctx.getModelControllerClient(), Util.SERVER_SSL_CONTEXT); for (String ssl : sslContextList) { if (! ssl.equals(DEFAULT_SSL_CONTEXT)) { ctx.handle("/subsystem=elytron/server-ssl-context=" + ssl + ":remove"); } } List<String> kmList = getNames(ctx.getModelControllerClient(), Util.KEY_MANAGER); for (String km : kmList) { if (! km.equals(DEFAULT_KEY_MANAGER)) { ctx.handle("/subsystem=elytron/key-manager=" + km + ":remove"); } } List<String> tmList = getNames(ctx.getModelControllerClient(), Util.TRUST_MANAGER); for (String tm : tmList) { ctx.handle("/subsystem=elytron/trust-manager=" + tm + ":remove"); } List<String> ksList = getNames(ctx.getModelControllerClient(), Util.KEY_STORE); for (String ks : ksList) { if (! ks.equals(DEFAULT_KEY_STORE)) { ctx.handle("/subsystem=elytron/key-store=" + ks + ":remove"); } } List<String> credentialStoreList = getNames(ctx.getModelControllerClient(), "credential-store"); for (String cs : credentialStoreList) { ctx.handle("/subsystem=elytron/credential-store=" + cs + ":remove"); } } private static void assertEmptyModel(String serverName) throws Exception { String ssl = getSSLContextName(ctx, serverName); if ( ssl != null && !DEFAULT_SSL_CONTEXT.equals(ssl)) { throw new Exception("Unexpected SSL context " + serverName); } assertTLSEmpty(); } private static void assertTLSNumResources(int numKS, int numKeyManager, int numTrustManager, int numSSLContext) throws Exception { List<String> ks = getNames(ctx.getModelControllerClient(), Util.KEY_STORE); Assert.assertEquals(DEFAULT_NUM_KEY_STORES + numKS, ks.size()); List<String> km = getNames(ctx.getModelControllerClient(), Util.KEY_MANAGER); Assert.assertEquals(DEFAULT_NUM_KEY_MANAGERS + numKeyManager, km.size()); List<String> tm = getNames(ctx.getModelControllerClient(), Util.TRUST_MANAGER); Assert.assertEquals(DEFAULT_NUM_TRUST_MANAGERS + numTrustManager, tm.size()); List<String> sslCtx = getNames(ctx.getModelControllerClient(), Util.SERVER_SSL_CONTEXT); Assert.assertEquals(DEFAULT_NUM_SSL_CONTEXTS + numSSLContext, sslCtx.size()); } private static void assertTLSEmpty() throws Exception { assertTLSNumResources(0, 0, 0, 0); } private static ModelNode buildKeyStoreResource(File path, String relativeTo, String password, String type, Boolean required, String alias) throws IOException { ModelNode localKS = new ModelNode(); if (path != null) { localKS.get(Util.PATH).set(path.getPath()); } if (relativeTo != null) { localKS.get(Util.RELATIVE_TO).set(relativeTo); } else { localKS.get(Util.RELATIVE_TO); } if (password != null) { localKS.get(Util.CREDENTIAL_REFERENCE).set(buildCredentialReferences(password)); } if (type != null) { localKS.get(Util.TYPE).set(type); } if (required != null) { localKS.get(Util.REQUIRED).set(required); } if (alias != null) { localKS.get(Util.ALIAS_FILTER, alias); } return localKS; } private static ModelNode buildSSLContextResource(String trustManager, String keyManager, Boolean want, Boolean need) throws IOException { ModelNode sslContext = new ModelNode(); if (trustManager != null) { sslContext.get(Util.TRUST_MANAGER).set(trustManager); } if (keyManager != null) { sslContext.get(Util.KEY_MANAGER).set(keyManager); } if (want != null) { sslContext.get(Util.WANT_CLIENT_AUTH).set(want); } if (need != null) { sslContext.get(Util.NEED_CLIENT_AUTH).set(need); } sslContext.get(Util.PROTOCOLS).add("TLSv1.2"); return sslContext; } private static ModelNode buildCredentialReferences(String password) { ModelNode mn = new ModelNode(); mn.get(Util.CLEAR_TEXT).set(password); return mn; } private static ModelNode getResource(String type, String name, ModelNode filter) throws Exception { final DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder(); final ModelNode request; builder.setOperationName(Util.READ_RESOURCE); builder.addNode(Util.SUBSYSTEM, Util.ELYTRON); builder.addNode(type, name); request = builder.buildRequest(); final ModelNode outcome = ctx.getModelControllerClient().execute(request); if (Util.isSuccess(outcome)) { ModelNode res = outcome.get(Util.RESULT); if (filter != null) { List<String> toRemove = new ArrayList<>(); for (String k : res.keys()) { if (!filter.hasDefined(k)) { toRemove.add(k); } } for (String k : toRemove) { res.remove(k); } } return res; } else { return null; } } private static void checkModel(String serverName, String keyStoreFile, String relativeTo, String password, String trustStoreFile, String tsPassword, String keyStoreName, String keyManagerName, String trustStoreName, String trustManagerName, String sslContextName) throws Exception { serverName = serverName == null ? DEFAULT_SERVER : serverName; // Check the model contains the provided values. ModelNode expectedKeyStore = buildKeyStoreResource(new File(keyStoreFile), relativeTo, password, "JKS", false, null); ModelNode kManager = getResource(Util.KEY_MANAGER, keyManagerName, null); ModelNode tManager; if (trustManagerName != null) { tManager = getResource(Util.TRUST_MANAGER, trustManagerName, null); ModelNode expectedTrustStore = buildKeyStoreResource(new File(trustStoreFile), relativeTo, tsPassword, "JKS", false, null); ModelNode ts = getResource(Util.KEY_STORE, tManager.get(Util.KEY_STORE).asString(), expectedTrustStore); Assert.assertEquals(trustStoreName, tManager.get(Util.KEY_STORE).asString()); Assert.assertEquals(expectedTrustStore, ts); } Assert.assertEquals(keyStoreName, kManager.get(Util.KEY_STORE).asString()); ModelNode ks = getResource(Util.KEY_STORE, kManager.get(Util.KEY_STORE).asString(), expectedKeyStore); Assert.assertEquals(expectedKeyStore, ks); //Check that the SSLContext properly references both km and ts ModelNode expectedSSLContext = buildSSLContextResource(trustManagerName, keyManagerName, false, trustManagerName != null); ModelNode actualSSLContext = getResource(Util.SERVER_SSL_CONTEXT, sslContextName, expectedSSLContext); Assert.assertEquals(expectedSSLContext, actualSSLContext); //Check that the sslContext is referenced from the interface String usedSslCtx = getSSLContextName(ctx, serverName); Assert.assertEquals(usedSslCtx, sslContextName); } // This completion is what aesh-readline completion is calling, so more // similar to interactive CLI session private List<String> complete(CommandContext ctx, String cmd, Boolean separator) { Completion<AeshCompleteOperation> completer = (Completion<AeshCompleteOperation>) ctx.getDefaultCommandCompleter(); AeshCompleteOperation op = new AeshCompleteOperation(cmd, cmd.length()); completer.complete(op); if (separator != null) { assertEquals(op.hasAppendSeparator(), separator); } List<String> candidates = new ArrayList<>(); for (TerminalString ts : op.getCompletionCandidates()) { candidates.add(ts.getCharacters()); } // aesh-readline does sort the candidates prior to display. Collections.sort(candidates); return candidates; } }
69,851
51.559819
168
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/JmsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.cli; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.jboss.arquillian.junit.Arquillian; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Dominik Pospisil <[email protected]> */ @RunWith(Arquillian.class) public class JmsTestCase extends AbstractCliTestBase { @BeforeClass public static void before() throws Exception { AbstractCliTestBase.initCLI(); } @AfterClass public static void after() throws Exception { AbstractCliTestBase.closeCLI(); } @Test public void testAddRemoveJmsQueue() throws Exception { testAddJmsQueue(); testRemoveJmsQueue(); } @Test public void testAddRemoveJmsTopic() throws Exception { testAddJmsTopic(); testRemoveJmsTopic(); } private void testAddJmsQueue() throws Exception { String queueName = "testJmsQueue"; // check the queue is not registered cli.sendLine("cd /subsystem=messaging-activemq/server=default/jms-queue"); cli.sendLine("ls"); String ls = cli.readOutput(); assertFalse(ls.contains(queueName)); // create queue cli.sendLine(String.format("jms-queue add --queue-address=%s --entries=%s", queueName, queueName)); // check it is listed cli.sendLine("cd /subsystem=messaging-activemq/server=default/jms-queue"); cli.sendLine("ls"); ls = cli.readOutput(); assertTrue(ls.contains(queueName)); } private void testRemoveJmsQueue() throws Exception { String queueName = "testJmsQueue"; // remove the queue cli.sendLine("jms-queue remove --queue-address=" + queueName); // check it is listed cli.sendLine("cd /subsystem=messaging-activemq/server=default/jms-queue"); cli.sendLine("ls"); String ls = cli.readOutput(); assertFalse(ls.contains(queueName)); } private void testAddJmsTopic() throws Exception { // check the queue is not registered cli.sendLine("cd /subsystem=messaging-activemq/server=default/jms-topic"); cli.sendLine("ls"); String ls = cli.readOutput(); Assert.assertNull(ls); // create topic cli.sendLine("jms-topic add --topic-address=testJmsTopic --entries=testJmsTopic"); // check it is listed cli.sendLine("cd /subsystem=messaging-activemq/server=default/jms-topic"); cli.sendLine("ls"); ls = cli.readOutput(); assertTrue(ls.contains("testJmsTopic")); } private void testRemoveJmsTopic() throws Exception { // create queue cli.sendLine("jms-topic remove --topic-address=testJmsTopic"); // check it is listed cli.sendLine("cd /subsystem=messaging-activemq/server=default/jms-topic"); cli.sendLine("ls"); String ls = cli.readOutput(); Assert.assertNull(ls); } }
4,187
32.238095
107
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/DeployTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.cli; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.URL; import java.util.concurrent.TimeUnit; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.management.util.SimpleServlet; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Dominik Pospisil <[email protected]> */ @RunWith(Arquillian.class) @RunAsClient public class DeployTestCase extends AbstractCliTestBase { private static WebArchive war; private static File warFile; @ArquillianResource URL url; @Deployment public static Archive<?> getDeployment() { JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "dummy.jar"); ja.addClass(DeployTestCase.class); return ja; } @BeforeClass public static void before() throws Exception { war = ShrinkWrap.create(WebArchive.class, "SimpleServlet.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(new StringAsset("Version1"), "page.html"); String tempDir = TestSuiteEnvironment.getTmpDir(); warFile = new File(tempDir + File.separator + "SimpleServlet.war"); new ZipExporterImpl(war).exportTo(warFile, true); AbstractCliTestBase.initCLI(); } @AfterClass public static void after() throws Exception { warFile.delete(); AbstractCliTestBase.closeCLI(); } @Test public void testDeployRedeployUndeploy() throws Exception { testDeploy(); testRedeploy(); testUndeploy(); } @Test public void testContentObjectDeploy() throws Exception { testWFLY3184(); testUndeploy(); } public void testDeploy() throws Exception { // deploy to server cli.sendLine("deploy " + warFile.getAbsolutePath()); // check deployment String response = HttpRequest.get(getBaseURL(url) + "SimpleServlet/SimpleServlet", 1000, 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >=0); } public void testRedeploy() throws Exception { // check we have original deployment String response = HttpRequest.get(getBaseURL(url) + "SimpleServlet/page.html", 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("Version1") >=0); // update the deployment - replace page.html war = ShrinkWrap.create(WebArchive.class, "SimpleServlet.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(new StringAsset("Version2"), "page.html"); new ZipExporterImpl(war).exportTo(warFile, true); // redeploy to server Assert.assertFalse(cli.sendLine("deploy " + warFile.getAbsolutePath(), true)); // force redeploy cli.sendLine("deploy " + warFile.getAbsolutePath() + " --force"); // check that new version is running final long firstTry = System.currentTimeMillis(); response = HttpRequest.get(getBaseURL(url) + "SimpleServlet/page.html", 1000, 10, TimeUnit.SECONDS); while(response.indexOf("Version2") < 0) { if(System.currentTimeMillis() - firstTry >= 1000) { break; } try { Thread.sleep(500); } catch(InterruptedException e) { break; } finally { response = HttpRequest.get(getBaseURL(url) + "SimpleServlet/page.html", 1000, 10, TimeUnit.SECONDS); } } assertTrue("Invalid response: " + response, response.indexOf("Version2") >=0); } public void testUndeploy() throws Exception { //undeploy cli.sendLine("undeploy SimpleServlet.war"); // check undeployment assertTrue(checkUndeployed(getBaseURL(url) + "SimpleServlet/SimpleServlet")); } private void testWFLY3184() throws Exception { // deploy to server cli.sendLine("/deployment="+warFile.getName() +":add(enabled=true,content={url=" + warFile.toURI().toURL().toExternalForm() + "})"); // check deployment String response = HttpRequest.get(getBaseURL(url) + "SimpleServlet/SimpleServlet", 1000, 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.contains("SimpleServlet")); } }
6,162
35.467456
140
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/objectstore/ObjectStoreBrowserService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.cli.objectstore; import com.arjuna.ats.arjuna.tools.osb.api.mbeans.RecoveryStoreBean; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; /** * Instantiates RecoveryStoreBean on JMX. * * @author <a href="mailto:[email protected]">Ivo Studensky</a> */ @Singleton @Startup public class ObjectStoreBrowserService { private RecoveryStoreBean rsb; @PostConstruct public void start() { rsb = new RecoveryStoreBean(); rsb.start(); } @PreDestroy public void stop() { if (rsb != null) rsb.stop(); } }
1,735
30.563636
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/cli/objectstore/TransactionObjectStoreTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.cli.objectstore; import com.arjuna.ats.arjuna.common.Uid; import com.arjuna.ats.arjuna.state.OutputObjectState; import com.arjuna.ats.arjuna.tools.osb.api.proxy.RecoveryStoreProxy; import com.arjuna.ats.arjuna.tools.osb.api.proxy.StoreManagerProxy; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.base.AbstractCliTestBase; 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.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * @author Ivo Studensky <[email protected]> */ @RunWith(Arquillian.class) @RunAsClient public class TransactionObjectStoreTestCase extends AbstractCliTestBase { private static final String FOO_TYPE = "/StateManager/LockManager/foo"; @ArquillianResource private ManagementClient managementClient; @Deployment public static Archive<?> getDeployment() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, TransactionObjectStoreTestCase.class.getSimpleName() + ".jar") .addClass(ObjectStoreBrowserService.class) .addAsManifestResource(new StringAsset("Dependencies: org.jboss.jts\n"), "MANIFEST.MF") .addAsManifestResource(TransactionObjectStoreTestCase.class.getPackage(), "permissions.xml", "permissions.xml"); return jar; } @BeforeClass public static void before() throws Exception { AbstractCliTestBase.initCLI(); } @AfterClass public static void after() throws Exception { AbstractCliTestBase.closeCLI(); } @Test public void testExposeAllLogs() throws Exception { String serviceUrl = managementClient.getRemoteJMXURL().toString(); try { RecoveryStoreProxy prs = StoreManagerProxy.getRecoveryStore(serviceUrl, null); // this immediately checks whether we really got a store manager proxy or not assertNotNull(prs.getStoreName()); // write a log record to the object store // create a record that by default the tooling does not expose byte[] data = new byte[10240]; OutputObjectState state = new OutputObjectState(); Uid uid = new Uid(); state.packBytes(data); assertTrue(prs.write_committed(uid, FOO_TYPE, state)); // probe the log store cli.sendLine("/subsystem=transactions/log-store=log-store:write-attribute(name=expose-all-logs,value=false)"); cli.sendLine("/subsystem=transactions/log-store=log-store:probe()"); // check the log record is not listed cli.sendLine("cd /subsystem=transactions/log-store=log-store/transactions"); cli.sendLine("ls"); String ls = cli.readOutput(); assertFalse("Unexpected uid in the log.", ls != null && ls.contains(uid.toString())); // probe the log store again for all records cli.sendLine("/subsystem=transactions/log-store=log-store:write-attribute(name=expose-all-logs,value=true)"); cli.sendLine("/subsystem=transactions/log-store=log-store:probe()"); // check the log record is listed cli.sendLine("cd /subsystem=transactions/log-store=log-store/transactions"); cli.sendLine("ls"); ls = cli.readOutput(); assertTrue("Could not find the expected uid in the log.", ls != null && ls.contains(uid.toString())); // remove the log record cli.sendLine("/subsystem=transactions/log-store=log-store/transactions=" + escapeColons(uid.toString()) + ":delete()"); // probe the log store again cli.sendLine("/subsystem=transactions/log-store=log-store:probe()"); // check the log record is not listed cli.sendLine("cd /subsystem=transactions/log-store=log-store/transactions"); cli.sendLine("ls"); ls = cli.readOutput(); assertFalse("Unexpected uid in the log after its remove.", ls != null && ls.contains(uid.toString())); // set back the expose-all-logs attribute cli.sendLine("/subsystem=transactions/log-store=log-store:write-attribute(name=expose-all-logs,value=false)"); } finally { StoreManagerProxy.releaseProxy(serviceUrl); } } private String escapeColons(String colons) { return colons.replaceAll(":", "\\\\:"); } }
6,042
42.789855
131
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/api/ClientCompatibilityUnitTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.api; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.security.SecureRandom; import java.util.Random; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.model.test.ChildFirstClassLoaderBuilder; import org.jboss.as.process.protocol.StreamUtils; import org.jboss.as.test.integration.management.ManagementOperations; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.ByteArrayAsset; 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; /** * Test supported remoting libraries combinations. * * @author Emanuel Muckenhuber */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(ClientCompatibilityUnitTestCase.ClientCompatibilityUnitTestCaseServerSetup.class) public class ClientCompatibilityUnitTestCase { static class ClientCompatibilityUnitTestCaseServerSetup implements ServerSetupTask { @Override public void setup(final ManagementClient managementClient, final String containerId) throws Exception { ModelNode socketBindingOp = Util.createAddOperation(PathAddress.parseCLIStyleAddress("/socket-binding-group=standard-sockets/socket-binding=management-native")); socketBindingOp.get("interface").set("management"); socketBindingOp.get("port").set("9999"); ManagementOperations.executeOperation(managementClient.getControllerClient(),socketBindingOp); ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.OP_ADDR).set(address()); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); op.get(ModelDescriptionConstants.SOCKET_BINDING).set("management-native"); op.get(ModelDescriptionConstants.SASL_AUTHENTICATION_FACTORY).set("management-sasl-authentication"); ManagementOperations.executeOperation(managementClient.getControllerClient(), op); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.OP_ADDR).set(address()); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.REMOVE); ManagementOperations.executeOperation(managementClient.getControllerClient(), op); ManagementOperations.executeOperation(managementClient.getControllerClient(), Util.createRemoveOperation(PathAddress.parseCLIStyleAddress("/socket-binding-group=standard-sockets/socket-binding=management-native"))); } private ModelNode address() { return PathAddress.pathAddress() .append(ModelDescriptionConstants.CORE_SERVICE, ModelDescriptionConstants.MANAGEMENT) .append(ModelDescriptionConstants.MANAGEMENT_INTERFACE, ModelDescriptionConstants.NATIVE_INTERFACE).toModelNode(); } } // Arquillian requires a deployment to trigger @ServerSetup handling @Deployment public static Archive fakeDeployment() { return ShrinkWrap.create(JavaArchive.class); } private static final String CONTROLLER_ADDRESS = System.getProperty("node0", "localhost"); private static final String WFCORE_CLIENT = "org.wildfly.core:wildfly-controller-client"; private static final String[] excludes = new String[]{"org.jboss.threads:jboss-threads", "org.jboss:jboss-dmr", "org.jboss.logging:jboss-logging"}; private static final Archive deployment; static { final WebArchive archive = ShrinkWrap.create(WebArchive.class); // Create basic archive which exceeds the remoting window size for (int i = 0; i < 10; i++) { final byte[] data = new byte[8096]; new Random(new SecureRandom().nextLong()).nextBytes(data); archive.add(new ByteArrayAsset(data), "data" + i); } deployment = archive; } @Test public void testCore101Final() throws Exception { testWF("1.0.1.Final", 9999); } @Test public void testCore101FinalHttp() throws Exception { testWF("1.0.1.Final", 9990); } @Test public void testCore210Final() throws Exception { testWF("2.1.0.Final", 9999); } @Test public void testCore210FinalHttp() throws Exception { testWF("2.1.0.Final", 9990); } @Test public void testCore221Final() throws Exception { testWF("2.2.1.Final", 9999); } @Test public void testCore221FinalHttp() throws Exception { testWF("2.2.1.Final", 9990); } @Test public void testCore3010Final() throws Exception { testWF("3.0.10.Final", 9999); } @Test public void testCore3010FinalHttp() throws Exception { testWF("3.0.10.Final", 9990); } // https://issues.redhat.com/browse/WFLY-18171 // Test WF Core versions that went into WildFly 23 and later (latest micro for each major/minor release) // Tests WF Core 15.0.1.Final for WildFly 23.0.2.Final. @Test public void testCore1501Final() throws Exception { testWF("15.0.1.Final", 9999); } @Test public void testCore1501FinalHttp() throws Exception { testWF("15.0.1.Final", 9990); } // Tests WF Core 16.0.1.Final for WildFly 24.0.1.Final. WildFly 24 was the last release that supported Picketbox @Test public void testCore1601Final() throws Exception { testWF("16.0.1.Final", 9999); } @Test public void testCore1601FinalHttp() throws Exception { testWF("16.0.1.Final", 9990); } // Tests WF Core 17.0.3.Final for WildFly 25.0.1.Final @Test public void testCore1703Final() throws Exception { testWF("17.0.3.Final", 9999); } @Test public void testCore1703FinalHttp() throws Exception { testWF("17.0.3.Final", 9990); } // WildFly 26.0 is skipped as it was soon followed up by WildFly 26.1 // Tests WF Core 18.1.2.Final for WildFly 26.1.3.Final. @Test public void testCore1812Final() throws Exception { testWF("18.1.2.Final", 9999); } @Test public void testCore1812FinalHttp() throws Exception { testWF("18.1.2.Final", 9990); } // Tests WF Core 19.0.1.Final for WildFly 27.0.1.Final @Test public void testCore1901Final() throws Exception { testWF("19.0.1.Final", 9999); } @Test public void testCore1901FinalHttp() throws Exception { testWF("19.0.1.Final", 9990); } // Tests WF Core 20.0.2.Final for WildFly 28.0.1.Final @Test public void testCore2002Final() throws Exception { testWF("20.0.2.Final", 9999); } @Test public void testCore2002FinalHttp() throws Exception { testWF("20.0.2.Final", 9990); } @Test public void testCurrent() throws Exception { test(ModelControllerClient.Factory.create(CONTROLLER_ADDRESS, 9999)); } @Test public void testCurrentHttp() throws Exception { test(ModelControllerClient.Factory.create(CONTROLLER_ADDRESS, 9990)); } private void testWF(final String version, int port) throws Exception { test(createClient(version, port)); } private void test(final ModelControllerClient client) throws Exception { try { final ModelNode operation = new ModelNode(); operation.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); operation.get(ModelDescriptionConstants.OP_ADDR).setEmptyList(); // include a lot of garbage operation.get(ModelDescriptionConstants.RECURSIVE).set(true); operation.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); operation.get(ModelDescriptionConstants.INCLUDE_DEFAULTS).set(true); final ModelNode result = client.execute(operation); Assert.assertEquals(operation.toString(), ModelDescriptionConstants.SUCCESS, result.get(ModelDescriptionConstants.OUTCOME).asString()); final ModelNode deploy = new ModelNode(); deploy.get(ModelDescriptionConstants.OP).set("add"); deploy.get(ModelDescriptionConstants.OP_ADDR).add("deployment", "compat-test.war"); deploy.get("content").get(0).get("input-stream-index").set(0); deploy.get("auto-start").set(true); final Operation o = OperationBuilder.create(deploy) .addInputStream(deployment.as(ZipExporter.class).exportAsInputStream()).build(); try { final ModelNode deployResult = client.execute(o); Assert.assertEquals(deployResult.toString(), ModelDescriptionConstants.SUCCESS, deployResult.get(ModelDescriptionConstants.OUTCOME).asString()); } finally { final ModelNode undeploy = new ModelNode(); undeploy.get(ModelDescriptionConstants.OP).set("remove"); undeploy.get(ModelDescriptionConstants.OP_ADDR).add("deployment", "compat-test.war"); try { client.execute(undeploy); } catch (IOException ignore) { ignore.printStackTrace(); } } } finally { StreamUtils.safeClose(client); } } protected static ModelControllerClient createClient(final String version, final int port) throws Exception { final ChildFirstClassLoaderBuilder classLoaderBuilder = new ChildFirstClassLoaderBuilder(false); classLoaderBuilder.addRecursiveMavenResourceURL(WFCORE_CLIENT + ":" + version, excludes); classLoaderBuilder.addParentFirstClassPattern("org.jboss.as.controller.client.ModelControllerClient"); classLoaderBuilder.addParentFirstClassPattern("org.jboss.as.controller.client.OperationMessageHandler"); classLoaderBuilder.addParentFirstClassPattern("org.jboss.as.controller.client.Operation"); classLoaderBuilder.addParentFirstClassPattern("org.jboss.as.controller.client.OperationResponse*"); final ClassLoader classLoader = classLoaderBuilder.build(); final Class<?> factoryClass = classLoader.loadClass("org.jboss.as.controller.client.ModelControllerClient$Factory"); final Method factory = factoryClass.getMethod("create", String.class, int.class); try { final Object client = factory.invoke(null, CONTROLLER_ADDRESS, port); final InvocationHandler invocationHandler = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(client, args); } }; final Class<?>[] interfaces = new Class<?>[]{ModelControllerClient.class}; return (ModelControllerClient) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler); } catch (InvocationTargetException e) { Throwable t = e.getCause(); if (t == null) { throw e; } throw t instanceof Exception ? (Exception) t : new RuntimeException(t); } } }
13,305
39.321212
173
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/api/ReadFeatureDescriptionTestCase.java
/* * Copyright 2018 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.integration.management.api; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ANNOTATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILDREN; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FEATURE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PACKAGES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PARAMS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROVIDES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_FEATURE_DESCRIPTION_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RECURSIVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REFS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REQUIRES; import java.io.IOException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Test of read-feature-description handling. * * @author Brian Stansberry */ @RunWith(Arquillian.class) @RunAsClient public class ReadFeatureDescriptionTestCase extends ContainerResourceMgmtTestBase { @Test public void testRecursiveReadFeature() throws IOException, MgmtOperationException { ModelNode op = Util.createEmptyOperation(READ_FEATURE_DESCRIPTION_OPERATION, PathAddress.EMPTY_ADDRESS); op.get(RECURSIVE).set(true); ModelNode result = executeForResult(op); int maxDepth = validateBaseFeature(result, Integer.MAX_VALUE); Assert.assertTrue(result.toString(), maxDepth > 3); // >3 is a good sign we're recursing all the way } private ModelNode executeForResult(ModelNode op) throws IOException, MgmtOperationException { ModelNode result = executeOperation(op); Assert.assertTrue(result.isDefined()); return result; } private static int validateBaseFeature(ModelNode base, int maxChildDepth) { Assert.assertTrue(base.toString(), base.hasDefined(FEATURE)); Assert.assertEquals(base.toString(), 1, base.asInt()); return validateFeature(base.get(FEATURE), null, maxChildDepth, 0); } private static int validateFeature(ModelNode feature, String expectedName, int maxChildDepth, int featureDepth) { int highestDepth = featureDepth; for (Property prop : feature.asPropertyList()) { switch (prop.getName()) { case NAME: if (expectedName != null) { Assert.assertEquals(feature.toString(), expectedName, prop.getValue().asString()); } break; case CHILDREN: if (prop.getValue().isDefined()) { Assert.assertTrue(feature.toString(), maxChildDepth > 0); for (Property child : prop.getValue().asPropertyList()) { int treeDepth = validateFeature(child.getValue(), child.getName(), +maxChildDepth - 1, featureDepth + 1); highestDepth = Math.max(highestDepth, treeDepth); } } break; case ANNOTATION: case PARAMS: case REFS: case PROVIDES: case REQUIRES: case PACKAGES: // all ok; no other validation right now break; default: Assert.fail("Unknown key " + prop.getName() + " in " + feature.toString()); } } return highestDepth; } }
4,889
44.277778
117
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/api/SimpleSubsystemsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.api; import java.io.IOException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.dmr.ModelNode; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode; import static org.junit.Assert.assertTrue; /** * @author Dominik Pospisil <[email protected]> */ @RunWith(Arquillian.class) @RunAsClient public class SimpleSubsystemsTestCase extends ContainerResourceMgmtTestBase { @Test @Ignore /* * The jaxrs subsystem is no longer empty. */ public void testJaxrs() throws Exception { testSimpleSubsystem("jaxrs"); } @Test public void testSar() throws Exception { testSimpleSubsystem("sar"); } @Test public void testPojo() throws Exception { testSimpleSubsystem("pojo"); } @Test public void testJdr() throws Exception { testSimpleSubsystem("jdr"); } private void testSimpleSubsystem(String subsystemName) throws IOException, MgmtOperationException { ModelNode op = createOpNode("subsystem=" + subsystemName, "read-resource"); ModelNode result = executeOperation(op); assertTrue("Subsystem not empty.", result.keys().size() == 0); } }
2,584
32.141026
103
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/api/SocketsAndInterfacesTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.api; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROCESS_STATE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESPONSE_HEADERS; 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.integration.management.util.ModelUtil.createOpNode; import java.io.IOException; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.util.Enumeration; import java.util.concurrent.Callable; 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.network.NetworkUtils; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.integration.management.util.WebUtil; import org.jboss.as.test.shared.RetryTaskExecutor; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.ServerSnapshot; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.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; /** * @author Dominik Pospisil <[email protected]> */ @RunWith(Arquillian.class) @RunAsClient public class SocketsAndInterfacesTestCase extends ContainerResourceMgmtTestBase { private static final Logger logger = Logger.getLogger(SocketsAndInterfacesTestCase.class); @ArquillianResource URL url; private NetworkInterface testNic; private String testHost; private static final int TEST_PORT = 9695; @Deployment public static Archive<?> getDeployment() { JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "SocketsAndInterfacesTestCase-dummy.jar"); ja.addClass(SocketsAndInterfacesTestCase.class); return ja; } private AutoCloseable snapshot; @Before public void before() throws IOException { snapshot = ServerSnapshot.takeSnapshot(getManagementClient()); if (System.getProperties().containsKey("ipv6")) { // if proxy is used, we need to use default host, because used host needs to be set in -DnonProxyHosts and -Dhttp.nonProxyHosts parameter // we can't choose one host randomly testHost = System.getProperty("node0"); testNic = getNic(testHost); } else { testNic = getNonDefaultNic(); // test the connector testHost = NetworkUtils.canonize(testNic.getInetAddresses().nextElement().getHostAddress()); } } @After public void after() throws Exception { snapshot.close(); snapshot = null; } @Test public void testAddUpdateRemove() throws Exception { if (testNic == null) { logger.error("Could not look up non-default interface"); return; } // add interface ModelNode op = createOpNode("interface=test123-interface", ADD); op.get("nic").set(testNic.getName()); op.get("inet-address").set(testHost); ModelNode result = executeOperation(op); // add socket binding using created interface op = createOpNode("socket-binding-group=standard-sockets/socket-binding=test123-binding", ADD); op.get("interface").set("test123-interface"); op.get("port").set(TEST_PORT); result = executeOperation(op); // add a web connector so we can test the interface op = createOpNode("subsystem=undertow/server=default-server/http-listener=test", ADD); op.get("socket-binding").set("test123-binding"); result = executeOperation(op); final URL url = new URL("http", testHost, TEST_PORT, "/"); Assert.assertTrue("Could not connect to created connector: " + url + "<>" + InetAddress.getByName(url.getHost()) + "..." + testNic + ".>" + result, WebUtil.testHttpURL(url.toString())); // change socket binding port op = createOpNode("socket-binding-group=standard-sockets/socket-binding=test123-binding", WRITE_ATTRIBUTE_OPERATION); op.get(NAME).set("port"); op.get(VALUE).set(TEST_PORT + 1); result = executeOperation(op, false); Assert.assertEquals(SUCCESS, result.get(OUTCOME).asString()); Assert.assertTrue(result.get(RESPONSE_HEADERS).get(PROCESS_STATE).asString().equals("reload-required")); logger.trace("Restarting server."); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); // wait until the connector is available on the new port final String testUrl = new URL("http", testHost, TEST_PORT + 1, "/").toString(); RetryTaskExecutor<Boolean> rte = new RetryTaskExecutor<Boolean>(); rte.retryTask(new Callable<Boolean>() { public Boolean call() throws Exception { boolean available = WebUtil.testHttpURL(testUrl); if (!available) throw new Exception("Connector not available."); return available; } }); logger.trace("Server is up."); // check the connector is not listening on the old port Assert.assertFalse("Could not connect to created connector.", WebUtil.testHttpURL(new URL( "http", testHost, TEST_PORT, "/").toString())); // try to remove the interface while the socket binding is still bound to it - should fail op = createOpNode("interface=test123-interface", REMOVE); result = executeOperation(op, false); Assert.assertFalse("Removed interface with socket binding bound to it.", SUCCESS.equals(result.get(OUTCOME).asString())); // try to remove socket binding while the connector is still using it - should fail op = createOpNode("socket-binding-group=standard-sockets/socket-binding=test123-binding", REMOVE); result = executeOperation(op, false); Assert.assertFalse("Removed socked binding with connector still using it.", SUCCESS.equals(result.get(OUTCOME).asString())); } private NetworkInterface getNonDefaultNic() throws SocketException, UnknownHostException { InetAddress defaultAddr = InetAddress.getByName(url.getHost()); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface nic = interfaces.nextElement(); if (!nic.isUp()) { continue; } for (InterfaceAddress addr : nic.getInterfaceAddresses()) { if (addr.getAddress().equals(defaultAddr)) continue; } // interface found return nic; } return null; // no interface found } private NetworkInterface getNic(String node) throws SocketException, UnknownHostException { if (node == null) { return null; } InetAddress node1Address = InetAddress.getByName(node); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface nic = interfaces.nextElement(); if (!nic.isUp()) { continue; } for (InterfaceAddress addr : nic.getInterfaceAddresses()) { if (addr.getAddress().equals(node1Address)) { return nic; } } } return null; // no interface found } }
9,491
42.342466
193
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/api/expression/Utils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.api.expression; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESOLVE_EXPRESSIONS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE; 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.integration.management.util.ModelUtil.createOpNode; import java.io.IOException; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.junit.Assert; /** * Utility class used for manipulation with system properties via dmr api. * * @author <a href="[email protected]">Ondrej Chaloupka</a> */ public class Utils { private static final Logger log = Logger.getLogger(Utils.class); public static void setProperty(String name, String value, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, ADD); modelNode.get(VALUE).set(value); ModelNode result = executeOp(modelNode, client); log.debugf("Added property %s, result: %s", name, result); } public static void removeProperty(String name, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, REMOVE); ModelNode result = executeOp(modelNode, client); log.debugf("Removing property %s. Result: %s.", name, result); } public static void redefineProperty(String name, String value, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, WRITE_ATTRIBUTE_OPERATION); modelNode.get(NAME).set(VALUE); modelNode.get(VALUE).set(value); ModelNode result = executeOp(modelNode, client); log.debugf("Redefine property %s to value %s. Result: %s.", name, value, result); } public static ModelNode executeOp(ModelNode op, ModelControllerClient client) { ModelNode modelNodeResult; try { modelNodeResult = client.execute(op); } catch (IOException ioe) { throw new RuntimeException(ioe); } if (!SUCCESS.equals(modelNodeResult.get(OUTCOME).asString())) { throw new RuntimeException("Management operation: " + op + " was not successful. Result was: " + modelNodeResult); } return modelNodeResult; } public static String getProperty(String name, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, READ_ATTRIBUTE_OPERATION); modelNode.get(NAME).set(VALUE); modelNode.get(RESOLVE_EXPRESSIONS).set(true); ModelNode result = executeOp(modelNode, client); Assert.assertEquals(SUCCESS, result.get(OUTCOME).asString()); ModelNode resolvedResult = result;//resolved by read operation already log.debugf("Resolved property %s with result: %s", name, resolvedResult); Assert.assertEquals(SUCCESS, resolvedResult.get(OUTCOME).asString()); return resolvedResult.get("result").asString(); } }
4,704
46.05
126
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/api/expression/ExpressionSubstitutionInContainerTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.api.expression; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.io.FilePermission; import java.util.PropertyPermission; import jakarta.ejb.EJB; import org.jboss.arquillian.container.test.api.Deployment; 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.remoting3.security.RemotingPermission; import org.jboss.as.test.integration.management.util.ModelUtil; import org.jboss.as.test.shared.TestSuiteEnvironment; 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.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.api.Authentication; /** * Validation of the system property substitution for expressions handling. Test for AS7-6120. * Global parameters testing could be found in domain module: ExpressionSupportSmokeTestCase * <p> * The expression substitution test runs the evaluation of expressions in bean deployed in container. * The managementClient injected by arquillian is taken via remote interface. * * @author <a href="[email protected]">Ondrej Chaloupka</a> */ @RunWith(Arquillian.class) public class ExpressionSubstitutionInContainerTestCase { private static final String ARCHIVE_NAME = "expression-substitution-test"; private static final String PROP_NAME = "qa.test.property"; private static final String PROP_DEFAULT_VALUE = "defaultValue"; private static final String EXPRESSION_PROP_NAME = "qa.test.exp"; private static final String EXPRESSION_PROP_VALUE = "expression.value"; private static final String INNER_PROP_NAME = "qa.test.inner.property"; private static final String INNER_PROP_DEFAULT_VALUE = "inner.value"; @EJB private StatelessBean bean; @ArquillianResource private ManagementClient managementClient; @Deployment public static Archive<?> deploy() { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addPackage(ExpressionSubstitutionInContainerTestCase.class.getPackage()); jar.addClasses(ModelUtil.class, TestSuiteEnvironment.class, Authentication.class); jar.addAsManifestResource(new StringAsset( "Manifest-Version: 1.0\n" + "Class-Path: \n" + // there has to be a spacer - otherwise you meet "java.io.IOException: invalid header field" "Dependencies: org.jboss.as.controller-client, org.jboss.as.controller, org.jboss.dmr, org.jboss.remoting \n"), "MANIFEST.MF"); jar.addAsManifestResource(createPermissionsXmlAsset( // Needed by the StatelessBean#addSystemProperty() new PropertyPermission("qa.test.*", "write"), new PropertyPermission("qa.test.*", "read"), new RemotingPermission("createEndpoint"), new RemotingPermission("connect"), new PropertyPermission("management.address", "read"), new PropertyPermission("node0", "read"), new PropertyPermission("as.managementPort", "read"), new PropertyPermission("management.port", "read"), new PropertyPermission("jboss.management.user", "read"), new PropertyPermission("jboss.management.password", "read"), new FilePermission(System.getProperty("jboss.inst") + "/standalone/tmp/auth/*", "read") ), "jboss-permissions.xml"); return jar; } /** * <system-properties> * <property name="qa.test.exp" value="expression.value"/> * <property name="qa.test.property" value="${qa.test.exp:defaultValue}"/> * </system-properties> */ @Test @InSequence(1) public void testPropertyDefinedFirst() { Utils.setProperty(EXPRESSION_PROP_NAME, EXPRESSION_PROP_VALUE, managementClient.getControllerClient()); Utils.setProperty(PROP_NAME, "${" + EXPRESSION_PROP_NAME + ":" + PROP_DEFAULT_VALUE + "}", managementClient.getControllerClient()); try { expresionEvaluation(); } finally { // removing tested properties Utils.removeProperty(EXPRESSION_PROP_NAME, managementClient.getControllerClient()); Utils.removeProperty(PROP_NAME, managementClient.getControllerClient()); } } /* * <system-properties> * <property name="qa.test.property" value="${qa.test.exp:defaultValue}"/> * <property name="qa.test.exp" value="expression.value"/> * </system-properties> */ /*@Ignore("AS7-6431") @Test @InSequence(2) public void testExpressionDefinedFirst() { Utils.setProperty(PROP_NAME, "${" + EXPRESSION_PROP_NAME + ":" + PROP_DEFAULT_VALUE + "}", managementClient.getControllerClient()); Utils.setProperty(EXPRESSION_PROP_NAME, EXPRESSION_PROP_VALUE, managementClient.getControllerClient()); try { expresionEvaluation(); } finally { // removing tested properties Utils.removeProperty(EXPRESSION_PROP_NAME, managementClient.getControllerClient()); Utils.removeProperty(PROP_NAME, managementClient.getControllerClient()); } }*/ /** * <system-properties> * <property name="qa.test.property" value="${qa.test.exp:defaultValue}"/> * </system-properties> */ @Test @InSequence(3) public void testSystemPropertyEvaluation() { // the system property has to be defined in the same VM as the container resides bean.addSystemProperty(EXPRESSION_PROP_NAME, EXPRESSION_PROP_VALUE); Utils.setProperty(PROP_NAME, "${" + EXPRESSION_PROP_NAME + ":" + PROP_DEFAULT_VALUE + "}", managementClient.getControllerClient()); try { systemPropertyEvaluation(); } finally { // removing tested properties Utils.removeProperty(PROP_NAME, managementClient.getControllerClient()); } } /** * <system-properties> * <property name="qa.test.property" value="${qa.test.exp:defaultValue}"/> * </system-properties> */ @Test @InSequence(4) public void testSystemPropertyEvaluationSetAfterExpression() { Utils.setProperty(PROP_NAME, "${" + EXPRESSION_PROP_NAME + ":" + PROP_DEFAULT_VALUE + "}", managementClient.getControllerClient()); // the system property has to be defined in the same VM as the container resides bean.addSystemProperty(EXPRESSION_PROP_NAME, EXPRESSION_PROP_VALUE); try { systemPropertyEvaluation(); } finally { // removing tested properties Utils.removeProperty(PROP_NAME, managementClient.getControllerClient()); } } private void systemPropertyEvaluation() { // test resolution of expressions String result = bean.getJBossProperty(PROP_NAME); Assert.assertEquals("jboss property " + PROP_NAME + " evaluation - value should be taken from system property", EXPRESSION_PROP_VALUE, result); result = bean.getSystemProperty(EXPRESSION_PROP_NAME); Assert.assertEquals("system property " + EXPRESSION_PROP_NAME + " from directly defined system property", EXPRESSION_PROP_VALUE, result); result = bean.getSystemProperty(PROP_NAME); Assert.assertEquals("system property " + PROP_NAME + " from evaluated jboss property", EXPRESSION_PROP_VALUE, result); } /** * <system-properties> * <property name="qa.test.exp" value="expression.value"/> * <property name="qa.test.inner.property" value="${qa.test.exp:inner.value}"/> * <property name="qa.test.property" value="${qa.test.inner.property:defaultValue}"/> * </system-properties> */ @Test @InSequence(5) public void testMultipleLevelExpression() { Utils.setProperty(EXPRESSION_PROP_NAME, EXPRESSION_PROP_VALUE, managementClient.getControllerClient()); Utils.setProperty(INNER_PROP_NAME, "${" + EXPRESSION_PROP_NAME + ":" + INNER_PROP_DEFAULT_VALUE + "}", managementClient.getControllerClient()); Utils.setProperty(PROP_NAME, "${" + INNER_PROP_NAME + ":" + PROP_DEFAULT_VALUE + "}", managementClient.getControllerClient()); try { // evaluation the inner prop name in addition String result = bean.getJBossProperty(INNER_PROP_NAME); Assert.assertEquals("jboss property " + INNER_PROP_NAME + " substitution evaluation expected", EXPRESSION_PROP_VALUE, result); result = bean.getSystemProperty(INNER_PROP_NAME); Assert.assertEquals("system property " + INNER_PROP_NAME + " from substitued jboss property", EXPRESSION_PROP_VALUE, result); // then evaluation of the rest expresionEvaluation(); } finally { // removing tested properties Utils.removeProperty(EXPRESSION_PROP_NAME, managementClient.getControllerClient()); Utils.removeProperty(PROP_NAME, managementClient.getControllerClient()); Utils.removeProperty(INNER_PROP_NAME, managementClient.getControllerClient()); } } /** * <system-properties> * <property name="first.defined.value" value="expression.value"/> * <property name="qa.test.property" value="${qa.test.exp:defaultValue}"/> * </system-properties> * <p> * Write attribute set: * <property name="qa.test.exp" value="expression.value"/> *//* @Ignore("AS7-6431") // for this test works there will be :reload after redefinition @Test @InSequence(6) public void testRedefinitionExpressionValue() { Utils.setProperty(EXPRESSION_PROP_NAME, "firstly.defined.value.", managementClient.getControllerClient()); Utils.setProperty(PROP_NAME, "${" + EXPRESSION_PROP_NAME + ":" + PROP_DEFAULT_VALUE + "}", managementClient.getControllerClient()); Utils.redefineProperty(EXPRESSION_PROP_NAME, EXPRESSION_PROP_VALUE, managementClient.getControllerClient()); try { expresionEvaluation(); } finally { // removing tested properties Utils.removeProperty(EXPRESSION_PROP_NAME, managementClient.getControllerClient()); Utils.removeProperty(PROP_NAME, managementClient.getControllerClient()); } }*/ private void expresionEvaluation() { String result = bean.getJBossProperty(EXPRESSION_PROP_NAME); Assert.assertEquals("jboss property " + EXPRESSION_PROP_NAME + " defined directly", EXPRESSION_PROP_VALUE, result); result = bean.getJBossProperty(PROP_NAME); Assert.assertEquals("jboss property " + PROP_NAME + " substitution evaluation expected", EXPRESSION_PROP_VALUE, result); result = bean.getSystemProperty(EXPRESSION_PROP_NAME); Assert.assertEquals("system property " + EXPRESSION_PROP_NAME + " from directly defined jboss property", EXPRESSION_PROP_VALUE, result); result = bean.getSystemProperty(PROP_NAME); Assert.assertEquals("system property " + PROP_NAME + " from evaluated jboss property", EXPRESSION_PROP_VALUE, result); } }
12,541
45.110294
151
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/api/expression/StatelessBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.api.expression; import jakarta.ejb.Stateless; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.logging.Logger; @Stateless public class StatelessBean { private static final Logger log = Logger.getLogger(StatelessBean.class); private ModelControllerClient getClient() { return TestSuiteEnvironment.getModelControllerClient(); } public String getJBossProperty(String name) { ModelControllerClient client = getClient(); String result = Utils.getProperty(name, client); log.debug("JBoss system property " + name + " was resolved to be " + result); return result; } public void addSystemProperty(String name, String value) { System.setProperty(name, value); } public String getSystemProperty(String name) { String result = System.getProperty(name); log.debug("System property " + name + " has value " + result); return result; } }
2,099
34.59322
85
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/api/web/VirtualServerTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.api.web; import java.io.IOException; import java.net.URL; import java.util.concurrent.TimeUnit; import org.jboss.logging.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.integration.management.util.SimpleServlet; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode; import static org.junit.Assert.assertTrue; /** * * @author Dominik Pospisil <[email protected]> */ @RunWith(Arquillian.class) @RunAsClient //todo this test could probably be done in manual mode test with wildfly runner, also could be merged into VirtualHostTestCase public class VirtualServerTestCase extends ContainerResourceMgmtTestBase { @ArquillianResource URL url; private static String defaultHost; private static String virtualHost; private static final Logger log = Logger.getLogger(VirtualServerTestCase.class.getName()); @Deployment(order=1) public static Archive<?> getDeployment() { JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "dummy.jar"); ja.addClass(VirtualServerTestCase.class); return ja; } @Deployment(managed=false, name="vsdeployment", order=2) public static Archive<?> getVDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, "vsDeployment.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(new StringAsset("Virtual Server Deployment"), "index.html"); war.addAsWebResource(new StringAsset("Rewrite Test"), "/rewritten/index.html"); war.addAsWebInfResource(new StringAsset("<jboss-web><virtual-host>test</virtual-host></jboss-web>"), "jboss-web.xml"); return war; } @Test public void testDefaultVirtualServer() throws IOException, MgmtOperationException { // get default VS ModelNode result = executeOperation(createOpNode("subsystem=undertow/server=default-server/host=default-host", "read-resource")); // check VS assertTrue(result.get("alias").isDefined()); assertTrue(result.get("default-web-module").asString().equals("ROOT.war")); } @Test public void addRemoveVirtualServer(@ArquillianResource Deployer deployer) throws Exception { if (! resolveHosts()) { log.trace("Unable to resolve alternate server host name."); return; } addVirtualServer(); // deploy to virtual server deployer.deploy("vsdeployment"); // check the deployment is available on and only on virtual server URL vURL = new URL(url.getProtocol(), virtualHost, url.getPort(), "/vsDeployment/index.html"); String response = HttpRequest.get(vURL.toString(), 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("Virtual Server Deployment") >=0); URL dURL = new URL(url.getProtocol(), defaultHost, url.getPort(), "/vsDeployment/index.html"); boolean failed = false; try { response = HttpRequest.get(dURL.toString(), 10, TimeUnit.SECONDS); } catch (Exception e) { failed = true; } assertTrue("Deployment also on default server. " , failed); // undeploy form virtual server deployer.undeploy("vsdeployment"); // remove virtual server removeVirtualServer(); } private void addVirtualServer() throws IOException, MgmtOperationException { ModelNode addOp = createOpNode("subsystem=undertow/server=default-server/host=test", "add"); addOp.get("alias").add(virtualHost); addOp.get("default-web-module").set("some-test.war"); ModelNode rewrite = new ModelNode(); rewrite.get("condition").setEmptyList(); rewrite.get("pattern").set("toberewritten"); rewrite.get("substitution").set("rewritten"); rewrite.get("flags").set("nocase"); //TODO add support for rewrites! //addOp.get("rewrite").add(rewrite); executeOperation(addOp); } private void removeVirtualServer() throws IOException, MgmtOperationException { executeOperation(createOpNode("subsystem=undertow/server=default-server/host=test", "remove")); } private boolean resolveHosts() { if (url.getHost().equals("localhost") || (url.getHost().equals("127.0.0.1"))) { defaultHost = "localhost"; virtualHost = "127.0.0.1"; return true; } return false; } }
6,320
38.018519
137
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/console/HttpManagementConstantHeadersTestCase.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.integration.management.console; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.io.Closeable; import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClients; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.http.Authentication; import org.jboss.as.test.integration.management.util.ServerReload; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * Test case to test custom / constant headers are applied to /console. * See WFCORE-1110. * * @author <a href="mailto:[email protected]">Tomas Terem</a> */ @RunWith(Arquillian.class) @RunAsClient public class HttpManagementConstantHeadersTestCase { private static final int MGMT_PORT = 9990; private static final String ROOT_CTX = "/"; private static final String CONSOLE_CTX = "/console"; private static final String ERROR_CTX = "/error"; private static final String METRICS_CTX = "/metrics"; private static final String TEST_VALUE = "TestValue"; private static final PathAddress INTERFACE_ADDRESS = PathAddress.pathAddress(PathElement.pathElement("core-service", "management"), PathElement.pathElement("management-interface", "http-interface")); @ContainerResource protected ManagementClient managementClient; private URL managementConsoleUrl; private URL errorUrl; private URL metricsUrl; private HttpClient httpClient; @Before public void createClient() throws Exception { String address = managementClient.getMgmtAddress(); this.managementConsoleUrl = new URL("http", address, MGMT_PORT, CONSOLE_CTX); this.errorUrl = new URL("http", address, MGMT_PORT, ERROR_CTX); this.metricsUrl = new URL("http", address, MGMT_PORT, METRICS_CTX); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(managementConsoleUrl.getHost(), managementConsoleUrl.getPort()), new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD)); this.httpClient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .build(); } @After public void closeClient() { if (httpClient instanceof Closeable) { try { ((Closeable) httpClient).close(); } catch (IOException e) { Logger.getLogger(HttpManagementConstantHeadersTestCase.class).error("Failed closing client", e); } } } private void activateHeaders() throws Exception { Map<String, List<Map<String, String>>> headersMap = new HashMap<>(); headersMap.put(ROOT_CTX, Collections.singletonList(Collections.singletonMap("X-All", "All"))); headersMap.put(CONSOLE_CTX, Collections.singletonList(Collections.singletonMap("X-Management", "Management"))); headersMap.put(ERROR_CTX, Collections.singletonList(Collections.singletonMap("X-Error", "Error"))); managementClient.getControllerClient().execute(createConstantHeadersOperation(headersMap)); ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient()); } private static ModelNode createConstantHeadersOperation(final Map<String, List<Map<String, String>>> constantHeadersValues) { ModelNode writeAttribute = new ModelNode(); writeAttribute.get("address").set(INTERFACE_ADDRESS.toModelNode()); writeAttribute.get("operation").set("write-attribute"); writeAttribute.get("name").set("constant-headers"); ModelNode constantHeaders = new ModelNode(); for (Entry<String, List<Map<String, String>>> entry : constantHeadersValues.entrySet()) { for (Map<String, String> header: entry.getValue()) { constantHeaders.add(createHeaderMapping(entry.getKey(), header)); } } writeAttribute.get("value").set(constantHeaders); return writeAttribute; } private static ModelNode createHeaderMapping(final String path, final Map<String, String> headerValues) { ModelNode headerMapping = new ModelNode(); headerMapping.get("path").set(path); ModelNode headers = new ModelNode(); headers.add(); // Ensure the type of 'headers' is List even if no content is added. headers.remove(0); for (Entry<String, String> entry : headerValues.entrySet()) { ModelNode singleMapping = new ModelNode(); singleMapping.get("name").set(entry.getKey()); singleMapping.get("value").set(entry.getValue()); headers.add(singleMapping); } headerMapping.get("headers").set(headers); return headerMapping; } @After public void removeHeaders() throws Exception { ModelNode undefineAttribute = new ModelNode(); undefineAttribute.get("address").set(INTERFACE_ADDRESS.toModelNode()); undefineAttribute.get("operation").set("undefine-attribute"); undefineAttribute.get("name").set("constant-headers"); managementClient.getControllerClient().execute(undefineAttribute); ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient()); } /** * Test that a call to the '/console' endpoint returns the expected headers. */ @Test public void testConsole() throws Exception { activateHeaders(); HttpGet get = new HttpGet(managementConsoleUrl.toURI().toString()); HttpResponse response = httpClient.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); Header header = response.getFirstHeader("X-All"); assertEquals("All", header.getValue()); header = response.getFirstHeader("X-Management"); assertEquals("Management", header.getValue()); header = response.getFirstHeader("X-Error"); assertNull("Header X-Error Unexpected", header); } /** * Test that a call to the '/error' endpoint returns the expected headers. */ @Test public void testError() throws Exception { activateHeaders(); HttpGet get = new HttpGet(errorUrl.toURI().toString()); HttpResponse response = httpClient.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); Header header = response.getFirstHeader("X-All"); assertEquals("All", header.getValue()); header = response.getFirstHeader("X-Error"); assertEquals("Error", header.getValue()); header = response.getFirstHeader("X-Management"); assertNull("Header X-Management Unexpected", header); } /** * Test that security headers can be configured and are returned from '/console' endpoint */ @Test public void testSecurity() throws Exception { Map<String, List<Map<String, String>>> headersMap = new HashMap<>(); List<Map<String, String>> headers = new LinkedList<>(); headers.add(Collections.singletonMap("X-XSS-Protection", "1; mode=block")); headers.add(Collections.singletonMap("X-Frame-Options", "SAMEORIGIN")); headers.add(Collections.singletonMap("Content-Security-Policy", "default-src https: data: 'unsafe-inline' 'unsafe-eval'")); headers.add(Collections.singletonMap("Strict-Transport-Security", "max-age=31536000; includeSubDomains;")); headers.add(Collections.singletonMap("X-Content-Type-Options", "nosniff")); headersMap.put(CONSOLE_CTX, headers); managementClient.getControllerClient().execute(createConstantHeadersOperation(headersMap)); ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient()); HttpGet get = new HttpGet(managementConsoleUrl.toURI().toString()); HttpResponse response = httpClient.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); Header header = response.getFirstHeader("X-XSS-Protection"); assertEquals("1; mode=block", header.getValue()); header = response.getFirstHeader("X-Frame-Options"); assertEquals("SAMEORIGIN", header.getValue()); header = response.getFirstHeader("Content-Security-Policy"); assertEquals("default-src https: data: 'unsafe-inline' 'unsafe-eval'", header.getValue()); header = response.getFirstHeader("Strict-Transport-Security"); assertEquals("max-age=31536000; includeSubDomains;", header.getValue()); header = response.getFirstHeader("X-Content-Type-Options"); assertEquals("nosniff", header.getValue()); } /** * Test that configured headers override original headers set by /console endpoint (except for disallowed headers) */ @Test public void testHeadersOverride() throws Exception { HttpGet get = new HttpGet(managementConsoleUrl.toURI().toString()); HttpResponse response = httpClient.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); Header[] headerArray = response.getAllHeaders(); List<Header> headerList = Arrays.stream(headerArray) .filter(header -> !header.getName().equals("Connection") && !header.getName().equals("Date") && !header.getName().equals("Transfer-Encoding") && !header.getName().equals("Content-Type") && !header.getName().equals("Content-Length")) .collect(Collectors.toList()); Map<String, List<Map<String, String>>> headersMap = new HashMap<>(); List<Map<String, String>> headers = new LinkedList<>(); for (Header header : headerList) { headers.add(Collections.singletonMap(header.getName(), TEST_VALUE)); } headersMap.put(CONSOLE_CTX, headers); managementClient.getControllerClient().execute(createConstantHeadersOperation(headersMap)); ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient()); get = new HttpGet(managementConsoleUrl.toURI().toString()); response = httpClient.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); for (Header header : headerList) { assertEquals(TEST_VALUE, response.getFirstHeader(header.getName()).getValue()); } } /** * Test that configured headers override original headers set by non-management /metrics endpoint (except for disallowed headers) */ @Test public void testHeadersOverrideNonManagementEndpoint() throws Exception { Assume.assumeTrue(checkIfMetricsUsable()); HttpGet get = new HttpGet(metricsUrl.toURI().toString()); HttpResponse response = httpClient.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); Header[] headerArray = response.getAllHeaders(); List<Header> headerList = Arrays.stream(headerArray) .filter(header -> !header.getName().equals("Connection") && !header.getName().equals("Date") && !header.getName().equals("Transfer-Encoding") && !header.getName().equals("Content-Type") && !header.getName().equals("Content-Length")) .collect(Collectors.toList()); Map<String, List<Map<String, String>>> headersMap = new HashMap<>(); List<Map<String, String>> headers = new LinkedList<>(); for (Header header : headerList) { headers.add(Collections.singletonMap(header.getName(), TEST_VALUE)); } headersMap.put(METRICS_CTX, headers); managementClient.getControllerClient().execute(createConstantHeadersOperation(headersMap)); ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient()); get = new HttpGet(metricsUrl.toURI().toString()); response = httpClient.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); for (Header header : headerList) { assertEquals(TEST_VALUE, response.getFirstHeader(header.getName()).getValue()); } } /** * Check if we cannot assume the use of metrics to run a test. We could have this situation when we are testing layers * and the current server provision does not configure metrics. */ private boolean checkIfMetricsUsable() throws IOException { if (Boolean.getBoolean("ts.layers")) { ModelNode metricsReadOp = Util.getReadResourceOperation(PathAddress.pathAddress(SUBSYSTEM, "metrics")); ModelNode result = managementClient.getControllerClient().execute(metricsReadOp); if (!result.get(OUTCOME).asString().equals(SUCCESS)) { return false; } } return false; } }
14,395
40.249284
197
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/console/XFrameOptionsHeaderTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.console; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.util.Arrays; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.http.Authentication; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests presence of X-Frame-Options header in response from management console * * @author Jan Kasik <[email protected]> */ @RunWith(Arquillian.class) @RunAsClient public class XFrameOptionsHeaderTestCase { private static final int MGMT_PORT = 9990; @ContainerResource private ManagementClient managementClient; @Test public void checkManagementConsoleForXFrameOptionsHeader() throws IOException, URISyntaxException { URL url = new URL("http", managementClient.getMgmtAddress(), MGMT_PORT, "/console/index.html"); checkURLForHeader(url, "X-Frame-Options", "SAMEORIGIN"); } private void checkURLForHeader(URL url, String headerName, String expectedHeaderValue) throws URISyntaxException, IOException { try (CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultCredentialsProvider(createCredentialsProvider(url)) .build()) { HttpContext httpContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet(url.toURI()); HttpResponse response = httpClient.execute(httpGet, httpContext); int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Wrong response code: " + statusCode + " for url '" + url.toString() + "'.", HttpURLConnection.HTTP_OK, statusCode); Header[] headers = response.getHeaders(headerName); assertNotNull("Unexpected behaviour of HttpResponse#getHeaders() returned null!", headers); assertTrue("There is no '" + headerName + "' header present! Headers present: " + Arrays.toString(response.getAllHeaders()), headers.length > 0); for (Header header : headers) { if (header.getValue().equals(expectedHeaderValue)) { return; } } fail("No header '" + headerName + "' with value '" + expectedHeaderValue + "' found!"); } } private CredentialsProvider createCredentialsProvider(URL url) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD); credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort(), "ManagementRealm"), credentials); return credentialsProvider; } }
4,733
42.431193
132
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/console/WebConsoleRedirectionTestCase.java
/* * JBoss, Home of Professional Open Source * Copyright 2017, Red Hat, Inc., and individual contributors as indicated * by the @authors tag. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.management.console; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import io.undertow.util.Headers; import java.net.HttpURLConnection; import java.net.URL; import org.apache.http.client.methods.HttpGet; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.junit.Test; import org.junit.runner.RunWith; /** * @author Tomas Hofman ([email protected]) */ @RunWith(Arquillian.class) @RunAsClient public class WebConsoleRedirectionTestCase { @SuppressWarnings("unused") @ContainerResource private ManagementClient managementClient; @Test public void testRedirectionInAdminMode() throws Exception { ServerReload.executeReloadAndWaitForCompletion(managementClient, true); try { final HttpURLConnection connection = getConnection(); assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, connection.getResponseCode()); String location = connection.getHeaderFields().get(Headers.LOCATION_STRING).get(0); assertEquals("/consoleerror/noConsoleForAdminModeError.html", location); } finally { ServerReload.executeReloadAndWaitForCompletion(managementClient, false); } } @Test public void testRedirectionInNormalMode() throws Exception { final HttpURLConnection connection = getConnection(); assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, connection.getResponseCode()); String location = connection.getHeaderFields().get(Headers.LOCATION_STRING).get(0); assertEquals("/console/index.html", location); } private HttpURLConnection getConnection() throws Exception { final URL url = new URL("http://" + TestSuiteEnvironment.getServerAddress() + ":" + TestSuiteEnvironment.getServerPort() + "/"); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); assertNotNull(connection); connection.setInstanceFollowRedirects(false); connection.setRequestMethod(HttpGet.METHOD_NAME); connection.connect(); return connection; } }
3,119
37.04878
136
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/TimerEJBRuntimeNameTestCase.java
package org.jboss.as.test.integration.management.deploy.runtime; import java.util.Hashtable; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; 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.test.integration.ejb.remote.common.EJBManagementUtil; import org.jboss.as.test.integration.management.deploy.runtime.ejb.singleton.timer.PointLessBean; import org.jboss.as.test.integration.management.deploy.runtime.ejb.singleton.timer.PointlessInterface; import org.jboss.as.test.integration.management.util.ModelUtil; 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.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @RunAsClient public class TimerEJBRuntimeNameTestCase extends AbstractRuntimeTestCase { private static final Logger log = Logger.getLogger(TimerEJBRuntimeNameTestCase.class); private static final String EJB_TYPE = EJBManagementUtil.SINGLETON; private static final Package BEAN_PACKAGE = PointLessBean.class.getPackage(); private static final Class<?> BEAN_CLASS = PointlessInterface.class; private static final String BEAN_NAME = "POINT"; private static final String RT_MODULE_NAME = "nooma-nooma6-" + EJB_TYPE; private static final String RT_NAME = RT_MODULE_NAME + ".ear"; private static final String DEPLOYMENT_MODULE_NAME = "test6-" + EJB_TYPE + "-test"; private static final String DEPLOYMENT_NAME = DEPLOYMENT_MODULE_NAME + ".ear"; private static final String SUB_DEPLOYMENT_MODULE_NAME = "ejb"; private static final String SUB_DEPLOYMENT_NAME = SUB_DEPLOYMENT_MODULE_NAME + ".jar"; private static ModelControllerClient controllerClient = TestSuiteEnvironment.getModelControllerClient(); @BeforeClass public static void setup() throws Exception { JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, SUB_DEPLOYMENT_NAME); ejbJar.addPackage(BEAN_PACKAGE); EnterpriseArchive earArchive = ShrinkWrap.create(EnterpriseArchive.class, DEPLOYMENT_NAME); earArchive.addAsModule(ejbJar); ModelNode addDeploymentOp = new ModelNode(); addDeploymentOp.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); addDeploymentOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); addDeploymentOp.get(ModelDescriptionConstants.CONTENT).get(0).get(ModelDescriptionConstants.INPUT_STREAM_INDEX).set(0); addDeploymentOp.get(ModelDescriptionConstants.RUNTIME_NAME).set(RT_NAME); addDeploymentOp.get(ModelDescriptionConstants.AUTO_START).set(true); ModelNode deployOp = new ModelNode(); deployOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.DEPLOY); deployOp.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); deployOp.get(ModelDescriptionConstants.ENABLED).set(true); ModelNode[] steps = new ModelNode[2]; steps[0] = addDeploymentOp; steps[1] = deployOp; ModelNode compositeOp = ModelUtil.createCompositeNode(steps); OperationBuilder ob = new OperationBuilder(compositeOp, true); ob.addInputStream(earArchive.as(ZipExporter.class).exportAsInputStream()); ModelNode result = controllerClient.execute(ob.build()); // just to blow up Assert.assertTrue("Failed to deploy: " + result, Operations.isSuccessfulOutcome(result)); } @AfterClass public static void tearDown() throws Exception { ModelNode result = controllerClient.execute(composite( undeploy(DEPLOYMENT_NAME), remove(DEPLOYMENT_NAME) )); // just to blow up Assert.assertTrue("Failed to undeploy: " + result, Operations.isSuccessfulOutcome(result)); } @Test public void testStepByStep() throws Exception { ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); readResource.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); ModelNode result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.SUBDEPLOYMENT, SUB_DEPLOYMENT_NAME); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.SUBSYSTEM, "ejb3"); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(EJB_TYPE, BEAN_NAME); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); } @Test public void testRecursive() throws Exception { ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); readResource.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); readResource.get(ModelDescriptionConstants.RECURSIVE).set(true); ModelNode result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); } @Test public void testTimer() throws Exception{ final InitialContext context = getInitialContext(); try{ PointlessInterface pointlessInterface = (PointlessInterface) context.lookup(getEJBJNDIBinding()); pointlessInterface.triggerTimer(); Thread.currentThread().sleep(1000); Assert.assertTrue("Did not receive timer invocation!",pointlessInterface.getTimerCount()>0); } finally{ safeClose(context); } } private String getEJBJNDIBinding() { final String appName = RT_MODULE_NAME; final String moduleName = SUB_DEPLOYMENT_MODULE_NAME; final String distinctName = ""; final String beanName = BEAN_NAME; final String viewClassName = BEAN_CLASS.getName(); return "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName; } private static InitialContext getInitialContext() throws NamingException { final Hashtable env = new Hashtable(); env.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); env.put(Context.INITIAL_CONTEXT_FACTORY, org.wildfly.naming.client.WildFlyInitialContextFactory.class.getName()); env.put(Context.PROVIDER_URL, "remote+http://" + TestSuiteEnvironment.getServerAddress() + ":" + 8080); return new InitialContext(env); } private static void safeClose(InitialContext context) { if (context == null) { return; } try { context.close(); } catch (Throwable t) { // just log log.trace("Ignoring a problem which occurred while closing: " + context, t); } context = null; } }
8,517
46.586592
127
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/StatelessEJBRemoteHomeRuntimeNameTestCase.java
package org.jboss.as.test.integration.management.deploy.runtime; import java.util.Hashtable; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; 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.test.integration.ejb.home.remotehome.SimpleHome; import org.jboss.as.test.integration.ejb.home.remotehome.SimpleInterface; import org.jboss.as.test.integration.ejb.home.remotehome.annotation.SimpleStatelessBean; import org.jboss.as.test.integration.ejb.remote.common.EJBManagementUtil; import org.jboss.as.test.integration.management.util.ModelUtil; 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.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @RunAsClient public class StatelessEJBRemoteHomeRuntimeNameTestCase extends AbstractRuntimeTestCase { private static Logger log = Logger.getLogger(StatelessEJBRemoteHomeRuntimeNameTestCase.class); private static final String EJB_TYPE = EJBManagementUtil.STATELESS; private static final Package BEAN_PACKAGE = SimpleHome.class.getPackage(); private static final Class<?> BEAN_CLASS = SimpleStatelessBean.class; private static final String RT_MODULE_NAME = "nooma-nooma3-" + EJB_TYPE; private static final String RT_NAME = RT_MODULE_NAME + ".ear"; private static final String DEPLOYMENT_MODULE_NAME = "test3-" + EJB_TYPE + "-test"; private static final String DEPLOYMENT_NAME = DEPLOYMENT_MODULE_NAME + ".ear"; private static final String SUB_DEPLOYMENT_MODULE_NAME = "ejb"; private static final String SUB_DEPLOYMENT_NAME = SUB_DEPLOYMENT_MODULE_NAME + ".jar"; private static ModelControllerClient controllerClient = TestSuiteEnvironment.getModelControllerClient(); private static InitialContext context; @BeforeClass public static void setup() throws Exception { context = getInitialContext(); JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, SUB_DEPLOYMENT_NAME); ejbJar.addPackage(BEAN_PACKAGE); ejbJar.addClass(BEAN_CLASS); EnterpriseArchive earArchive = ShrinkWrap.create(EnterpriseArchive.class, DEPLOYMENT_NAME); earArchive.addAsModule(ejbJar); ModelNode addDeploymentOp = new ModelNode(); addDeploymentOp.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); addDeploymentOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); addDeploymentOp.get(ModelDescriptionConstants.CONTENT).get(0).get(ModelDescriptionConstants.INPUT_STREAM_INDEX).set(0); addDeploymentOp.get(ModelDescriptionConstants.RUNTIME_NAME).set(RT_NAME); addDeploymentOp.get(ModelDescriptionConstants.AUTO_START).set(true); ModelNode deployOp = new ModelNode(); deployOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.DEPLOY); deployOp.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); deployOp.get(ModelDescriptionConstants.ENABLED).set(true); ModelNode[] steps = new ModelNode[2]; steps[0] = addDeploymentOp; steps[1] = deployOp; ModelNode compositeOp = ModelUtil.createCompositeNode(steps); OperationBuilder ob = new OperationBuilder(compositeOp, true); ob.addInputStream(earArchive.as(ZipExporter.class).exportAsInputStream()); ModelNode result = controllerClient.execute(ob.build()); // just to blow up Assert.assertTrue("Failed to deploy: " + result, Operations.isSuccessfulOutcome(result)); } @AfterClass public static void tearDown() throws Exception { safeClose(context); ModelNode result = controllerClient.execute(composite( undeploy(DEPLOYMENT_NAME), remove(DEPLOYMENT_NAME) )); // just to blow up Assert.assertTrue("Failed to undeploy: " + result, Operations.isSuccessfulOutcome(result)); } private static InitialContext getInitialContext() throws NamingException { final Hashtable env = new Hashtable(); env.put(Context.URL_PKG_PREFIXES, "org.wildfly.naming.client"); env.put(Context.INITIAL_CONTEXT_FACTORY, org.wildfly.naming.client.WildFlyInitialContextFactory.class.getName()); env.put(Context.PROVIDER_URL, "remote+http://" + TestSuiteEnvironment.getServerAddress() + ":" + 8080); return new InitialContext(env); } private static void safeClose(InitialContext context) { if (context == null) { return; } try { context.close(); } catch (Throwable t) { // just log log.trace("Ignoring a problem which occurred while closing: " + context, t); } context = null; } private String getEJBHomeJNDIBinding() { final String appName = RT_MODULE_NAME; final String moduleName = SUB_DEPLOYMENT_MODULE_NAME; final String distinctName = ""; final String beanName = BEAN_CLASS.getSimpleName(); final String viewClassName = SimpleHome.class.getName(); return "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName; } @Test @InSequence(value = 1) public void testGetEjbHome() throws Exception { Object home = context.lookup(getEJBHomeJNDIBinding()); Assert.assertTrue(home instanceof SimpleHome); } @Test @InSequence(value = 2) public void testStatelessLocalHome() throws Exception { SimpleHome home = (SimpleHome) context.lookup(getEJBHomeJNDIBinding()); SimpleInterface ejbInstance = home.createSimple(); Assert.assertEquals("Hello World", ejbInstance.sayHello()); home = (SimpleHome) ejbInstance.getEJBHome(); ejbInstance = home.createSimple(); Assert.assertEquals("Hello World", ejbInstance.sayHello()); } @Test @InSequence(value = 3) public void testStepByStep() throws Exception { ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); readResource.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); ModelNode result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.SUBDEPLOYMENT, SUB_DEPLOYMENT_NAME); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.SUBSYSTEM, "ejb3"); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(EJB_TYPE, BEAN_CLASS.getSimpleName()); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); } @Test @InSequence(value = 4) public void testRecursive() throws Exception { ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); readResource.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); readResource.get(ModelDescriptionConstants.RECURSIVE).set(true); ModelNode result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); } }
8,989
45.580311
127
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/StatefulEJBRemoteHomeRuntimeNameTestCase.java
package org.jboss.as.test.integration.management.deploy.runtime; import java.util.Hashtable; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; 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.test.integration.ejb.home.remotehome.SimpleStatefulHome; import org.jboss.as.test.integration.ejb.home.remotehome.SimpleInterface; import org.jboss.as.test.integration.ejb.home.remotehome.annotation.SimpleStatefulBean; import org.jboss.as.test.integration.ejb.remote.common.EJBManagementUtil; import org.jboss.as.test.integration.management.util.ModelUtil; 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.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @RunAsClient public class StatefulEJBRemoteHomeRuntimeNameTestCase extends AbstractRuntimeTestCase { private static Logger log = Logger.getLogger(StatefulEJBRemoteHomeRuntimeNameTestCase.class); private static final String EJB_TYPE = EJBManagementUtil.STATEFUL; private static final Package BEAN_PACKAGE = SimpleStatefulHome.class.getPackage(); private static final Class<?> BEAN_CLASS = SimpleStatefulBean.class; private static final String RT_MODULE_NAME = "nooma-nooma1-" + EJB_TYPE; private static final String RT_NAME = RT_MODULE_NAME + ".ear"; private static final String DEPLOYMENT_MODULE_NAME = "test1-" + EJB_TYPE + "-test"; private static final String DEPLOYMENT_NAME = DEPLOYMENT_MODULE_NAME + ".ear"; private static final String SUB_DEPLOYMENT_MODULE_NAME = "ejb"; private static final String SUB_DEPLOYMENT_NAME = SUB_DEPLOYMENT_MODULE_NAME + ".jar"; private static ModelControllerClient controllerClient = TestSuiteEnvironment.getModelControllerClient(); private static InitialContext context; @BeforeClass public static void setup() throws Exception { context = getInitialContext(); JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, SUB_DEPLOYMENT_NAME); ejbJar.addPackage(BEAN_PACKAGE); ejbJar.addClass(BEAN_CLASS); EnterpriseArchive earArchive = ShrinkWrap.create(EnterpriseArchive.class, DEPLOYMENT_NAME); earArchive.addAsModule(ejbJar); ModelNode addDeploymentOp = new ModelNode(); addDeploymentOp.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); addDeploymentOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); addDeploymentOp.get(ModelDescriptionConstants.CONTENT).get(0).get(ModelDescriptionConstants.INPUT_STREAM_INDEX).set(0); addDeploymentOp.get(ModelDescriptionConstants.RUNTIME_NAME).set(RT_NAME); addDeploymentOp.get(ModelDescriptionConstants.AUTO_START).set(true); ModelNode deployOp = new ModelNode(); deployOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.DEPLOY); deployOp.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); deployOp.get(ModelDescriptionConstants.ENABLED).set(true); ModelNode[] steps = new ModelNode[2]; steps[0] = addDeploymentOp; steps[1] = deployOp; ModelNode compositeOp = ModelUtil.createCompositeNode(steps); OperationBuilder ob = new OperationBuilder(compositeOp, true); ob.addInputStream(earArchive.as(ZipExporter.class).exportAsInputStream()); ModelNode result = controllerClient.execute(ob.build()); // just to blow up Assert.assertTrue("Failed to deploy: " + result, Operations.isSuccessfulOutcome(result)); } @AfterClass public static void tearDown() throws Exception { safeClose(context); ModelNode result = controllerClient.execute(composite( undeploy(DEPLOYMENT_NAME), remove(DEPLOYMENT_NAME) )); // just to blow up Assert.assertTrue("Failed to undeploy: " + result, Operations.isSuccessfulOutcome(result)); } private static InitialContext getInitialContext() throws NamingException { final Hashtable env = new Hashtable(); env.put(Context.URL_PKG_PREFIXES, "org.wildfly.naming.client"); env.put(Context.INITIAL_CONTEXT_FACTORY, org.wildfly.naming.client.WildFlyInitialContextFactory.class.getName()); env.put(Context.PROVIDER_URL, "remote+http://" + TestSuiteEnvironment.getServerAddress() + ":" + 8080); return new InitialContext(env); } private static void safeClose(InitialContext context) { if (context == null) { return; } try { context.close(); } catch (Throwable t) { // just log log.trace("Ignoring a problem which occurred while closing: " + context, t); } context = null; } private String getEJBHomeJNDIBinding() { final String appName = RT_MODULE_NAME; final String moduleName = SUB_DEPLOYMENT_MODULE_NAME; final String distinctName = ""; final String beanName = BEAN_CLASS.getSimpleName(); final String viewClassName = SimpleStatefulHome.class.getName(); return "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName; } @Test @InSequence(value = 1) public void testGetEjbHome() throws Exception { Object home = context.lookup(getEJBHomeJNDIBinding()); Assert.assertTrue(home instanceof SimpleStatefulHome); } @Test @InSequence(value = 2) public void testStatefulLocalHome() throws Exception { SimpleStatefulHome home = (SimpleStatefulHome) context.lookup(getEJBHomeJNDIBinding()); SimpleInterface ejbInstance = home.createSimple("Hello World"); Assert.assertEquals("Hello World", ejbInstance.sayHello()); home = (SimpleStatefulHome) ejbInstance.getEJBHome(); ejbInstance = home.createSimple("Hello World"); Assert.assertEquals("Hello World", ejbInstance.sayHello()); } @Test @InSequence(value = 3) public void testStepByStep() throws Exception { ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); readResource.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); ModelNode result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.SUBDEPLOYMENT, SUB_DEPLOYMENT_NAME); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.SUBSYSTEM, "ejb3"); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(EJB_TYPE, BEAN_CLASS.getSimpleName()); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); } @Test @InSequence(value = 4) public void testRecursive() throws Exception { ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); readResource.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); readResource.get(ModelDescriptionConstants.RECURSIVE).set(true); ModelNode result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); } }
9,066
45.737113
127
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/AbstractRuntimeTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.deploy.runtime; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.dmr.ModelNode; /** * @author <a href="mailto:[email protected]">Carlo de Wolf</a> */ public class AbstractRuntimeTestCase { protected static ModelNode composite(final ModelNode... operations) { final ModelNode compositeOperation = Util.getEmptyOperation(ModelDescriptionConstants.COMPOSITE, new ModelNode()); final ModelNode steps = compositeOperation.get(ModelDescriptionConstants.STEPS); for (ModelNode operation : operations) { steps.add(operation); } return compositeOperation; } protected static ModelNode remove(final String name) { return Util.getEmptyOperation(ModelDescriptionConstants.REMOVE, new ModelNode().add(ModelDescriptionConstants.DEPLOYMENT, name)); } protected static ModelNode undeploy(final String name) { return Util.getEmptyOperation(ModelDescriptionConstants.UNDEPLOY, new ModelNode().add(ModelDescriptionConstants.DEPLOYMENT, name)); } }
2,198
43.877551
139
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/ServletRuntimeNameTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc. and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.deploy.runtime; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; 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.common.HttpRequest; import org.jboss.as.test.integration.management.deploy.runtime.servlet.Servlet; import org.jboss.as.test.integration.management.util.ModelUtil; 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.EnterpriseArchive; 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; @RunWith(Arquillian.class) @RunAsClient public class ServletRuntimeNameTestCase extends AbstractRuntimeTestCase { private static final Logger log = Logger.getLogger(ServletRuntimeNameTestCase.class); private static final Class SERVLET_CLASS = Servlet.class; private static final String RT_MODULE_NAME = "nooma-nooma7"; private static final String RT_NAME = RT_MODULE_NAME + ".ear"; private static final String DEPLOYMENT_MODULE_NAME = "test7-test"; private static final String DEPLOYMENT_NAME = DEPLOYMENT_MODULE_NAME + ".ear"; private static final String SUB_DEPLOYMENT_MODULE_NAME = "servlet"; private static final String SUB_DEPLOYMENT_NAME = SUB_DEPLOYMENT_MODULE_NAME + ".war"; private static ModelControllerClient controllerClient = TestSuiteEnvironment.getModelControllerClient(); @BeforeClass public static void setup() throws Exception { WebArchive war = ShrinkWrap.create(WebArchive.class, SUB_DEPLOYMENT_NAME); war.addClass(SERVLET_CLASS); EnterpriseArchive earArchive = ShrinkWrap.create(EnterpriseArchive.class, DEPLOYMENT_NAME); earArchive.addAsModule(war); ModelNode addDeploymentOp = new ModelNode(); addDeploymentOp.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); addDeploymentOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); addDeploymentOp.get(ModelDescriptionConstants.CONTENT).get(0).get(ModelDescriptionConstants.INPUT_STREAM_INDEX).set(0); addDeploymentOp.get(ModelDescriptionConstants.RUNTIME_NAME).set(RT_NAME); addDeploymentOp.get(ModelDescriptionConstants.AUTO_START).set(true); ModelNode deployOp = new ModelNode(); deployOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.DEPLOY); deployOp.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); deployOp.get(ModelDescriptionConstants.ENABLED).set(true); ModelNode[] steps = new ModelNode[2]; steps[0] = addDeploymentOp; steps[1] = deployOp; ModelNode compositeOp = ModelUtil.createCompositeNode(steps); OperationBuilder ob = new OperationBuilder(compositeOp, true); ob.addInputStream(earArchive.as(ZipExporter.class).exportAsInputStream()); ModelNode result = controllerClient.execute(ob.build()); // just to blow up Assert.assertTrue("Failed to deploy: " + result, Operations.isSuccessfulOutcome(result)); } @AfterClass public static void tearDown() throws Exception { ModelNode result = controllerClient.execute(composite( undeploy(DEPLOYMENT_NAME), remove(DEPLOYMENT_NAME) )); // just to blow up Assert.assertTrue("Failed to undeploy: " + result, Operations.isSuccessfulOutcome(result)); } @Test public void testStepByStep() throws Exception { ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); readResource.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); ModelNode result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.SUBDEPLOYMENT, SUB_DEPLOYMENT_NAME); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.SUBSYSTEM, "undertow"); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add("servlet", SERVLET_CLASS.getName()); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); } @Test public void testRecursive() throws Exception { ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); readResource.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); readResource.get(ModelDescriptionConstants.RECURSIVE).set(true); ModelNode result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); } @Test public void testServletCall() throws Exception { String url = "http://" + TestSuiteEnvironment.getServerAddress() + ":8080/"+SUB_DEPLOYMENT_MODULE_NAME+Servlet.URL_PATTERN; String res = HttpRequest.get(url, 2, TimeUnit.SECONDS); Assert.assertEquals(Servlet.SUCCESS, res); } /** WFLY-2061 test */ @Test public void testDeploymentStatus() throws IOException { PathAddress address = PathAddress.pathAddress(PathElement.pathElement(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME)); final ModelNode operation = Util.createEmptyOperation(READ_ATTRIBUTE_OPERATION, address); operation.get(NAME).set("status"); final ModelNode outcome = controllerClient.execute(operation); Assert.assertEquals(SUCCESS, outcome.get(OUTCOME).asString()); Assert.assertEquals("OK", outcome.get(RESULT).asString()); } }
8,820
48.836158
134
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/FailedDeploymentJaxrsRuntimeTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.management.deploy.runtime; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBDEPLOYMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.integration.management.deploy.runtime.jaxrs.HelloApplication; import org.jboss.as.test.integration.management.deploy.runtime.jaxrs.HelloResource; import org.jboss.as.test.integration.management.deploy.runtime.jaxrs.PureProxyApiService; import org.jboss.as.test.integration.management.deploy.runtime.jaxrs.PureProxyEndPoint; import org.jboss.as.test.integration.management.deploy.runtime.jaxrs.SubHelloResource; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @RunAsClient public class FailedDeploymentJaxrsRuntimeTestCase extends AbstractFailedDeploymentRuntimeTestCase { private static final String DEPLOYMENT_NAME = "failed-jaxrs.ear"; private static final String SUBDEPLOYMENT_NAME = "failed-jaxrs.war"; @BeforeClass public static void setup() throws Exception { WebArchive war = ShrinkWrap.create(WebArchive.class, SUBDEPLOYMENT_NAME); war.addClass(HelloApplication.class); war.addClass(HelloResource.class); war.addClass(SubHelloResource.class); war.addClass(PureProxyApiService.class); war.addClass(PureProxyEndPoint.class); setup(DEPLOYMENT_NAME, war); } @AfterClass public static void tearDown() throws Exception { tearDown(DEPLOYMENT_NAME); } @Override void validateReadResourceResponse(ModelNode response) { Assert.assertTrue(response.toString(), response.hasDefined(RESULT, SUBDEPLOYMENT, getSubdeploymentName(), SUBSYSTEM, "jaxrs", "rest-resource", HelloResource.class.getCanonicalName())); } @Override String getDeploymentName() { return DEPLOYMENT_NAME; } @Override String getSubdeploymentName() { return SUBDEPLOYMENT_NAME; } }
3,114
38.43038
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/JaxrsRuntimeNameTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc. and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.deploy.runtime; import java.net.URL; import java.util.List; import java.util.concurrent.TimeUnit; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.management.deploy.runtime.jaxrs.HelloApplication; import org.jboss.as.test.integration.management.deploy.runtime.jaxrs.HelloResource; import org.jboss.as.test.integration.management.deploy.runtime.jaxrs.PureProxyApiService; import org.jboss.as.test.integration.management.deploy.runtime.jaxrs.PureProxyEndPoint; import org.jboss.as.test.integration.management.deploy.runtime.jaxrs.SubHelloResource; 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.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.hamcrest.MatcherAssert.assertThat; import org.hamcrest.CoreMatchers; import org.jboss.as.controller.operations.common.Util; @RunWith(Arquillian.class) @RunAsClient public class JaxrsRuntimeNameTestCase extends AbstractRuntimeTestCase { private static final String CONSUMES = "consumes"; private static final String DEPLOYMENT_NAME = "hello-rs.war"; private static final String JAVA_METHOD = "java-method"; private static final String PRODUCES = "produces"; private static final String RESOURCE_CLASS = "resource-class"; private static final String RESOURCE_METHODS = "resource-methods"; private static final String RESOURCE_PATH = "resource-path"; private static final String RESOURCE_PATHS = "rest-resource-paths"; private static final String REST_RESOURCE_NAME = "rest-resource"; private static final String SUB_RESOURCE_LOCATORS = "sub-resource-locators"; private static final String SUBSYSTEM_NAME = "jaxrs"; private static final ModelControllerClient controllerClient = TestSuiteEnvironment.getModelControllerClient(); @ArquillianResource private URL url; @Deployment(testable = false) public static Archive<?> deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_NAME); war.addClass(HelloApplication.class); war.addClass(HelloResource.class); war.addClass(SubHelloResource.class); war.addClass(PureProxyApiService.class); war.addClass(PureProxyEndPoint.class); return war; } private String performCall(String urlPattern) throws Exception { return HttpRequest.get(url + urlPattern, 10, TimeUnit.SECONDS); } @Test public void testSubResource() throws Exception { assertThat(performCall("hello"), is("Hello World!")); } @Test public void testStepByStep() throws Exception { PathAddress deploymentAddress = PathAddress.pathAddress(DEPLOYMENT, DEPLOYMENT_NAME); ModelNode readResource = Util.createOperation(READ_RESOURCE_OPERATION, deploymentAddress); ModelNode result = controllerClient.execute(readResource); assertThat("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result), is(true)); PathAddress subsystemAddress = deploymentAddress.append(SUBSYSTEM, SUBSYSTEM_NAME); readResource = Util.createOperation(READ_RESOURCE_OPERATION, subsystemAddress); result = controllerClient.execute(readResource); assertThat("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result), is(true)); readResource = Util.createOperation("show-resources", subsystemAddress); result = controllerClient.execute(readResource); assertThat("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result), is(true)); List<ModelNode> jaxrsResources = Operations.readResult(result).asList(); assertThat(jaxrsResources, is(notNullValue())); assertThat(jaxrsResources.size(), is(5)); int count = 0; for (ModelNode jaxrsResource: jaxrsResources) { if (jaxrsResource.get(RESOURCE_CLASS).asString().equals(HelloResource.class.getName())) { count++; String path = jaxrsResource.get(RESOURCE_PATH).asString(); switch (path) { case "/update": assertThat(jaxrsResource.toString(), jaxrsResource.get(RESOURCE_METHODS).asList().get(0).asString(), is("PUT /hello-rs/hello/update - org.jboss.as.test.integration.management.deploy.runtime.jaxrs.HelloResource.updateMessage(...)")); break; case "/json": assertThat(jaxrsResource.toString(), jaxrsResource.get(RESOURCE_METHODS).asList().get(0).asString(), is("GET /hello-rs/hello/json - org.jboss.as.test.integration.management.deploy.runtime.jaxrs.HelloResource.getHelloWorldJSON()")); break; case "/xml": assertThat(jaxrsResource.toString(), jaxrsResource.get(RESOURCE_METHODS).asList().get(0).asString(), is("GET /hello-rs/hello/xml - org.jboss.as.test.integration.management.deploy.runtime.jaxrs.HelloResource.getHelloWorldXML()")); break; case "/": assertThat(jaxrsResource.toString(), jaxrsResource.get(RESOURCE_METHODS).asList().get(0).asString(), is("GET /hello-rs/hello/ - org.jboss.as.test.integration.management.deploy.runtime.jaxrs.HelloResource.getHelloWorld()")); break; default: assertThat(jaxrsResource.toString(), false, is(true)); } } else if (jaxrsResource.get(RESOURCE_CLASS).asString().equals(PureProxyApiService.class.getName())) { count++; String path = jaxrsResource.get(RESOURCE_PATH).asString(); assertThat(jaxrsResource.toString(), path, is("pure/proxy/test/{a}/{b}")); assertThat(jaxrsResource.toString(), jaxrsResource.get(RESOURCE_METHODS).asList().get(0).asString(), is("GET /hello-rs/hello/pure/proxy/test/{a}/{b} - org.jboss.as.test.integration.management.deploy.runtime.jaxrs.PureProxyApiService.test(...)")); } } assertThat(count, is(5)); } @Test public void testReadRestResource() throws Exception { ModelNode removeResource = Util.createRemoveOperation(PathAddress.pathAddress(DEPLOYMENT, DEPLOYMENT_NAME).append(SUBSYSTEM, SUBSYSTEM_NAME)); assertThat(Operations.getFailureDescription(controllerClient.execute(removeResource)).asString(), CoreMatchers.containsString("WFLYCTL0031")); ModelNode readResource = Util.createOperation(READ_RESOURCE_OPERATION, PathAddress.pathAddress(DEPLOYMENT, DEPLOYMENT_NAME) .append(SUBSYSTEM, SUBSYSTEM_NAME) .append(REST_RESOURCE_NAME, HelloResource.class.getCanonicalName())); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); ModelNode result = controllerClient.execute(readResource); assertThat("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result), is(true)); ModelNode res = Operations.readResult(result); assertThat(res.isDefined(), is(true)); assertThat(res.get(RESOURCE_CLASS).asString(), is(HelloResource.class.getCanonicalName())); List<ModelNode> subResList = res.get(RESOURCE_PATHS).asList(); assertThat(subResList.size(), is(4)); ModelNode rootRes = subResList.get(0); // '/' assertThat(rootRes.get(RESOURCE_PATH).asString(), is("/")); assertThat(rootRes.get(JAVA_METHOD).asString(), is("java.lang.String " + HelloResource.class.getCanonicalName() + ".getHelloWorld()")); assertThat(rootRes.get(CONSUMES).isDefined(), is(false)); assertThat(rootRes.get(PRODUCES).asList().size(), is(1)); assertThat(rootRes.get(PRODUCES).asList().get(0).asString(), is("text/plain")); assertThat(rootRes.get(RESOURCE_METHODS).asList().size(), is(1)); assertThat(rootRes.get(RESOURCE_METHODS).asList().get(0).asString(), is("GET /hello-rs/hello/")); ModelNode jsonRes = subResList.get(1);// '/json' assertThat(jsonRes.get(RESOURCE_PATH).asString(), is("/json")); assertThat(jsonRes.get(JAVA_METHOD).asString(), is("jakarta.json.JsonObject " + HelloResource.class.getCanonicalName() + ".getHelloWorldJSON()")); assertThat(jsonRes.get(CONSUMES).isDefined(), is(false)); assertThat(jsonRes.get(PRODUCES).asList().size(), is(1)); assertThat(jsonRes.get(PRODUCES).asList().get(0).asString(), is("application/json")); assertThat(jsonRes.get(RESOURCE_METHODS).asList().size(), is(1)); assertThat(jsonRes.get(RESOURCE_METHODS).asList().get(0).asString(), is("GET /hello-rs/hello/json")); ModelNode updateRes = subResList.get(2);// '/update' assertThat(updateRes.get(RESOURCE_PATH).asString(), is("/update")); assertThat(updateRes.get(JAVA_METHOD).asString(), is("void " + HelloResource.class.getCanonicalName() + ".updateMessage(@QueryParam java.lang.String content = 'Hello')")); assertThat(updateRes.get(PRODUCES).isDefined(), is(false)); assertThat(updateRes.get(CONSUMES).asList().size(), is(1)); assertThat(updateRes.get(CONSUMES).asList().get(0).asString(), is("text/plain")); assertThat(updateRes.get(RESOURCE_METHODS).asList().size(), is(1)); assertThat(updateRes.get(RESOURCE_METHODS).asList().get(0).asString(), is("PUT /hello-rs/hello/update")); ModelNode xmlRes = subResList.get(3);// '/xml' assertThat(xmlRes.get(RESOURCE_PATH).asString(), is("/xml")); assertThat(xmlRes.get(JAVA_METHOD).asString(), is("java.lang.String " + HelloResource.class.getCanonicalName() + ".getHelloWorldXML()")); assertThat(xmlRes.get(CONSUMES).isDefined(), is(false)); assertThat(xmlRes.get(PRODUCES).asList().size(), is(1)); assertThat(xmlRes.get(PRODUCES).asList().get(0).asString(), is("application/xml")); assertThat(xmlRes.get(RESOURCE_METHODS).asList().size(), is(1)); assertThat(xmlRes.get(RESOURCE_METHODS).asList().get(0).asString(), is("GET /hello-rs/hello/xml")); List<ModelNode> subLocatorList = res.get(SUB_RESOURCE_LOCATORS).asList(); assertThat(subLocatorList.size(), is(1)); ModelNode subLocatorRes = subLocatorList.get(0); assertThat(subLocatorRes.get(RESOURCE_CLASS).asString(), is(SubHelloResource.class.getCanonicalName())); List<ModelNode> subResInsideSubLocator = subLocatorRes.get(RESOURCE_PATHS).asList(); assertThat(subResInsideSubLocator.size(), is(2)); ModelNode subRootHi = subResInsideSubLocator.get(0); assertThat(subRootHi.get(RESOURCE_PATH).asString(), is("/sub/")); assertThat(subRootHi.get(JAVA_METHOD).asString(), is("java.lang.String " + SubHelloResource.class.getCanonicalName() + ".hi()")); assertThat(subRootHi.get(CONSUMES).isDefined(), is(false)); assertThat(subRootHi.get(PRODUCES).asList().size(), is(1)); assertThat(subRootHi.get(PRODUCES).asList().get(0).asString(), is("text/plain")); assertThat(subRootHi.get(RESOURCE_METHODS).asList().size(), is(1)); assertThat(subRootHi.get(RESOURCE_METHODS).asList().get(0).asString(), is("GET /hello-rs/hello/sub/")); ModelNode pingNode = subResInsideSubLocator.get(1); assertThat(pingNode.get(RESOURCE_PATH).asString(), is("/sub/ping/{name}")); assertThat(pingNode.get(JAVA_METHOD).asString(), is("java.lang.String " + SubHelloResource.class.getCanonicalName() + ".ping(@PathParam java.lang.String name = 'JBoss')")); assertThat(pingNode.get(CONSUMES).isDefined(), is(false)); assertThat(pingNode.get(PRODUCES).asList().size(), is(1)); assertThat(pingNode.get(PRODUCES).asList().get(0).asString(), is("text/plain")); assertThat(pingNode.get(RESOURCE_METHODS).asList().size(), is(1)); assertThat(pingNode.get(RESOURCE_METHODS).asList().get(0).asString(), is("GET /hello-rs/hello/sub/ping/{name}")); } @Test public void testReadRestEndPointIntf() throws Exception { assertThat(performCall("hello/pure/proxy/test/Hello/World"), is("Hello World")); ModelNode readResource = Util.createOperation(READ_RESOURCE_OPERATION, PathAddress.pathAddress(DEPLOYMENT, DEPLOYMENT_NAME) .append(SUBSYSTEM, SUBSYSTEM_NAME) .append(REST_RESOURCE_NAME, PureProxyEndPoint.class.getCanonicalName())); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); ModelNode result = controllerClient.execute(readResource); assertThat("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result), is(true)); ModelNode res = Operations.readResult(result); assertThat(res.isDefined(), is(true)); assertThat(res.get(RESOURCE_CLASS).asString(), is(PureProxyEndPoint.class.getCanonicalName())); List<ModelNode> subResList = res.get(RESOURCE_PATHS).asList(); assertThat(subResList.size(), is(1)); ModelNode rootRes = subResList.get(0); assertThat(rootRes.get(RESOURCE_PATH).asString(), is("pure/proxy/test/{a}/{b}")); assertThat(rootRes.get(JAVA_METHOD).asString(), is("java.lang.String " + PureProxyEndPoint.class.getCanonicalName() + ".test(@PathParam java.lang.String a, @PathParam java.lang.String b)")); assertThat(rootRes.get(CONSUMES).isDefined(), is(false)); assertThat(rootRes.get(PRODUCES).isDefined(), is(false)); assertThat(rootRes.get(RESOURCE_METHODS).asList().size(), is(1)); assertThat(rootRes.get(RESOURCE_METHODS).asList().get(0).asString(), is("GET /hello-rs/hello/pure/proxy/test/{a}/{b}")); } @Test public void testRecursive() throws Exception { ModelNode readResource = Util.createOperation(READ_RESOURCE_OPERATION, PathAddress.pathAddress(DEPLOYMENT, DEPLOYMENT_NAME)); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); readResource.get(ModelDescriptionConstants.RECURSIVE).set(true); ModelNode result = controllerClient.execute(readResource); assertThat("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result), is(true)); } }
16,275
59.958801
262
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/StatelessEJBRuntimeNameTestCase.java
package org.jboss.as.test.integration.management.deploy.runtime; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; 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.test.integration.management.deploy.runtime.ejb.stateless.PointLessMathBean; import org.jboss.as.test.integration.management.util.ModelUtil; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; 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.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @RunAsClient public class StatelessEJBRuntimeNameTestCase extends AbstractRuntimeTestCase { private static final String EJB_TYPE = "stateless-session-bean"; private static final Package BEAN_PACKAGE = PointLessMathBean.class.getPackage(); private static final String BEAN_NAME = "POINT"; private static final String RT_NAME = "nooma-nooma4-"+EJB_TYPE+".ear"; private static final String DEPLOYMENT_NAME = "test4-"+EJB_TYPE+"-test.ear"; private static final String SUB_DEPLOYMENT_NAME = "ejb.jar"; private static ModelControllerClient controllerClient = TestSuiteEnvironment.getModelControllerClient(); @BeforeClass public static void setup() throws Exception { JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, SUB_DEPLOYMENT_NAME); ejbJar.addPackage(BEAN_PACKAGE); EnterpriseArchive earArchive = ShrinkWrap.create(EnterpriseArchive.class, DEPLOYMENT_NAME); earArchive.addAsModule(ejbJar); ModelNode addDeploymentOp = new ModelNode(); addDeploymentOp.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); addDeploymentOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); addDeploymentOp.get(ModelDescriptionConstants.CONTENT).get(0).get(ModelDescriptionConstants.INPUT_STREAM_INDEX).set(0); addDeploymentOp.get(ModelDescriptionConstants.RUNTIME_NAME).set(RT_NAME); addDeploymentOp.get(ModelDescriptionConstants.AUTO_START).set(true); ModelNode deployOp = new ModelNode(); deployOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.DEPLOY); deployOp.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); deployOp.get(ModelDescriptionConstants.ENABLED).set(true); ModelNode[] steps = new ModelNode[2]; steps[0] = addDeploymentOp; steps[1] = deployOp; ModelNode compositeOp = ModelUtil.createCompositeNode(steps); OperationBuilder ob = new OperationBuilder(compositeOp, true); ob.addInputStream(earArchive.as(ZipExporter.class).exportAsInputStream()); ModelNode result = controllerClient.execute(ob.build()); // just to blow up Assert.assertTrue("Failed to deploy: " + result, Operations.isSuccessfulOutcome(result)); } @AfterClass public static void tearDown() throws Exception { ModelNode result = controllerClient.execute(composite( undeploy(DEPLOYMENT_NAME), remove(DEPLOYMENT_NAME) )); // just to blow up Assert.assertTrue("Failed to undeploy: " + result, Operations.isSuccessfulOutcome(result)); } @Test public void testStepByStep() throws Exception { ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); readResource.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); ModelNode result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.SUBDEPLOYMENT, SUB_DEPLOYMENT_NAME); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.SUBSYSTEM, "ejb3"); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(EJB_TYPE, BEAN_NAME); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); } @Test public void testRecursive() throws Exception { ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); readResource.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); readResource.get(ModelDescriptionConstants.RECURSIVE).set(true); ModelNode result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); } }
6,011
48.68595
127
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/AbstractFailedDeploymentRuntimeTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.management.deploy.runtime; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOY; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INPUT_STREAM_INDEX; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RECURSIVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLBACK_ON_RUNTIME_FAILURE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLED_BACK; 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.test.integration.management.deploy.runtime.servlet.BadContextListener; import org.jboss.as.test.integration.management.util.ModelUtil; 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.WebArchive; import org.junit.Assert; import org.junit.Test; import java.io.IOException; public abstract class AbstractFailedDeploymentRuntimeTestCase extends AbstractRuntimeTestCase { static ModelControllerClient controllerClient = TestSuiteEnvironment.getModelControllerClient(); /** * Create and deploy an EAR application that includes a war that has a ServletContextListener that * will throw an exception when invoked, thus failing the deployment. The deploy op will be configured * to not rollback-on-runtime-failure, leaving the deployment in place, allowing the management layer's * handling of the deployment to be tested. * * @param deploymentName the name that should be used for the ear deployment. * @param badWar the WebArchive in which the failed deployment should be inserted. Subclasses can provide * other content in the WebArchive in order to test how that content is handled. * @param otherModules other modules that should be packaged in the ear * @throws IOException if one occurs */ static void setup(String deploymentName, WebArchive badWar, Archive<?>... otherModules) throws IOException { badWar.addClass(BadContextListener.class); EnterpriseArchive earArchive = ShrinkWrap.create(EnterpriseArchive.class, deploymentName); earArchive.addAsModule(badWar); for (Archive<?> otherModule : otherModules) { earArchive.addAsModule(otherModule); } ModelNode addDeploymentOp = new ModelNode(); addDeploymentOp.get(ModelDescriptionConstants.ADDRESS).add(DEPLOYMENT, deploymentName); addDeploymentOp.get(ModelDescriptionConstants.OP).set(ADD); addDeploymentOp.get(ModelDescriptionConstants.CONTENT).get(0).get(INPUT_STREAM_INDEX).set(0); addDeploymentOp.get(ModelDescriptionConstants.AUTO_START).set(true); ModelNode deployOp = new ModelNode(); deployOp.get(ModelDescriptionConstants.OP).set(DEPLOY); deployOp.get(ModelDescriptionConstants.ADDRESS).add(DEPLOYMENT, deploymentName); deployOp.get(ModelDescriptionConstants.ENABLED).set(true); ModelNode[] steps = new ModelNode[2]; steps[0] = addDeploymentOp; steps[1] = deployOp; ModelNode compositeOp = ModelUtil.createCompositeNode(steps); compositeOp.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false); OperationBuilder ob = new OperationBuilder(compositeOp, true); ob.addInputStream(earArchive.as(ZipExporter.class).exportAsInputStream()); ModelNode result = controllerClient.execute(ob.build()); Assert.assertTrue("deploy did not fail: " + result, Operations.isSuccessfulOutcome(result)); Assert.assertTrue(result.toString(), result.hasDefined(RESULT, "step-2", ROLLED_BACK)); Assert.assertFalse(result.toString(), result.get(RESULT, "step-2", ROLLED_BACK).asBoolean()); Assert.assertEquals(result.toString(), FAILED, result.get(RESULT, "step-2", OUTCOME).asString()); } static void tearDown(String deploymentName) throws Exception { ModelNode result = controllerClient.execute(composite( undeploy(deploymentName), remove(deploymentName) )); Assert.assertTrue("Failed to undeploy: " + result, Operations.isSuccessfulOutcome(result)); } /** * Perform a :read-resource(recursive=true,include-runtime=true) against the deployment resource and * validates that it is successful. Calls {@link #validateReadResourceResponse(ModelNode)} to allow subclasses * to perform further validation. * * @throws IOException if one occurs */ @Test public void testReadResource() throws IOException { ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, getDeploymentName()); op.get(ModelDescriptionConstants.OP).set(READ_RESOURCE_OPERATION); op.get(RECURSIVE).set(true); op.get(INCLUDE_RUNTIME).set(true); ModelNode response = controllerClient.execute(op); Assert.assertTrue("Failed to read: " + response, Operations.isSuccessfulOutcome(response)); validateReadResourceResponse(response); } /** * Hook to allow subclasses to perform further validation of the response to the read-resource call made * by {@link #testReadResource()} * @param response the response to the read-resource call */ void validateReadResourceResponse(ModelNode response) { // No-op } /** * Gets the name that should be used for the deployment resource. * @return the name */ abstract String getDeploymentName(); /** * Gets the name that should be used for the war subdeployment resource. * @return the name */ abstract String getSubdeploymentName(); }
7,612
48.116129
114
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/MDBEJBRuntimeNameTestsCase.java
package org.jboss.as.test.integration.management.deploy.runtime; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import jakarta.jms.Connection; import jakarta.jms.Destination; import jakarta.jms.Message; import jakarta.jms.MessageProducer; import jakarta.jms.Queue; import jakarta.jms.QueueConnection; import jakarta.jms.QueueConnectionFactory; import jakarta.jms.QueueReceiver; import jakarta.jms.QueueSession; import jakarta.jms.Session; import jakarta.jms.TextMessage; import javax.naming.InitialContext; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; 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.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.integration.ejb.remote.common.EJBManagementUtil; import org.jboss.as.test.integration.management.deploy.runtime.ejb.message.Constants; import org.jboss.as.test.integration.management.deploy.runtime.ejb.message.SimpleMDB; import org.jboss.as.test.integration.management.util.ModelUtil; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.descriptor.api.Descriptors; import org.jboss.shrinkwrap.descriptor.api.spec.se.manifest.ManifestDescriptor; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @RunAsClient public class MDBEJBRuntimeNameTestsCase extends AbstractRuntimeTestCase { private static final Logger log = Logger.getLogger(MDBEJBRuntimeNameTestsCase.class); private static final String QUEUE_NAME = "Queue-for-" + MDBEJBRuntimeNameTestsCase.class.getName(); private static final String EJB_TYPE = EJBManagementUtil.MESSAGE_DRIVEN; private static final Class BEAN_CLASS = SimpleMDB.class; private static final Package BEAN_PACKAGE = BEAN_CLASS.getPackage(); private static final String BEAN_NAME = "POINT"; private static final String RT_MODULE_NAME = "nooma-nooma5-" + EJB_TYPE; private static final String RT_NAME = RT_MODULE_NAME + ".ear"; private static final String DEPLOYMENT_MODULE_NAME = "test5-" + EJB_TYPE + "-test"; private static final String DEPLOYMENT_NAME = DEPLOYMENT_MODULE_NAME + ".ear"; private static final String SUB_DEPLOYMENT_MODULE_NAME = "ejb"; private static final String SUB_DEPLOYMENT_NAME = SUB_DEPLOYMENT_MODULE_NAME + ".jar"; @ContainerResource private InitialContext context; @ContainerResource private ManagementClient managementClient; private JMSOperations adminSupport; @Before public void setup() throws Exception { adminSupport = JMSOperationsProvider.getInstance(managementClient); //Remote JMS - bind name... to make it available remotely, lookup original name. adminSupport.createJmsQueue(QUEUE_NAME, "java:jboss/exported/" + Constants.QUEUE_JNDI_NAME); JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, SUB_DEPLOYMENT_NAME); ejbJar.addPackage(BEAN_PACKAGE); ejbJar.setManifest(new StringAsset( Descriptors.create(ManifestDescriptor.class) .attribute("Dependencies", "org.apache.activemq.artemis.ra") .exportAsString())); EnterpriseArchive earArchive = ShrinkWrap.create(EnterpriseArchive.class, DEPLOYMENT_NAME); earArchive.addAsModule(ejbJar); ModelNode addDeploymentOp = new ModelNode(); addDeploymentOp.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); addDeploymentOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); addDeploymentOp.get(ModelDescriptionConstants.CONTENT).get(0).get(ModelDescriptionConstants.INPUT_STREAM_INDEX).set(0); addDeploymentOp.get(ModelDescriptionConstants.RUNTIME_NAME).set(RT_NAME); addDeploymentOp.get(ModelDescriptionConstants.AUTO_START).set(true); ModelNode deployOp = new ModelNode(); deployOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.DEPLOY); deployOp.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); deployOp.get(ModelDescriptionConstants.ENABLED).set(true); ModelNode[] steps = new ModelNode[2]; steps[0] = addDeploymentOp; steps[1] = deployOp; ModelNode compositeOp = ModelUtil.createCompositeNode(steps); OperationBuilder ob = new OperationBuilder(compositeOp, true); ob.addInputStream(earArchive.as(ZipExporter.class).exportAsInputStream()); ModelNode result = managementClient.getControllerClient().execute(ob.build()); // just to blow up Assert.assertTrue("Failed to deploy: " + result, Operations.isSuccessfulOutcome(result)); } @After public void tearDown() throws Exception { ModelNode result = managementClient.getControllerClient().execute(composite( undeploy(DEPLOYMENT_NAME), remove(DEPLOYMENT_NAME) )); // just to blow up Assert.assertTrue("Failed to undeploy: " + result, Operations.isSuccessfulOutcome(result)); adminSupport.removeJmsQueue(QUEUE_NAME); } @Test @InSequence(1) public void testMDB() throws Exception { final QueueConnectionFactory factory = (QueueConnectionFactory) context.lookup("java:/jms/RemoteConnectionFactory"); final QueueConnection connection = factory.createQueueConnection("guest", "guest"); try { connection.start(); final QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); final Queue replyDestination = session.createTemporaryQueue(); final String requestMessage = "test"; final Message message = session.createTextMessage(requestMessage); message.setJMSReplyTo(replyDestination); final Destination destination = (Destination) context.lookup(Constants.QUEUE_JNDI_NAME); final MessageProducer producer = session.createProducer(destination); producer.send(message); producer.close(); // wait for a reply final QueueReceiver receiver = session.createReceiver(replyDestination); final Message reply = receiver.receive(TimeoutUtil.adjust(1000)); assertNotNull( "Did not receive a reply on the reply queue. Perhaps the original (request) message didn't make it to the MDB?", reply); final String result = ((TextMessage) reply).getText(); assertEquals("Unexpected reply messsage", Constants.REPLY_MESSAGE_PREFIX + requestMessage, result); } finally { if (connection != null) { // just closing the connection will close the session and other related resources (@see jakarta.jms.Connection) safeClose(connection); } } } @Test @InSequence(2) public void testStepByStep() throws Exception { ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); readResource.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); ModelNode result = managementClient.getControllerClient().execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.SUBDEPLOYMENT, SUB_DEPLOYMENT_NAME); result = managementClient.getControllerClient().execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.SUBSYSTEM, "ejb3"); result = managementClient.getControllerClient().execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(EJB_TYPE, BEAN_NAME); result = managementClient.getControllerClient().execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); } @Test @InSequence(3) public void testRecursive() throws Exception { ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); readResource.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); readResource.get(ModelDescriptionConstants.RECURSIVE).set(true); ModelNode result = managementClient.getControllerClient().execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); } private static void safeClose(final Connection connection) { if (connection == null) { return; } try { connection.close(); } catch (Throwable t) { // just log log.trace("Ignoring a problem which occurred while closing: " + connection, t); } } }
10,470
47.253456
132
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/FailedDeploymentUndertowRuntimeTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.management.deploy.runtime; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.integration.management.deploy.runtime.servlet.Servlet; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.runner.RunWith; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBDEPLOYMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; @RunWith(Arquillian.class) @RunAsClient public class FailedDeploymentUndertowRuntimeTestCase extends AbstractFailedDeploymentRuntimeTestCase { private static final String DEPLOYMENT_NAME = "failed-undertow.ear"; private static final String SUBDEPLOYMENT_NAME = "failed-undertow.war"; @BeforeClass public static void setup() throws Exception { WebArchive badWar = ShrinkWrap.create(WebArchive.class, SUBDEPLOYMENT_NAME); badWar.addClass(Servlet.class); setup(DEPLOYMENT_NAME, badWar); } @AfterClass public static void tearDown() throws Exception { tearDown(DEPLOYMENT_NAME); } @Override void validateReadResourceResponse(ModelNode response) { Assert.assertTrue(response.toString(), response.hasDefined(RESULT, SUBDEPLOYMENT, getSubdeploymentName(), SUBSYSTEM, "undertow", "servlet", Servlet.class.getCanonicalName())); } @Override String getDeploymentName() { return DEPLOYMENT_NAME; } @Override String getSubdeploymentName() { return SUBDEPLOYMENT_NAME; } }
2,573
35.253521
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/StatefulEJBRuntimeNameTestCase.java
package org.jboss.as.test.integration.management.deploy.runtime; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; 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.test.integration.management.deploy.runtime.ejb.statefull.PointLessMathBean; import org.jboss.as.test.integration.management.util.ModelUtil; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; 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.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @RunAsClient public class StatefulEJBRuntimeNameTestCase extends AbstractRuntimeTestCase { private static final String EJB_TYPE = "stateful-session-bean"; private static final Package BEAN_PACKAGE = PointLessMathBean.class.getPackage(); private static final String BEAN_NAME = "POINT"; private static final String RT_NAME = "nooma-nooma2-"+EJB_TYPE+".ear"; private static final String DEPLOYMENT_NAME = "test2-"+EJB_TYPE+"-test.ear"; private static final String SUB_DEPLOYMENT_NAME = "ejb.jar"; private static ModelControllerClient controllerClient = TestSuiteEnvironment.getModelControllerClient(); @BeforeClass public static void setup() throws Exception { JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, SUB_DEPLOYMENT_NAME); ejbJar.addPackage(BEAN_PACKAGE); EnterpriseArchive earArchive = ShrinkWrap.create(EnterpriseArchive.class, DEPLOYMENT_NAME); earArchive.addAsModule(ejbJar); ModelNode addDeploymentOp = new ModelNode(); addDeploymentOp.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); addDeploymentOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); addDeploymentOp.get(ModelDescriptionConstants.CONTENT).get(0).get(ModelDescriptionConstants.INPUT_STREAM_INDEX).set(0); addDeploymentOp.get(ModelDescriptionConstants.RUNTIME_NAME).set(RT_NAME); addDeploymentOp.get(ModelDescriptionConstants.AUTO_START).set(true); ModelNode deployOp = new ModelNode(); deployOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.DEPLOY); deployOp.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); deployOp.get(ModelDescriptionConstants.ENABLED).set(true); ModelNode[] steps = new ModelNode[2]; steps[0] = addDeploymentOp; steps[1] = deployOp; ModelNode compositeOp = ModelUtil.createCompositeNode(steps); OperationBuilder ob = new OperationBuilder(compositeOp, true); ob.addInputStream(earArchive.as(ZipExporter.class).exportAsInputStream()); ModelNode result = controllerClient.execute(ob.build()); // just to blow up Assert.assertTrue("Failed to deploy: " + result, Operations.isSuccessfulOutcome(result)); } @AfterClass public static void tearDown() throws Exception { ModelNode result = controllerClient.execute(composite( undeploy(DEPLOYMENT_NAME), remove(DEPLOYMENT_NAME) )); // just to blow up Assert.assertTrue("Failed to undeploy: " + result, Operations.isSuccessfulOutcome(result)); } @Test public void testStepByStep() throws Exception { ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); readResource.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); ModelNode result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.SUBDEPLOYMENT, SUB_DEPLOYMENT_NAME); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.SUBSYSTEM, "ejb3"); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); readResource.get(ModelDescriptionConstants.ADDRESS).add(EJB_TYPE, BEAN_NAME); result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); } @Test public void testRecursive() throws Exception { ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.ADDRESS).add(ModelDescriptionConstants.DEPLOYMENT, DEPLOYMENT_NAME); readResource.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); readResource.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); readResource.get(ModelDescriptionConstants.RECURSIVE).set(true); ModelNode result = controllerClient.execute(readResource); // just to blow up Assert.assertTrue("Failed to list resources: " + result, Operations.isSuccessfulOutcome(result)); } public StatefulEJBRuntimeNameTestCase() { // TODO Auto-generated constructor stub } }
6,110
47.888
127
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/ejb/message/Constants.java
package org.jboss.as.test.integration.management.deploy.runtime.ejb.message; public interface Constants { String QUEUE_JNDI_NAME = "queue/org.jboss.as.test.integration.management.deploy.runtime.ejb.message.SimpleMDB-queue"; String REPLY_MESSAGE_PREFIX = "org.jboss.as.test.integration.management.deploy.runtime.ejb.message.SimpleMDB-queue-reply-prefix"; }
366
44.875
133
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/ejb/message/SimpleMDB.java
package org.jboss.as.test.integration.management.deploy.runtime.ejb.message; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.annotation.Resource; import jakarta.ejb.ActivationConfigProperty; import jakarta.ejb.MessageDriven; import jakarta.jms.Connection; import jakarta.jms.ConnectionFactory; import jakarta.jms.Destination; import jakarta.jms.JMSException; import jakarta.jms.Message; import jakarta.jms.MessageListener; import jakarta.jms.MessageProducer; import jakarta.jms.Session; import jakarta.jms.TextMessage; import javax.naming.NamingException; import org.jboss.logging.Logger; @MessageDriven(name="POINT",activationConfig = {@ActivationConfigProperty(propertyName = "destination", propertyValue = "java:jboss/exported/" + Constants.QUEUE_JNDI_NAME)}) public class SimpleMDB implements MessageListener { private static final Logger log = Logger.getLogger(SimpleMDB.class.getName()); //NOTE: this is local, above - ActivationConfigProperty has exported JNDI, wicked. @Resource(lookup = "java:/JmsXA") private ConnectionFactory factory; private Connection connection; private Session session; @Override public void onMessage(Message message) { try { log.trace(this + " received message " + message); final Destination destination = message.getJMSReplyTo(); // ignore messages that need no reply if (destination == null) { log.trace(this + " noticed that no reply-to destination has been set. Just returning"); return; } final MessageProducer replyProducer = session.createProducer(destination); final Message replyMsg = session.createTextMessage(Constants.REPLY_MESSAGE_PREFIX + ((TextMessage) message).getText()); replyMsg.setJMSCorrelationID(message.getJMSMessageID()); replyProducer.send(replyMsg); replyProducer.close(); } catch (JMSException e) { throw new RuntimeException(e); } } @PreDestroy protected void preDestroy() throws JMSException { log.trace("@PreDestroy on " + this); safeClose(this.connection); } @PostConstruct protected void postConstruct() throws JMSException, NamingException { log.trace(this + " MDB @PostConstructed"); this.connection = this.factory.createConnection(); this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } static void safeClose(final Connection connection) { if (connection == null) { return; } try { connection.close(); } catch (Throwable t) { // just log log.trace("Ignoring a problem which occurred while closing: " + connection, t); } } }
2,864
34.8125
173
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/ejb/stateless/PointlessMathInterface.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.deploy.runtime.ejb.stateless; /** * @author baranowb * */ public interface PointlessMathInterface { double pointlesMathOperation(double a, double b, double c); }
1,243
37.875
78
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/ejb/stateless/PointLessMathBean.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.integration.management.deploy.runtime.ejb.stateless; import jakarta.ejb.Stateless; /** * @author baranowb */ @Stateless(name="POINT") public class PointLessMathBean implements PointlessMathInterface { @Override public double pointlesMathOperation(double a, double b, double c) { return b * b - 4 * a * c; } }
1,389
34.641026
78
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/ejb/singleton/timer/PointlessInterface.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.deploy.runtime.ejb.singleton.timer; import jakarta.ejb.Remote; /** * @author baranowb * */ @Remote public interface PointlessInterface { void triggerTimer() throws Exception; int getTimerCount(); }
1,286
32.868421
84
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/ejb/singleton/timer/PointLessBean.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.integration.management.deploy.runtime.ejb.singleton.timer; import jakarta.annotation.Resource; import jakarta.ejb.Singleton; import jakarta.ejb.Timeout; import jakarta.ejb.Timer; import jakarta.ejb.TimerConfig; import jakarta.ejb.TimerService; /** * @author baranowb */ @Singleton(name = "POINT") public class PointLessBean implements PointlessInterface { private static final TimerConfig TIMER_CONFIG = new TimerConfig("Eye Candy", true); private int count = 0; @Resource TimerService timerService; @Override public void triggerTimer() throws Exception { count = 0; timerService.createSingleActionTimer(100, TIMER_CONFIG); } @Override public int getTimerCount() { return count; } @Timeout public void timeout(Timer timer) { count++; } }
1,886
29.934426
87
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/ejb/statefull/PointlesMathInterface.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.deploy.runtime.ejb.statefull; /** * @author baranowb * */ public interface PointlesMathInterface { double pointlesMathOperation(double a, double b, double c); }
1,242
37.84375
78
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/ejb/statefull/PointLessMathBean.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.integration.management.deploy.runtime.ejb.statefull; import jakarta.ejb.Stateful; /** * @author baranowb */ @Stateful(name = "POINT") public class PointLessMathBean implements PointlesMathInterface { @Override public double pointlesMathOperation(double a, double b, double c) { return b * b - 4 * a * c; } }
1,388
34.615385
78
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/jaxrs/PureProxyApiService.java
/* * Copyright (C) 2018 Red Hat, inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package org.jboss.as.test.integration.management.deploy.runtime.jaxrs; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; /** * @author <a href="mailto:[email protected]">Lin Gao</a> */ @Path("pure/proxy") public interface PureProxyApiService { @Path("test/{a}/{b}") @GET String test(@PathParam("a") String a, @PathParam("b") String b); }
1,340
35.243243
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/jaxrs/SubHelloResource.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc. and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.deploy.runtime.jaxrs; import jakarta.ws.rs.DefaultValue; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; /** * @author <a href="mailto:[email protected]">Lin Gao</a> * */ @Produces({"text/plain"}) public class SubHelloResource { @GET public String hi() { return "Hi"; } @GET @Path("ping/{name}") public String ping(@PathParam("name") @DefaultValue("JBoss") String name) { return "ping " + name; } }
1,587
32.083333
79
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/jaxrs/HelloResource.java
/* * Copyright (C) 2014 Red Hat, inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package org.jboss.as.test.integration.management.deploy.runtime.jaxrs; import java.util.concurrent.atomic.AtomicReference; import jakarta.ejb.Singleton; import jakarta.json.Json; import jakarta.json.JsonObject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DefaultValue; import jakarta.ws.rs.GET; import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; /** * * @author <a href="mailto:[email protected]">Emmanuel Hugonnet</a> (c) 2014 * Red Hat, inc. */ @Path("/") @Singleton public class HelloResource { private AtomicReference<String> message = new AtomicReference<>("World"); private String createHelloMessage(final String msg) { return "Hello " + msg + "!"; } @GET @Path("/") @Produces({"text/plain"}) public String getHelloWorld() { return createHelloMessage(message.get()); } @GET @Path("/json") @Produces({"application/json"}) public JsonObject getHelloWorldJSON() { return Json.createObjectBuilder() .add("result", createHelloMessage(message.get())) .build(); } @GET @Path("/xml") @Produces({"application/xml"}) public String getHelloWorldXML() { return "<xml><result>" + createHelloMessage(message.get()) + "</result></xml>"; } @PUT @Consumes("text/plain") @Path("/update") public void updateMessage(@QueryParam("content") @DefaultValue("Hello") String content) { message.set(content); } @Path("/sub") public SubHelloResource sub() { return new SubHelloResource(); } }
2,597
29.209302
93
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/jaxrs/HelloApplication.java
/* * Copyright (C) 2014 Red Hat, inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package org.jboss.as.test.integration.management.deploy.runtime.jaxrs; import java.util.HashSet; import java.util.Set; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.core.Application; /** * * @author <a href="mailto:[email protected]">Emmanuel Hugonnet</a> (c) 2014 * Red Hat, inc. */ @ApplicationPath("/hello") public class HelloApplication extends Application { @Override public Set<Class<?>> getClasses() { final Set<Class<?>> classes = new HashSet<>(); classes.add(HelloResource.class); classes.add(PureProxyEndPoint.class); return classes; } }
1,566
34.613636
78
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/jaxrs/PureProxyEndPoint.java
/* * Copyright (C) 2018 Red Hat, inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package org.jboss.as.test.integration.management.deploy.runtime.jaxrs; /** * @author <a href="mailto:[email protected]">Lin Gao</a> */ public class PureProxyEndPoint implements PureProxyApiService { @Override public String test(String a, String b) { return a + " " + b; } }
1,249
35.764706
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/servlet/Servlet.java
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.deploy.runtime.servlet; import java.io.IOException; import java.nio.charset.StandardCharsets; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Simplistic servlet * @author baranowb * */ @WebServlet (urlPatterns = Servlet.URL_PATTERN) public class Servlet extends HttpServlet { public static final String URL_PATTERN ="/runny-nose"; public static String SUCCESS="minion"; private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getOutputStream().write(SUCCESS.getBytes(StandardCharsets.UTF_8)); } }
1,903
37.857143
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/management/deploy/runtime/servlet/BadContextListener.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.management.deploy.runtime.servlet; import jakarta.servlet.ServletContextEvent; import jakarta.servlet.ServletContextListener; import jakarta.servlet.annotation.WebListener; /** * A ServletContextListener that fails contextInitialized. Intended * use is as a way to fail a deployment. */ @WebListener public class BadContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { throw new UnsupportedOperationException(); } }
1,253
34.828571
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jdr/mgmt/JdrReportManagmentTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jdr.mgmt; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Enumeration; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Assume; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests the JDR Report subsystem management interfaces. * * @author Mike M. Clark */ @RunAsClient @RunWith(Arquillian.class) public class JdrReportManagmentTestCase { @ContainerResource private ManagementClient managementClient; @Test public void generateStandaloneJdrReport() throws Exception { // Create the generate-jdr-report operation final ModelNode address = new ModelNode(); address.add("subsystem", "jdr"); ModelNode operation = Util.getEmptyOperation("generate-jdr-report", address); // Execute generate-jdr-report operation ModelNode response = managementClient.getControllerClient().execute(operation); String outcome = response.get("outcome").asString(); Assert.assertEquals("JDR Generation failed. Failed response: " + response.asString(), "success", outcome); ModelNode result = response.get("result"); validateJdrTimeStamps(result); String location = result.get("report-location").asString(); Assert.assertNotNull("JDR report location was null", location); // Validate report itself. File reportFile = new File(location); assertTrue("JDR report missing, not located at " + location, reportFile.exists()); validateJdrReportContents(reportFile); // Clean up report file reportFile.delete(); } /** * Tests if jdr.* script files are present in the WFLY_HOME/bin directory. * The default server copy, see ts.copy-wildfly, does not copy these resources, so we only * execute this test when we are testing galleon layers, hence ts.layers enabled. */ @Test public void ensureShellScriptExists() { Assume.assumeTrue("This test is only executed if we are testing Galleon Layers", Boolean.getBoolean("ts.layers")); Path binPath = Paths.get(System.getProperty("jboss.home"), "bin"); assertTrue("jdr.sh was not found in " + binPath.toString(), binPath.resolve("jdr.sh").toFile().exists()); assertTrue("jdr.bat was not found in " + binPath.toString(), binPath.resolve("jdr.bat").toFile().exists()); assertTrue("jdr.ps1 was not found in " + binPath.toString(), binPath.resolve("jdr.ps1").toFile().exists()); } private void validateJdrReportContents(File reportFile) { String reportName = reportFile.getName().replace(".zip", ""); ZipFile reportZip = null; try { reportZip = new ZipFile(reportFile); Enumeration<ZipEntry> e = (Enumeration<ZipEntry>) reportZip.entries(); Set<String> fileNames = new HashSet<>(); while (e.hasMoreElements()) { String fileName = e.nextElement().toString(); fileNames.add(fileName); } validateReportEntries(fileNames, reportName, reportZip); } catch (Exception e) { throw new RuntimeException("Unable to validate JDR report: " + reportFile.getName(), e); } finally { if (reportZip != null) { try { reportZip.close(); } catch (IOException e) { throw new RuntimeException("Unable to close JDR report: " + reportFile.getName(), e); } } } } private void validateReportEntries(Set<String> fileNames, String reportName, ZipFile reportZip) throws IOException { ZipEntry zipENtry = validateEntryNotEmpty("product.txt", fileNames, reportName, reportZip); String productName = readProductDirectory(reportZip.getInputStream(zipENtry)); validateEntryNotEmpty("version.txt", fileNames, reportName, reportZip); validateEntryNotEmpty("JBOSS_HOME/standalone/configuration/standalone(.*).xml$", "JBOSS_HOME\\\\standalone\\\\configuration\\\\standalone(.*).xml$", fileNames, reportName, reportZip); validateEntryNotEmpty("sos_strings/" + productName + "/tree.txt", fileNames, reportName, reportZip); validateEntryNotEmpty("sos_strings/" + productName + "/jarcheck.txt", fileNames, reportName, reportZip); validateEntryNotEmpty("sos_strings/" + productName + "/dump-services.json", fileNames, reportName, reportZip); validateEntryNotEmpty("sos_strings/" + productName + "/configuration.json", fileNames, reportName, reportZip); validateEntryNotEmpty("sos_strings/" + productName + "/cluster-proxies-configuration.json", fileNames, reportName, reportZip); validateEntryPresent("sos_strings/" + productName + "/deployment-dependencies.txt", fileNames, reportName, reportZip); validateEntryNotEmpty("sos_strings/" + productName + "/jndi-view.json", fileNames, reportName, reportZip); validateEntryNotEmpty("sos_strings/" + productName + "/local-module-dependencies.txt", fileNames, reportName, reportZip); validateEntryNotEmpty("sos_strings/" + productName + "/system-properties.txt", fileNames, reportName, reportZip); validateEmptyEntry("sos_logs/skips.log", fileNames, reportName, reportZip); } /** * Check if entry (reportname/filename) is presented in reportZip file and is not empty * * @param fileName Name of file inside report * @param reportZip Report zip file * @param reportName Report root folder name * @return The entry found */ private ZipEntry validateEntryNotEmpty(String fileName, Set<String> fileNames, String reportName, ZipFile reportZip) { return validateEntryNotEmpty(fileName, null, fileNames, reportName, reportZip); } /** * Check if entry (reportname/filename) is presented in reportZip file and is not empty * * @param fileName Name of file inside report * @param fileNameOptional Optional name of file inside report * @param reportZip Report zip file * @param reportName Report root folder name * @return The entry found */ private ZipEntry validateEntryNotEmpty(String fileName, String fileNameOptional, Set<String> fileNames, String reportName, ZipFile reportZip) { ZipEntry zipENtry = getZipEntry(reportZip, fileName, fileNameOptional, fileNames, reportName); assertTrue("Report entry " + fileName + " was empty or could not be determined", zipENtry.getSize() > 0); return zipENtry; } /** * Check if entry (reportname/filename) is presented in reportZip file, either empty or not empty. * * @param fileName Name of file inside report * @param reportZip Report zip file * @param reportName Report root folder name */ private void validateEntryPresent(String fileName, Set<String> fileNames, String reportName, ZipFile reportZip) { ZipEntry zipENtry = getZipEntry(reportZip, fileName, null, fileNames, reportName); assertNotNull("Report entry " + fileName + " was not present", zipENtry); } private ZipEntry getZipEntry(ZipFile reportZip, String fileName, String fileNameOptional, Set<String> fileNames, String reportName) { String entryInZip = reportName + "/" + fileName; Pattern p = Pattern.compile(entryInZip); Optional<String> realFileName = fileNames.stream().filter(name -> p.matcher(name).find()).findFirst(); if (!realFileName.isPresent() && fileNameOptional != null) { entryInZip = reportName + "/" + fileNameOptional; Pattern p2 = Pattern.compile(entryInZip); realFileName = fileNames.stream().filter(name -> p2.matcher(name).find()).findFirst(); } assertTrue("Report entry " + fileName + " missing from JDR report " + reportName, realFileName.isPresent()); return reportZip.getEntry(realFileName.get()); } private void validateJdrTimeStamps(ModelNode result) { // TODO: Validate time structures beyond just not null. Assert.assertNotNull("JDR start time was null.", result.get("start-time").asString()); Assert.assertNotNull("JDR end time was null.", result.get("end-time").asString()); } /** * Check if entry (reportname/filename) is presented in reportZip file and is empty * * @param fileName Name of file inside report * @param reportZip Report zip file * @param reportName Report root folder name */ private void validateEmptyEntry(String fileName, Set<String> fileNames, String reportName, ZipFile reportZip) { ZipEntry zipEntry = getZipEntry(reportZip, fileName, null, fileNames, reportName); assertFalse("Report entry " + fileName + " should be empty", zipEntry.getSize() > 0); } private String readProductDirectory(InputStream in) throws IOException { StringBuilder sb = new StringBuilder(); try(BufferedReader br = new BufferedReader(new InputStreamReader(in, Charset.forName(StandardCharsets.UTF_8.name())))) { String line; while ((line = br.readLine()) != null) { sb.append(line); } } return sb.toString(); } }
11,407
43.913386
156
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/logging/LoggingDeploymentResourceTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.logging; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; import java.util.Properties; 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.helpers.Operations; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests that deployments that have a {@code logging.properties} file are configured correctly. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunWith(Arquillian.class) @RunAsClient public class LoggingDeploymentResourceTestCase { private static final String WAR_DEPLOYMENT_NAME = "logging-test-war.war"; private static final String EAR_DEPLOYMENT_NAME = "logging-test-ear.ear"; private static final String EAR_WAR_DEPLOYMENT_NAME = "logging-test-ear.war"; private static final String EAR_PARENT_DEPLOYMENT_NAME = "logging-test-parent-ear.ear"; private static final String EAR_CHILD_WAR_DEPLOYMENT_NAME = "logging-test-child-ear.war"; @ArquillianResource private static ManagementClient client; @Deployment(name = WAR_DEPLOYMENT_NAME) public static WebArchive createWarDeployment() { final WebArchive war = ShrinkWrap.create(WebArchive.class, WAR_DEPLOYMENT_NAME); // Create a logging.properties file final Properties config = createLoggingConfig("test-logging-war.log"); war.addAsManifestResource(createAsset(config), "logging.properties"); return war; } @Deployment(name = EAR_DEPLOYMENT_NAME) public static EnterpriseArchive createEarDeployment() { final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_NAME); // Create a logging.properties file final Properties config = createLoggingConfig("test-logging-ear.log"); ear.addAsManifestResource(createAsset(config), "logging.properties"); ear.addAsModule(ShrinkWrap.create(WebArchive.class, EAR_WAR_DEPLOYMENT_NAME).addClass(Dummy.class)); return ear; } @Deployment(name = EAR_PARENT_DEPLOYMENT_NAME) public static EnterpriseArchive createEarSepDeployment() { final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_PARENT_DEPLOYMENT_NAME); // Create a logging.properties file final Properties earConfig = createLoggingConfig("test-logging-parent-ear.log"); ear.addAsManifestResource(createAsset(earConfig), "logging.properties"); final WebArchive war = ShrinkWrap.create(WebArchive.class, EAR_CHILD_WAR_DEPLOYMENT_NAME); // Create a logging.properties file final Properties warConfig = createLoggingConfig("test-logging-child-war.log"); war.addAsManifestResource(createAsset(warConfig), "logging.properties"); ear.addAsModule(war); return ear; } @OperateOnDeployment(WAR_DEPLOYMENT_NAME) @Test public void testWarDeploymentConfigurationResource() throws Exception { final ModelNode loggingConfiguration = readDeploymentResource(WAR_DEPLOYMENT_NAME, WAR_DEPLOYMENT_NAME + "/META-INF/logging.properties"); // The address should have logging.properties final Deque<Property> resultAddress = new ArrayDeque<>(Operations.getOperationAddress(loggingConfiguration).asPropertyList()); Assert.assertTrue("The configuration path did not include logging.properties", resultAddress.getLast().getValue().asString().contains("logging.properties")); final ModelNode handler = loggingConfiguration.get("handler", "FILE"); Assert.assertTrue("The FILE handler was not found effective configuration", handler.isDefined()); Assert.assertTrue(handler.hasDefined("properties")); String fileName = null; // Find the fileName property for (Property property : handler.get("properties").asPropertyList()) { if ("fileName".equals(property.getName())) { fileName = property.getValue().asString(); break; } } Assert.assertNotNull("fileName property not found", fileName); Assert.assertTrue(fileName.endsWith("test-logging-war.log")); } @OperateOnDeployment(EAR_DEPLOYMENT_NAME) @Test public void testEarDeploymentConfigurationResource() throws Exception { ModelNode loggingConfiguration = readDeploymentResource(EAR_DEPLOYMENT_NAME, EAR_DEPLOYMENT_NAME + "/META-INF/logging.properties"); // The address should have logging.properties Deque<Property> resultAddress = new ArrayDeque<>(Operations.getOperationAddress(loggingConfiguration).asPropertyList()); Assert.assertTrue("The configuration path did not include logging.properties", resultAddress.getLast().getValue().asString().contains("logging.properties")); ModelNode handler = loggingConfiguration.get("handler", "FILE"); Assert.assertTrue("The FILE handler was not found effective configuration", handler.isDefined()); Assert.assertTrue(handler.hasDefined("properties")); String fileName = null; // Find the fileName property for (Property property : handler.get("properties").asPropertyList()) { if ("fileName".equals(property.getName())) { fileName = property.getValue().asString(); break; } } Assert.assertNotNull("fileName property not found", fileName); Assert.assertTrue(fileName.endsWith("test-logging-ear.log")); // Check the WAR which should inherit the EAR's logging.properties loggingConfiguration = readSubDeploymentResource(EAR_DEPLOYMENT_NAME, EAR_WAR_DEPLOYMENT_NAME, EAR_DEPLOYMENT_NAME + "/META-INF/logging.properties"); // The address should have logging.properties resultAddress = new ArrayDeque<>(Operations.getOperationAddress(loggingConfiguration).asPropertyList()); Assert.assertTrue("The configuration path did not include logging.properties", resultAddress.getLast().getValue().asString().contains("logging.properties")); handler = loggingConfiguration.get("handler", "FILE"); Assert.assertTrue("The FILE handler was not found effective configuration", handler.isDefined()); Assert.assertTrue(handler.hasDefined("properties")); fileName = null; // Find the fileName property for (Property property : handler.get("properties").asPropertyList()) { if ("fileName".equals(property.getName())) { fileName = property.getValue().asString(); break; } } Assert.assertNotNull("fileName property not found", fileName); Assert.assertTrue(fileName.endsWith("test-logging-ear.log")); } @OperateOnDeployment(EAR_PARENT_DEPLOYMENT_NAME) @Test public void testDeploymentConfigurationResource() throws Exception { ModelNode loggingConfiguration = readDeploymentResource(EAR_PARENT_DEPLOYMENT_NAME, EAR_PARENT_DEPLOYMENT_NAME + "/META-INF/logging.properties"); // The address should have logging.properties Deque<Property> resultAddress = new ArrayDeque<>(Operations.getOperationAddress(loggingConfiguration).asPropertyList()); Assert.assertTrue("The configuration path did not include logging.properties", resultAddress.getLast().getValue().asString().contains("logging.properties")); ModelNode handler = loggingConfiguration.get("handler", "FILE"); Assert.assertTrue("The FILE handler was not found effective configuration", handler.isDefined()); Assert.assertTrue(handler.hasDefined("properties")); String fileName = null; // Find the fileName property for (Property property : handler.get("properties").asPropertyList()) { if ("fileName".equals(property.getName())) { fileName = property.getValue().asString(); break; } } Assert.assertNotNull("fileName property not found", fileName); Assert.assertTrue(fileName.endsWith("test-logging-parent-ear.log")); // Check the WAR which should have it's own configuration loggingConfiguration = readSubDeploymentResource(EAR_PARENT_DEPLOYMENT_NAME, EAR_CHILD_WAR_DEPLOYMENT_NAME, EAR_CHILD_WAR_DEPLOYMENT_NAME + "/META-INF/logging.properties"); // The address should have logging.properties resultAddress = new ArrayDeque<>(Operations.getOperationAddress(loggingConfiguration).asPropertyList()); Assert.assertTrue("The configuration path did not include logging.properties", resultAddress.getLast().getValue().asString().contains("logging.properties")); handler = loggingConfiguration.get("handler", "FILE"); Assert.assertTrue("The FILE handler was not found effective configuration", handler.isDefined()); Assert.assertTrue(handler.hasDefined("properties")); fileName = null; // Find the fileName property for (Property property : handler.get("properties").asPropertyList()) { if ("fileName".equals(property.getName())) { fileName = property.getValue().asString(); break; } } Assert.assertNotNull("fileName property not found", fileName); Assert.assertTrue(fileName.endsWith("test-logging-child-war.log")); } static ModelNode executeOperation(final ModelNode op) throws IOException { ModelNode result = client.getControllerClient().execute(op); if (!Operations.isSuccessfulOutcome(result)) { Assert.assertTrue(Operations.getFailureDescription(result).toString(), false); } return result; } /** * Reads the deployment resource. * * @param deploymentName the name of the deployment * @param configurationName the name of the configuration for the address * * @return the model for the deployment * * @throws IOException if an error occurs connecting to the server */ static ModelNode readDeploymentResource(final String deploymentName, final String configurationName) throws IOException { ModelNode address = Operations.createAddress("deployment", deploymentName, "subsystem", "logging", "configuration", configurationName); ModelNode op = Operations.createReadResourceOperation(address, true); op.get("include-runtime").set(true); final ModelNode result = Operations.readResult(executeOperation(op)); // Add the address on the result as the tests might need it result.get(ModelDescriptionConstants.OP_ADDR).set(address); return result; } /** * Reads the deployment resource. * * @param deploymentName the name of the deployment * @param subDeploymentName the name of the sub-deployment to read the configuration from * @param configurationName the name of the configuration for the address * * @return the model for the deployment * * @throws IOException if an error occurs connecting to the server */ static ModelNode readSubDeploymentResource(final String deploymentName, final String subDeploymentName, final String configurationName) throws IOException { ModelNode address = Operations.createAddress("deployment", deploymentName, "subdeployment", subDeploymentName, "subsystem", "logging", "configuration", configurationName); ModelNode op = Operations.createReadResourceOperation(address, true); op.get("include-runtime").set(true); final ModelNode result = Operations.readResult(executeOperation(op)); // Add the address on the result as the tests might need it result.get(ModelDescriptionConstants.OP_ADDR).set(address); return result; } private static Asset createAsset(final Properties properties) { return () -> { final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { properties.store(out, null); } catch (IOException e) { throw new RuntimeException(e); } return new ByteArrayInputStream(out.toByteArray()); }; } private static Properties createLoggingConfig(final String fileName) { final Properties config = new Properties(); config.setProperty("logger.handlers", "FILE"); config.setProperty("handler.FILE", "org.jboss.logmanager.handlers.PeriodicRotatingFileHandler"); config.setProperty("handler.FILE.level", "${jboss.boot.server.log.console.level:ALL}"); config.setProperty("handler.FILE.properties", "autoFlush,fileName"); config.setProperty("handler.FILE.autoFlush", "true"); config.setProperty("handler.FILE.fileName", "${jboss.server.log.dir}/" + fileName); config.setProperty("handler.FILE.formatter", "PATTERN"); config.setProperty("formatter.PATTERN", "org.jboss.logmanager.formatters.PatternFormatter"); config.setProperty("formatter.PATTERN.properties", "pattern"); config.setProperty("formatter.PATTERN.pattern", "%d{HH:mm:ss,SSS} %C.%M:%L (%t) %5p %c{1}:%L - %m%n"); return config; } }
14,952
50.38488
180
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/logging/Dummy.java
package org.jboss.as.test.integration.logging; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class Dummy { }
148
17.625
68
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/logging/config/LoggingConfigTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.logging.config; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import jakarta.json.JsonObject; 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.api.ServerSetup; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(AbstractConfigTestCase.LogFileServerSetupTask.class) public class LoggingConfigTestCase extends AbstractConfigTestCase { private static final String EAR_DEPLOYMENT = "logging-deployment-1"; private static final String WAR_DEPLOYMENT = "logging-deployment-2"; private static final String EAR_DEPLOYMENT_NAME = "logging-ear.ear"; private static final String EJB_DEPLOYMENT_NAME = "logging-ejb.jar"; private static final String WAR_DEPLOYMENT_1_NAME = "logging-war-1.war"; private static final String WAR_DEPLOYMENT_2_NAME = "logging-war-2.war"; private static final String FILE_NAME = "logging-config-json.log"; @Deployment(name = EAR_DEPLOYMENT, order = 1) public static EnterpriseArchive createEar() throws Exception { return ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_NAME) .addAsModules( ShrinkWrap.create(WebArchive.class, WAR_DEPLOYMENT_1_NAME) .addAsManifestResource(createLoggingConfiguration(FILE_NAME), "logging.properties") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(LoggingServlet.class), ShrinkWrap.create(JavaArchive.class, EJB_DEPLOYMENT_NAME) .addClasses(LoggingStartup.class, LoggerResource.class) ); } @Deployment(name = WAR_DEPLOYMENT, order = 2) public static WebArchive createWar() { return ShrinkWrap.create(WebArchive.class, WAR_DEPLOYMENT_2_NAME) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(LoggingServlet.class, LoggerResource.class); } @Test public void testDeployments(@OperateOnDeployment(EAR_DEPLOYMENT) @ArquillianResource URL war1, @OperateOnDeployment(WAR_DEPLOYMENT) @ArquillianResource URL war2) throws Exception { // First invoke the first deployment to log final String msg1 = "Test from shared WAR1"; UrlBuilder builder = UrlBuilder.of(war1, "log"); builder.addParameter("msg", msg1); performCall(builder.build()); // Next invoke the second deployment which should not use the log context from the first deployment final String msg2 = "Test from shared WAR2"; builder = UrlBuilder.of(war2, "log"); builder.addParameter("msg", msg2); performCall(builder.build()); final List<JsonObject> depLogs = readJsonLogFile(FILE_NAME); // There should be two log messages in the dependency logs; 1 from the servlet and 1 from the logger resource injected into the servlet assertLength(depLogs, 2, FILE_NAME); // Check the expected dep log file Collection<JsonObject> unexpectedLogs = depLogs.stream() .filter(logMessage -> { final String msg = logMessage.getString("message"); return (!msg.equals(LoggingServlet.formatMessage(msg1)) && // This is the current behavior, but it seems incorrect. See WFCORE-4888 for details. !(msg.equals(LoggerResource.formatLogMsg(msg1)))); }) .collect(Collectors.toList()); assertUnexpectedLogs(unexpectedLogs, FILE_NAME); // Now we want to make sure that only WAR2 logs made it into the default log context final List<JsonObject> defaultLogs = readJsonLogFileFromModel(null, DEFAULT_LOG_FILE); // There should be 1 startup messages in this file, 3 from WAR2 servlet and 1 from the static logger in WAR1 assertLength(defaultLogs, 5, DEFAULT_LOG_FILE); unexpectedLogs = defaultLogs.stream() .filter(logMessage -> { final String msg = logMessage.getString("message"); return !msg.equals(LoggerResource.formatStaticLogMsg(msg1)) && !msg.equals(LoggingServlet.formatMessage(msg2)) && !msg.equals(LoggerResource.formatLogMsg(msg2)) && !msg.equals(LoggerResource.formatStaticLogMsg(msg2)) && !msg.equals(LoggingStartup.STARTUP_MESSAGE); }) .collect(Collectors.toList()); assertUnexpectedLogs(unexpectedLogs, DEFAULT_LOG_FILE); } }
6,389
48.153846
184
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/logging/config/LoggingServlet.java
/* * Copyright 2020 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.logging.config; import java.io.IOException; import jakarta.inject.Inject; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.jboss.logging.Logger; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @WebServlet("/log") public class LoggingServlet extends HttpServlet { static final String LOGGER_NAME = LoggingServlet.class.getName(); private static final Logger LOGGER = Logger.getLogger(LOGGER_NAME); @Inject private LoggerResource loggerResource; @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final String msg = req.getParameter("msg"); LOGGER.info(formatMessage(msg)); loggerResource.log(msg); loggerResource.logStatic(msg); } static String formatMessage(final String msg) { return String.format("%s - servlet", msg); } }
1,738
32.442308
125
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/logging/config/LoggingProfileTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.logging.config; import static org.jboss.as.controller.client.helpers.Operations.CompositeOperationBuilder; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import jakarta.json.JsonObject; 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.api.ServerSetup; import org.jboss.as.controller.client.helpers.Operations; 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.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(LoggingProfileTestCase.LoggingProfileSetupTask.class) public class LoggingProfileTestCase extends AbstractConfigTestCase { private static final String PROFILE_NAME = "test-profile"; private static final String EAR_DEPLOYMENT = "logging-profile-deployment-1"; private static final String WAR_DEPLOYMENT = "logging-profile-deployment-2"; private static final String EAR_DEPLOYMENT_NAME = "logging-profile-ear.ear"; private static final String EJB_DEPLOYMENT_NAME = "logging-profile-ejb.jar"; private static final String WAR_DEPLOYMENT_1_NAME = "logging-profile-war-1.war"; private static final String WAR_DEPLOYMENT_2_NAME = "logging-profile-war-2.war"; private static final String FILE_NAME = "logging-profile-json.log"; @Deployment(name = EAR_DEPLOYMENT, order = 2) public static EnterpriseArchive createEar() { return ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_NAME) .addAsModules( ShrinkWrap.create(WebArchive.class, WAR_DEPLOYMENT_1_NAME) .addAsWebResource(new StringAsset("Logging-Profile: " + PROFILE_NAME), "META-INF/MANIFEST.MF") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(LoggingServlet.class), ShrinkWrap.create(JavaArchive.class, EJB_DEPLOYMENT_NAME) .addClasses(LoggingStartup.class, LoggerResource.class) ); } @Deployment(name = WAR_DEPLOYMENT, order = 1) public static WebArchive createWar() { return ShrinkWrap.create(WebArchive.class, WAR_DEPLOYMENT_2_NAME) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(LoggingServlet.class, LoggerResource.class); } @Test public void testDeployments(@OperateOnDeployment(EAR_DEPLOYMENT) @ArquillianResource URL war1, @OperateOnDeployment(WAR_DEPLOYMENT) @ArquillianResource URL war2) throws Exception { // First invoke the first deployment to log final String msg1 = "Test from shared WAR1"; UrlBuilder builder = UrlBuilder.of(war1, "log"); builder.addParameter("msg", msg1); performCall(builder.build()); // Next invoke the second deployment which should not use the log context from the first deployment final String msg2 = "Test from shared WAR2"; builder = UrlBuilder.of(war2, "log"); builder.addParameter("msg", msg2); performCall(builder.build()); final List<JsonObject> depLogs = readJsonLogFileFromModel(PROFILE_NAME, FILE_NAME); // There should be two log messages in the dependency logs; 1 from the servlet and 1 from the logger resource injected into the servlet assertLength(depLogs, 2, FILE_NAME); // Check the expected dep log file Collection<JsonObject> unexpectedLogs = depLogs.stream() .filter(logMessage -> { final String msg = logMessage.getString("message"); return (!msg.equals(LoggingServlet.formatMessage(msg1)) && // This is the current behavior, but it seems incorrect. See WFCORE-4888 for details. !(msg.equals(LoggerResource.formatLogMsg(msg1)))); }) .collect(Collectors.toList()); assertUnexpectedLogs(unexpectedLogs, FILE_NAME); // Now we want to make sure that only WAR2 logs made it into the default log context final List<JsonObject> defaultLogs = readJsonLogFileFromModel(null, DEFAULT_LOG_FILE); // There should be 1 startup messages in this file, 3 from WAR2 servlet and 1 from the static logger in WAR1 assertLength(defaultLogs, 5, DEFAULT_LOG_FILE); unexpectedLogs = defaultLogs.stream() .filter(logMessage -> { final String msg = logMessage.getString("message"); return !msg.equals(LoggerResource.formatStaticLogMsg(msg1)) && !msg.equals(LoggingServlet.formatMessage(msg2)) && !msg.equals(LoggerResource.formatLogMsg(msg2)) && !msg.equals(LoggerResource.formatStaticLogMsg(msg2)) && !msg.equals(LoggingStartup.STARTUP_MESSAGE); }) .collect(Collectors.toList()); assertUnexpectedLogs(unexpectedLogs, DEFAULT_LOG_FILE); } public static class LoggingProfileSetupTask extends LogFileServerSetupTask { @Override protected CompositeOperationBuilder createBuilder() { final CompositeOperationBuilder builder = super.createBuilder(); builder.addStep(Operations.createAddOperation(createSubsystemAddress(PROFILE_NAME))); addDefaults(builder, PROFILE_NAME, FILE_NAME); return builder; } } }
7,162
48.061644
184
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/logging/config/LoggingConfigSharedTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.logging.config; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import jakarta.json.JsonObject; 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.api.ServerSetup; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(AbstractConfigTestCase.LogFileServerSetupTask.class) public class LoggingConfigSharedTestCase extends AbstractConfigTestCase { private static final String WAR_DEPLOYMENT_1 = "logging-war-1"; private static final String WAR_DEPLOYMENT_2 = "logging-war-2"; private static final String EJB_DEPLOYMENT = "logging-ejb"; private static final String EJB_DEPLOYMENT_NAME = "logging-ejb.jar"; private static final String WAR_DEPLOYMENT_1_NAME = "logging-war-1.war"; private static final String WAR_DEPLOYMENT_2_NAME = "logging-war-2.war"; private static final String FILE_NAME = "logging-config-shared-json.log"; // This needs to be deployed first as the two other deployments rely on this @Deployment(name = EJB_DEPLOYMENT, order = 1) public static JavaArchive createEjbDeployment() { return ShrinkWrap.create(JavaArchive.class, EJB_DEPLOYMENT_NAME) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(LoggingStartup.class, LoggerResource.class); } // This should be deployed last to ensure that WAR_DEPLOYMENT_2 does register a log context @Deployment(name = WAR_DEPLOYMENT_1, order = 3) public static WebArchive createWar1() throws Exception { return ShrinkWrap.create(WebArchive.class, WAR_DEPLOYMENT_1_NAME) .addAsManifestResource(createLoggingConfiguration(FILE_NAME), "logging.properties") .addAsManifestResource(createJBossDeploymentStructure(), "jboss-deployment-structure.xml") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(LoggingServlet.class); } @Deployment(name = WAR_DEPLOYMENT_2, order = 2) public static WebArchive createWar2() { return ShrinkWrap.create(WebArchive.class, WAR_DEPLOYMENT_2_NAME) .addAsManifestResource(createJBossDeploymentStructure(), "jboss-deployment-structure.xml") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(LoggingServlet.class); } @Test public void testDeployments(@OperateOnDeployment(WAR_DEPLOYMENT_1) @ArquillianResource URL war1, @OperateOnDeployment(WAR_DEPLOYMENT_2) @ArquillianResource URL war2) throws Exception { // First invoke the first deployment to log final String msg1 = "Test from shared WAR1"; UrlBuilder builder = UrlBuilder.of(war1, "log"); builder.addParameter("msg", msg1); performCall(builder.build()); // Next invoke the second deployment which should not use the log context from the first deployment final String msg2 = "Test from shared WAR2"; builder = UrlBuilder.of(war2, "log"); builder.addParameter("msg", msg2); performCall(builder.build()); final List<JsonObject> depLogs = readJsonLogFile(FILE_NAME); // There should only be a log message from the servlet assertLength(depLogs, 1, FILE_NAME); // Check the expected dep log file Collection<JsonObject> unexpectedLogs = depLogs.stream() .filter(logMessage -> { final String msg = logMessage.getString("message"); return (!msg.equals(LoggingServlet.formatMessage(msg1))); }) .collect(Collectors.toList()); assertUnexpectedLogs(unexpectedLogs, FILE_NAME); // Now we want to make sure that only WAR2 logs made it into the default log context final List<JsonObject> defaultLogs = readJsonLogFileFromModel(null, DEFAULT_LOG_FILE); // There should be 1 startup messages in this file, 3 from WAR2 servlet and 2 from the static logger in WAR1 assertLength(defaultLogs, 6, DEFAULT_LOG_FILE); unexpectedLogs = defaultLogs.stream() .filter(logMessage -> { final String msg = logMessage.getString("message"); return !msg.equals(LoggerResource.formatStaticLogMsg(msg1)) && !msg.equals(LoggerResource.formatLogMsg(msg1)) && !msg.equals(LoggingServlet.formatMessage(msg2)) && !msg.equals(LoggerResource.formatLogMsg(msg2)) && !msg.equals(LoggerResource.formatStaticLogMsg(msg2)) && !msg.equals(LoggingStartup.STARTUP_MESSAGE); }) .collect(Collectors.toList()); assertUnexpectedLogs(unexpectedLogs, DEFAULT_LOG_FILE); } private static Asset createJBossDeploymentStructure() { return new StringAsset( "<jboss-deployment-structure>\n" + " <deployment>\n" + " <dependencies>\n" + " <module name=\"deployment." + EJB_DEPLOYMENT_NAME + "\" meta-inf=\"import\" />\n" + " </dependencies>\n" + " </deployment>\n" + "</jboss-deployment-structure>"); } }
7,098
47.292517
188
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/logging/config/LoggerResource.java
/* * Copyright 2020 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.logging.config; import jakarta.enterprise.context.ApplicationScoped; import org.jboss.logging.Logger; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @ApplicationScoped public class LoggerResource { static final String LOGGER_NAME = LoggerResource.class.getName(); private static final Logger LOGGER = Logger.getLogger(LOGGER_NAME); public void logStatic(final String msg) { LOGGER.info(formatStaticLogMsg(msg)); } public void log(final String msg) { Logger.getLogger(LOGGER_NAME).info(formatLogMsg(msg)); } static String formatStaticLogMsg(final String msg) { return String.format("%s - static resource", msg); } static String formatLogMsg(final String msg) { return String.format("%s - resource", msg); } }
1,452
29.270833
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/logging/config/LoggingStartup.java
/* * Copyright 2020 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.logging.config; import jakarta.annotation.PostConstruct; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; import org.jboss.logging.Logger; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @Singleton @Startup public class LoggingStartup { static final String LOGGER_NAME = LoggingStartup.class.getName(); static final String STARTUP_MESSAGE = "Test startup from EJB"; private final Logger LOGGER = Logger.getLogger(LOGGER_NAME); @PostConstruct public void logEjbMessage() { LOGGER.info(STARTUP_MESSAGE); } }
1,214
29.375
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/logging/config/LoggingProfileSharedTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.logging.config; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import jakarta.json.JsonObject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.OverProtocol; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(LoggingProfileSharedTestCase.LoggingProfileSetupTask.class) public class LoggingProfileSharedTestCase extends AbstractConfigTestCase { private static final String PROFILE_NAME = "test-shared-profile"; private static final String WAR_DEPLOYMENT_1 = "logging-profile-war-1"; private static final String WAR_DEPLOYMENT_2 = "logging-profile-war-2"; private static final String EJB_DEPLOYMENT = "logging-profile-ejb"; private static final String EJB_DEPLOYMENT_NAME = "logging-profile-ejb.jar"; private static final String WAR_DEPLOYMENT_1_NAME = "logging-profile-war-1.war"; private static final String WAR_DEPLOYMENT_2_NAME = "logging-profile-war-2.war"; private static final String FILE_NAME = "logging-profile-shared-json.log"; // This needs to be deployed first as the two other deployments rely on this @Deployment(name = EJB_DEPLOYMENT, order = 1) public static JavaArchive createEjbDeployment() { return ShrinkWrap.create(JavaArchive.class, EJB_DEPLOYMENT_NAME) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(LoggingStartup.class, LoggerResource.class); } // This should be deployed last to ensure that WAR_DEPLOYMENT_2 does register a log context @Deployment(name = WAR_DEPLOYMENT_1, order = 3) @OverProtocol("Servlet 5.0") public static WebArchive createWar1() { return ShrinkWrap.create(WebArchive.class, WAR_DEPLOYMENT_1_NAME) .addAsManifestResource(createJBossDeploymentStructure(), "jboss-deployment-structure.xml") .addAsManifestResource(new StringAsset("Logging-Profile: " + PROFILE_NAME), "MANIFEST.MF") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(LoggingServlet.class); } @Deployment(name = WAR_DEPLOYMENT_2, order = 2) public static WebArchive createWar2() { return ShrinkWrap.create(WebArchive.class, WAR_DEPLOYMENT_2_NAME) .addAsManifestResource(createJBossDeploymentStructure(), "jboss-deployment-structure.xml") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(LoggingServlet.class); } @Test public void testDeployments(@OperateOnDeployment(WAR_DEPLOYMENT_1) @ArquillianResource URL war1, @OperateOnDeployment(WAR_DEPLOYMENT_2) @ArquillianResource URL war2) throws Exception { // First invoke the first deployment to log final String msg1 = "Test from shared WAR1"; UrlBuilder builder = UrlBuilder.of(war1, "log"); builder.addParameter("msg", msg1); performCall(builder.build()); // Next invoke the second deployment which should not use the log context from the first deployment final String msg2 = "Test from shared WAR2"; builder = UrlBuilder.of(war2, "log"); builder.addParameter("msg", msg2); performCall(builder.build()); final List<JsonObject> depLogs = readJsonLogFileFromModel(PROFILE_NAME, FILE_NAME); // There should only be a log message from the servlet assertLength(depLogs, 1, FILE_NAME); // Check the expected dep log file Collection<JsonObject> unexpectedLogs = depLogs.stream() .filter(logMessage -> { final String msg = logMessage.getString("message"); return (!msg.equals(LoggingServlet.formatMessage(msg1))); }) .collect(Collectors.toList()); assertUnexpectedLogs(unexpectedLogs, FILE_NAME); // Now we want to make sure that only WAR2 logs made it into the default log context final List<JsonObject> defaultLogs = readJsonLogFileFromModel(null, DEFAULT_LOG_FILE); // There should be 1 startup messages in this file, 3 from WAR2 servlet and 2 from the static logger in WAR1 assertLength(defaultLogs, 6, DEFAULT_LOG_FILE); unexpectedLogs = defaultLogs.stream() .filter(logMessage -> { final String msg = logMessage.getString("message"); return !msg.equals(LoggerResource.formatStaticLogMsg(msg1)) && !msg.equals(LoggerResource.formatLogMsg(msg1)) && !msg.equals(LoggingServlet.formatMessage(msg2)) && !msg.equals(LoggerResource.formatLogMsg(msg2)) && !msg.equals(LoggerResource.formatStaticLogMsg(msg2)) && !msg.equals(LoggingStartup.STARTUP_MESSAGE); }) .collect(Collectors.toList()); assertUnexpectedLogs(unexpectedLogs, DEFAULT_LOG_FILE); } private static Asset createJBossDeploymentStructure() { return new StringAsset( "<jboss-deployment-structure>\n" + " <deployment>\n" + " <dependencies>\n" + " <module name=\"deployment." + EJB_DEPLOYMENT_NAME + "\" meta-inf=\"import\" />\n" + " </dependencies>\n" + " </deployment>\n" + "</jboss-deployment-structure>"); } public static class LoggingProfileSetupTask extends LogFileServerSetupTask { @Override protected Operations.CompositeOperationBuilder createBuilder() { final Operations.CompositeOperationBuilder builder = super.createBuilder(); builder.addStep(Operations.createAddOperation(createSubsystemAddress(PROFILE_NAME))); addDefaults(builder, PROFILE_NAME, FILE_NAME); return builder; } } }
7,853
47.481481
188
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/logging/config/AbstractConfigTestCase.java
/* * Copyright 2020 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.logging.config; import static org.jboss.as.controller.client.helpers.Operations.CompositeOperationBuilder; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; import jakarta.json.Json; import jakarta.json.JsonObject; import jakarta.json.JsonReader; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.OperationMessageHandler; import org.jboss.as.controller.client.OperationResponse; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.asset.ByteArrayAsset; import org.junit.Assert; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ abstract class AbstractConfigTestCase { static final String DEFAULT_LOG_FILE = "json.log"; @ContainerResource protected ManagementClient client; List<JsonObject> readJsonLogFileFromModel(final String logProfileName, final String logFileName) throws IOException { return readJsonLogFile(logProfileName, logFileName, true); } List<JsonObject> readJsonLogFile(final String logFileName) throws IOException { return readJsonLogFile(null, logFileName, false); } ModelNode executeOperation(final ModelNode op) throws IOException { return executeOperation(Operation.Factory.create(op)); } ModelNode executeOperation(final Operation op) throws IOException { return executeOperation(client, op); } private List<JsonObject> readJsonLogFile(final String logProfileName, final String logFileName, final boolean fromModel) throws IOException { final List<JsonObject> lines = new ArrayList<>(); try ( BufferedReader reader = fromModel ? readLogFileFromModel(logProfileName, logFileName) : readLogFile(logFileName) ) { String line; while ((line = reader.readLine()) != null) { try (JsonReader jsonReader = Json.createReader(new StringReader(line))) { lines.add(jsonReader.readObject()); } } } return lines; } private BufferedReader readLogFileFromModel(final String profileName, final String logFileName) throws IOException { final ModelNode address = createSubsystemAddress(profileName, "log-file", logFileName); final ModelNode op = Operations.createReadAttributeOperation(address, "stream"); final OperationResponse response = client.getControllerClient().executeOperation(Operation.Factory.create(op), OperationMessageHandler.logging); final ModelNode result = response.getResponseNode(); if (Operations.isSuccessfulOutcome(result)) { final OperationResponse.StreamEntry entry = response.getInputStream(Operations.readResult(result).asString()); if (entry == null) { throw new RuntimeException(String.format("Failed to find entry with UUID %s for log file %s", Operations.readResult(result).asString(), logFileName)); } return new BufferedReader(new InputStreamReader(entry.getStream(), StandardCharsets.UTF_8)); } throw new RuntimeException(String.format("Failed to read log file %s: %s", logFileName, Operations.getFailureDescription(result).asString())); } private BufferedReader readLogFile(final String logFileName) throws IOException { final Path path = resolveLogDirectory().resolve(logFileName); Assert.assertTrue("Path " + path + " does not exist.", Files.exists(path)); return Files.newBufferedReader(path, StandardCharsets.UTF_8); } private Path resolveLogDirectory() throws IOException { final ModelNode address = Operations.createAddress("path", "jboss.server.log.dir"); final ModelNode op = Operations.createOperation("path-info", address); final ModelNode result = executeOperation(op); final Path dir = Paths.get(result.get("path", "resolved-path").asString()); Assert.assertTrue("Log directory " + dir + " does not exist", Files.exists(dir)); return dir; } static void performCall(final String url) throws Exception { HttpRequest.get(url, TimeoutUtil.adjust(10), TimeUnit.SECONDS); } static void assertUnexpectedLogs(final Collection<JsonObject> unexpectedLogs, final String logFile) { if (!unexpectedLogs.isEmpty()) { final StringBuilder msg = new StringBuilder("Found unexpected log messages in file ") .append(logFile) .append(':'); appendLines(unexpectedLogs, msg); Assert.fail(msg.toString()); } } static void assertLength(final Collection<JsonObject> lines, final int len, final String logFile) { if (len != lines.size()) { final StringBuilder msg = new StringBuilder("Found ") .append(lines.size()) .append(" lines expected ") .append(len) .append(" in file ") .append(logFile) .append(':'); appendLines(lines, msg); Assert.fail(msg.toString()); } } static void appendLines(final Collection<JsonObject> lines, final StringBuilder msg) { for (JsonObject logMsg : lines) { msg.append(System.lineSeparator()) .append('\t') .append(logMsg.getString("level")).append(' ') .append('[').append(logMsg.getString("threadName")).append("] ") .append('[').append(logMsg.getString("loggerName")).append("] ") .append(logMsg.getString("message")); } } static Asset createLoggingConfiguration(final String fileName) throws IOException { final Properties properties = new Properties(); // Configure the root logger properties.setProperty("logger.level", "INFO"); properties.setProperty("logger.handlers", fileName); // Configure the handler properties.setProperty("handler." + fileName, "org.jboss.logmanager.handlers.FileHandler"); properties.setProperty("handler." + fileName + ".level", "ALL"); properties.setProperty("handler." + fileName + ".formatter", "json"); properties.setProperty("handler." + fileName + ".properties", "append,autoFlush,fileName"); properties.setProperty("handler." + fileName + ".append", "false"); properties.setProperty("handler." + fileName + ".autoFlush", "true"); properties.setProperty("handler." + fileName + ".fileName", "${jboss.server.log.dir}" + File.separatorChar + fileName); // Add the JSON formatter properties.setProperty("formatter.json", "org.jboss.logmanager.formatters.JsonFormatter"); final ByteArrayOutputStream out = new ByteArrayOutputStream(); properties.store(new OutputStreamWriter(out, StandardCharsets.UTF_8), null); return new ByteArrayAsset(out.toByteArray()); } static ModelNode executeOperation(final ManagementClient client, final Operation op) throws IOException { final ModelNode result = client.getControllerClient().execute(op); if (!Operations.isSuccessfulOutcome(result)) { Assert.fail(Operations.getFailureDescription(result).toString()); } // Reload if required if (result.hasDefined(ClientConstants.RESPONSE_HEADERS)) { final ModelNode responseHeaders = result.get(ClientConstants.RESPONSE_HEADERS); if (responseHeaders.hasDefined("process-state")) { if (ClientConstants.CONTROLLER_PROCESS_STATE_RELOAD_REQUIRED.equals(responseHeaders.get("process-state").asString())) { ServerReload.executeReloadAndWaitForCompletion(client); } else if (ClientConstants.CONTROLLER_PROCESS_STATE_RESTART_REQUIRED.equalsIgnoreCase(responseHeaders.get("process-state").asString())) { Assert.fail("Tests that require a restart need to be manual mode tests."); } } } return Operations.readResult(result); } static ModelNode createSubsystemAddress(final String profileName, final String... parts) { final Collection<String> address = new ArrayList<>(); address.add("subsystem"); address.add("logging"); if (profileName != null) { address.add("logging-profile"); address.add(profileName); } Collections.addAll(address, parts); return Operations.createAddress(address); } @SuppressWarnings({"UnusedReturnValue", "SameParameterValue"}) static class UrlBuilder { private final URL url; private final String[] paths; private final Map<String, String> params; private UrlBuilder(final URL url, final String... paths) { this.url = url; this.paths = paths; params = new HashMap<>(); } static UrlBuilder of(final URL url, final String... paths) { return new UrlBuilder(url, paths); } UrlBuilder addParameter(final String key, final String value) { params.put(key, value); return this; } String build() throws UnsupportedEncodingException { final StringBuilder result = new StringBuilder(url.toExternalForm()); if (paths != null) { for (String path : paths) { result.append('/').append(path); } } boolean isFirst = true; for (Map.Entry<String, String> entry : params.entrySet()) { if (isFirst) { result.append('?'); } else { result.append('&'); } result.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append('=').append(URLEncoder.encode(entry.getValue(), "UTF-8")); isFirst = false; } return result.toString(); } } public static class LogFileServerSetupTask extends SnapshotRestoreSetupTask { private static final String DEFAULT_HANDLER_NAME = "json-file"; private static final String JSON_FORMATTER_NAME = "json"; @Override protected void doSetup(final ManagementClient client, final String containerId) throws Exception { executeOperation(client, createBuilder().build()); } protected CompositeOperationBuilder createBuilder() { final CompositeOperationBuilder builder = CompositeOperationBuilder.create(); addDefaults(builder, null, DEFAULT_LOG_FILE); return builder; } static void addDefaults(final CompositeOperationBuilder builder, final String profileName, final String logFileName) { // Create a JSON formatter on the default log context final ModelNode address = createSubsystemAddress(profileName, "json-formatter", JSON_FORMATTER_NAME); builder.addStep(Operations.createAddOperation(address)); // Add a new file handler to write JSON logs to ModelNode op = createFileAddOp(profileName, logFileName); builder.addStep(op); // Create new loggers for each logger we want and add the handler op = Operations.createAddOperation(createSubsystemAddress(profileName, "logger", LoggingServlet.LOGGER_NAME)); op.get("handlers").setEmptyList().add(DEFAULT_HANDLER_NAME); builder.addStep(op); op = Operations.createAddOperation(createSubsystemAddress(profileName, "logger", LoggerResource.LOGGER_NAME)); op.get("handlers").setEmptyList().add(DEFAULT_HANDLER_NAME); builder.addStep(op); op = Operations.createAddOperation(createSubsystemAddress(profileName, "logger", LoggingStartup.LOGGER_NAME)); op.get("handlers").setEmptyList().add(DEFAULT_HANDLER_NAME); builder.addStep(op); } static ModelNode createFileAddOp(final String profileName, final String fileName) { // add file handler final ModelNode op = Operations.createAddOperation(createSubsystemAddress(profileName, "file-handler", DEFAULT_HANDLER_NAME)); op.get("level").set("INFO"); op.get("append").set(false); op.get("autoflush").set(true); final ModelNode file = new ModelNode(); file.get("relative-to").set("jboss.server.log.dir"); file.get("path").set(fileName); op.get("file").set(file); op.get("named-formatter").set(JSON_FORMATTER_NAME); return op; } } }
14,460
43.770898
153
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/DeploymentOperationsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CONTENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ENABLED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INPUT_STREAM_INDEX; 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.READ_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLBACK_ON_RUNTIME_FAILURE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.jboss.as.protocol.StreamUtils.safeClose; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; 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.Operation; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.dmr.ModelNode; 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.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * @author Emanuel Muckenhuber */ @RunWith(Arquillian.class) @RunAsClient public class DeploymentOperationsTestCase extends ContainerResourceMgmtTestBase { private final PathAddress DEPLOYMENT_ONE = PathAddress.pathAddress(PathElement.pathElement(DEPLOYMENT, "deployment-one")); private final PathAddress DEPLOYMENT_TWO = PathAddress.pathAddress(PathElement.pathElement(DEPLOYMENT, "deployment-two")); private static final String tempDir = System.getProperty("java.io.tmpdir"); private File deployDir; @Before public void before() throws Exception { deployDir = new File(tempDir + File.separator + "tempDeployments"); if (deployDir.exists()) { FileUtils.deleteDirectory(deployDir); } assertTrue("Unable to create deployment scanner directory.", deployDir.mkdir()); } @After public void after() throws Exception { FileUtils.deleteDirectory(deployDir); } @Test public void testDeploymentRollbackOnRuntimeFailure() throws Exception { final File deploymentOne = new File(deployDir, "deployment-one.jar"); final File deploymentTwo = new File(deployDir, "deployment-two.jar"); createDeployment(deploymentOne, "org.jboss.modules"); createDeployment(deploymentTwo, "non.existing.dependency"); final ModelNode composite = new ModelNode(); composite.get(OP).set(COMPOSITE); composite.get(OPERATION_HEADERS).get(ROLLBACK_ON_RUNTIME_FAILURE).set(false); final ModelNode nested = composite.get(STEPS).setEmptyList().add(); nested.get(OP).set(COMPOSITE); nested.get(OP_ADDR).setEmptyList(); final ModelNode steps = nested.get(STEPS).setEmptyList(); final ModelNode deployOne = steps.add(); deployOne.get(OP).set(ADD); deployOne.get(OP_ADDR).set(DEPLOYMENT_ONE.toModelNode()); deployOne.get(ENABLED).set(true); deployOne.get(CONTENT).add().get(INPUT_STREAM_INDEX).set(0); final ModelNode deployTwo = steps.add(); deployTwo.get(OP).set(ADD); deployTwo.get(OP_ADDR).set(DEPLOYMENT_TWO.toModelNode()); deployTwo.get(ENABLED).set(true); deployTwo.get(CONTENT).add().get(INPUT_STREAM_INDEX).set(1); final Operation operation = OperationBuilder.create(composite, true) .addFileAsAttachment(deploymentOne) .addFileAsAttachment(deploymentTwo) .build(); final ModelControllerClient client = getModelControllerClient(); try { // Deploy final ModelNode overallResult = client.execute(operation); Assert.assertTrue(overallResult.asString(), SUCCESS.equals(overallResult.get(OUTCOME).asString())); final ModelNode result = overallResult.get(RESULT, "step-1"); Assert.assertTrue(result.asString(), SUCCESS.equals(result.get(OUTCOME).asString())); final ModelNode step1 = result.get(RESULT, "step-1"); Assert.assertEquals(SUCCESS, step1.get(OUTCOME).asString()); final ModelNode step2 = result.get(RESULT, "step-2"); Assert.assertEquals(FAILED, step2.get(OUTCOME).asString()); } finally { safeClose(operation); } // Check if deployment-one and -two exist executeOperation(Util.createEmptyOperation(READ_RESOURCE_OPERATION, DEPLOYMENT_ONE)); executeOperation(Util.createEmptyOperation(READ_RESOURCE_OPERATION, DEPLOYMENT_TWO)); //do cleanup executeOperation(Util.createRemoveOperation(DEPLOYMENT_ONE)); executeOperation(Util.createRemoveOperation(DEPLOYMENT_TWO)); } protected void createDeployment(final File file, final String dependency) throws IOException { final JavaArchive archive = ShrinkWrap.create(JavaArchive.class); final String dependencies = "Dependencies: " + dependency; archive.add(new StringAsset(dependencies), "META-INF/MANIFEST.MF"); archive.as(ZipExporter.class).exportTo(file); } }
7,622
44.921687
126
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/SubDeploymentOperationsTestCase.java
/* * Copyright (C) 2016 Red Hat, inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package org.jboss.as.test.integration.deployment; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.deployment.classloading.ear.subdeployments.ejb.EJBBusinessInterface; import org.jboss.as.test.integration.deployment.classloading.ear.subdeployments.ejb.SimpleSLSB; import org.jboss.as.test.integration.deployment.classloading.ear.subdeployments.servlet.EjbInvokingServlet; import org.jboss.as.test.integration.deployment.classloading.ear.subdeployments.servlet.HelloWorldServlet; 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.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; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * Tests to check that the subdeployments function properly with other subdeployments after using * the explode operation. * @author <a href="mailto:[email protected]">Michal Jurc</a> (c) 2016 Red Hat, Inc. */ @RunWith(Arquillian.class) @RunAsClient public class SubDeploymentOperationsTestCase { private static final Logger logger = Logger.getLogger(SubDeploymentOperationsTestCase.class); private static final String TEST_DEPLOYMENT_NAME = "subdeployment-test.ear"; private static final String JAR_SUBDEPLOYMENT_NAME = "subdeployment-test-ejb.jar"; private static final String WAR_SUBDEPLOYMENT_NAME = "subdeployment-test-web.war"; private static final String ARCHIVED_DEPLOYMENT_ERROR_CODE = "WFLYSRV0258"; @ContainerResource ManagementClient managementClient; @Before public void setUpDeployment() throws Exception { ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); op.get(ModelDescriptionConstants.OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT, TEST_DEPLOYMENT_NAME); ModelNode result = managementClient.getControllerClient().execute(op); if (Operations.isSuccessfulOutcome(result)) { undeploy(TEST_DEPLOYMENT_NAME); remove(TEST_DEPLOYMENT_NAME); } result = initialDeploy(); Assert.assertTrue("Failure to set the initial development up: " + result.toString(), Operations.isSuccessfulOutcome(result)); result = undeploy(TEST_DEPLOYMENT_NAME); Assert.assertTrue("Failure to undeploy the initial development: " + result.toString(), Operations.isSuccessfulOutcome(result)); } @After public void cleanUpDeployment() throws Exception { ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION); op.get(ModelDescriptionConstants.OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT, TEST_DEPLOYMENT_NAME); ModelNode result = managementClient.getControllerClient().execute(op); if (Operations.isSuccessfulOutcome(result)) { undeploy(TEST_DEPLOYMENT_NAME); remove(TEST_DEPLOYMENT_NAME); } } @Test public void testExplodeJarSubDeployment() throws Exception { ModelNode result = explode(TEST_DEPLOYMENT_NAME, ""); Assert.assertTrue("Failure to explode the initial deployment: " + result.toString(), Operations.isSuccessfulOutcome(result)); result = explode(TEST_DEPLOYMENT_NAME, JAR_SUBDEPLOYMENT_NAME); Assert.assertTrue("Failure to explode JAR subdeployment: " + result.toString(), Operations.isSuccessfulOutcome(result)); result = deploy(TEST_DEPLOYMENT_NAME); Assert.assertTrue("Failure to redeploy the deployment: " + result.toString(), Operations.isSuccessfulOutcome(result)); testEjbClassAvailableInServlet(); } @Test public void testExplodeWarSubDeployment() throws Exception { ModelNode result = explode(TEST_DEPLOYMENT_NAME, ""); Assert.assertTrue("Failure to explode the initial deployment: " + result.toString(), Operations.isSuccessfulOutcome(result)); result = explode(TEST_DEPLOYMENT_NAME, WAR_SUBDEPLOYMENT_NAME); Assert.assertTrue("Failure to explode WAR subdeployment: " + result.toString(), Operations.isSuccessfulOutcome(result)); result = deploy(TEST_DEPLOYMENT_NAME); Assert.assertTrue("Failure to redeploy the deployment: " + result.toString(), Operations.isSuccessfulOutcome(result)); testEjbClassAvailableInServlet(); } @Test public void testExplodeJarAndWarSubDeployment() throws Exception { ModelNode result = explode(TEST_DEPLOYMENT_NAME, ""); Assert.assertTrue("Failure to explode the initial deployment: " + result.toString(), Operations.isSuccessfulOutcome(result)); result = explode(TEST_DEPLOYMENT_NAME, JAR_SUBDEPLOYMENT_NAME); Assert.assertTrue("Failure to explode JAR subdeployment: " + result.toString(), Operations.isSuccessfulOutcome(result)); result = explode(TEST_DEPLOYMENT_NAME, WAR_SUBDEPLOYMENT_NAME); Assert.assertTrue("Failure to explode WAR subdeployment: " + result.toString(), Operations.isSuccessfulOutcome(result)); result = deploy(TEST_DEPLOYMENT_NAME); Assert.assertTrue("Failure to redeploy the deployment: " + result.toString(), Operations.isSuccessfulOutcome(result)); testEjbClassAvailableInServlet(); } @Test public void testExplodeJarSubDeploymentArchiveDeployment() throws Exception { ModelNode result = explode(TEST_DEPLOYMENT_NAME, JAR_SUBDEPLOYMENT_NAME); Assert.assertFalse("Exploding JAR subdeployment of archived deployment should fail, but outcome was " + result.toString(), Operations.isSuccessfulOutcome(result)); String failure = Operations.getFailureDescription(result).asString(); Assert.assertTrue("Exploding JAR subdeployment of archived deployment failed with wrong reason: " + failure, failure.contains(ARCHIVED_DEPLOYMENT_ERROR_CODE)); result = deploy(TEST_DEPLOYMENT_NAME); Assert.assertTrue("Failure to redeploy the deployment: " + result.toString(), Operations.isSuccessfulOutcome(result)); testEjbClassAvailableInServlet(); } @Test public void testExplodeWarSubDeploymentArchiveDeployment() throws Exception { ModelNode result = explode(TEST_DEPLOYMENT_NAME, WAR_SUBDEPLOYMENT_NAME); Assert.assertFalse("Exploding WAR subdeployment of archived deployment should fail, but outcome was " + result.toString(), Operations.isSuccessfulOutcome(result)); String failure = Operations.getFailureDescription(result).asString(); Assert.assertTrue("Exploding WAR subdeployment of archived deployment failed with wrong reason: " + failure, failure.contains(ARCHIVED_DEPLOYMENT_ERROR_CODE)); result = deploy(TEST_DEPLOYMENT_NAME); Assert.assertTrue("Failure to redeploy the deployment: " + result.toString(), Operations.isSuccessfulOutcome(result)); testEjbClassAvailableInServlet(); } private ModelNode initialDeploy() throws Exception { ModelNode result; List<InputStream> attachments = new ArrayList<>(); JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, JAR_SUBDEPLOYMENT_NAME) .addClasses(EJBBusinessInterface.class, SimpleSLSB.class); WebArchive war = ShrinkWrap.create(WebArchive.class, WAR_SUBDEPLOYMENT_NAME) .addClasses(HelloWorldServlet.class, EjbInvokingServlet.class); EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, TEST_DEPLOYMENT_NAME) .addAsModule(ejbJar) .addAsModule(war); try (InputStream is = ear.as(ZipExporter.class).exportAsInputStream()) { ModelNode compositeOp = new ModelNode(); ModelNode addOp = new ModelNode(); addOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD); addOp.get(ModelDescriptionConstants.OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT, TEST_DEPLOYMENT_NAME); addOp.get(ModelDescriptionConstants.CONTENT).add(ModelDescriptionConstants.INPUT_STREAM_INDEX, 0); ModelNode content = new ModelNode(); content.get(ModelDescriptionConstants.INPUT_STREAM_INDEX).set(0); ModelNode deployOp = new ModelNode(); deployOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.DEPLOY); deployOp.get(ModelDescriptionConstants.OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT, TEST_DEPLOYMENT_NAME); compositeOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.COMPOSITE); compositeOp.get(ModelDescriptionConstants.STEPS).setEmptyList(); compositeOp.get(ModelDescriptionConstants.STEPS).add(addOp); compositeOp.get(ModelDescriptionConstants.STEPS).add(deployOp); attachments.add(is); result = managementClient.getControllerClient().execute(Operation.Factory.create(compositeOp, attachments)); } return result; } private ModelNode deploy(String deployment) throws Exception { ModelNode deployOp = new ModelNode(); deployOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.DEPLOY); deployOp.get(ModelDescriptionConstants.OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT, deployment); return managementClient.getControllerClient().execute(deployOp); } private ModelNode explode(String deployment, String path) throws Exception { ModelNode explodeOp = new ModelNode(); explodeOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.EXPLODE); explodeOp.get(ModelDescriptionConstants.OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT, deployment); if (!path.isEmpty()) { explodeOp.get(ModelDescriptionConstants.PATH).set(path); } return managementClient.getControllerClient().execute(explodeOp); } private ModelNode undeploy(String deployment) throws Exception { ModelNode undeployOp = new ModelNode(); undeployOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.UNDEPLOY); undeployOp.get(ModelDescriptionConstants.OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT, deployment); return managementClient.getControllerClient().execute(undeployOp); } private ModelNode remove(String deployment) throws Exception { ModelNode removeOp = new ModelNode(); removeOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.REMOVE); removeOp.get(ModelDescriptionConstants.OP_ADDR).set(ModelDescriptionConstants.DEPLOYMENT, deployment); return managementClient.getControllerClient().execute(removeOp); } private void testEjbClassAvailableInServlet() throws Exception { final HttpClient httpClient = HttpClients.createDefault(); final String message = "JBossEAP"; final String requestURL = TestSuiteEnvironment.getHttpUrl().toString() + "/subdeployment-test-web" + HelloWorldServlet.URL_PATTERN + "?" + HelloWorldServlet.PARAMETER_NAME + "=" + message; final HttpGet request = new HttpGet(requestURL); final HttpResponse response = httpClient.execute(request); final HttpEntity entity = response.getEntity(); Assert.assertNotNull("Response message from servlet was null", entity); final String responseMessage = EntityUtils.toString(entity); Assert.assertEquals("Unexpected echo message from servlet at " + requestURL, message, responseMessage); } }
13,740
51.247148
196
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/dependencies/StringView.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.integration.deployment.dependencies; import jakarta.ejb.Remote; /** * @author Stuart Douglas */ @Remote public interface StringView { String getString(); }
1,216
32.805556
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/dependencies/DependentInjectServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.dependencies; import jakarta.annotation.PostConstruct; import jakarta.ejb.EJB; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.inject.Inject; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(urlPatterns = "/test", loadOnStartup = 1) @ApplicationScoped public class DependentInjectServlet extends HttpServlet { @EJB(lookup = "java:global/dependee/DependeeEjb") StringView depdendent; @Inject BeanManager beanManager; @PostConstruct public void doStuff() { if (!"hello".equals(depdendent.getString())) { throw new RuntimeException("wrong string"); } beanManager.createInstance(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write(depdendent.getString()); } }
2,202
35.114754
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/dependencies/DependeeEjb.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.dependencies; import jakarta.annotation.PostConstruct; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; @Singleton @Startup public class DependeeEjb implements StringView { public String hello; @PostConstruct public void post() throws InterruptedException { Thread.sleep(100); hello = "hello"; } @Override public String getString() { return hello; } }
1,491
31.434783
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/dependencies/DependentEjb.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.dependencies; import jakarta.annotation.PostConstruct; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; import javax.naming.InitialContext; import javax.naming.NamingException; @Singleton @Startup public class DependentEjb implements StringView { private String hello; @PostConstruct public void post() throws NamingException { StringView ejb = (StringView) new InitialContext().lookup("java:global/dependee/DependeeEjb"); hello = ejb.getString(); } @Override public String getString() { return hello; } }
1,645
33.291667
102
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/dependencies/EjbDependencyRestartTestCase.java
package org.jboss.as.test.integration.deployment.dependencies; 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.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ArchiveDeployer; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.common.HttpRequest; 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.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; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Tests inter deployment dependencies that are established via @EJB Injection */ @RunWith(Arquillian.class) @RunAsClient public class EjbDependencyRestartTestCase { // Dummy deployment so arq will be able to inject a ManagementClient @Deployment public static Archive<?> getDeployment() { return ShrinkWrap.create(JavaArchive.class, "dummy.jar"); } private static JavaArchive DEPENDEE = ShrinkWrap.create(JavaArchive.class, "dependee.jar") .addClasses(DependeeEjb.class, StringView.class); private static WebArchive DEPENDENT = ShrinkWrap.create(WebArchive.class, "dependent.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(DependentInjectServlet.class, StringView.class); @ArquillianResource public ManagementClient managementClient; // We don't inject this via @ArquillianResource because ARQ can't fully control // DEPENDEE and DEPENDENT and things go haywire if we try. But we use ArchiveDeployer // because it's a convenient API for handling deploy/undeploy of Shrinkwrap archives private ArchiveDeployer deployer; @Before public void setup() { deployer = new ArchiveDeployer(managementClient); } @After public void cleanUp() { try { deployer.undeploy(DEPENDENT.getName()); } catch (Exception e) { // Ignore } try { deployer.undeploy(DEPENDEE.getName()); } catch (Exception e) { // Ignore } } @Test public void testDeploymentDependenciesWithRestart() throws IOException, DeploymentException, TimeoutException, ExecutionException { deployer.deploy(DEPENDEE); deployer.deploy(DEPENDENT); Assert.assertEquals("hello", doGetRequest()); ModelNode response = managementClient.getControllerClient().execute(Util.createEmptyOperation("redeploy", PathAddress.pathAddress("deployment", DEPENDEE.getName()))); Assert.assertEquals(response.toString(), "success", response.get("outcome").asString()); Assert.assertEquals("hello", doGetRequest()); } protected String doGetRequest() throws IOException, ExecutionException, TimeoutException { return HttpRequest.get(managementClient.getWebUri() + "/dependent/test", 10, TimeUnit.SECONDS); } }
3,572
35.090909
174
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/dependencies/InterDeploymentDependenciesTestCase.java
package org.jboss.as.test.integration.deployment.dependencies; import java.io.IOException; import java.util.Hashtable; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; 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.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ArchiveDeployer; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests inter deployment dependencies */ @RunWith(Arquillian.class) @RunAsClient public class InterDeploymentDependenciesTestCase { private static final String APP_NAME = ""; private static final String DISTINCT_NAME = ""; // Dummy deployment so arq will be able to inject a ManagementClient @Deployment public static Archive<?> getDeployment() { return ShrinkWrap.create(JavaArchive.class, "dummy.jar"); } private static JavaArchive DEPENDEE = ShrinkWrap.create(JavaArchive.class, "dependee.jar") .addClasses(DependeeEjb.class, StringView.class); private static JavaArchive DEPENDENT = ShrinkWrap.create(JavaArchive.class, "dependent.jar") .addClasses(DependentEjb.class, StringView.class) .addAsManifestResource(InterDeploymentDependenciesTestCase.class.getPackage(), "jboss-all.xml", "jboss-all.xml"); private static Context context; @BeforeClass public static void beforeClass() throws Exception { final Hashtable<String, String> props = new Hashtable<>(); props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); context = new InitialContext(props); } @ArquillianResource public ManagementClient managementClient; // We don't inject this via @ArquillianResource because ARQ can't fully control // DEPENDEE and DEPENDENT and things go haywire if we try. But we use ArchiveDeployer // because it's a convenient API for handling deploy/undeploy of Shrinkwrap archives private ArchiveDeployer deployer; @Before public void setup() { deployer = new ArchiveDeployer(managementClient); } @After public void cleanUp() { try { deployer.undeploy(DEPENDENT.getName()); } catch (Exception e) { // Ignore } try { deployer.undeploy(DEPENDEE.getName()); } catch (Exception e) { // Ignore } } @Test public void testDeploymentDependencies() throws NamingException, DeploymentException { try { deployer.deploy(DEPENDENT); Assert.fail("Deployment did not fail"); } catch (Exception e) { // expected } deployer.deploy(DEPENDEE); deployer.deploy(DEPENDENT); StringView ejb = lookupStringView(); Assert.assertEquals("hello", ejb.getString()); } @Test public void testDeploymentDependenciesWithRestart() throws NamingException, IOException, DeploymentException { try { deployer.deploy(DEPENDENT); Assert.fail("Deployment did not fail"); } catch (Exception e) { // expected } deployer.deploy(DEPENDEE); deployer.deploy(DEPENDENT); StringView ejb = lookupStringView(); Assert.assertEquals("hello", ejb.getString()); ModelNode response = managementClient.getControllerClient().execute(Util.createEmptyOperation("redeploy", PathAddress.pathAddress("deployment", DEPENDEE.getName()))); Assert.assertEquals(response.toString(), "success", response.get("outcome").asString()); ejb = lookupStringView(); Assert.assertEquals("hello", ejb.getString()); } private static StringView lookupStringView() throws NamingException { return (StringView) context.lookup("ejb:" + APP_NAME + "/dependent/" + DISTINCT_NAME + "/" + DependentEjb.class.getSimpleName() + "!" + StringView.class.getName()); } }
4,630
32.557971
174
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/dependencies/DependentInjectEjb.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.dependencies; import jakarta.annotation.PostConstruct; import jakarta.annotation.Resource; import jakarta.ejb.EJB; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.inject.Inject; import jakarta.validation.Validator; @Singleton @Startup public class DependentInjectEjb implements StringView { @EJB(lookup = "java:global/dependee/DependeeEjb") StringView depdendent; @Resource Validator validator; @Inject BeanManager beanManager; @PostConstruct public void post() throws InterruptedException { beanManager.createInstance(); } @Override public String getString() { return depdendent.getString(); } }
1,816
30.877193
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/dependencies/ear/InterDeploymentDependenciesEarTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.dependencies.ear; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.IOException; import java.util.Hashtable; import jakarta.ejb.NoSuchEJBException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; 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.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ArchiveDeployer; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.ManagementOperations; import org.jboss.as.test.integration.management.util.MgmtOperationException; 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.EmptyAsset; 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; /** * Test for inter-deployment dependencies in EAR files. It also contains a module dependency simple test - EJB module depends on * WEB module in app1.ear. * * @author Josef Cacek */ @RunWith(Arquillian.class) @RunAsClient public class InterDeploymentDependenciesEarTestCase { private static Logger LOGGER = Logger.getLogger(InterDeploymentDependenciesEarTestCase.class); private static final String DEP_APP1 = "app1"; private static final String DEP_APP2 = "app2"; private static final String MODULE_EJB = "hello"; private static final String MODULE_WEB = "staller"; @ArquillianResource public ManagementClient managementClient; // We don't inject this via @ArquillianResource because ARQ can't fully control // DEPA_APP1 and DEP_APP2 and things go haywire if we try. But we use ArchiveDeployer // because it's a convenient API for handling deploy/undeploy of Shrinkwrap archives private ArchiveDeployer deployer; // Public methods -------------------------------------------------------- // Dummy deployment so arq will be able to inject a ManagementClient @Deployment public static Archive<?> getDeployment() { return ShrinkWrap.create(JavaArchive.class, "dummy.jar"); } private static EnterpriseArchive DEPENDEE = ShrinkWrap .create(EnterpriseArchive.class, DEP_APP1 + ".ear") .addAsModule(createWar()) .addAsModule(createBeanJar()) .addAsLibrary(createLogLibrary()) .addAsManifestResource(InterDeploymentDependenciesEarTestCase.class.getPackage(), "application.xml", "application.xml"); private static EnterpriseArchive DEPENDENT = ShrinkWrap .create(EnterpriseArchive.class, DEP_APP2 + ".ear") .addAsLibrary(createLogLibrary()) .addAsModule(createBeanJar()) .addAsManifestResource(InterDeploymentDependenciesEarTestCase.class.getPackage(), "jboss-all.xml", "jboss-all.xml").addAsModule(createBeanJar()); @Before public void setup() { deployer = new ArchiveDeployer(managementClient); } @After public void cleanUp() { try { deployer.undeploy(DEPENDENT.getName()); } catch (Exception e) { // Ignore } try { deployer.undeploy(DEPENDEE.getName()); } catch (Exception e) { // Ignore } } /** * Tests enterprise application dependencies. */ @Test public void test() throws NamingException, IOException, DeploymentException { try { deployer.deploy(DEPENDENT); fail("Application deployment must fail if the dependencies are not satisfied."); } catch (Exception e) { LOGGER.debug("Expected fail", e); } deployer.deploy(DEPENDEE); deployer.deploy(DEPENDENT); final LogAccess helloApp1 = lookupEJB(DEP_APP1); final LogAccess helloApp2 = lookupEJB(DEP_APP2); assertEquals(SleeperContextListener.class.getSimpleName() + LogAccessBean.class.getSimpleName(), helloApp1.getLog()); assertEquals(LogAccessBean.class.getSimpleName(), helloApp2.getLog()); forceDependeeUndeploy(); try { helloApp2.getLog(); fail("Calling EJB from dependent application should fail"); } catch (IllegalStateException | NoSuchEJBException e) { //OK } // cleanUp will undeploy DEP_APP2 } @Test public void testWithRestart() throws NamingException, IOException, DeploymentException, MgmtOperationException { try { deployer.deploy(DEPENDENT); fail("Application deployment must fail if the dependencies are not satisfied."); } catch (Exception e) { LOGGER.debug("Expected fail", e); } deployer.deploy(DEPENDEE); deployer.deploy(DEPENDENT); LogAccess helloApp1 = lookupEJB(DEP_APP1); LogAccess helloApp2 = lookupEJB(DEP_APP2); assertEquals(SleeperContextListener.class.getSimpleName() + LogAccessBean.class.getSimpleName(), helloApp1.getLog()); assertEquals(LogAccessBean.class.getSimpleName(), helloApp2.getLog()); ModelNode redeploy = Util.createEmptyOperation("redeploy", PathAddress.pathAddress("deployment", DEPENDEE.getName())); ManagementOperations.executeOperation(managementClient.getControllerClient(), redeploy); helloApp1 = lookupEJB(DEP_APP1); helloApp2 = lookupEJB(DEP_APP2); assertEquals(SleeperContextListener.class.getSimpleName() + LogAccessBean.class.getSimpleName(), helloApp1.getLog()); assertEquals(LogAccessBean.class.getSimpleName(), helloApp2.getLog()); forceDependeeUndeploy(); try { helloApp2.getLog(); fail("Calling EJB from dependent application should fail"); } catch (IllegalStateException | NoSuchEJBException e) { //OK } // cleanUp will undeploy DEP_APP2 } // Private methods ------------------------------------------------------- /** * Lookups LogAccess bean for given application name. * * @param appName application name * @return the LogAccess bean * @throws NamingException if lookup fails */ private LogAccess lookupEJB(String appName) throws NamingException { final Hashtable<String, String> jndiProperties = new Hashtable<>(); jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); final Context context = new InitialContext(jndiProperties); return (LogAccess) context.lookup("ejb:" + appName + "/" + MODULE_EJB + "/" + LogAccessBean.class.getSimpleName() + "!" + LogAccess.class.getName()); } private void forceDependeeUndeploy() throws IOException { ModelNode forcedUndeploy = Util.createEmptyOperation("undeploy", PathAddress.pathAddress("deployment", DEPENDEE.getName())); forcedUndeploy.get("operation-headers", "rollback-on-runtime-failure").set(false); ModelNode response = managementClient.getControllerClient().execute(forcedUndeploy); // This will succeed until WFCORE-1762 is fixed; once it is check that the failure didn't // result in rollback if ("failed".equals(response.get("outcome").asString())) { Assert.assertFalse(response.toString(), response.get("rolled-back").asBoolean(true)); } } /** * Creates a shared lib with logger. */ private static JavaArchive createLogLibrary() { return ShrinkWrap.create(JavaArchive.class, "log.jar").addClass(Log.class); } /** * Creates testing web-app (module for app1.ear) */ private static Archive<?> createWar() { return ShrinkWrap.create(WebArchive.class, MODULE_WEB + ".war") .setWebXML(InterDeploymentDependenciesEarTestCase.class.getPackage(), "web.xml") .addClass(SleeperContextListener.class); } /** * Creates a testing EJB module (for app1 and app2) */ private static Archive<?> createBeanJar() { return ShrinkWrap.create(JavaArchive.class, MODULE_EJB + ".jar") .addClasses(LogAccess.class, LogAccessBean.class).addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); } }
9,981
39.577236
132
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/dependencies/ear/Log.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.dependencies.ear; /** * A Log. Simple logger - only holds static {@link StringBuffer} instance. * * @author Josef Cacek */ public class Log { /** The log. */ public static final StringBuffer SB = new StringBuffer(); }
1,305
36.314286
74
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/dependencies/ear/LogAccessBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.dependencies.ear; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.ejb.Remote; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; import org.jboss.logging.Logger; /** * A Singleton EJB - implementation of {@link LogAccess} interface. * * @author Josef Cacek */ @Singleton @Startup @Remote(LogAccess.class) public class LogAccessBean implements LogAccess { private static Logger LOGGER = Logger.getLogger(LogAccessBean.class); // Public methods -------------------------------------------------------- /** * Lifecycle hook. */ @PostConstruct @PreDestroy public void logLifecycleAction() { LOGGER.trace("logLifecycleAction"); Log.SB.append(getClass().getSimpleName()); } /** * Returns {@link Log#SB} content. * * @return * @see org.jboss.as.test.integration.deployment.dependencies.ear.LogAccess#getLog() */ public String getLog() { return Log.SB.toString(); } }
2,096
30.298507
88
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/dependencies/ear/SleeperContextListener.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.dependencies.ear; import jakarta.servlet.ServletContextEvent; import jakarta.servlet.ServletContextListener; import org.jboss.logging.Logger; /** * A lifecycle hook for the test web-app. * * @author Josef Cacek */ public class SleeperContextListener implements ServletContextListener { private static Logger LOGGER = Logger.getLogger(SleeperContextListener.class); // Public methods -------------------------------------------------------- /** * @param arg0 * @see jakarta.servlet.ServletContextListener#contextDestroyed(jakarta.servlet.ServletContextEvent) */ public void contextDestroyed(ServletContextEvent arg0) { LOGGER.trace("Context destroyed"); } /** * @param arg0 * @see jakarta.servlet.ServletContextListener#contextInitialized(jakarta.servlet.ServletContextEvent) */ public void contextInitialized(ServletContextEvent arg0) { LOGGER.trace("Context initialized - going to sleep"); try { Thread.sleep(100); } catch (InterruptedException e) { LOGGER.warn("Interrupted!"); } LOGGER.trace("Woke up"); Log.SB.append(getClass().getSimpleName()); } }
2,280
34.640625
106
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/dependencies/ear/LogAccess.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.integration.deployment.dependencies.ear; /** * A remote interface for basic EJB tests. * * @author Josef Cacek */ public interface LogAccess { String getLog(); }
1,221
36.030303
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/xml/datasource/Employee.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.xml.datasource; import jakarta.persistence.Entity; import jakarta.persistence.Id; /** * Employee entity class * * @author Scott Marlow */ @Entity public class Employee { @Id private int id; private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
1,725
24.761194
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/xml/datasource/DeployedXmlDataSourceManagementTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.xml.datasource; import java.io.IOException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.standalone.DeploymentPlan; import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentActionResult; import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentManager; import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentPlanResult; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILDREN; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MODEL_DESCRIPTION; 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.RECURSIVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; /** * Test deployment of -ds.xml files * * @author Stuart Douglas */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(DeployedXmlDataSourceManagementTestCase.DeployedXmlDataSourceManagementTestCaseSetup.class) public class DeployedXmlDataSourceManagementTestCase { public static final String TEST_DS_XML = "test-ds.xml"; public static final String JPA_DS_XML = "jpa-ds.xml"; static class DeployedXmlDataSourceManagementTestCaseSetup implements ServerSetupTask { @Override public void setup(final ManagementClient managementClient, final String containerId) throws Exception { ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(managementClient.getControllerClient()); final String packageName = DeployedXmlDataSourceManagementTestCase.class.getPackage().getName().replace(".", "/"); DeploymentPlan plan = manager.newDeploymentPlan() .add(DeployedXmlDataSourceManagementTestCase.class.getResource("/" + packageName + "/" + TEST_DS_XML)).andDeploy() .build(); Future<ServerDeploymentPlanResult> future = manager.execute(plan); ServerDeploymentPlanResult result = future.get(20, TimeUnit.SECONDS); ServerDeploymentActionResult actionResult = result.getDeploymentActionResult(plan.getId()); if (actionResult != null) { final Throwable deploymentException = actionResult.getDeploymentException(); if (deploymentException != null) { throw new RuntimeException(deploymentException); } } plan = manager.newDeploymentPlan() .add(DeployedXmlDataSourceManagementTestCase.class.getResource("/" + packageName + "/" + JPA_DS_XML)).andDeploy() .build(); future = manager.execute(plan); future.get(20, TimeUnit.SECONDS); actionResult = result.getDeploymentActionResult(plan.getId()); if (actionResult != null) { final Throwable deploymentException = actionResult.getDeploymentException(); if (deploymentException != null) { throw new RuntimeException(deploymentException); } } } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(managementClient.getControllerClient()); DeploymentPlan undeployPlan = manager.newDeploymentPlan() .undeploy(TEST_DS_XML).andRemoveUndeployed() .build(); manager.execute(undeployPlan).get(); undeployPlan = manager.newDeploymentPlan() .undeploy(JPA_DS_XML).andRemoveUndeployed() .build(); manager.execute(undeployPlan).get(); } } @ContainerResource private ManagementClient managementClient; @Deployment public static Archive<?> deploy() { return ShrinkWrap.create(JavaArchive.class, "testDsXmlDeployment.jar") .addClass(DeployedXmlDataSourceManagementTestCase.class) .addAsManifestResource(DeployedXmlDataSourceManagementTestCase.class.getPackage(), "MANIFEST.MF", "MANIFEST.MF"); } @Test public void testDeployedDatasourceInManagementModel() throws IOException { final ModelNode address = new ModelNode(); address.add("deployment", TEST_DS_XML); address.add("subsystem", "datasources"); address.add("data-source", "java:jboss/datasources/DeployedDS"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("read-resource"); operation.get(OP_ADDR).set(address); operation.get(INCLUDE_RUNTIME).set(true); ModelNode result = managementClient.getControllerClient().execute(operation).get(RESULT); Assert.assertEquals("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE", result.get("connection-url").asString()); } @Test public void testDeployedXaDatasourceInManagementModel() throws IOException { final ModelNode address = new ModelNode(); address.add("deployment", TEST_DS_XML); address.add("subsystem", "datasources"); address.add("xa-data-source", "java:/H2XADS"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("read-resource"); operation.get(OP_ADDR).set(address); operation.get(INCLUDE_RUNTIME).set(true); ModelNode result = managementClient.getControllerClient().execute(operation).get(RESULT); Assert.assertEquals("h2", result.get("driver-name").asString()); } @Test public void testDeployedXaDatasourcePropertiesInManagementModel() throws IOException { final ModelNode address = new ModelNode(); address.add("deployment", TEST_DS_XML); address.add("subsystem", "datasources"); address.add("xa-data-source", "java:/H2XADS"); address.add("xa-datasource-properties", "URL"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("read-attribute"); operation.get(OP_ADDR).set(address); operation.get(NAME).set(VALUE); ModelNode result = managementClient.getControllerClient().execute(operation); Assert.assertEquals("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE", result.get(RESULT).asString()); } @Test public void testDeployedDatasourceStatisticsInManagementModel() throws IOException { final ModelNode address = new ModelNode(); address.add("deployment", TEST_DS_XML); address.add("subsystem", "datasources"); address.add("data-source", "java:jboss/datasources/DeployedDS"); address.protect(); final ModelNode poolAddress = new ModelNode().set(address); poolAddress.add("statistics", "pool"); ModelNode operation = new ModelNode(); operation.get(OP).set("read-resource"); operation.get(OP_ADDR).set(poolAddress); operation.get(INCLUDE_RUNTIME).set(true); ModelNode result = managementClient.getControllerClient().execute(operation).get(RESULT); Assert.assertTrue("ActiveCount", result.hasDefined("ActiveCount")); final ModelNode jdbcAddress = new ModelNode().set(address); jdbcAddress.add("statistics", "jdbc"); operation.get(OP_ADDR).set(jdbcAddress); result = managementClient.getControllerClient().execute(operation).get(RESULT); Assert.assertTrue("PreparedStatementCacheAccessCount", result.hasDefined("PreparedStatementCacheAccessCount")); } @Test public void testDeployedXaDatasourceStatisticsInManagementModel() throws IOException { final ModelNode address = new ModelNode(); address.add("deployment", TEST_DS_XML); address.add("subsystem", "datasources"); address.add("xa-data-source", "java:/H2XADS"); address.protect(); final ModelNode poolAddress = new ModelNode().set(address); poolAddress.add("statistics", "pool"); ModelNode operation = new ModelNode(); operation.get(OP).set("read-resource"); operation.get(OP_ADDR).set(poolAddress); operation.get(INCLUDE_RUNTIME).set(true); ModelNode result = managementClient.getControllerClient().execute(operation).get(RESULT); Assert.assertTrue("ActiveCount", result.hasDefined("ActiveCount")); final ModelNode jdbcAddress = new ModelNode().set(address); jdbcAddress.add("statistics", "jdbc"); operation.get(OP_ADDR).set(jdbcAddress); result = managementClient.getControllerClient().execute(operation).get(RESULT); Assert.assertTrue("PreparedStatementCacheAccessCount", result.hasDefined("PreparedStatementCacheAccessCount")); } /** Test for https://issues.jboss.org/browse/WFLY-2203 */ @Test public void testOverrideRegistrations() throws IOException { ModelNode address = new ModelNode(); address.add("deployment", TEST_DS_XML); address.add("subsystem", "datasources"); ModelNode operation = new ModelNode(); operation.get(OP).set("read-resource-description"); operation.get(OP_ADDR).set(address); operation.get(RECURSIVE).set(true); ModelNode result = managementClient.getControllerClient().execute(operation).get(RESULT); Assert.assertTrue(result.toString(), result.get(CHILDREN, "data-source", MODEL_DESCRIPTION, "*").isDefined()); Assert.assertTrue(result.toString(), result.get(CHILDREN, "data-source", MODEL_DESCRIPTION, "java:jboss/datasources/DeployedDS", CHILDREN, "statistics", MODEL_DESCRIPTION, "pool").isDefined()); Assert.assertTrue(result.toString(), result.get(CHILDREN, "data-source", MODEL_DESCRIPTION, "java:jboss/datasources/DeployedDS", CHILDREN, "statistics", MODEL_DESCRIPTION, "jdbc").isDefined()); Assert.assertTrue(result.toString(), result.get(CHILDREN, "xa-data-source", MODEL_DESCRIPTION, "*").isDefined()); Assert.assertTrue(result.toString(), result.get(CHILDREN, "xa-data-source", MODEL_DESCRIPTION, "java:/H2XADS", CHILDREN, "statistics", MODEL_DESCRIPTION, "pool").isDefined()); Assert.assertTrue(result.toString(), result.get(CHILDREN, "xa-data-source", MODEL_DESCRIPTION, "java:/H2XADS", CHILDREN, "statistics", MODEL_DESCRIPTION, "jdbc").isDefined()); address = new ModelNode(); address.add("deployment", JPA_DS_XML); address.add("subsystem", "datasources"); operation.get(OP_ADDR).set(address); result = managementClient.getControllerClient().execute(operation).get(RESULT); Assert.assertTrue(result.toString(), result.get(CHILDREN, "data-source", MODEL_DESCRIPTION, "*").isDefined()); Assert.assertTrue(result.toString(), result.get(CHILDREN, "xa-data-source", MODEL_DESCRIPTION, "*").isDefined()); Assert.assertTrue(result.toString(), result.get(CHILDREN, "xa-data-source", MODEL_DESCRIPTION, "java:/JPADS", CHILDREN, "statistics", MODEL_DESCRIPTION, "pool").isDefined()); Assert.assertTrue(result.toString(), result.get(CHILDREN, "xa-data-source", MODEL_DESCRIPTION, "java:/JPADS", CHILDREN, "statistics", MODEL_DESCRIPTION, "jdbc").isDefined()); } }
13,489
50.48855
201
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/xml/datasource/DeployedXmlDataSourceTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.xml.datasource; import java.sql.Connection; import java.sql.ResultSet; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.naming.InitialContext; import javax.sql.DataSource; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.standalone.DeploymentPlan; import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentActionResult; import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentManager; import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentPlanResult; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Test deployment of -ds.xml files * * @author Stuart Douglas */ @RunWith(Arquillian.class) @ServerSetup(DeployedXmlDataSourceTestCase.DeployedXmlDataSourceTestCaseSetup.class) public class DeployedXmlDataSourceTestCase { static class DeployedXmlDataSourceTestCaseSetup implements ServerSetupTask { @Override public void setup(final ManagementClient managementClient, final String containerId) throws Exception { final ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(managementClient.getControllerClient()); final String packageName = DeployedXmlDataSourceTestCase.class.getPackage().getName().replace(".", "/"); final DeploymentPlan plan = manager.newDeploymentPlan().add(DeployedXmlDataSourceTestCase.class.getResource("/" + packageName + "/" + TEST_DS_XML)).andDeploy().build(); final Future<ServerDeploymentPlanResult> future = manager.execute(plan); final ServerDeploymentPlanResult result = future.get(20, TimeUnit.SECONDS); final ServerDeploymentActionResult actionResult = result.getDeploymentActionResult(plan.getId()); if (actionResult != null) { final Throwable deploymentException = actionResult.getDeploymentException(); if (deploymentException != null) { throw new RuntimeException(deploymentException); } } } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { final ServerDeploymentManager manager = ServerDeploymentManager.Factory.create(managementClient.getControllerClient()); final DeploymentPlan undeployPlan = manager.newDeploymentPlan().undeploy(TEST_DS_XML).andRemoveUndeployed().build(); manager.execute(undeployPlan).get(); } } public static final String TEST_DS_XML = "test-ds.xml"; @Deployment public static Archive<?> deploy() { return ShrinkWrap.create(JavaArchive.class, "testDsXmlDeployment.jar") .addClass(DeployedXmlDataSourceTestCase.class) .addAsManifestResource(DeployedXmlDataSourceTestCase.class.getPackage(), "MANIFEST.MF", "MANIFEST.MF"); } @ArquillianResource private InitialContext initialContext; @Test public void testDeployedDataSource() throws Throwable { final DataSource dataSource = (DataSource) initialContext.lookup("java:jboss/datasources/DeployedDS"); Assert.assertNotNull(dataSource); Connection conn = dataSource.getConnection(); ResultSet rs = conn.prepareStatement("select 1").executeQuery(); Assert.assertTrue(rs.next()); conn.close(); } @Test public void testDeployedXaDataSource() throws Throwable { final DataSource dataSource = (DataSource) initialContext.lookup("java:/H2XADS"); Assert.assertNotNull(dataSource); Connection conn = dataSource.getConnection(); ResultSet rs = conn.prepareStatement("select 1").executeQuery(); Assert.assertTrue(rs.next()); conn.close(); } }
5,338
43.123967
180
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/xml/datasource/JpaRemote.java
package org.jboss.as.test.integration.deployment.xml.datasource; import java.util.Set; import jakarta.ejb.Remote; /** * @author Stuart Douglas */ @Remote public interface JpaRemote { void addEmployee(String name); Set<String> getEmployees(); }
260
13.5
64
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/xml/datasource/DeployedXmlJpaDataSourceTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.xml.datasource; import java.util.Set; import javax.naming.InitialContext; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Test deployment of -ds.xml files as Jakarta Persistence data sources * * @author Stuart Douglas */ @RunWith(Arquillian.class) public class DeployedXmlJpaDataSourceTestCase { public static final String TEST_DS_XML = "test-ds.xml"; public static final String JPA_DEPLOYMENT_NAME = "jpaDeployment"; @Deployment(name = JPA_DEPLOYMENT_NAME) public static Archive<?> deployJpa() { return ShrinkWrap.create(JavaArchive.class, JPA_DEPLOYMENT_NAME + ".jar") .addClasses(Employee.class, JpaRemoteBean.class, JpaRemote.class, DeployedXmlJpaDataSourceTestCase.class) .addAsManifestResource(DeployedXmlJpaDataSourceTestCase.class.getPackage(), "MANIFEST.MF", "MANIFEST.MF") .addAsManifestResource(DeployedXmlJpaDataSourceTestCase.class.getPackage(), "persistence.xml", "persistence.xml") .addAsManifestResource(DeployedXmlJpaDataSourceTestCase.class.getPackage(), "jpa-ds.xml", "jpa-ds.xml"); } @ArquillianResource private InitialContext initialContext; @Test public void testJpaUsedWithXMLXaDataSource() throws Throwable { final JpaRemote remote = (JpaRemote) initialContext.lookup("java:module/JpaRemoteBean"); remote.addEmployee("Bob"); remote.addEmployee("Sue"); final Set<String> emps = remote.getEmployees(); Assert.assertEquals(2, emps.size()); Assert.assertTrue(emps.contains("Bob")); Assert.assertTrue(emps.contains("Sue")); } }
3,136
37.728395
96
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/xml/datasource/JpaRemoteBean.java
package org.jboss.as.test.integration.deployment.xml.datasource; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import jakarta.ejb.Stateless; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; /** * @author Stuart Douglas */ @Stateless public class JpaRemoteBean implements JpaRemote { private static final AtomicInteger idGenerator = new AtomicInteger(0); @PersistenceContext private EntityManager entityManager; @Override public void addEmployee(final String name) { Employee e = new Employee(); e.setId(idGenerator.incrementAndGet()); e.setName(name); entityManager.persist(e); } @Override public Set<String> getEmployees() { final List<Employee> emps = entityManager.createQuery("select e from Employee e").getResultList(); final Set<String> ret = new HashSet<String>(); for (Employee e : emps) { ret.add(e.getName()); } return ret; } }
1,082
25.414634
106
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/structure/parsing/NoOpEJB.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.integration.deployment.structure.parsing; import jakarta.ejb.Stateless; /** * @author Jaikiran Pai */ @Stateless public class NoOpEJB { public void doNothing() { return; } }
1,245
32.675676
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/structure/parsing/JBossDeploymentStructure11ParsingTestCase.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.integration.deployment.structure.parsing; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; 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.Test; import org.junit.runner.RunWith; import javax.naming.InitialContext; /** * Tests that parsing of a jboss-deployment-structure.xml using 1.1 version xsd, works as expected * * @author Jaikiran Pai */ @RunWith(Arquillian.class) public class JBossDeploymentStructure11ParsingTestCase { private static final Logger logger = Logger.getLogger(JBossDeploymentStructure11ParsingTestCase.class); private static final String MODULE_NAME = "jboss-deployment-structure-11-parsing-test"; @Deployment public static Archive createDeployment() { final JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, MODULE_NAME + ".jar"); ejbJar.addPackage(JBossDeploymentStructure11ParsingTestCase.class.getPackage()); ejbJar.addAsManifestResource(JBossDeploymentStructure11ParsingTestCase.class.getPackage(), "jboss-deployment-structure_1_1.xml", "jboss-deployment-structure.xml"); return ejbJar; } /** * Tests that the deployment containing the jboss-deployment-structure.xml was parsed and deployed successfully. */ @Test public void testSuccessfulDeployment() throws Exception { // just a lookup and invocation on the EJB should be fine, since it indicates that the deployment // was deployed successfully. final NoOpEJB noOpEJB = InitialContext.doLookup("java:module/" + NoOpEJB.class.getSimpleName() + "!" + NoOpEJB.class.getName()); noOpEJB.doNothing(); } }
2,853
41.597015
171
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/structure/jar/ToBeIgnored.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.structure.jar; /** * User: jpai */ public class ToBeIgnored { }
1,140
37.033333
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/structure/jar/ClassLoadingEJB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.structure.jar; import jakarta.annotation.Resource; import jakarta.ejb.Stateless; import javax.naming.InitialContext; import javax.naming.NamingException; /** * User: jpai */ @Stateless public class ClassLoadingEJB { @Resource(lookup = "java:module/ModuleName") private String moduleName; @Resource(lookup = "java:app/AppName") private String appName; public Class<?> loadClass(String className) throws ClassNotFoundException { if (className == null || className.trim().isEmpty()) { throw new RuntimeException("Classname parameter cannot be null or empty"); } return this.getClass().getClassLoader().loadClass(className); } public String query(String name) throws NamingException { return new InitialContext().lookup(name).toString(); } public String getResourceModuleName() { return moduleName; } public String getResourceAppName() { return appName; } }
2,045
32.540984
86
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/structure/jar/JarJBossDeploymentStructureTestCase.java
package org.jboss.as.test.integration.deployment.structure.jar; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.junit.Assert.assertEquals; import jakarta.ejb.EJB; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.logging.Logger; 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.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests parsing of jboss-deployment-structure.xml file in a deployment * <p/> * User: Jaikiran Pai */ @RunWith(Arquillian.class) public class JarJBossDeploymentStructureTestCase { private static final Logger logger = Logger.getLogger(JarJBossDeploymentStructureTestCase.class); @EJB(mappedName = "java:module/ClassLoadingEJB") private ClassLoadingEJB ejb; public static final String TO_BE_FOUND_CLASS_NAME = "org.jboss.as.test.integration.deployment.structure.jar.Available"; public static final String TO_BE_MISSSING_CLASS_NAME = "org.jboss.as.test.integration.deployment.structure.jar.ToBeIgnored"; @Deployment public static Archive<?> createDeployment() { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "deployment-structure.jar"); jar.addAsManifestResource(JarJBossDeploymentStructureTestCase.class.getPackage(), "jboss-deployment-structure.xml", "jboss-deployment-structure.xml"); final JavaArchive jarOne = ShrinkWrap.create(JavaArchive.class, "available.jar"); jarOne.addClass(Available.class); final JavaArchive ignoredJar = ShrinkWrap.create(JavaArchive.class, "ignored.jar"); ignoredJar.addClass(ToBeIgnored.class); final JavaArchive otherJar = ShrinkWrap.create(JavaArchive.class, "otherJar.jar"); otherJar.addClass(InSameModule.class); jar.addClasses(ClassLoadingEJB.class, JarJBossDeploymentStructureTestCase.class); jar.add(jarOne, "a", ZipExporter.class); jar.add(ignoredJar, "i", ZipExporter.class); jar.add(otherJar, "other", ZipExporter.class); jar.addAsManifestResource(createPermissionsXmlAsset( new RuntimePermission("getClassLoader"), new RuntimePermission("getProtectionDomain")), "permissions.xml"); return jar; } /** * Make sure the <filter> element in jboss-deployment-structure.xml is processed correctly and the * exclude/include is honoured * * @throws Exception */ @Test public void testDeploymentStructureFilters() throws Exception { this.ejb.loadClass(TO_BE_FOUND_CLASS_NAME); try { this.ejb.loadClass(TO_BE_MISSSING_CLASS_NAME); Assert.fail("Unexpectedly found class " + TO_BE_MISSSING_CLASS_NAME); } catch (ClassNotFoundException cnfe) { // expected } } @Test public void testUsePhysicalCodeSource() throws ClassNotFoundException { Class<?> clazz = this.ejb.loadClass(TO_BE_FOUND_CLASS_NAME); Assert.assertTrue(clazz.getProtectionDomain().getCodeSource().getLocation().getProtocol().equals("jar")); Assert.assertTrue(ClassLoadingEJB.class.getProtectionDomain().getCodeSource().getLocation().getProtocol().equals("jar")); } @Test public void testAddingOtherJarResourceRoot() throws ClassNotFoundException { Class<?> clazz = this.ejb.loadClass("org.jboss.as.test.integration.deployment.structure.jar.InSameModule"); } /** * EE.5.15, part of testsuite migration AS6->AS7 (jbas7556) */ @Test public void testModuleName() throws Exception { String result = ejb.query("java:module/ModuleName"); assertEquals("deployment-structure", result); result = ejb.getResourceModuleName(); assertEquals("deployment-structure", result); } @Test public void testAppName() throws Exception { String result = ejb.query("java:app/AppName"); assertEquals("deployment-structure", result); result = ejb.getResourceAppName(); assertEquals("deployment-structure", result); } }
4,335
37.371681
158
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/deployment/structure/jar/Available.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.deployment.structure.jar; /** * User: jpai */ public class Available { }
1,138
36.966667
70
java