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/web/security/runas/RunAsAdminServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.web.security.runas; import jakarta.annotation.security.DeclareRoles; import jakarta.annotation.security.RunAs; import jakarta.servlet.annotation.WebServlet; /** * RunAs annotated servlet which calls protected EJB method {@link Hello#sayHello()}. * * @author olukas */ @WebServlet(RunAsAdminServlet.SERVLET_PATH) @DeclareRoles({HelloBean.AUTHORIZED_ROLE, HelloBean.NOT_AUTHORIZED_ROLE}) @RunAs(HelloBean.AUTHORIZED_ROLE) public class RunAsAdminServlet extends CallProtectedEjbServlet { private static final long serialVersionUID = 1L; public static final String SERVLET_PATH = "/RunAsAdminServlet"; }
1,687
38.255814
85
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/security/runas/RunAsServlet.java
package org.jboss.as.test.integration.web.security.runas; import java.io.IOException; import jakarta.annotation.security.RunAs; import jakarta.ejb.EJB; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Stuart Douglas */ @WebServlet(name = "RunAsServlet", urlPatterns = "/runAs") @RunAs("peter") public class RunAsServlet extends HttpServlet { @EJB private CurrentUserEjb currentUserEjb; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write(currentUserEjb.getCurrentUser()); } }
791
28.333333
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/security/runas/WebSecurityRunAsTestCase.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.web.security.runas; import java.net.URL; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.categories.CommonCriteria; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; /** * Unit Test the RunAs function * * @author Anil Saldhana */ @RunWith(Arquillian.class) @RunAsClient @Category(CommonCriteria.class) public class WebSecurityRunAsTestCase { @Deployment public static WebArchive deployment() throws Exception { WebArchive war = ShrinkWrap.create(WebArchive.class, "web-secure-runas.war"); war.addClasses(RunAsInitServlet.class, CurrentUserEjb.class, RunAsServlet.class); war.addAsWebInfResource(WebSecurityRunAsTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml"); war.addAsWebInfResource(WebSecurityRunAsTestCase.class.getPackage(), "web.xml", "web.xml"); return war; } @ArquillianResource private URL url; @Test public void testServletRunAsInInitMethod() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet(url.toExternalForm() + "/runAsInit"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); Assert.assertEquals("anil", result); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } @Test public void testServletRunAsInMethod() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet(url.toExternalForm() + "/runAs"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); Assert.assertEquals("peter", result); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
4,011
37.951456
111
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/security/runas/RunAsInitServlet.java
package org.jboss.as.test.integration.web.security.runas; import java.io.IOException; import jakarta.annotation.security.RunAs; import jakarta.ejb.EJB; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Stuart Douglas */ @WebServlet(name = "RunAsInitServlet", urlPatterns = "/runAsInit", loadOnStartup = 100) @RunAs("anil") public class RunAsInitServlet extends HttpServlet { private volatile String initName; @EJB private CurrentUserEjb currentUserEjb; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write(initName); } @Override public void init() throws ServletException { initName = currentUserEjb.getCurrentUser(); } }
961
27.294118
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/security/runas/CurrentUserEjb.java
package org.jboss.as.test.integration.web.security.runas; import java.security.Principal; import jakarta.annotation.Resource; import jakarta.annotation.security.PermitAll; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateless; /** * @author Stuart Douglas */ @Stateless @PermitAll public class CurrentUserEjb { @Resource private SessionContext sessionContext; public String getCurrentUser() { Principal callerPrincipal = sessionContext.getCallerPrincipal(); if (callerPrincipal == null) { return null; } return callerPrincipal.getName(); } }
619
21.142857
72
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/security/authentication/BasicAuthMechanismServerSetupTask.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.web.security.authentication; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.security.common.CoreUtils; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; import org.wildfly.test.security.common.elytron.ElytronDomainSetup; import org.wildfly.test.security.common.elytron.ServletElytronDomainSetup; import java.io.File; import java.util.List; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.*; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode; /** * Server setup task for test BasicAuthenticationMechanismPicketboxRemovedTestCase. * Enables elytron and removes security subsystem. */ public class BasicAuthMechanismServerSetupTask extends SnapshotRestoreSetupTask { protected String getSecurityDomainName() { return "auth-test"; } protected String getUsersFile() { return new File(BasicAuthMechanismServerSetupTask.class.getResource("users.properties").getFile()).getAbsolutePath(); } protected String getGroupsFile() { return new File(BasicAuthMechanismServerSetupTask.class.getResource("roles.properties").getFile()).getAbsolutePath(); } @Override public void doSetup(ManagementClient managementClient, String containerId) throws Exception { // /subsystem=elytron/properties-realm=auth-test-ejb3-UsersRoles:add(users-properties={path=users.properties, plain-text=true},groups-properties={path=roles.properties}) // /subsystem=elytron/security-domain=auth-test:add(default-realm=auth-test-ejb3-UsersRoles, realms=[{realm=auth-test-ejb3-UsersRoles}]) ElytronDomainSetup elytronDomainSetup = new ElytronDomainSetup(getUsersFile(), getGroupsFile(), getSecurityDomainName()); elytronDomainSetup.setup(managementClient, containerId); // /subsystem=elytron/http-authentication-factory=auth-test:add(http-server-mechanism-factory=global,security-domain=auth-test,mechanism-configurations=[{mechanism-name=BASIC}]) // /subsystem=undertow/application-security-domain=auth-test:add(http-authentication-factory=auth-test) ServletElytronDomainSetup servletElytronDomainSetup = new ServletElytronDomainSetup(getSecurityDomainName()); servletElytronDomainSetup.setup(managementClient, containerId); // /subsystem=elytron/sasl-authentication-factory=auth-test:add(sasl-server-factory=configured,security-domain=auth-test,mechanism-configurations=[{mechanism-name=BASIC}]) ModelNode addSaslAuthentication = createOpNode("subsystem=elytron/sasl-authentication-factory=" + getSecurityDomainName(), ADD); addSaslAuthentication.get("sasl-server-factory").set("configured"); addSaslAuthentication.get("security-domain").set(getSecurityDomainName()); addSaslAuthentication.get("mechanism-configurations").get(0).get("mechanism-name").set("PLAIN"); // /subsystem=remoting/http-connector=http-remoting-connector:write-attribute(name=sasl-authentication-factory, value=auth-test) ModelNode updateRemotingConnector = createOpNode("subsystem=remoting/http-connector=http-remoting-connector", WRITE_ATTRIBUTE_OPERATION); updateRemotingConnector.get(ClientConstants.NAME).set("sasl-authentication-factory"); updateRemotingConnector.get(ClientConstants.VALUE).set(getSecurityDomainName()); // /subsystem=ejb3/application-security-domain=auth-test:add(security-domain=auth-test) ModelNode addEjbDomain = createOpNode("subsystem=ejb3/application-security-domain=" + getSecurityDomainName(), ADD); addEjbDomain.get("security-domain").set(getSecurityDomainName()); // /subsystem=ejb3:write-attribute(name=default-missing-method-permissions-deny-access, value=false) ModelNode updateDefaultMissingMethod = createOpNode("subsystem=ejb3", WRITE_ATTRIBUTE_OPERATION); updateDefaultMissingMethod.get(ClientConstants.NAME).set("default-missing-method-permissions-deny-access"); updateDefaultMissingMethod.get(ClientConstants.VALUE).set(false); // core-service=management/management-interface=http-interface:write-attribute(name=http-upgrade,value={enabled=true, sasl-authentication-factory=management-sasl-authentication}) ModelNode writeAttrOp4 = createOpNode("core-service=management/management-interface=http-interface", WRITE_ATTRIBUTE_OPERATION); writeAttrOp4.get(ClientConstants.NAME).set("http-upgrade"); writeAttrOp4.get(ClientConstants.VALUE).add("enabled", true); writeAttrOp4.get(ClientConstants.VALUE).add("sasl-authentication-factory", getSecurityDomainName()); // core-service=management/management-interface=http-interface:write-attribute(name=http-authentication-factory,value=management-http-authentication) ModelNode writeAttrOp5 = createOpNode("core-service=management/management-interface=http-interface", WRITE_ATTRIBUTE_OPERATION); writeAttrOp5.get(ClientConstants.NAME).set("http-authentication-factory"); writeAttrOp5.get(ClientConstants.VALUE).set(getSecurityDomainName()); ModelNode updateOp = Util.createCompositeOperation(List.of(addSaslAuthentication, updateRemotingConnector, addEjbDomain, updateDefaultMissingMethod, writeAttrOp4, writeAttrOp5)); updateOp.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false); updateOp.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true); CoreUtils.applyUpdate(updateOp, managementClient.getControllerClient()); ModelNode removeSecurityOp = new ModelNode(); removeSecurityOp.get(OP).set(REMOVE); removeSecurityOp.get(OP_ADDR).add(SUBSYSTEM, "security"); CoreUtils.applyUpdate(removeSecurityOp, managementClient.getControllerClient()); } }
6,881
62.722222
186
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/security/authentication/BasicAuthenticationMechanismPicketboxRemovedTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.web.security.authentication; 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.HttpClients; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.web.security.authentication.deployment.SecuredEJB; import org.jboss.as.test.integration.web.security.authentication.deployment.SecuredEJBServlet; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import java.net.URL; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Automated test for [ WFLY-10671 ] - tests tracker for picketbox subsystem removing. * * [ WFLY-10671 ] is a tracker for issues: * [ WFLY-10282 ] Test Enables elytron and removes security subsystem. After secured EJB is deployed and accessed using basic authorization test checks if correct response is returned after the EJB is called from the secured servlet. * [ WFLY-10292 ] After switching to elytron and removing picketbox subsystem DefaultJMSConnectionFactory is not found during server startup. * * @author Daniel Cihak */ @RunWith(Arquillian.class) @ServerSetup(BasicAuthMechanismServerSetupTask.class) @RunAsClient public class BasicAuthenticationMechanismPicketboxRemovedTestCase { private static final String USER = "user1"; private static final String PASSWORD = "password1"; private static final String EJB_SECURITY = "ejb-security"; @Deployment(name = EJB_SECURITY) public static WebArchive appDeployment1() { WebArchive war = ShrinkWrap.create(WebArchive.class, EJB_SECURITY + ".war"); war.addClasses(BasicAuthenticationMechanismPicketboxRemovedTestCase.class, SecuredEJB.class, SecuredEJBServlet.class); war.addAsWebInfResource(BasicAuthenticationMechanismPicketboxRemovedTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml"); war.addAsWebInfResource(BasicAuthenticationMechanismPicketboxRemovedTestCase.class.getPackage(), "web.xml", "web.xml"); return war; } /** * Test checks if correct response is returned after the EJB is called from the secured servlet. * * @param url * @throws Exception */ @Test public void test(@ArquillianResource URL url) throws Exception { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(USER, PASSWORD)); try (CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credentialsProvider) .build()) { HttpGet httpget = new HttpGet(url.toExternalForm() + "SecuredEJBServlet/"); HttpResponse response = httpclient.execute(httpget); assertNotNull("Response is 'null', we expected non-null response!", response); String text = Utils.getContent(response); assertEquals(200, response.getStatusLine().getStatusCode()); assertTrue("User principal different from what we expected!", text.contains("Principal: " + USER)); assertTrue("Remote user different from what we expected!", text.contains("Remote User: " + USER)); assertTrue("Authentication type different from what we expected!", text.contains("Authentication Type: BASIC")); } } }
5,157
48.596154
233
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/security/authentication/deployment/SecuredEJB.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.web.security.authentication.deployment; import jakarta.annotation.Resource; import jakarta.annotation.security.RolesAllowed; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateless; import org.jboss.ejb3.annotation.SecurityDomain; @Stateless @RolesAllowed({ "guest" }) @SecurityDomain("auth-test") public class SecuredEJB { @Resource private SessionContext ctx; public String getSecurityInfo() { return ctx.getCallerPrincipal().toString(); } }
1,318
32.820513
77
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/security/authentication/deployment/SecuredEJBServlet.java
/* * JBoss, Home of Professional Open Source * Copyright 2015, 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.web.security.authentication.deployment; import jakarta.ejb.EJB; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * A simple secured Servlet which calls a secured EJB. Upon successful authentication and authorization the EJB will return the * principal's name. Servlet security is implemented using annotations. * * @author Sherif Makary * */ @SuppressWarnings("serial") @WebServlet(name = "SecuredEJBServlet", urlPatterns = {"/SecuredEJBServlet/"}, loadOnStartup = 1) @ServletSecurity(@HttpConstraint(rolesAllowed = {"guest"})) public class SecuredEJBServlet extends HttpServlet { private static String PAGE_HEADER = "<html><head><title>ejb-security</title></head><body>"; private static String PAGE_FOOTER = "</body></html>"; @EJB private SecuredEJB securedEJB; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); String principal = securedEJB.getSecurityInfo(); String remoteUser = req.getRemoteUser(); String authType = req.getAuthType(); writer.println(PAGE_HEADER); writer.println("<h1>" + "Successfully called Secured EJB " + "</h1>"); writer.println("<p>" + "Principal: " + principal + "</p>"); writer.println("<p>" + "Remote User: " + remoteUser + "</p>"); writer.println("<p>" + "Authentication Type: " + authType + "</p>"); writer.println(PAGE_FOOTER); writer.close(); } }
2,693
39.818182
127
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/filter/AnnotatedFilterDeploymentTestCase.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.web.filter; import java.net.URL; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertEquals; /** * BZ-1235627 * * @author Tomas Hofman ([email protected]) */ @RunWith(Arquillian.class) @RunAsClient public class AnnotatedFilterDeploymentTestCase { @ArquillianResource private Deployer deployer; @Deployment(name = "v30") public static WebArchive deployV30() { WebArchive war = ShrinkWrap.create(WebArchive.class, "v30.war"); war.addClasses(AnnotatedFilter.class, EmptyServlet.class); war.addAsWebInfResource(AnnotatedFilterDeploymentTestCase.class.getPackage(), "web30.xml", "web.xml"); return war; } @Deployment(name = "v30MetadataComplete") public static WebArchive deployV30MetadataComplete() { WebArchive war = ShrinkWrap.create(WebArchive.class, "v30MetadataComplete.war"); war.addClasses(AnnotatedFilter.class, EmptyServlet.class); war.addAsWebInfResource(AnnotatedFilterDeploymentTestCase.class.getPackage(), "web30_metadata_complete.xml", "web.xml"); return war; } @Deployment(name = "v24") public static WebArchive deployV24() { WebArchive war = ShrinkWrap.create(WebArchive.class, "v24.war"); war.addClasses(AnnotatedFilter.class, EmptyServlet.class); war.addAsWebInfResource(AnnotatedFilterDeploymentTestCase.class.getPackage(), "web24.xml", "web.xml"); return war; } private String performCall(URL url, String urlPattern) throws Exception { String finalUrl = url.toURI().resolve(urlPattern).toString(); return HttpRequest.get(finalUrl, 1, SECONDS); } @Test @OperateOnDeployment("v24") public void testFilterPresent24(@ArquillianResource URL url) throws Exception { String result = performCall(url, "EmptyServlet"); assertEquals(AnnotatedFilter.OUTPUT, result); } @Test @OperateOnDeployment("v30") public void testFilterPresent30(@ArquillianResource URL url) throws Exception { String result = performCall(url, "EmptyServlet"); assertEquals(AnnotatedFilter.OUTPUT, result); } @Test @OperateOnDeployment("v30MetadataComplete") public void testFilterPresent30MetadataComplete(@ArquillianResource URL url) throws Exception { String result = performCall(url, "EmptyServlet"); assertEquals(EmptyServlet.OUTPUT, result); } }
4,059
38.038462
128
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/filter/EmptyServlet.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.web.filter; import java.io.IOException; import java.io.PrintWriter; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Tomas Hofman ([email protected]) */ public class EmptyServlet extends HttpServlet { public static final String OUTPUT = "servlet"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); writer.print(OUTPUT); writer.close(); } }
1,702
36.021739
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/filter/AnnotatedFilter.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.web.filter; import java.io.IOException; import java.nio.charset.StandardCharsets; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.annotation.WebFilter; /** * @author Tomas Hofman ([email protected]) */ @WebFilter(value = "/*", description = "Annotated filter") public class AnnotatedFilter implements Filter { public static final String OUTPUT = "filter"; @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletResponse.getOutputStream().write(OUTPUT.getBytes(StandardCharsets.UTF_8)); } @Override public void destroy() { } }
2,038
34.77193
152
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/injection/SimpleStatelessSessionBean.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.web.injection; import jakarta.ejb.LocalBean; import jakarta.ejb.Stateless; /** * A simple stateless session bean. * * @author <a href="mailto:[email protected]">Carlo de Wolf</a> */ @Stateless @LocalBean public class SimpleStatelessSessionBean { public String echo(String msg) { return "Echo " + msg; } }
1,393
34.74359
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/injection/SimpleServlet.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.web.injection; import java.io.IOException; import java.io.Writer; import jakarta.ejb.EJB; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author <a href="mailto:[email protected]">Carlo de Wolf</a> * @author Eduardo Martins */ @WebServlet(name = "SimpleServlet", urlPatterns = { "/simple" }) public class SimpleServlet extends HttpServlet { @EJB private SimpleStatelessSessionBean bean; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { testAS7_5347(resp); String msg = req.getParameter("input"); Writer writer = resp.getWriter(); writer.write(bean.echo(msg)); } private void testAS7_5347(HttpServletResponse resp) throws IOException { // java:module includes child EJBContext, which can't be looked up on a servlet, yet list() on this context must not // fail, more info at AS7-5347 try { new InitialContext().list("java:module"); } catch (NamingException e) { resp.getWriter().write("AS7-5347 solution check failed"); } } }
2,453
36.753846
124
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/injection/ServletInjectionTestCase.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.web.injection; import java.net.URL; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertEquals; /** * @author <a href="mailto:[email protected]">Carlo de Wolf</a> */ @RunWith(Arquillian.class) @RunAsClient public class ServletInjectionTestCase { @ArquillianResource private URL url; @Deployment public static WebArchive deployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, "war-example.war"); war.addClasses(HttpRequest.class, SimpleServlet.class, SimpleStatelessSessionBean.class); return war; } private String performCall(String urlPattern, String param) throws Exception { return HttpRequest.get(url.toExternalForm() + urlPattern + "?input=" + param, 10, SECONDS); } @Test public void testEcho() throws Exception { String result = performCall("simple", "Hello+world"); assertEquals("Echo Hello world", result); } }
2,464
35.791045
99
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/tx/TxControlUnitTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, 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.web.tx; import static org.junit.Assert.assertEquals; import java.net.HttpURLConnection; import java.net.URL; import jakarta.transaction.Status; import org.junit.Assert; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; 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.logging.Logger; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests of servlet transaction lifecycle handling, particularly AS7-5329. * * @author Brian Stansberry (c) 2012 Red Hat Inc. */ @RunWith(Arquillian.class) @RunAsClient public class TxControlUnitTestCase { private static Logger log = Logger.getLogger(TxControlUnitTestCase.class); private static final String STATUS_ACTIVE = String.valueOf(Status.STATUS_ACTIVE); @Deployment (name = "tx-control.war", testable = false) public static WebArchive controlDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, "tx-control.war"); war.addClass(TxControlServlet.class); return war; } @Deployment(name = "tx-status.war", testable = false) public static WebArchive statusDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, "tx-status.war"); war.addClass(TxStatusServlet.class); return war; } /** * Test a RequestDispatcher forward with tx commit. * * @throws Exception */ @Test @OperateOnDeployment("tx-control.war") public void testForwardCommit(@ArquillianResource(TxControlServlet.class) URL baseURL) throws Exception { testURL(baseURL, false, true); } /** * Test a RequestDispatcher forward that fails to commit the tx. * * @throws Exception */ @Test @OperateOnDeployment("tx-control.war") public void testForwardNoCommit(@ArquillianResource(TxControlServlet.class) URL baseURL) throws Exception { testURL(baseURL, false, false); } /** * Test a RequestDispatcher include with tx commit. * * @throws Exception */ @Test @OperateOnDeployment("tx-control.war") public void testIncludeCommit(@ArquillianResource(TxControlServlet.class) URL baseURL) throws Exception { testURL(baseURL, true, true); } /** * Test a RequestDispatcher include that fails to commit the tx. * * @throws Exception */ @Test @OperateOnDeployment("tx-control.war") public void testIncludeNoCommit(@ArquillianResource(TxControlServlet.class) URL baseURL) throws Exception { testURL(baseURL, true, false); } private void testURL(URL baseURL, boolean include, boolean commit) throws Exception { URL url = new URL(baseURL + TxControlServlet.URL_PATTERN + "?include=" + include + "&commit=" + commit); HttpGet httpget = new HttpGet(url.toURI()); DefaultHttpClient httpclient = new DefaultHttpClient(); log.trace("executing request" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Wrong response code: " + statusCode, HttpURLConnection.HTTP_OK, statusCode); if (include) { Header outerStatus = response.getFirstHeader(TxControlServlet.OUTER_STATUS_HEADER); Assert.assertNotNull(TxControlServlet.OUTER_STATUS_HEADER + " is null", outerStatus); Header innerStatus = response.getFirstHeader(TxControlServlet.INNER_STATUS_HEADER); Assert.assertNotNull(TxControlServlet.INNER_STATUS_HEADER + " is null", innerStatus); assertEquals("Wrong inner transaction status: " + innerStatus.getValue(), STATUS_ACTIVE, innerStatus.getValue()); assertEquals("Wrong inner transaction status: " + outerStatus.getValue(), STATUS_ACTIVE, outerStatus.getValue()); } // else TxControlServlet is using RequestDispatcher.forward and can't write to the response // Unfortunately, there's no simple mechanism to test that in the commit=false case the server cleaned up // the uncommitted tx. The cleanup (TransactionRollbackSetupAction) rolls back the tx and logs, but this // does not result in any behavior visible to the client. } }
5,759
37.918919
125
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/tx/TxControlServlet.java
/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss 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.web.tx; import java.io.IOException; import javax.naming.InitialContext; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.transaction.Status; import jakarta.transaction.UserTransaction; import org.jboss.logging.Logger; /** * A servlet that initiates a transaction, uses a RequestDispatcher to include or forward to {@link TxStatusServlet} * and then optionally commits the transaction. Used to test that the transaction propagates and that failure to * commit it is properly detected. * * @author Brian Stansberry (c) 2012 Red Hat Inc. */ @WebServlet(name = "TxControlServlet", urlPatterns = "/" + TxControlServlet.URL_PATTERN) public class TxControlServlet extends HttpServlet { private static final long serialVersionUID = -853278446594804509L; private static Logger log = Logger.getLogger(TxControlServlet.class); /** The name of the context to which requests are forwarded */ private static final String forwardContext = "/tx-status"; private static final String forwardPath = TxStatusServlet.URL_PATTERN; static final String URL_PATTERN = "TxControlServlet"; static final String INNER_STATUS_HEADER = "X-Inner-Transaction-Status"; static final String OUTER_STATUS_HEADER = "X-Outer-Transaction-Status"; /** * Lookup the UserTransaction and begin a transaction. * * @param request * @param response * @throws ServletException * @throws IOException */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (log.isTraceEnabled()) { log.trace("[" + forwardContext + "], PathInfo: " + request.getPathInfo() + ", QueryString: " + request.getQueryString() + ", ContextPath: " + request.getContextPath() + ", HeaderNames: " + request.getHeaderNames() + ", isCommitted: " + response.isCommitted()); } String includeParam = request.getParameter("include"); if (includeParam == null) throw new IllegalStateException("No include parameter seen"); boolean include = Boolean.valueOf(includeParam); String commitParam = request.getParameter("commit"); if (commitParam == null) throw new IllegalStateException("No commit parameter seen"); boolean commit = Boolean.valueOf(commitParam); UserTransaction transaction; try { transaction = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); transaction.begin(); } catch (Exception e) { throw new RuntimeException(e); } ServletContext sc = getServletContext().getContext(forwardContext); if (sc != null) { // if (log.isTraceEnabled()) log.trace("Found ServletContext for: " + forwardContext); RequestDispatcher rd = sc.getRequestDispatcher(forwardPath); if (rd != null) { // if (log.isTraceEnabled()) log.trace("Found RequestDispatcher for: " + forwardPath); if (include) { rd.include(request, response); } else { rd.forward(request, response); } // Get the tx status that TxStatusServlet saw Integer status = (Integer) request.getAttribute(TxStatusServlet.ATTRIBUTE); if (status == null) { throw new ServletException("No transaction status"); } if (include) { // We can still write to the response w/ an include, so pass the status to the client response.setHeader(INNER_STATUS_HEADER, status.toString()); } else if (status.intValue() != Status.STATUS_ACTIVE) { throw new ServletException("Status is " + status); } } else { throw new ServletException("No RequestDispatcher for: " + forwardContext + forwardPath); } } else { throw new ServletException("No ServletContext for: " + forwardContext); } try { // Get the tx status now int ourStatus = transaction.getStatus(); if (include) { // We can still write to the response w/ an include, so pass the status to the client response.setHeader(OUTER_STATUS_HEADER, String.valueOf(ourStatus)); } else if (ourStatus != Status.STATUS_ACTIVE) { throw new ServletException("Status is " + ourStatus); } if (commit) { transaction.commit(); } } catch (Exception e) { throw new ServletException(e); } } }
6,137
41.041096
121
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/tx/TxStatusServlet.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.web.tx; import java.io.IOException; import javax.naming.InitialContext; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.transaction.Status; import jakarta.transaction.UserTransaction; import org.jboss.logging.Logger; /** * A servlet that checks for the status of a propagated transaction, failing if it is not {@link Status#STATUS_ACTIVE}. * * @author Brian Stansberry (c) 2012 Red Hat Inc. */ @WebServlet(name = "TxStatusServlet", urlPatterns = TxStatusServlet.URL_PATTERN) public class TxStatusServlet extends HttpServlet { private static Logger log = Logger.getLogger(TxStatusServlet.class); static final String URL_PATTERN = "/TxStatusServlet"; static final String ATTRIBUTE = "status"; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.trace("In TxStatusServlet"); UserTransaction transaction; try { transaction = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); int status = transaction.getStatus(); log.trace("Transaction status is " + status); request.setAttribute(ATTRIBUTE, Integer.valueOf(status)); } catch (Exception e) { log.error("Failed retrieving transaction status", e); throw new RuntimeException(e); } } }
2,620
39.953125
121
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/response/DefaultResponseCodeTestCase.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.web.response; import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode; import static org.jboss.as.test.shared.ServerReload.executeReloadAndWaitForCompletion; import java.net.URL; import jakarta.servlet.http.HttpServletResponse; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; 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.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.shared.ServerSnapshot; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * Simple test to check if server will return default code if no app is registered under path. * * @author baranowb * */ @RunWith(Arquillian.class) @RunAsClient public class DefaultResponseCodeTestCase extends ContainerResourceMgmtTestBase { private static final String URL_PATTERN = "simple"; @ArquillianResource URL url; private HttpClient httpclient = null; @Deployment public static WebArchive deployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, DefaultResponseCodeTestCase.class.getSimpleName() + ".war"); war.addClasses(SimpleServlet.class); return war; } @Before public void setup() { this.httpclient = HttpClientBuilder.create().build(); } @Test public void testNormalOpMode() throws Exception { HttpGet httpget = new HttpGet(url.toString() + URL_PATTERN); HttpResponse response = this.httpclient.execute(httpget); Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); httpget = new HttpGet(url.toString() + URL_PATTERN+"/xxx"); response = this.httpclient.execute(httpget); Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); } @Test public void testDefaultResponseCode() throws Exception { try (AutoCloseable snapshot = ServerSnapshot.takeSnapshot(getManagementClient())){ ModelNode operation = createOpNode("subsystem=undertow/server=default-server/host=default-host", "write-attribute"); operation.get("name").set("default-response-code"); operation.get("value").set(506); executeOperation(operation); operation = createOpNode("subsystem=undertow/server=default-server/host=default-host", "remove"); operation.get("address").add("location","/"); executeOperation(operation); executeReloadAndWaitForCompletion(getManagementClient()); HttpGet httpget = new HttpGet(url.toString() + URL_PATTERN); HttpResponse response = this.httpclient.execute(httpget); Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); String badUrl = url.toString(); badUrl = badUrl.substring(0,badUrl.length()-1); httpget = new HttpGet(badUrl + "xxx/xxx"); response = this.httpclient.execute(httpget); Assert.assertEquals(506, response.getStatusLine().getStatusCode()); } } }
4,645
41.236364
128
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/response/RewriteLocationByDeplomentTestCase.java
package org.jboss.as.test.integration.web.response; import java.io.IOException; import java.net.URI; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.integration.management.util.ModelUtil; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.ServerSnapshot; 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.Test; import org.junit.runner.RunWith; /** * @author Tomas Hofman ([email protected]) */ @RunWith(Arquillian.class) @RunAsClient public class RewriteLocationByDeplomentTestCase extends ContainerResourceMgmtTestBase { @ArquillianResource Deployer deployer; @SuppressWarnings("WeakerAccess") @ContainerResource ManagementClient managementClient; @Deployment(name = "app", managed = false) public static WebArchive deployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, DefaultResponseCodeTestCase.class.getSimpleName() + ".war"); war.addClasses(SimpleRootServlet.class); war.addAsWebInfResource(new StringAsset("<jboss-web><context-root>/test</context-root></jboss-web>"), "jboss-web.xml"); return war; } @Test public void testDeploymentOverLocation() throws Exception { try(AutoCloseable snapshot = ServerSnapshot.takeSnapshot(managementClient)) { // check that "/test" path returns 404 HttpResponse response = getResponse("/test"); Assert.assertEquals(404, response.getStatusLine().getStatusCode()); // create location "/test" serving welcome-content ModelNode op = ModelUtil.createOpNode("subsystem=undertow/server=default-server/host=default-host", "add"); op.get("address").add("location", "/test"); op.get("handler").set("welcome-content"); executeOperation(op); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); response = getResponse("/test"); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); Assert.assertTrue("Expected to receive welcome page, but content length is 0", response.getEntity().getContentLength() > 0); // deploy an app at the same location and check it's accessible deployer.deploy("app"); response = getResponse("/test"); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); Assert.assertTrue("Expected to receive servlet response without any content", response.getEntity().getContentLength() == 0); // undeploy app and check that welcome-content is accessible again deployer.undeploy("app"); response = getResponse("/test"); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); Assert.assertTrue("Expected to receive welcome page, but content length is 0", response.getEntity().getContentLength() > 0); } } private HttpResponse getResponse(String path) throws IOException { URI webUri = managementClient.getWebUri(); HttpGet httpGet = new HttpGet(webUri.resolve(path)); return HttpClientBuilder.create().build().execute(httpGet); } }
4,011
42.608696
121
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/response/SimpleRootServlet.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.web.response; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author baranowb * */ @WebServlet(name = "SimpleServlet", urlPatterns = { "/" }) public class SimpleRootServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(HttpServletResponse.SC_OK); } }
1,663
35.977778
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/response/DefaultResponseCodeAtRootTestCase.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.web.response; import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode; import static org.jboss.as.test.shared.ServerReload.executeReloadAndWaitForCompletion; import java.net.URL; import jakarta.servlet.http.HttpServletResponse; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.controller.client.helpers.Operations.CompositeOperationBuilder; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.shared.ServerSnapshot; 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.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * Simple test to check if server will return default code if no app is registered under path. * * @author baranowb * */ @RunWith(Arquillian.class) @RunAsClient public class DefaultResponseCodeAtRootTestCase extends ContainerResourceMgmtTestBase { private static final String URL_PATTERN = "/"; private URL url; @ArquillianResource Deployer deployer; private HttpClient httpclient = null; @Deployment(testable = false, managed = false, name = "test") public static WebArchive deployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, DefaultResponseCodeAtRootTestCase.class.getSimpleName() + ".war"); war.addClasses(SimpleServlet.class); war.addAsWebInfResource(new StringAsset( "<jboss-web>"+ "<context-root>/</context-root>"+ "</jboss-web>"),"jboss-web.xml"); return war; } @Before public void setup() throws Exception { this.httpclient = HttpClientBuilder.create().build(); this.url = super.getManagementClient().getWebUri().toURL(); } @Test public void testNormalOpMode() throws Exception { deployer.deploy("test"); try { HttpGet httpget = new HttpGet(url.toString()); HttpResponse response = this.httpclient.execute(httpget); //403 apparently Assert.assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatusLine().getStatusCode()); httpget = new HttpGet(url.toString() + URL_PATTERN + "xxx"); response = this.httpclient.execute(httpget); Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); } finally { deployer.undeploy("test"); } } @Test public void testDefaultResponseCode() throws Exception { try (AutoCloseable snapshot = ServerSnapshot.takeSnapshot(getManagementClient())){ CompositeOperationBuilder cob = CompositeOperationBuilder.create(); ModelNode operation = createOpNode("subsystem=undertow/server=default-server/host=default-host", "write-attribute"); operation.get("name").set("default-response-code"); operation.get("value").set(506); cob.addStep(operation); // if location service is removed, if no deployment == no virtual host. operation = createOpNode("subsystem=undertow/server=default-server/host=default-host", "remove"); operation.get("address").add("location","/"); cob.addStep(operation); executeOperation(cob.build().getOperation()); executeReloadAndWaitForCompletion(getManagementClient()); deployer.deploy("test"); HttpGet httpget = null; HttpResponse response = null; httpget = new HttpGet(url.toString() + URL_PATTERN+"xxx/xxxxx"); response = this.httpclient.execute(httpget); Assert.assertEquals(404, response.getStatusLine().getStatusCode()); deployer.undeploy("test"); httpget = new HttpGet(url.toString() + URL_PATTERN); response = this.httpclient.execute(httpget); Assert.assertEquals(""+httpget,506, response.getStatusLine().getStatusCode()); } } }
5,614
41.862595
128
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/response/DefaultServletTestCase.java
package org.jboss.as.test.integration.web.response; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.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.logging.Logger; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.servlet.http.HttpServletResponse; import java.net.URL; /** * Tests the "default servlet" of the web container * * @author Jaikiran Pai */ @RunWith(Arquillian.class) @RunAsClient public class DefaultServletTestCase { private static final String WEB_APP_CONTEXT = "default-servlet-test"; private static final String APP_XHTML_FILE_NAME = "app.xhtml"; private static final String INFDIRS_DEPLOYMENT = "infdirectories"; private static final Logger logger = Logger.getLogger(DefaultServletTestCase.class); @ArquillianResource URL url; private HttpClient httpclient; @Deployment(name = WEB_APP_CONTEXT) public static WebArchive deployment() { final WebArchive war = ShrinkWrap.create(WebArchive.class, WEB_APP_CONTEXT + ".war"); war.addAsWebResource(DefaultServletTestCase.class.getPackage(), APP_XHTML_FILE_NAME, APP_XHTML_FILE_NAME); return war; } @Deployment(name = INFDIRS_DEPLOYMENT) public static Archive<?> createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, INFDIRS_DEPLOYMENT + ".war"); war.add(new StringAsset("Welcome in WEB-INFOOBAR"), "WEB-INFOOBAR/test.html"); war.add(new StringAsset("Welcome in META-INFOOBAR"), "META-INFOOBAR/test.html"); return war; } @Before public void setup() { this.httpclient = HttpClientBuilder.create().build(); } /** * Tests that the default servlet doesn't show the source (code) of a resource when an incorrect URL is used to access that resource. * * @throws Exception * @see https://developer.jboss.org/thread/266805 for more details */ @OperateOnDeployment(WEB_APP_CONTEXT) @Test public void testForbidSourceFileAccess() throws Exception { // first try accessing the valid URL and expect it to serve the right content final String correctURL = url.toString() + APP_XHTML_FILE_NAME; final HttpGet httpGetCorrectURL = new HttpGet(correctURL); final HttpResponse response = this.httpclient.execute(httpGetCorrectURL); Assert.assertEquals("Unexpected response code for URL " + correctURL, HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); final String content = EntityUtils.toString(response.getEntity()); Assert.assertTrue("Unexpected content served at " + correctURL, content.contains("Hello World")); // now try accessing the same URL with a "." at the end of the resource name. // This should throw a 404 error and NOT show up the "source" content of the resource final String nonExistentURL = url.toString() + APP_XHTML_FILE_NAME + "."; final HttpGet httpGetNonExistentURL = new HttpGet(nonExistentURL); final HttpResponse responseForNonExistentURL = this.httpclient.execute(httpGetNonExistentURL); Assert.assertEquals("Unexpected response code for URL " + nonExistentURL, HttpServletResponse.SC_NOT_FOUND, responseForNonExistentURL.getStatusLine().getStatusCode()); } /** * Tests if the default servlet serves content from any directories starting with WEB-INF or META-INF * * [WFLY-15045] * * @param webAppURL * @throws Exception */ @OperateOnDeployment(INFDIRS_DEPLOYMENT) @Test public void testInfDirectories(@ArquillianResource URL webAppURL) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(new HttpGet(webAppURL.toURI() + "WEB-INFOOBAR/test.html")); Assert.assertEquals(200, httpResponse.getStatusLine().getStatusCode()); EntityUtils.consumeQuietly(httpResponse.getEntity()); httpResponse = httpClient.execute(new HttpGet(webAppURL.toURI() + "META-INFOOBAR/test.html")); Assert.assertEquals(200, httpResponse.getStatusLine().getStatusCode()); } }
4,864
43.227273
175
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/response/SimpleServlet.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.web.response; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author baranowb * */ @WebServlet(name = "SimpleServlet", urlPatterns = { "/simple" }) public class SimpleServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(HttpServletResponse.SC_OK); } }
1,665
36.022222
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/sse/SseHandler.java
package org.jboss.as.test.integration.web.sse; import io.undertow.server.handlers.sse.ServerSentEventConnection; import io.undertow.server.handlers.sse.ServerSentEventConnectionCallback; import io.undertow.servlet.sse.ServerSentEvent; import java.io.IOException; /** * @author Stuart Douglas */ @ServerSentEvent("/foo/{bar}") public class SseHandler implements ServerSentEventConnectionCallback { @Override public void connected(ServerSentEventConnection connection, String lastEventId) { connection.send("Hello " + connection.getParameter("bar")); connection.send("msg2"); connection.send("msg3", new ServerSentEventConnection.EventCallback() { @Override public void done(ServerSentEventConnection connection, String data, String event, String id) { try { connection.close(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void failed(ServerSentEventConnection connection, String data, String event, String id, IOException e) { try { connection.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } }); } }
1,355
33.769231
123
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/sse/ServerSentEventsTestCase.java
/* * JBoss, Home of Professional Open Source * Copyright 2015, 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.web.sse; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import java.net.URL; import java.util.concurrent.TimeUnit; @RunWith(Arquillian.class) @RunAsClient public class ServerSentEventsTestCase { @Deployment(testable = false) public static Archive<?> deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, "sse.war"); // war.addPackage(HttpRequest.class.getPackage()); // war.addPackage(JaxrsAsyncTestCase.class.getPackage()); war.addClasses(SseHandler.class, SimpleServlet.class); return war; } @ArquillianResource private URL url; @Test public void testServletStillWorks() throws Exception { final String response = HttpRequest.get(url.toExternalForm() + "simple", 20, TimeUnit.SECONDS); Assert.assertEquals(SimpleServlet.SIMPLE_SERVLET, response); } @Test public void testSSEConnection() throws Exception { final String response = HttpRequest.get(url.toExternalForm() + "foo/Stuart", 20, TimeUnit.SECONDS); Assert.assertEquals("data:Hello Stuart\n" + "\n" + "data:msg2\n" + "\n" + "data:msg3\n" + "\n", response); } }
2,733
36.972222
107
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/sse/SimpleServlet.java
package org.jboss.as.test.integration.web.sse; 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 = "/simple") public class SimpleServlet extends HttpServlet { public static final String SIMPLE_SERVLET = "simple servlet"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write(SIMPLE_SERVLET); } }
674
28.347826
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/access/log/ConsoleAccessLogTestCase.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.web.access.log; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.StringReader; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.TimeUnit; import jakarta.json.Json; import jakarta.json.JsonObject; import jakarta.json.JsonReader; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.client.helpers.Operations.CompositeOperationBuilder; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests various console-access-log by overriding the {@link System#out stdout} and capturing each line. * <p> * Please note there was previously a test for a false predicate which has been removed. The reason for this is when * testing that something is not logged we could get false positives as there could be a race condition between when * the log is read vs when it is written. * </p> * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(ConsoleAccessLogTestCase.ConsoleAccessLogSetupTask.class) @SuppressWarnings("MagicNumber") public class ConsoleAccessLogTestCase { private static final ModelNode CONSOLE_ACCESS_LOG_ADDRESS = Operations.createAddress("subsystem", "undertow", "server", "default-server", "host", "default-host", "setting", "console-access-log"); private static final String[] ATTRIBUTE_NAMES = { "authentication-type", "bytes-sent", "date-time", "host-and-port", "local-ip", "local-port", "local-server-name", "query-string", "relative-path", "remote-host", "remote-ip", "remote-user", "request-line", "request-method", "request-path", "request-protocol", "request-scheme", "request-url", "resolved-path", "response-code", "response-reason-phrase", "response-time", "secure-exchange", "ssl-cipher", "ssl-client-cert", "ssl-session-id", "stored-response", "thread-name", "transport-protocol", }; private static final int DFT_TIMEOUT = 60; @ArquillianResource private ManagementClient client; @ArquillianResource private URL url; private Stdout stdout; private PrintStream currentStdout; @Deployment public static WebArchive deployment() { return ShrinkWrap.create(WebArchive.class, "simple-war.war") .addClass(SimpleServlet.class); } @Before @SuppressWarnings("UseOfSystemOutOrSystemErr") public void setup() { // Capture the current stdout to be replaced then replace stdout currentStdout = System.out; stdout = new Stdout(currentStdout); System.setOut(new PrintStream(stdout)); } @After public void tearDown() throws IOException { // Replaced with the captured stdout System.setOut(currentStdout); executeOperation(client.getControllerClient(), Operations.createRemoveOperation(CONSOLE_ACCESS_LOG_ADDRESS), false); } @Test public void testDefaults() throws Exception { executeOperation(client.getControllerClient(), Operations.createAddOperation(CONSOLE_ACCESS_LOG_ADDRESS)); sendRequest(); final Collection<JsonObject> lines = findLines(); Assert.assertFalse("Did not find eventSource in " + stdout.toString(), lines.isEmpty()); for (JsonObject jsonObject : lines) { Assert.assertEquals("web-access", jsonObject.getString("eventSource")); Assert.assertEquals("default-host", jsonObject.getString("hostName")); Assert.assertEquals(HttpStatus.SC_OK, jsonObject.getInt("responseCode")); } } @Test public void testAllAttributes() throws Exception { final ModelNode op = Operations.createAddOperation(CONSOLE_ACCESS_LOG_ADDRESS); final ModelNode attributes = op.get("attributes"); for (String name : ATTRIBUTE_NAMES) { attributes.get(name).setEmptyObject(); } // Attributes with required parameters attributes.get("path-parameter").setEmptyObject().get("names").add("testPathParameter"); attributes.get("predicate").setEmptyObject().get("names").add("testPredicate"); attributes.get("query-parameter").setEmptyObject().get("names").add("testQueryParameter"); attributes.get("request-header").setEmptyObject().get("names").add("User-Agent"); attributes.get("response-header").setEmptyObject().get("names").add("Content-Type"); executeOperation(client.getControllerClient(), op); sendRequest(); final Collection<JsonObject> lines = findLines(); Assert.assertFalse("Did not find eventSource in " + stdout.toString(), lines.isEmpty()); for (JsonObject jsonObject : lines) { // First assert all keys are there for (String name : ATTRIBUTE_NAMES) { Assert.assertNotNull("Missing key " + name, jsonObject.get(translateToKey(name))); } Assert.assertNotNull("Missing key testPathParameter", jsonObject.get("testPathParameter")); Assert.assertNotNull("Missing key testPredicate", jsonObject.get("testPredicate")); Assert.assertNotNull("Missing key testQueryParameter", jsonObject.get("testQueryParameter")); Assert.assertNotNull("Missing key User-Agent", jsonObject.get("User-Agent")); Assert.assertNotNull("Missing key Content-Type", jsonObject.get("Content-Type")); // Assert known values Assert.assertEquals("web-access", jsonObject.getString("eventSource")); Assert.assertEquals("default-host", jsonObject.getString("hostName")); Assert.assertEquals("GET", jsonObject.getString("requestMethod")); Assert.assertEquals(url.getProtocol(), jsonObject.getString("requestScheme")); Assert.assertEquals("/simple-war/simple", jsonObject.getString("requestUrl")); Assert.assertEquals("/simple-war", jsonObject.getString("resolvedPath")); Assert.assertEquals(HttpStatus.SC_OK, jsonObject.getInt("responseCode")); Assert.assertEquals(url.getPort(), jsonObject.getInt("localPort")); Assert.assertEquals("/simple", jsonObject.getString("relativePath")); Assert.assertEquals("OK", jsonObject.getString("responseReasonPhrase")); Assert.assertTrue(jsonObject.getString("Content-Type").startsWith("application/json")); } } @Test public void testKeyOverrides() throws Exception { final ModelNode op = Operations.createAddOperation(CONSOLE_ACCESS_LOG_ADDRESS); final ModelNode attributes = op.get("attributes"); final Collection<String> keys = new ArrayList<>(); for (String name : ATTRIBUTE_NAMES) { final String key = reformatKeyOverride(name); keys.add(key); attributes.get(name).setEmptyObject().get("key").set(key); } executeOperation(client.getControllerClient(), op); sendRequest(); final Collection<JsonObject> lines = findLines(); Assert.assertFalse("Did not find eventSource in " + stdout.toString(), lines.isEmpty()); for (JsonObject jsonObject : lines) { // First assert all keys are there for (String key : keys) { Assert.assertNotNull("Missing key " + key, jsonObject.get(translateToKey(key))); } } } @Test public void testOverrides() throws Exception { final String dateFormat = "yyyy-MM-dd'T'HH:mm:ssSSS"; final ModelNode op = Operations.createAddOperation(CONSOLE_ACCESS_LOG_ADDRESS); op.get("include-host-name").set(false); op.get("metadata").add("@version", "1"); final ModelNode attributes = op.get("attributes"); final ModelNode dateTime = attributes.get("date-time").setEmptyObject(); dateTime.get("date-format").set(dateFormat); dateTime.get("key").set("@timestamp"); dateTime.get("time-zone").set("GMT"); attributes.get("local-port").setEmptyObject().get("key").set("port"); attributes.get("response-code").setEmptyObject().get("key").set("http_response_code"); final ModelNode responseHeader = attributes.get("response-header").setEmptyObject(); responseHeader.get("key-prefix").set("response_header_"); final ModelNode names = responseHeader.get("names").setEmptyList(); names.add("Content-Type"); names.add("Content-Encoding"); attributes.get("request-method").setEmptyObject().get("key").set("request_method"); attributes.get("request-scheme").setEmptyObject().get("key").set("request_scheme"); attributes.get("request-url").setEmptyObject().get("key").set("request_url"); final ModelNode queryString = attributes.get("query-string").setEmptyObject(); queryString.get("key").set("query_string"); queryString.get("include-question-mark").set(true); executeOperation(client.getControllerClient(), op); sendRequest(new BasicNameValuePair("testParam", "testValue")); final Collection<JsonObject> lines = findLines(); Assert.assertFalse("Did not find eventSource in " + stdout.toString(), lines.isEmpty()); for (JsonObject jsonObject : lines) { Assert.assertEquals("web-access", jsonObject.getString("eventSource")); Assert.assertNull("include-host-name attribute was set to false and should not be included in the output.", jsonObject.get("hostName")); Assert.assertEquals("Expected @version to be 1", "1", jsonObject.getString("@version")); final String timestamp = jsonObject.getString("@timestamp"); try { DateTimeFormatter.ofPattern(dateFormat).parse(timestamp); } catch (DateTimeParseException e) { Assert.fail(String.format("Failed to parse date %s with pattern %s: %s", timestamp, dateFormat, e.getMessage())); } Assert.assertEquals("?testParam=testValue", jsonObject.getString("query_string")); Assert.assertEquals("GET", jsonObject.getString("request_method")); Assert.assertEquals(url.getProtocol(), jsonObject.getString("request_scheme")); Assert.assertEquals("/simple-war/simple", jsonObject.getString("request_url")); Assert.assertEquals(HttpStatus.SC_OK, jsonObject.getInt("http_response_code")); Assert.assertEquals(url.getPort(), jsonObject.getInt("port")); Assert.assertTrue(jsonObject.getString("response_header_Content-Type").startsWith("application/json")); Assert.assertNotNull(jsonObject.get("response_header_Content-Encoding")); } } private void sendRequest(final NameValuePair... params) throws IOException, URISyntaxException { final URI uri = new URI(url.toString() + "simple"); final URIBuilder builder = new URIBuilder(uri); if (params != null && params.length > 0) { builder.setParameters(params); } final HttpGet request = new HttpGet(builder.build()); try ( CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = httpClient.execute(request) ) { Assert.assertEquals("Failed to access " + uri, HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } } private Collection<JsonObject> findLines() throws InterruptedException { // Note this could be a potential spot for a race in the test validation. The console-access-log is // asynchronous so we need to wait to ensure it's fully written to the console. final Collection<JsonObject> result = new ArrayList<>(); int counter = 0; int timeout = TimeoutUtil.adjust(DFT_TIMEOUT) * 1000; final long sleep = 100L; while (timeout > 0) { long before = System.currentTimeMillis(); final String[] lines = stdout.getLines(counter); counter = lines.length; for (String line : lines) { if (!line.isEmpty()) { try (JsonReader reader = Json.createReader(new StringReader(line))) { final JsonObject jsonObject = reader.readObject(); if (jsonObject.get("eventSource") != null) { result.add(jsonObject); } } } } if (!result.isEmpty()) { break; } timeout -= (System.currentTimeMillis() - before); TimeUnit.MILLISECONDS.sleep(sleep); timeout -= sleep; } return result; } private static ModelNode executeOperation(final ModelControllerClient client, final ModelNode op) throws IOException { return executeOperation(client, op, true); } private static ModelNode executeOperation(final ModelControllerClient client, final ModelNode op, final boolean failOnError) throws IOException { return executeOperation(client, Operation.Factory.create(op), failOnError); } private static ModelNode executeOperation(final ModelControllerClient client, final Operation op, final boolean failOnError) throws IOException { final ModelNode result = client.execute(op); if (failOnError && !Operations.isSuccessfulOutcome(result)) { Assert.fail(String.format("Failed to execute operation: %s%n%s", op, Operations.getFailureDescription(result).asString())); } return Operations.readResult(result); } private static String translateToKey(final String attributeName) { final StringBuilder result = new StringBuilder(attributeName.length()); boolean toUpper = false; for (char c : attributeName.toCharArray()) { if (c == '-') { toUpper = true; } else { if (toUpper) { result.append(Character.toUpperCase(c)); toUpper = false; } else { result.append(c); } } } return result.toString(); } private static String reformatKeyOverride(final String key) { return key.replace('-', '_'); } public static class ConsoleAccessLogSetupTask implements ServerSetupTask { private final ModelNode formatterAddress = Operations.createAddress("subsystem", "logging", "json-formatter", "json"); private final ModelNode consoleHandlerAddress = Operations.createAddress("subsystem", "logging", "console-handler", "CONSOLE"); private ModelNode currentFormatter; @Override public void setup(final ManagementClient managementClient, final String s) throws Exception { final ModelControllerClient client = managementClient.getControllerClient(); // Get the current console handler formatter name currentFormatter = executeOperation(client, Operations.createReadAttributeOperation(consoleHandlerAddress, "named-formatter")); final CompositeOperationBuilder builder = CompositeOperationBuilder.create() .addStep(Operations.createAddOperation(formatterAddress)) // Change the current formatter just in case a message is logged so the line will still be valid JSON .addStep(Operations.createWriteAttributeOperation(consoleHandlerAddress, "named-formatter", "json")); executeOperation(client, builder.build(), true); } @Override public void tearDown(final ManagementClient managementClient, final String s) throws Exception { final ModelControllerClient client = managementClient.getControllerClient(); final CompositeOperationBuilder builder = CompositeOperationBuilder.create(); // Reset the named-formatter on the console if (currentFormatter != null) { builder.addStep(Operations.createWriteAttributeOperation(consoleHandlerAddress, "named-formatter", currentFormatter)); } else { builder.addStep(Operations.createUndefineAttributeOperation(consoleHandlerAddress, "named-formatter")); } builder.addStep(Operations.createRemoveOperation(formatterAddress)); executeOperation(client, builder.build(), true); } } private static class Stdout extends OutputStream { private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private static final String[] EMPTY = new String[0]; private final OutputStream dftStdout; private byte[] buffer; private int bufferLen; private String[] lines; private int lineLen; private Stdout(final OutputStream dftStdout) { this.dftStdout = dftStdout; buffer = new byte[1024]; lines = new String[20]; } @Override public synchronized void write(final int b) throws IOException { append(b); dftStdout.write(b); } @Override public synchronized void write(final byte[] b, final int off, final int len) throws IOException { // Check the array of a new line for (int i = off; i < len; i++) { append(b[i]); } dftStdout.write(b, off, len); } @Override public void write(final byte[] b) throws IOException { write(b, 0, b.length); dftStdout.write(b); } @Override public void flush() throws IOException { dftStdout.flush(); } @Override public String toString() { final StringBuilder result = new StringBuilder(); final Iterator<String> iter = Arrays.asList(getLines()).iterator(); while (iter.hasNext()) { result.append(iter.next()); if (iter.hasNext()) { result.append(System.lineSeparator()); } } return result.toString(); } @SuppressWarnings("StatementWithEmptyBody") private void append(final int b) { if (b == '\n') { ensureLineCapacity(lineLen + 1); lines[lineLen++] = new String(buffer, 0, bufferLen, StandardCharsets.UTF_8); bufferLen = 0; } else if (b == '\r') { // For out purposes just ignore this character } else { ensureBufferCapacity(bufferLen + 1); buffer[bufferLen++] = (byte) b; } } private void ensureBufferCapacity(final int minCapacity) { if (minCapacity - buffer.length > 0) growBuffer(minCapacity); } private void growBuffer(final int minCapacity) { final int oldCapacity = buffer.length; int newCapacity = oldCapacity << 1; if (newCapacity - minCapacity < 0) { newCapacity = minCapacity; } if (newCapacity - MAX_ARRAY_SIZE > 0) { newCapacity = (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } buffer = Arrays.copyOf(buffer, newCapacity); } private void ensureLineCapacity(final int minCapacity) { if (minCapacity - lines.length > 0) growLine(minCapacity); } private void growLine(final int minCapacity) { final int oldCapacity = lines.length; int newCapacity = oldCapacity << 1; if (newCapacity - minCapacity < 0) { newCapacity = minCapacity; } if (newCapacity - MAX_ARRAY_SIZE > 0) { newCapacity = (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } lines = Arrays.copyOf(lines, newCapacity); } synchronized String[] getLines() { if (lineLen == 0) { return EMPTY; } return Arrays.copyOf(lines, lineLen); } synchronized String[] getLines(final int offset) { if (lineLen == 0) { return EMPTY; } return Arrays.copyOfRange(lines, offset, lineLen); } } }
22,847
42.686424
149
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/access/log/SimpleServlet.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.web.access.log; import java.io.IOException; import java.io.PrintWriter; import jakarta.json.Json; import jakarta.json.stream.JsonGenerator; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.ws.rs.core.MediaType; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @WebServlet("simple") public class SimpleServlet extends HttpServlet { @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final PrintWriter writer = response.getWriter(); response.setContentType(MediaType.APPLICATION_JSON); try (JsonGenerator generator = Json.createGenerator(writer)) { generator.writeStartObject(); generator.writeStartObject("parameters"); request.getParameterMap().forEach((key, values) -> { if (values == null) { generator.writeNull(key); } else if (values.length > 1) { generator.writeStartArray(key); for (String value : values) { generator.write(value); } generator.writeEnd(); } else { final String value = values[0]; if (value == null) { generator.writeNull(key); } else { generator.write(key, value); } } }); generator.writeEnd(); // end parameters generator.writeEnd(); // end main } } }
2,457
34.114286
133
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/servlet/registration/ReplacementServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 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.web.servlet.registration; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; public class ReplacementServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("ok"); } }
1,515
41.111111
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/servlet/registration/DefaultServletReplacmentTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 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.web.servlet.registration; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertEquals; import java.net.URL; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @RunAsClient public class DefaultServletReplacmentTestCase { @ArquillianResource private URL url; @Deployment public static WebArchive single() { WebArchive war = ShrinkWrap.create(WebArchive.class, "single.war"); war.addClasses(HttpRequest.class, ReplacementServlet.class, DefaultReplacingServletContextListener.class); return war; } private String performCall(URL url, String urlPattern) throws Exception { return HttpRequest.get(url.toExternalForm() + urlPattern, 1000, SECONDS); } @Test public void testLifeCycle() throws Exception { String result = performCall(url, "/"); assertEquals("ok", result); } }
2,371
36.0625
114
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/servlet/registration/DefaultReplacingServletContextListener.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 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.web.servlet.registration; import jakarta.servlet.ServletContextEvent; import jakarta.servlet.ServletContextListener; import jakarta.servlet.ServletRegistration; import jakarta.servlet.annotation.WebListener; @WebListener public class DefaultReplacingServletContextListener implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { ServletRegistration registration = sce.getServletContext().addServlet("ReplacementServlet", new ReplacementServlet()); registration.addMapping("/"); } public void contextDestroyed(ServletContextEvent sce) { } }
1,678
42.051282
126
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/servlet/preservepath/PreservePathTestCase.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.web.servlet.preservepath; 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.jboss.as.test.integration.management.util.ModelUtil.createOpNode; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.io.BufferedReader; import java.io.File; import java.io.FilePermission; import java.io.FileReader; import java.net.URL; import java.net.URLEncoder; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; 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.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.security.common.CoreUtils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.UrlAsset; 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; @RunAsClient @RunWith(Arquillian.class) public class PreservePathTestCase { @ArquillianResource private URL url; @ArquillianResource private ManagementClient managementClient; static final String tempDir = TestSuiteEnvironment.getTmpDir(); static final int TIMEOUT = TimeoutUtil.adjust(5000); @Before public void setUp() throws Exception { ModelNode setPreservePathOp = createOpNode("subsystem=undertow/servlet-container=default", UNDEFINE_ATTRIBUTE_OPERATION); setPreservePathOp.get("name").set("preserve-path-on-forward"); CoreUtils.applyUpdate(setPreservePathOp, managementClient.getControllerClient()); ServerReload.executeReloadAndWaitForCompletion(managementClient); } @After public void tearDown() throws Exception { File file = new File(tempDir + "/output.txt"); if (file.exists()) { file.delete(); } ModelNode setPreservePathOp = createOpNode("subsystem=undertow/servlet-container=default", UNDEFINE_ATTRIBUTE_OPERATION); setPreservePathOp.get("name").set("preserve-path-on-forward"); CoreUtils.applyUpdate(setPreservePathOp, managementClient.getControllerClient()); ServerReload.executeReloadAndWaitForCompletion(managementClient); } @Deployment public static WebArchive deployment() { WebArchive war = ShrinkWrap.create(WebArchive.class); war.addClass(ForwardingServlet.class); war.addClass(PreservePathFilter.class); war.add(new UrlAsset(PreservePathTestCase.class.getResource("preserve-path.jsp")), "preserve-path.jsp"); war.addAsWebInfResource(PreservePathTestCase.class.getPackage(), "web.xml", "web.xml"); war.addAsManifestResource(createPermissionsXmlAsset( new FilePermission(tempDir + "/*", "write") ), "permissions.xml"); return war; } @Test public void testPreservePath() throws Exception { runTestPreservePath(true); } @Test public void testDontPreservePath() throws Exception { runTestPreservePath(false); } @Test public void testDefaultPreservePath() throws Exception { runTestPreservePath(null); } private void runTestPreservePath(Boolean preservePathOnForward) throws Exception { setPreservePathOnForward(preservePathOnForward); HttpClient httpclient = HttpClientBuilder.create().build(); HttpGet httpget = new HttpGet(url.toString() + "/test?path="+ URLEncoder.encode(tempDir)); HttpResponse response = httpclient.execute(httpget); long end = System.currentTimeMillis() + TIMEOUT; File file = new File(tempDir + "/output.txt"); while ((!file.exists() || file.length() == 0) && System.currentTimeMillis() < end) { Thread.sleep(100); } Assert.assertTrue(file + " was not created within the timeout", file.exists()); Assert.assertTrue(file + " is empty", file.length() > 0); final String expectedServletPath; final String expectedRequestURL; if (preservePathOnForward != null && preservePathOnForward) { expectedServletPath = "/test"; expectedRequestURL = url + "test"; } else{ expectedServletPath = "/preserve-path.jsp"; expectedRequestURL = url + "preserve-path.jsp"; } final String expectedRequestURI = new URL(expectedRequestURL).getPath(); try (BufferedReader r = new BufferedReader(new FileReader(file))) { String servletPath = r.readLine(); Assert.assertEquals("servletPath: " + expectedServletPath, servletPath); String requestUrl = r.readLine(); Assert.assertEquals("requestUrl: " + expectedRequestURL, requestUrl); String requestUri = r.readLine(); Assert.assertEquals("requestUri: " + expectedRequestURI, requestUri); } } private void setPreservePathOnForward(Boolean preservePathOnForward) throws Exception { String opName = preservePathOnForward == null ? UNDEFINE_ATTRIBUTE_OPERATION : WRITE_ATTRIBUTE_OPERATION; ModelNode setPreservePathOp = createOpNode("subsystem=undertow/servlet-container=default", opName); setPreservePathOp.get("name").set("preserve-path-on-forward"); if (preservePathOnForward != null) { setPreservePathOp.get("value").set(preservePathOnForward); } CoreUtils.applyUpdate(setPreservePathOp, managementClient.getControllerClient()); ServerReload.executeReloadAndWaitForCompletion(managementClient); } }
6,888
38.365714
127
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/servlet/preservepath/PreservePathFilter.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.web.servlet.preservepath; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class PreservePathFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { filterChain.doFilter(servletRequest, servletResponse); HttpServletRequest request = (HttpServletRequest) servletRequest; String tmpFolder = request.getParameter("path"); File file = new File(tmpFolder + "/output.txt"); file.createNewFile(); try( BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file))) { String text = "servletPath: " + request.getServletPath() + "\nrequestUrl: " + request.getRequestURL().toString() + "\nrequestUri: " + request.getRequestURI(); bufferedWriter.write(text); } } }
2,089
37
87
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/servlet/preservepath/ForwardingServlet.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.web.servlet.preservepath; import jakarta.servlet.RequestDispatcher; 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") public class ForwardingServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String nextJSP = "/preserve-path.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP); dispatcher.forward(req,resp); } }
1,550
39.815789
112
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/servlet/buffersize/ResponseBufferSizeTestCase.java
package org.jboss.as.test.integration.web.servlet.buffersize; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.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.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays; @RunAsClient @RunWith(Arquillian.class) public class ResponseBufferSizeTestCase { private static final Logger log = LoggerFactory.getLogger(ResponseBufferSizeTestCase.class); public static final String DEPLOYMENT = "response-buffer-size.war"; @Deployment(name = DEPLOYMENT) public static Archive<?> getDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT); war.addClass(ResponseBufferSizeServlet.class); return war; } @Test @OperateOnDeployment(DEPLOYMENT) public void increaseBufferSizeTest(@ArquillianResource URL url) throws Exception { URL testURL = new URL(url.toString() + "ResponseBufferSizeServlet?" + ResponseBufferSizeServlet.SIZE_CHANGE_PARAM_NAME + "=1.5" + "&" + ResponseBufferSizeServlet.DATA_LENGTH_IN_PERCENTS_PARAM_NAME + "=0.8"); // more than original size, less than new buffer size final HttpGet request = new HttpGet(testURL.toString()); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { response = httpClient.execute(request); Assert.assertEquals("Failed to access " + testURL, HttpURLConnection.HTTP_OK, response.getStatusLine().getStatusCode()); String content = EntityUtils.toString(response.getEntity()); Assert.assertFalse(content.contains(ResponseBufferSizeServlet.RESPONSE_COMMITED_MESSAGE)); final Header[] transferEncodingHeaders = response.getHeaders("Transfer-Encoding"); log.trace("transferEncodingHeaders: " + Arrays.toString(transferEncodingHeaders)); final Header[] contentLengthHeader = response.getHeaders("Content-Length"); log.trace("contentLengthHeader: " + Arrays.toString(contentLengthHeader)); for (Header transferEncodingHeader : transferEncodingHeaders) { Assert.assertNotEquals("Transfer-Encoding shouldn't be chunked as set BufferSize shouldn't be filled yet, " + "probably caused due https://bugzilla.redhat.com/show_bug.cgi?id=1212566", "chunked", transferEncodingHeader.getValue()); } Assert.assertFalse("Content-Length header not specified", contentLengthHeader.length == 0); } finally { IOUtils.closeQuietly(response); httpClient.close(); } } }
3,479
43.615385
147
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/servlet/buffersize/ResponseBufferSizeServlet.java
package org.jboss.as.test.integration.web.servlet.buffersize; 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(name = "ResponseBufferSizeServlet", urlPatterns = {"/ResponseBufferSizeServlet"}) public class ResponseBufferSizeServlet extends HttpServlet { public static final String SIZE_CHANGE_PARAM_NAME = "sizeChange"; public static final String DATA_LENGTH_IN_PERCENTS_PARAM_NAME = "dataLengthInPercents"; public static final String RESPONSE_COMMITED_MESSAGE = "Response committed"; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sizeChangeAsStr = request.getParameter(SIZE_CHANGE_PARAM_NAME); String dataLengthInPercentsAsStr = request.getParameter(DATA_LENGTH_IN_PERCENTS_PARAM_NAME); double sizeChange = 1.0; double dataLengthModifier = 1.0; if (sizeChangeAsStr != null) { sizeChange = Double.parseDouble(sizeChangeAsStr); } if (sizeChangeAsStr != null) { dataLengthModifier = Double.parseDouble(dataLengthInPercentsAsStr); } int origBufferSize = response.getBufferSize(); int newBufferSize = (int)(origBufferSize * sizeChange); int dataLength = (int)(newBufferSize*dataLengthModifier); int lineLength = 160; // setting line length to create nicer output // generating output of specified size response.setBufferSize(newBufferSize); StringBuffer outputBuffer = new StringBuffer(dataLength); for (int i = 0; i < dataLength; i++) { outputBuffer.append("X"); if ((dataLength%lineLength) == 0) { outputBuffer.append('\n'); i++; } } response.getWriter().write(outputBuffer.toString()); if (response.isCommitted()) { response.getWriter().println(RESPONSE_COMMITED_MESSAGE); } } }
2,182
37.982143
121
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/headers/ResponseCodeTestCase.java
/* * JBoss, Home of Professional Open Source * Copyright 2015, 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.web.headers; import java.net.URL; 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.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.jaxrs.packaging.war.WebXml; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Test if certain response code wont erase content-type * * @author baranowb */ @RunWith(Arquillian.class) @RunAsClient public class ResponseCodeTestCase { private static final HttpClient HTTP_CLIENT = HttpClients.createDefault(); @Deployment(testable = false) public static Archive<?> deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, "jaxrsnoap.war"); war.addClass(RSCodeResponder.class); war.addAsWebInfResource(WebXml.get("<servlet-mapping>\n" + " <servlet-name>jakarta.ws.rs.core.Application</servlet-name>\n" + " <url-pattern>/jaxrs/*</url-pattern>\n" + " </servlet-mapping>\n" + "\n"), "web.xml"); return war; } @ArquillianResource private URL url; // TODO: redo once/if Arq will support JUnitParams? @Test public void test200() throws Exception { final HttpGet get = new HttpGet(url.toExternalForm() + "jaxrs/test/returnCode/200"); final HttpResponse response = HTTP_CLIENT.execute(get); doContentTypeChecks(response, 200); } @Test public void test300() throws Exception { final HttpGet get = new HttpGet(url.toExternalForm() + "jaxrs/test/returnCode/300"); final HttpResponse response = HTTP_CLIENT.execute(get); doContentTypeChecks(response, 300); } @Test public void test400() throws Exception { final HttpGet get = new HttpGet(url.toExternalForm() + "jaxrs/test/returnCode/400"); final HttpResponse response = HTTP_CLIENT.execute(get); doContentTypeChecks(response, 400); } @Test public void test404() throws Exception { final HttpGet get = new HttpGet(url.toExternalForm() + "jaxrs/test/returnCode/404"); final HttpResponse response = HTTP_CLIENT.execute(get); doContentTypeChecks(response, 404); } @Test public void test500() throws Exception { final HttpGet get = new HttpGet(url.toExternalForm() + "jaxrs/test/returnCode/500"); final HttpResponse response = HTTP_CLIENT.execute(get); doContentTypeChecks(response, 500); } /* This test is commented out as it is testing server info data and not response codes. It should be moved to maybe somke testsuite that works on top of "real" distribution and not trimmed down one that is used in rest of testsuite. */ /* @Test public void testServerInfo() throws Exception { final HttpGet get = new HttpGet(url.toExternalForm() + "jaxrs/test/server/info"); final HttpResponse response = HTTP_CLIENT.execute(get); final HttpEntity entity = response.getEntity(); Assert.assertNotNull("Null entity!", entity); final String content = EntityUtils.toString(response.getEntity()); Assert.assertTrue("Wrong content! " + content, content.matches("WildFly Full .*\\(WildFly Core .*\\) - .*")); }*/ private void doContentTypeChecks(final HttpResponse response, final int code) throws Exception { doContentTypeChecks(response, code, true); } public void doContentTypeChecks(final HttpResponse response, final int code, final boolean expectContent) throws Exception { Assert.assertEquals("Wrong response code!", code, response.getStatusLine().getStatusCode()); Assert.assertEquals("Missing content type!", 1, response.getHeaders("Content-Type").length); if (expectContent) { final HttpEntity entity = response.getEntity(); Assert.assertNotNull("Null entity!", entity); final String content = EntityUtils.toString(response.getEntity()); Assert.assertEquals("Wrong content!", RSCodeResponder.CONTENT, content); } } }
5,612
40.88806
128
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/headers/RSCodeResponder.java
/* * JBoss, Home of Professional Open Source * Copyright 2015, 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.web.headers; import java.nio.charset.StandardCharsets; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpServletResponse; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; /** * @author baranowb */ @Path("/test") public class RSCodeResponder { public static final String CONTENT = "{\"employees\":["+ "{\"firstName\":\"John\", \"lastName\":\"Doe\"},"+ "{\"firstName\":\"Anna\", \"lastName\":\"Smith\"},"+ "{\"firstName\":\"Peter\", \"lastName\":\"Jones\"}"+ "]}"; @GET @Path("returnCode/{code}") @Produces(MediaType.APPLICATION_JSON) public Response return204(@PathParam("code") final String code,@Context HttpServletResponse resp) throws Exception{ resp.setContentType("application/json"); resp.getOutputStream().write((CONTENT).getBytes(StandardCharsets.UTF_8)); return Response.status(Integer.parseInt(code)).build(); } @GET @Path("server/info") @Produces(MediaType.TEXT_PLAIN) public String return204(@Context ServletContext servletContext) throws Exception{ return servletContext.getServerInfo(); } }
2,383
36.84127
119
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/headers/authentication/ResponseHeaderAuthenticationServerSetupTask.java
package org.jboss.as.test.integration.web.headers.authentication; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.security.common.CoreUtils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.wildfly.test.security.common.other.KeyStoreUtils; import org.wildfly.test.security.common.other.KeyUtils; import java.io.File; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.PrivateKey; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.List; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLBACK_ON_RUNTIME_FAILURE; import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode; /** * Server setup task for test ResponseHeaderAuthenticationTestCase. * Configures key-store and application-security-domain. */ public class ResponseHeaderAuthenticationServerSetupTask extends SnapshotRestoreSetupTask { public static final String PASSWORD = "password1"; private static final String ALIAS = "single-sign-on"; private static final String KEYSTORE_FILE_NAME = "single-sign-on.jks"; @Override public void doSetup(ManagementClient managementClient, String containerId) throws Exception { // /subsystem=elytron/http-authentication-factory=application-http-authentication:add(http-server-mechanism-factory=global, security-domain=ApplicationDomain,mechanism-configurations=[{mechanism-name=BASIC, mechanism-realm-configurations=[{realm-name=Application Realm}]},{mechanism-name=FORM}]) ModelNode addHttpAuthenticationFactory = createOpNode("subsystem=elytron/http-authentication-factory=test-http-authentication", ADD); addHttpAuthenticationFactory.get("http-server-mechanism-factory").set("global"); addHttpAuthenticationFactory.get("security-domain").set("ApplicationDomain"); addHttpAuthenticationFactory.get("mechanism-configurations").get(0).get("mechanism-name").set("BASIC"); addHttpAuthenticationFactory.get("mechanism-configurations").get(0).get("mechanism-realm-configurations").get(0).get("realm-name").set("Application Realm"); addHttpAuthenticationFactory.get("mechanism-configurations").get(1).get("mechanism-name").set("FORM"); // /subsystem=elytron/key-store=single-sign-on:add(path=single-sign-on.jks, type=JKS, relative-to=jboss.server.config.dir, credential-reference={clear-text=password}) ModelNode addKeyStore = createOpNode("subsystem=elytron/key-store=single-sign-on", ADD); addKeyStore.get("path").set(KEYSTORE_FILE_NAME); addKeyStore.get("type").set("JKS"); addKeyStore.get("relative-to").set("jboss.server.config.dir"); ModelNode credentialReference = new ModelNode(); credentialReference.get("clear-text").set(ResponseHeaderAuthenticationTestCase.PASSWORD); addKeyStore.get("credential-reference").set(credentialReference); // /subsystem=undertow/application-security-domain=ApplicationDomain:add(http-authentication-factory=application-http-authentication) ModelNode addSecurityDomain = createOpNode("subsystem=undertow/application-security-domain=ApplicationDomain", ADD); addSecurityDomain.get("http-authentication-factory").set("test-http-authentication"); // /subsystem=undertow/application-security-domain=ApplicationDomain/setting=single-sign-on:add(key-alias=single-sign-on, credential-reference={clear-text=password},key-store=single-sign-on) ModelNode addSingleSignOn = createOpNode("subsystem=undertow/application-security-domain=ApplicationDomain/setting=single-sign-on", ADD); addSingleSignOn.get("key-alias").set("single-sign-on"); addSingleSignOn.get("credential-reference").set(credentialReference); addSingleSignOn.get("key-store").set("single-sign-on"); ModelNode updateOp = Util.createCompositeOperation(List.of(addHttpAuthenticationFactory, addKeyStore, addSecurityDomain, addSingleSignOn)); updateOp.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(true); updateOp.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true); CoreUtils.applyUpdate(updateOp, managementClient.getControllerClient()); this.createKeyStore(); ServerReload.executeReloadAndWaitForCompletion(managementClient); } /** * Creates key store with certificate and stores it on the path {$jboss.home}/standalone/configuration/single-sign-on.jks * * @throws Exception */ private void createKeyStore() throws Exception { File keyStoreFile = new File(TestSuiteEnvironment.getSystemProperty("jboss.home") + File.separator + "standalone" + File.separator + "configuration" + File.separator + KEYSTORE_FILE_NAME); keyStoreFile.createNewFile(); String serverName = "server"; KeyPair server = KeyUtils.generateKeyPair(); X509Certificate serverCert = KeyUtils.generateX509Certificate(serverName, server); KeyStore keyStore = loadKeyStore(); // generate a key pair KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048, new SecureRandom()); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey signingKey = keyPair.getPrivate(); keyStore.setKeyEntry(ALIAS, signingKey, PASSWORD.toCharArray(), new X509Certificate[]{serverCert}); KeyStoreUtils.saveKeystore(keyStore, PASSWORD, keyStoreFile); } private static KeyStore loadKeyStore() throws Exception { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, PASSWORD.toCharArray()); return ks; } }
6,290
56.190909
303
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/headers/authentication/ResponseHeaderAuthenticationTestCase.java
package org.jboss.as.test.integration.web.headers.authentication; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.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 java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertNotEquals; /** * Test configures elytron with the key-store and security domain for undertow. * Deploys application with the user/password form and fills the form with the predefined application user credentials. * Test checks the "Set-Cookie" response header if there is not undefined domain value. * Test for [ WFLY-11071 ]. * * @author Daniel Cihak */ @RunWith(Arquillian.class) @ServerSetup(ResponseHeaderAuthenticationServerSetupTask.class) @RunAsClient public class ResponseHeaderAuthenticationTestCase { public static final String PASSWORD = "password1"; private static final String DEPLOYMENT = "test"; private static final String DOMAIN_ATTRIBUTE = "domain="; @Deployment(name=DEPLOYMENT) public static Archive<?> createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war"); war.addAsWebInfResource(ResponseHeaderAuthenticationTestCase.class.getPackage(), "web.xml", "/web.xml"); war.addAsWebInfResource(ResponseHeaderAuthenticationTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml"); war.addAsWebResource(ResponseHeaderAuthenticationTestCase.class.getPackage(), "login.html", "login.html"); war.addAsWebResource(ResponseHeaderAuthenticationTestCase.class.getPackage(), "index.jsp", "index.jsp"); war.addAsWebResource(ResponseHeaderAuthenticationTestCase.class.getPackage(), "error.jsp", "error.jsp"); return war; } /** * Tests if the SSO response header has not domain value undefined. * * @param url * @throws Exception */ @Test public void testResponseHeaderAuthentication(@ArquillianResource URL url) throws Exception { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { String appUrl = url.toExternalForm() + "j_security_check"; HttpPost httpPost = new HttpPost(appUrl); httpPost.addHeader("Referer", url.toExternalForm() + "login.html"); List<NameValuePair> formParams = new ArrayList<>(); formParams.add(new BasicNameValuePair("j_username", "user1")); formParams.add(new BasicNameValuePair("j_password", PASSWORD)); httpPost.setEntity(new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8)); HttpResponse response = httpClient.execute(httpPost); Header[] setCookieHeaders = response.getHeaders("Set-Cookie"); for (Header header: setCookieHeaders) { String headerValue = header.getValue(); if (headerValue.startsWith("JSESSIONIDSSO=") && headerValue.contains(DOMAIN_ATTRIBUTE)) { String domainValue = headerValue.split(DOMAIN_ATTRIBUTE)[1]; assertNotEquals(domainValue, "undefined"); } } } } }
3,898
43.306818
123
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/suspend/WebSuspendTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, 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.web.suspend; import java.io.FilePermission; import java.net.HttpURLConnection; import java.net.SocketPermission; import java.net.URL; import java.util.PropertyPermission; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.remoting3.security.RemotingPermission; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; /** * Tests for suspend/resume functionality in the web subsystem */ @RunWith(Arquillian.class) public class WebSuspendTestCase { protected static Logger log = Logger.getLogger(WebSuspendTestCase.class); @ArquillianResource private ManagementClient managementClient; @Deployment public static WebArchive deployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, "web-suspend.war"); war.addPackage(WebSuspendTestCase.class.getPackage()); war.addPackage(HttpRequest.class.getPackage()); war.addClass(TestSuiteEnvironment.class); war.addAsResource(new StringAsset("Dependencies: org.jboss.dmr, org.jboss.as.controller, org.jboss.remoting\n"), "META-INF/MANIFEST.MF"); war.addAsManifestResource(createPermissionsXmlAsset( new PropertyPermission("management.address", "read"), new PropertyPermission("jboss.http.port", "read"), new PropertyPermission("node0", "read"), // executorService.shutdown() needs the following permission new RuntimePermission("modifyThread"), // ManagementClient needs the following permissions and a dependency on 'org.jboss.remoting3' module new RemotingPermission("createEndpoint"), new RemotingPermission("connect"), // HttpClient needs the following permission new SocketPermission(TestSuiteEnvironment.getServerAddress() + ":" + TestSuiteEnvironment.getHttpPort(), "connect,resolve"), new FilePermission(System.getProperty("jboss.inst") + "/standalone/tmp/auth/*", "read") ), "permissions.xml"); return war; } @Test public void testRequestInShutdown() throws Exception { final String address = "http://" + TestSuiteEnvironment.getServerAddress() + ":" + TestSuiteEnvironment.getHttpPort() + "/web-suspend/ShutdownServlet"; ExecutorService executorService = Executors.newSingleThreadExecutor(); try { Future<Object> result = executorService.submit(new Callable<Object>() { @Override public Object call() throws Exception { return HttpRequest.get(address, 60, TimeUnit.SECONDS); } }); Thread.sleep(1000); //nasty, but we need to make sure the HTTP request has started ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.OP).set("suspend"); managementClient.getControllerClient().execute(op); ShutdownServlet.requestLatch.countDown(); Assert.assertEquals(ShutdownServlet.TEXT, result.get()); final HttpURLConnection conn = (HttpURLConnection) new URL(address).openConnection(); try { conn.setDoInput(true); int responseCode = conn.getResponseCode(); Assert.assertEquals(503, responseCode); } finally { conn.disconnect(); } } finally { ShutdownServlet.requestLatch.countDown(); executorService.shutdown(); ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.OP).set("resume"); managementClient.getControllerClient().execute(op); } } }
5,661
41.253731
159
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/web/suspend/ShutdownServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, 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.web.suspend; import java.io.IOException; import java.util.concurrent.CountDownLatch; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * A servlet that is used to test different way of setting and retrieving cookies. * * @author [email protected] */ @WebServlet(name = "ShutdownServlet", urlPatterns = { "/ShutdownServlet" }) public class ShutdownServlet extends HttpServlet { private static final long serialVersionUID = -5891682551205336273L; public static final CountDownLatch requestLatch = new CountDownLatch(1); public static final String TEXT = "Running Request"; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { requestLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } response.getWriter().write(TEXT); response.getWriter().close(); } }
2,202
37.649123
121
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/mail/providers/MethodInjectQualifier.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.mail.providers; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; @Qualifier @Retention(RUNTIME) @Target({ METHOD, FIELD }) public @interface MethodInjectQualifier { }
1,033
30.333333
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/mail/providers/MailSessionCustomProviderTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.mail.providers; import java.util.List; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.annotation.Resource; import jakarta.inject.Inject; import jakarta.mail.Provider; import jakarta.mail.Session; @RunWith(Arquillian.class) public class MailSessionCustomProviderTestCase { @Resource(lookup = "java:jboss/mail/Default") private Session sessionOne; @Inject private Session sessionTwo; @Inject @MethodInjectQualifier private Session sessionThree; @Deployment public static WebArchive createDeployment() { return ShrinkWrap.create(WebArchive.class) .addClasses(MailSessionProducer.class, MethodInjectQualifier.class) .addAsResource(MailSessionCustomProviderTestCase.class.getPackage(),"javamail.providers", "META-INF/javamail.providers") .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); } @Test public void testCustomProvidersInApplication() { Assert.assertNotNull(sessionOne); Assert.assertNotNull(sessionTwo); Assert.assertNotNull(sessionThree); List<Session> sessions = List.of(sessionOne, sessionTwo, sessionThree); for(Session session : sessions) { Provider[] providers = session.getProviders(); int found = 0; for (Provider p : providers) { if (p.toString().equals("jakarta.mail.Provider[TRANSPORT,CustomTransport,org.jboss.qa.management.mail.custom.CustomTransport,JBoss QE]")) { found++; } if (p.toString().equals("jakarta.mail.Provider[STORE,CustomStore,org.jboss.qa.management.mail.custom.CustomStore,JBoss QE]")) { found++; } } Assert.assertTrue("The expected custom providers cannot be found on the default Mail Session", found == 2); } } }
3,265
36.54023
155
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/mail/providers/MailSessionProducer.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.mail.providers; import jakarta.annotation.Resource; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Produces; import jakarta.mail.Session; @ApplicationScoped public class MailSessionProducer { @Produces @Resource(mappedName = "java:jboss/mail/Default") private Session sessionFieldProducer; @Resource(mappedName = "java:jboss/mail/Default") private Session sessionMethodProducer; @Produces @MethodInjectQualifier public Session methodProducer() { return sessionMethodProducer; } }
1,202
29.075
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/mail/cdi/MailAnnotationSessionCDIInjectionTest.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.mail.cdi; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.inject.Inject; import jakarta.mail.Session; /** * Verifies Mail Session created from an annotation can be injected using CDI */ @RunWith(Arquillian.class) public class MailAnnotationSessionCDIInjectionTest { @Inject Session sessionOne; @Inject @MethodInjectQualifier Session sessionTwo; @Deployment public static Archive<?> deploy() { return ShrinkWrap.create(WebArchive.class, "mail-annotation-cdi-injection-test.war") .addClasses(MethodInjectQualifier.class, MailAnnotationSessionProducer.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); } @Test public void test() throws IOException, ExecutionException, TimeoutException { Assert.assertNotNull(sessionOne); Assert.assertNotNull(sessionTwo); } }
1,976
30.380952
93
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/mail/cdi/MethodInjectQualifier.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.mail.cdi; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; @Qualifier @Retention(RUNTIME) @Target({ METHOD, FIELD }) public @interface MethodInjectQualifier { }
1,027
30.151515
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/mail/cdi/MailAnnotationSessionProducer.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.mail.cdi; import jakarta.annotation.Resource; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Produces; import jakarta.mail.MailSessionDefinition; import jakarta.mail.Session; @MailSessionDefinition( name = "java:/mail/test-mail-cdi-session-1", host = "localhost", transportProtocol = "smtp", properties = { "mail.smtp.host=localhost", "mail.smtp.port=5554", "mail.smtp.sendpartial=true", "mail.debug=true" } ) @MailSessionDefinition( name = "java:/mail/test-mail-cdi-session-2", host = "localhost", transportProtocol = "smtp", properties = { "mail.smtp.host=localhost", "mail.smtp.port=5555", "mail.smtp.sendpartial=true", "mail.debug=true" }) @ApplicationScoped public class MailAnnotationSessionProducer { @Produces @Resource(mappedName = "java:/mail/test-mail-cdi-session-1") private Session sessionFieldProducer; @Resource(mappedName = "java:/mail/test-mail-cdi-session-2") private Session sessionMethodProducer; @Produces @MethodInjectQualifier public Session methodProducer() { return sessionMethodProducer; } }
1,948
30.435484
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/mail/cdi/MailSessionProducer.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.mail.cdi; import jakarta.annotation.Resource; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Produces; import jakarta.mail.Session; @ApplicationScoped public class MailSessionProducer { @Produces @Resource(mappedName = "java:jboss/mail/Default") private Session sessionFieldProducer; @Resource(mappedName = "java:jboss/mail/Default") private Session sessionMethodProducer; @Produces @MethodInjectQualifier public Session methodProducer() { return sessionMethodProducer; } }
1,196
28.925
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/mail/cdi/MailSessionCDIInjectionTest.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.mail.cdi; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.inject.Inject; import jakarta.mail.Session; /** * Verifies Mail Session can be injected using CDI */ @RunWith(Arquillian.class) public class MailSessionCDIInjectionTest { @Inject Session sessionOne; @Inject @MethodInjectQualifier Session sessionTwo; @Deployment public static Archive<?> deploy() { return ShrinkWrap.create(WebArchive.class, "mail-cdi-injection-test.war") .addClasses(MailSessionProducer.class, MethodInjectQualifier.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); } @Test public void test() throws IOException, ExecutionException, TimeoutException { Assert.assertNotNull(sessionOne); Assert.assertNotNull(sessionTwo); } }
1,917
29.935484
83
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/mail/annotation/MailServlet.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.mail.annotation; import jakarta.mail.MailSessionDefinition; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; @MailSessionDefinition( name = "java:/mail/test-mail-session-1", host = "localhost", transportProtocol = "smtp", properties = { "mail.smtp.host=localhost", "mail.smtp.port=5554", "mail.smtp.sendpartial=true", "mail.debug=true" } ) @MailSessionDefinition( name = "java:/mail/test-mail-session-2", host = "localhost", transportProtocol = "smtp", properties = { "mail.smtp.host=localhost", "mail.smtp.port=5555", "mail.smtp.sendpartial=true", "mail.debug=true" }) @WebServlet public final class MailServlet extends HttpServlet { }
1,521
30.061224
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/mail/annotation/RepeatableMailSessionDefinitionTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.mail.annotation; import jakarta.annotation.Resource; import jakarta.mail.Session; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class RepeatableMailSessionDefinitionTestCase { @Resource(mappedName = "java:/mail/test-mail-session-1") private Session session1; @Resource(mappedName = "java:/mail/test-mail-session-2") private Session session2; @Deployment public static WebArchive createDeployment() { return ShrinkWrap.create(WebArchive.class) .addClass(MailServlet.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); } @Test public void testRepeatedMailSessionDefinition() { Assert.assertNotNull(session1); Assert.assertNotNull(session2); } }
2,141
33.548387
73
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/mail/annotation/MailDefiner.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.mail.annotation; import jakarta.ejb.Stateless; import jakarta.mail.MailSessionDefinition; /** * @author <a href="mailto:[email protected]">William DeCoste</a> */ @Stateless @MailSessionDefinition( name = "java:app/mail/MySession", host = "somewhere.myco.com", from = "[email protected]") public class MailDefiner { }
1,436
32.418605
71
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/mail/annotation/MailSessionDefinitionAnnotationTest.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.mail.annotation; 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; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. */ @RunWith(Arquillian.class) public class MailSessionDefinitionAnnotationTest { @ArquillianResource InitialContext ctx; @Deployment public static Archive<?> deploy() { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "mail-injection-test.jar"); jar.addClasses(MailSessionDefinitionAnnotationTest.class, StatelessMail.class, MailDefiner.class); jar.addAsManifestResource(MailSessionDefinitionAnnotationTest.class.getPackage(), "ejb-jar.xml", "ejb-jar.xml"); return jar; } @Test public void testMailInjection() throws Exception { InitialContext ctx = new InitialContext(); StatelessMail statelessMail = (StatelessMail) ctx.lookup("java:module/" + StatelessMail.class.getSimpleName()); Assert.assertNotNull(statelessMail); statelessMail.testMailInjection(); } }
2,486
37.261538
120
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/mail/annotation/StatelessMail.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.mail.annotation; import jakarta.annotation.Resource; import jakarta.ejb.Stateless; import jakarta.mail.Session; import org.junit.Assert; /** * @author Tomaz Cerar */ @Stateless public class StatelessMail { @Resource(name = "java:app/mail/MySession") private Session mailSession; @Resource(lookup = "java:jboss/mail/Default") private Session session; public void testMailInjection() { Assert.assertNotNull(mailSession); Assert.assertNotNull(session); } }
1,589
30.176471
71
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/undeploy/RemoveSFSBOnUndeployTestCase.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.ejb.stateful.undeploy; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.URL; import java.util.Hashtable; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.jboss.logging.Logger; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @RunAsClient public class RemoveSFSBOnUndeployTestCase { private static final Logger log = Logger.getLogger(RemoveSFSBOnUndeployTestCase.class.getName()); @ArquillianResource Deployer deployer; private static Context context; @BeforeClass public static void beforeClass() throws Exception { final Hashtable props = new Hashtable(); props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); context = new InitialContext(props); } @Deployment(name = "remote", testable = false) public static WebArchive createRemoteTestArchive() { return ShrinkWrap.create(WebArchive.class, "remote.war") .addClasses(TestServlet.class); } @Deployment(name="ejb", managed = false, testable = false) public static JavaArchive createMainTestArchive() { return ShrinkWrap.create(JavaArchive.class, "ejb.jar") .addClasses(TestSfsb.class, TestSfsbRemote.class) .addAsManifestResource(new StringAsset("Dependencies: deployment.remote.war\n"), "MANIFEST.MF"); } @Test public void testSfsbDestroyedOnUndeploy( @ArquillianResource @OperateOnDeployment("remote") URL url) throws IOException, ExecutionException, TimeoutException, NamingException { deployer.deploy("ejb"); try { final TestSfsbRemote localEcho = (TestSfsbRemote) context.lookup("ejb:/ejb/" + TestSfsb.class.getSimpleName() + "!" + TestSfsbRemote.class.getName()+"?stateful"); localEcho.invoke(); assertEquals("PostConstruct", HttpRequest.get(url + "/test", 10, TimeUnit.SECONDS)); assertEquals("invoke", HttpRequest.get(url + "/test", 10, TimeUnit.SECONDS)); }finally { deployer.undeploy("ejb"); } assertEquals("PreDestroy", HttpRequest.get(url + "/test", 10, TimeUnit.SECONDS)); } }
4,102
39.623762
174
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/undeploy/TestSfsb.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.ejb.stateful.undeploy; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.ejb.Stateful; /** * @author Stuart Douglas */ @Stateful public class TestSfsb implements TestSfsbRemote{ @PostConstruct public void init() { TestServlet.addMessage("PostConstruct"); } @PreDestroy public void destroy() { TestServlet.addMessage("PreDestroy"); } @Override public void invoke() { TestServlet.addMessage("invoke"); } }
1,576
31.183673
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/undeploy/TestServlet.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.ejb.stateful.undeploy; import java.io.IOException; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Stuart Douglas */ @WebServlet(urlPatterns = "/test") public class TestServlet extends HttpServlet { private static LinkedBlockingDeque<String> messages = new LinkedBlockingDeque<>(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { resp.getWriter().write(messages.poll(30, TimeUnit.SECONDS)); } catch (InterruptedException e) { throw new RuntimeException(e); } } public static void addMessage(String message) { messages.add(message); } }
2,040
36.796296
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/undeploy/TestSfsbRemote.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.ejb.stateful.undeploy; import jakarta.ejb.Remote; /** * @author Stuart Douglas */ @Remote public interface TestSfsbRemote { void invoke(); }
1,211
34.647059
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/remove/BaseSFSB.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.ejb.stateful.remove; import jakarta.ejb.Remove; /** * @author Jaikiran Pai */ public class BaseSFSB { @Remove(retainIfException = true) public void baseRetainIfAppException() { throw new SimpleAppException(); } @Remove public void baseRemoveEvenIfAppException() { throw new SimpleAppException(); } @Remove public void baseJustRemove() { // do nothing } }
1,484
30.595745
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/remove/SFSBWithRemoveMethods.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.ejb.stateful.remove; import jakarta.ejb.Remove; import jakarta.ejb.Stateful; /** * User: jpai */ @Stateful public class SFSBWithRemoveMethods extends BaseSFSB { @Remove public void remove() { // do nothing } @Remove(retainIfException = true) public void retainIfAppException() { throw new SimpleAppException(); } @Remove public void removeEvenIfAppException() { throw new SimpleAppException(); } public void doNothing() { } }
1,565
28.54717
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/remove/RemoveMethodOnSFSBTestCase.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.ejb.stateful.remove; import jakarta.ejb.EJB; import jakarta.ejb.NoSuchEJBException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.logging.Logger; 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; /** * Tests the {@link jakarta.ejb.Remove @Remove} methods on Stateful session beans. * <p/> * User: Jaikiran Pai */ @RunWith(Arquillian.class) public class RemoveMethodOnSFSBTestCase { private static final Logger log = Logger.getLogger(RemoveMethodOnSFSBTestCase.class.getName()); @Deployment public static JavaArchive createDeployment() { // create the ejb jar final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "sfsb-remove-method-test.jar"); jar.addPackage(SFSBWithRemoveMethods.class.getPackage()); return jar; } @EJB (mappedName = "java:module/SFSBWithRemoveMethods!org.jboss.as.test.integration.ejb.stateful.remove.SFSBWithRemoveMethods") private SFSBWithRemoveMethods sfsbWithRemoveMethods; /** * Tests that an invocation on a SFSB method annotated with @Remove results in the removal of the bean instance */ @Test public void testSimpleRemoveOnSFSB() { // remove the SFSB sfsbWithRemoveMethods.remove(); // try invoking again. we should expect a NoSuchEJBException try { sfsbWithRemoveMethods.remove(); Assert.fail("SFSB was expected to be removed after a call to the @Remove method"); } catch (NoSuchEJBException nsee) { // expected log.trace("Got the expected NoSuchEJBException after invoking remove on the SFSB"); } } /** * Tests that an invocation on SFSB method annotated with @Remove and with "retainIfException = true" *doesn't* result * in removal of the bean when an application exception is thrown. */ @Test public void testRemoveWithRetainIfExceptionOnSFSB() { // invoke the remove method which throws an app exception try { sfsbWithRemoveMethods.retainIfAppException(); Assert.fail("Did not get the expected app exception"); } catch (SimpleAppException sae) { // expected } // invoke again and it should *not* throw NoSuchEJBException try { sfsbWithRemoveMethods.retainIfAppException(); Assert.fail("Did not get the expected app exception on second invocation on SFSB"); } catch (SimpleAppException sae) { // expected } } /** * Tests that an invocation on SFSB method annotated with @Remove (and without the retainIfException set to true) results in * removal of the bean even in case of application exception. */ @Test public void testRemoveEvenIfAppExceptionOnSFSB() throws Exception { // invoke the remove method which throws an app exception try { sfsbWithRemoveMethods.removeEvenIfAppException(); Assert.fail("Did not get the expected app exception"); } catch (SimpleAppException sae) { // expected } // invoke again and it *must* throw NoSuchEJBException try { sfsbWithRemoveMethods.removeEvenIfAppException(); Assert.fail("Did not get the expected NoSuchEJBException on second invocation on SFSB"); } catch (NoSuchEJBException nsee) { // expected log.trace("Got the expected NoSuchEJBException on second invocation on SFSB"); } } /** * Tests that an invocation on a simple SFSB method which doesn't have the @Remove on it, *doesn't* result in the bean * instance removal. */ @Test public void testSimpleNonRemoveMethodOnSFSB() { sfsbWithRemoveMethods.doNothing(); sfsbWithRemoveMethods.doNothing(); sfsbWithRemoveMethods.doNothing(); } /** * Tests that an invocation on SFSB base class method annotated with @Remove (and without the retainIfException set to true) results in * removal of the bean even in case of application exception. */ @Test public void testRemoveEvenIfAppExceptionOnSFSBBaseClass() { // invoke the remove method which throws an app exception try { sfsbWithRemoveMethods.baseRemoveEvenIfAppException(); Assert.fail("Did not get the expected app exception"); } catch (SimpleAppException sae) { // expected } // invoke again and it *must* throw NoSuchEJBException try { sfsbWithRemoveMethods.doNothing(); Assert.fail("Did not get the expected NoSuchEJBException on second invocation on SFSB"); } catch (NoSuchEJBException nsee) { // expected log.trace("Got the expected NoSuchEJBException on second invocation on SFSB"); } } /** * Tests that an invocation on a SFSB base class method annotated with @Remove results in the removal of the bean instance */ @Test public void testSimpleRemoveOnSFSBBaseClass() { // remove the SFSB sfsbWithRemoveMethods.baseJustRemove(); // try invoking again. we should expect a NoSuchEJBException try { sfsbWithRemoveMethods.doNothing(); Assert.fail("SFSB was expected to be removed after a call to the @Remove method"); } catch (NoSuchEJBException nsee) { // expected log.trace("Got the expected NoSuchEJBException after invoking remove on the SFSB"); } } /** * Tests that an invocation on SFSB base class method annotated with @Remove and with "retainIfException = true" *doesn't* result * in removal of the bean when an application exception is thrown. */ @Test public void testRemoveWithRetainIfExceptionOnSFSBBaseClass() { // invoke the remove method which throws an app exception try { sfsbWithRemoveMethods.baseRetainIfAppException(); Assert.fail("Did not get the expected app exception"); } catch (SimpleAppException sae) { // expected } // invoke again and it should *not* throw NoSuchEJBException try { sfsbWithRemoveMethods.baseRetainIfAppException(); Assert.fail("Did not get the expected app exception on second invocation on SFSB"); } catch (SimpleAppException sae) { // expected } } }
7,719
37.40796
139
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/remove/SimpleAppException.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.ejb.stateful.remove; import jakarta.ejb.ApplicationException; /** * User: jpai */ @ApplicationException public class SimpleAppException extends RuntimeException { }
1,231
36.333333
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/exception/DestroyMarkerBean.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.ejb.stateful.exception; import jakarta.ejb.LocalBean; import jakarta.ejb.Remote; import jakarta.ejb.Singleton; @Singleton @Remote @LocalBean public class DestroyMarkerBean implements DestroyMarkerBeanInterface { private boolean preDestroy = false; public boolean is() { return preDestroy; } public void set(boolean preDestroy) { this.preDestroy = preDestroy; } }
1,465
33.093023
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/exception/ExceptionTestCase.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.ejb.stateful.exception; import jakarta.ejb.EJBException; import jakarta.ejb.NoSuchEJBException; import javax.naming.InitialContext; import javax.naming.NamingException; 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.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests that post construct callbacks are not called on system exception, * and that the bean is destroyed * * @author Stuart Douglas */ @RunWith(Arquillian.class) public class ExceptionTestCase { protected static final String ARCHIVE_NAME = "ExceptionTestCase"; @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addPackage(ExceptionTestCase.class.getPackage()); return jar; } @ArquillianResource private InitialContext iniCtx; private DestroyMarkerBeanInterface isPreDestroy; private <T> T lookup(Class<T> beanType) throws NamingException { return beanType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanType.getSimpleName() + "!" + beanType.getName())); } protected SFSB1Interface getBean() throws NamingException { return lookup(SFSB1.class); } protected DestroyMarkerBeanInterface getMarker() throws NamingException { return lookup(DestroyMarkerBean.class); } @Before public void before() throws NamingException { isPreDestroy = getMarker(); } /** * Ensure that a system exception destroys the bean. */ @Test public void testSystemExceptionDestroysBean() throws Exception { SFSB1Interface sfsb1 = getBean(); Assert.assertFalse(isPreDestroy.is()); try { sfsb1.systemException(); Assert.fail("It was expected a RuntimeException being thrown"); } catch (RuntimeException e) { Assert.assertTrue(e.getMessage().contains(SFSB1.MESSAGE)); } Assert.assertFalse(isPreDestroy.is()); try { sfsb1.systemException(); Assert.fail("Expecting NoSuchEjbException"); } catch (NoSuchEJBException expected) { } } /** * Throwing EJBException which as child of RuntimeException causes * SFSB to be removed. */ @Test public void testEjbExceptionDestroysBean() throws Exception { SFSB1Interface sfsb1 = getBean(); Assert.assertFalse(isPreDestroy.is()); try { sfsb1.ejbException(); Assert.fail("It was expected a EJBException being thrown"); } catch (EJBException e) { Assert.assertTrue(e.getMessage().contains(SFSB1.MESSAGE)); } Assert.assertFalse("Thrown exception removes SFS but does not call any callback", isPreDestroy.is()); try { sfsb1.ejbException(); Assert.fail("Expecting NoSuchEjbException"); } catch (NoSuchEJBException expected) { } } /** * Throwing non {@link RuntimeException} which does not cause * SFSB being removed. */ @Test public void testUserExceptionDoesNothing() throws Exception { SFSB1Interface sfsb1 = getBean(); Assert.assertFalse(isPreDestroy.is()); try { sfsb1.userException(); Assert.fail("It was expected a user exception being thrown"); } catch (TestException e) { Assert.assertTrue(e.getMessage().contains(SFSB1.MESSAGE)); } Assert.assertFalse(isPreDestroy.is()); try { sfsb1.userException(); Assert.fail("It was expected a user exception being thrown"); } catch (TestException e) { Assert.assertTrue(e.getMessage().contains(SFSB1.MESSAGE)); } sfsb1.remove(); Assert.assertTrue("As remove was called preDestroy callback is expected", isPreDestroy.is()); } }
5,278
32.839744
135
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/exception/DestroyMarkerBeanInterface.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.ejb.stateful.exception; public interface DestroyMarkerBeanInterface { boolean is(); void set(boolean preDestroy); }
1,187
39.965517
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/exception/ExceptionEjbClientTestCase.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.ejb.stateful.exception; import static org.junit.Assert.assertTrue; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.codehaus.plexus.util.ExceptionUtils; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.ejb.client.RequestSendFailedException; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.naming.client.WildFlyInitialContextFactory; /** * The same bundle of tests as runs at {@link ExceptionTestCase} but these ones * are managed at client mode - all calls runs over ejb remoting. * * @author Ondrej Chaloupka */ @RunAsClient @RunWith(Arquillian.class) public class ExceptionEjbClientTestCase extends ExceptionTestCase { private static Context context; @BeforeClass public static void beforeClass() throws Exception { final Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, WildFlyInitialContextFactory.class.getName()); props.put(Context.PROVIDER_URL, "remote+http://" + TestSuiteEnvironment.getServerAddress() + ":" + 8080); context = new InitialContext(props); } private <T> T lookup(Class<? extends T> beanType, Class<T> interfaceType,boolean isStateful) throws NamingException { String ejbLookup = String.format("ejb:/%s/%s!%s%s", ARCHIVE_NAME, beanType.getSimpleName(), interfaceType.getName(), (isStateful ? "?stateful" : "")); return interfaceType.cast(context.lookup(ejbLookup)); } protected SFSB1Interface getBean() throws NamingException { return lookup(SFSB1.class, SFSB1Interface.class, true); } protected DestroyMarkerBeanInterface getMarker() throws NamingException { return lookup(DestroyMarkerBean.class, DestroyMarkerBeanInterface.class, false); } /** * Test exception contains destination when there is no server running (wrong server) */ @Test public void testConnectException() throws Exception { try { Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.wildfly.naming.client.WildFlyInitialContextFactory"); //Wrong server so an exception will be thrown props.put(Context.PROVIDER_URL, "remote+http://localhost:1000"); Context ctx = new InitialContext(props); DestroyMarkerBeanInterface destroyM = (DestroyMarkerBeanInterface) ctx.lookup(String.format("ejb:/%s/%s!%s", ARCHIVE_NAME, DestroyMarkerBean.class.getSimpleName(), DestroyMarkerBeanInterface.class.getName())); destroyM.is(); Assert.fail("It was expected a RequestSendFailedException being thrown"); } catch (RequestSendFailedException e) { assertTrue("Destination should be displayed", ExceptionUtils.getFullStackTrace(e).contains("remote+http://localhost:1000")); } } }
4,178
41.642857
221
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/exception/TestException.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.ejb.stateful.exception; public class TestException extends Exception { private static final long serialVersionUID = 1L; public TestException(String message) { super(message); } }
1,263
38.5
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/exception/SFSB1.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.ejb.stateful.exception; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.ejb.EJB; import jakarta.ejb.EJBException; import jakarta.ejb.LocalBean; import jakarta.ejb.Remote; import jakarta.ejb.Remove; import jakarta.ejb.Stateful; /** * stateful session bean */ @Stateful @Remote @LocalBean public class SFSB1 implements SFSB1Interface { public static final String MESSAGE = "Expected Exception"; @EJB private DestroyMarkerBean marker; @PostConstruct public void postConstruct() { marker.set(false); } @PreDestroy public void preDestroy() { marker.set(true); } public void systemException() { throw new RuntimeException(MESSAGE); } public void ejbException() { throw new EJBException(MESSAGE); } public void userException() throws TestException { throw new TestException(MESSAGE); } @Remove public void remove() { // just removed } }
2,071
26.626667
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/exception/SFSB1Interface.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.ejb.stateful.exception; public interface SFSB1Interface { void systemException(); void ejbException(); void userException() throws TestException; void remove(); }
1,242
39.096774
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/timeout/PassivatingBean.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.ejb.stateful.timeout; import java.util.concurrent.TimeUnit; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.ejb.Stateful; import jakarta.ejb.StatefulTimeout; import org.jboss.ejb3.annotation.Cache; /** * stateful session bean */ @Stateful @Cache("distributable") @StatefulTimeout(value = 1000, unit = TimeUnit.MILLISECONDS) public class PassivatingBean { static volatile boolean preDestroy; @PostConstruct private void postConstruct() { preDestroy = false; } @PreDestroy private void preDestroy() { preDestroy = true; } public void doStuff() { } }
1,717
29.678571
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/timeout/AnnotatedBean.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.ejb.stateful.timeout; import java.util.concurrent.TimeUnit; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.ejb.Stateful; import jakarta.ejb.StatefulTimeout; /** * stateful session bean */ @Stateful @StatefulTimeout(value = 1000, unit = TimeUnit.MILLISECONDS) public class AnnotatedBean { static volatile boolean preDestroy; @PostConstruct private void postConstruct() { preDestroy = false; } @PreDestroy private void preDestroy() { preDestroy = true; } public void doStuff() { } }
1,649
30.730769
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/timeout/DescriptorBean.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.ejb.stateful.timeout; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; /** * stateful session bean */ public class DescriptorBean { static volatile boolean preDestroy; @PostConstruct private void postConstruct() { preDestroy = false; } @PreDestroy private void preDestroy() { preDestroy = true; } public void doStuff() { } }
1,476
30.425532
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/timeout/StatefulTimeoutTestCase.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.ejb.stateful.timeout; import jakarta.ejb.NoSuchEJBException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; 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.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests that the stateful timeout annotation and deployment descriptor elements works. * Tests in this class do not configure default-stateful-bean-session-timeout or any other custom server setup. * * @author Stuart Douglas */ @RunWith(Arquillian.class) public class StatefulTimeoutTestCase extends StatefulTimeoutTestBase1 { @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addPackage(StatefulTimeoutTestBase1.class.getPackage()); jar.add(new StringAsset(DEPLOYMENT_DESCRIPTOR_CONTENT), "META-INF/ejb-jar.xml"); jar.add(EmptyAsset.INSTANCE, "META-INF/beans.xml"); return jar; } @Test public void testStatefulTimeoutFromAnnotation() throws Exception { super.testStatefulTimeoutFromAnnotation(); } @Test public void testStatefulTimeoutWithPassivation() throws Exception { super.testStatefulTimeoutWithPassivation(); } @Test public void testStatefulTimeoutFromDescriptor() throws Exception { super.testStatefulTimeoutFromDescriptor(); } @Test public void testStatefulBeanNotDiscardedWhileInTransaction() throws Exception { super.testStatefulBeanNotDiscardedWhileInTransaction(); } @Test public void testStatefulBeanWithPassivationNotDiscardedWhileInTransaction() throws Exception { super.testStatefulBeanWithPassivationNotDiscardedWhileInTransaction(); } /** * Verifies that a stateful bean that does not configure stateful timeout anywhere will not be timeout or to be removed. */ @Test public void testNoTimeout() throws Exception { TimeoutNotConfiguredBean timeoutNotConfiguredBean = lookup(TimeoutNotConfiguredBean.class); timeoutNotConfiguredBean.doStuff(); Thread.sleep(3000); timeoutNotConfiguredBean.doStuff(); Assert.assertFalse(TimeoutNotConfiguredBean.preDestroy); } /** * Verifies that a stateful bean with timeout value 0 is eligible for removal immediately, and its * preDestroy method is invoked. */ @Test public void testStatefulTimeout0() throws Exception { Annotated0TimeoutBean timeout0 = lookup(Annotated0TimeoutBean.class); timeout0.doStuff(); try { timeout0.doStuff(); throw new RuntimeException("Expecting NoSuchEJBException"); } catch (NoSuchEJBException expected) { } Assert.assertTrue(Annotated0TimeoutBean.preDestroy); } }
4,116
37.12037
124
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/timeout/StatefulTimeoutTestBase2.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ejb.stateful.timeout; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.io.FilePermission; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.ManagementOperations; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.dmr.ModelNode; import org.jboss.remoting3.security.RemotingPermission; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; abstract class StatefulTimeoutTestBase2 extends StatefulTimeoutTestBase1 { static final PathAddress EJB3_ADDRESS = PathAddress.pathAddress("subsystem", "ejb3"); static final String DEFAULT_STATEFUL_TIMEOUT_NAME = "default-stateful-bean-session-timeout"; @ArquillianResource static ManagementClient managementClient; @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addPackage(StatefulTimeoutTestBase1.class.getPackage()); jar.addClasses(ModelNode.class, PathAddress.class, ManagementOperations.class, MgmtOperationException.class); jar.addAsManifestResource(new StringAsset("Dependencies: org.jboss.remoting, org.jboss.as.controller\n"), "MANIFEST.MF"); jar.addAsManifestResource(createPermissionsXmlAsset( new RemotingPermission("createEndpoint"), new RemotingPermission("connect"), new FilePermission(System.getProperty("jboss.inst") + "/standalone/tmp/auth/*", "read") ), "permissions.xml"); jar.add(new StringAsset(DEPLOYMENT_DESCRIPTOR_CONTENT), "META-INF/ejb-jar.xml"); jar.add(EmptyAsset.INSTANCE, "META-INF/beans.xml"); return jar; } static ModelNode readAttribute() throws Exception { return executeOperation(Util.getReadAttributeOperation(EJB3_ADDRESS, DEFAULT_STATEFUL_TIMEOUT_NAME)); } static ModelNode writeAttribute(int value) throws Exception { return executeOperation(Util.getWriteAttributeOperation(EJB3_ADDRESS, DEFAULT_STATEFUL_TIMEOUT_NAME, value)); } static ModelNode executeOperation(ModelNode op) throws Exception { return ManagementOperations.executeOperation(managementClient.getControllerClient(), op); } }
3,789
45.790123
129
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/timeout/StatefulTimeoutTestBase1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ejb.stateful.timeout; import jakarta.ejb.NoSuchEJBException; import jakarta.inject.Inject; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.transaction.UserTransaction; import org.jboss.arquillian.test.api.ArquillianResource; import org.junit.Assert; abstract class StatefulTimeoutTestBase1 { static final String ARCHIVE_NAME = "StatefulTimeoutTestCase"; /** * Deployment descriptor content to configure stateful-timeout for DescriptorBean. */ static String DEPLOYMENT_DESCRIPTOR_CONTENT = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " version=\"3.1\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd\">\n" + " <enterprise-beans>\n" + " <session>\n" + " <ejb-name>" + DescriptorBean.class.getSimpleName() + "</ejb-name>\n" + " <ejb-class>" + DescriptorBean.class.getName() + "</ejb-class>\n" + " <session-type>Stateful</session-type>\n" + " <stateful-timeout>\n" + " <timeout>1</timeout>\n" + " <unit>Seconds</unit>\n" + " </stateful-timeout>\n" + " <concurrency-management-type>Container</concurrency-management-type>\n" + " </session>\n" + " </enterprise-beans>\n" + "</ejb-jar>"; @ArquillianResource InitialContext iniCtx; @Inject UserTransaction userTransaction; <T> T lookup(Class<T> beanType) throws NamingException { return beanType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanType.getSimpleName() + "!" + beanType.getName())); } void testStatefulTimeoutFromAnnotation() throws Exception { AnnotatedBean sfsb1 = lookup(AnnotatedBean.class); Assert.assertFalse(AnnotatedBean.preDestroy); sfsb1.doStuff(); Thread.sleep(2000); try { sfsb1.doStuff(); throw new RuntimeException("Expecting NoSuchEjbException"); } catch (NoSuchEJBException expected) { } Assert.assertTrue(AnnotatedBean.preDestroy); } void testStatefulTimeoutWithPassivation() throws Exception { PassivatingBean sfsb1 = lookup(PassivatingBean.class); Assert.assertFalse(PassivatingBean.preDestroy); sfsb1.doStuff(); Thread.sleep(2000); try { sfsb1.doStuff(); throw new RuntimeException("Expecting NoSuchEjbException"); } catch (NoSuchEJBException expected) { } Assert.assertTrue(PassivatingBean.preDestroy); } void testStatefulTimeoutFromDescriptor() throws Exception { DescriptorBean sfsb1 = lookup(DescriptorBean.class); Assert.assertFalse(DescriptorBean.preDestroy); sfsb1.doStuff(); Thread.sleep(2000); try { sfsb1.doStuff(); throw new RuntimeException("Expecting NoSuchEjbException"); } catch (NoSuchEJBException expected) { } Assert.assertTrue(DescriptorBean.preDestroy); } void testStatefulBeanNotDiscardedWhileInTransaction() throws Exception { try { userTransaction.begin(); AnnotatedBean2 sfsb1 = lookup(AnnotatedBean2.class); Assert.assertFalse(AnnotatedBean2.preDestroy); sfsb1.doStuff(); Thread.sleep(2000); sfsb1.doStuff(); Assert.assertFalse(AnnotatedBean2.preDestroy); } finally { userTransaction.commit(); } } void testStatefulBeanWithPassivationNotDiscardedWhileInTransaction() throws Exception { try { userTransaction.begin(); PassivatingBean2 sfsb1 = lookup(PassivatingBean2.class); Assert.assertFalse(PassivatingBean2.preDestroy); sfsb1.doStuff(); Thread.sleep(2000); sfsb1.doStuff(); Assert.assertFalse(PassivatingBean2.preDestroy); } finally { userTransaction.commit(); } } }
5,376
37.407143
145
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/timeout/PassivatingBean2.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.ejb.stateful.timeout; import java.util.concurrent.TimeUnit; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.ejb.Stateful; import jakarta.ejb.StatefulTimeout; import org.jboss.ejb3.annotation.Cache; /** * stateful session bean */ @Stateful @Cache("distributable") @StatefulTimeout(value = 1000, unit = TimeUnit.MILLISECONDS) public class PassivatingBean2 { static volatile boolean preDestroy; @PostConstruct private void postConstruct() { preDestroy = false; } @PreDestroy private void preDestroy() { preDestroy = true; } public void doStuff() { } }
1,717
30.236364
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/timeout/AnnotatedBean2.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.ejb.stateful.timeout; import java.util.concurrent.TimeUnit; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.ejb.Stateful; import jakarta.ejb.StatefulTimeout; /** * stateful session bean */ @Stateful @StatefulTimeout(value = 1000, unit = TimeUnit.MILLISECONDS) public class AnnotatedBean2 { static volatile boolean preDestroy; @PostConstruct private void postConstruct() { preDestroy = false; } @PreDestroy private void preDestroy() { preDestroy = true; } public void doStuff() { } }
1,650
30.75
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/timeout/Annotated0TimeoutBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ejb.stateful.timeout; import jakarta.annotation.PreDestroy; import jakarta.ejb.Stateful; import jakarta.ejb.StatefulTimeout; import java.util.concurrent.TimeUnit; /** * stateful session bean with timeout value 0. */ @Stateful @StatefulTimeout(value = 0, unit = TimeUnit.MILLISECONDS) public class Annotated0TimeoutBean { public static volatile boolean preDestroy = false; @PreDestroy public void preDestroy() { preDestroy = true; } public void doStuff() { } }
1,561
32.234043
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/timeout/DefaultStatefulTimeout1000TestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ejb.stateful.timeout; import jakarta.ejb.NoSuchEJBException; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.ManagementOperations; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests that the default stateful timeout value 1000 configured in the server works. */ @RunWith(Arquillian.class) @ServerSetup(DefaultStatefulTimeout1000TestCase.ServerSetup.class) public class DefaultStatefulTimeout1000TestCase extends StatefulTimeoutTestBase2 { /** * stateful timeout is configured with annotation by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulTimeoutFromAnnotation() throws Exception { super.testStatefulTimeoutFromAnnotation(); } /** * stateful timeout is configured with annotation by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulTimeoutWithPassivation() throws Exception { super.testStatefulTimeoutWithPassivation(); } /** * stateful timeout is configured with descriptor by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulTimeoutFromDescriptor() throws Exception { super.testStatefulTimeoutFromDescriptor(); } /** * stateful timeout is configured with annotation by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulBeanNotDiscardedWhileInTransaction() throws Exception { super.testStatefulBeanNotDiscardedWhileInTransaction(); } /** * stateful timeout is configured with annotation by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulBeanWithPassivationNotDiscardedWhileInTransaction() throws Exception { super.testStatefulBeanWithPassivationNotDiscardedWhileInTransaction(); } /** * Verifies that a stateful bean that does not configure stateful timeout via annotation or descriptor * will take the configured server default-stateful-bean-session-timeout (1000 milliseconds) */ @Test public void testNoTimeoutByApplication() throws Exception { Assert.assertEquals(1000, readAttribute().asLong()); TimeoutNotConfiguredBean timeoutNotConfiguredBean = lookup(TimeoutNotConfiguredBean.class); Assert.assertFalse(TimeoutNotConfiguredBean.preDestroy); timeoutNotConfiguredBean.doStuff(); Thread.sleep(2000); try { timeoutNotConfiguredBean.doStuff(); throw new RuntimeException("Expecting NoSuchEJBException"); } catch (NoSuchEJBException expected) { //ignore } Assert.assertTrue(TimeoutNotConfiguredBean.preDestroy); } /** * The server setup task that configures ejb3 subsystem attribute default-stateful-bean-session-timeout. */ public static class ServerSetup extends SnapshotRestoreSetupTask { protected void doSetup(ManagementClient client, String containerId) throws Exception { ModelNode writeDefaultStatefulTimeoutOp = Util.getWriteAttributeOperation(EJB3_ADDRESS, DEFAULT_STATEFUL_TIMEOUT_NAME, 1000); ManagementOperations.executeOperation(client.getControllerClient(), writeDefaultStatefulTimeoutOp); } } }
4,902
39.520661
137
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/timeout/TimeoutNotConfiguredBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ejb.stateful.timeout; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.ejb.Stateful; /** * stateful session bean that does not configure stateful timeout via annotation or deployment descriptor. */ @Stateful public class TimeoutNotConfiguredBean { static volatile boolean preDestroy; @PostConstruct private void postConstruct() { preDestroy = false; } @PreDestroy private void preDestroy() { preDestroy = true; } public void doStuff() { } }
1,607
31.816327
106
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/timeout/DefaultStatefulTimeout0TestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ejb.stateful.timeout; import jakarta.ejb.NoSuchEJBException; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.ManagementOperations; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests that the default stateful timeout value 0 configured in the server works. */ @RunWith(Arquillian.class) @ServerSetup(DefaultStatefulTimeout0TestCase.ServerSetup.class) public class DefaultStatefulTimeout0TestCase extends StatefulTimeoutTestBase2 { private static final int CONFIGURED_TIMEOUT = 0; /** * stateful timeout is configured with annotation by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulTimeoutFromAnnotation() throws Exception { super.testStatefulTimeoutFromAnnotation(); } /** * stateful timeout is configured with annotation by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulTimeoutWithPassivation() throws Exception { super.testStatefulTimeoutWithPassivation(); } /** * stateful timeout is configured with descriptor by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulTimeoutFromDescriptor() throws Exception { super.testStatefulTimeoutFromDescriptor(); } /** * stateful timeout is configured with annotation by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulBeanNotDiscardedWhileInTransaction() throws Exception { super.testStatefulBeanNotDiscardedWhileInTransaction(); } /** * stateful timeout is configured with annotation by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulBeanWithPassivationNotDiscardedWhileInTransaction() throws Exception { super.testStatefulBeanWithPassivationNotDiscardedWhileInTransaction(); } /** * Verifies that a stateful bean that does not configure stateful timeout via annotation or descriptor * will take the configured server default-stateful-bean-session-timeout (0 milliseconds, immediate timeout) */ @Test public void testNoTimeoutByApplication() throws Exception { Assert.assertEquals(CONFIGURED_TIMEOUT, readAttribute().asLong()); TimeoutNotConfiguredBean timeoutNotConfiguredBean = lookup(TimeoutNotConfiguredBean.class); timeoutNotConfiguredBean.doStuff(); Thread.sleep(2000); try { timeoutNotConfiguredBean.doStuff(); throw new RuntimeException("Expecting NoSuchEJBException"); } catch (NoSuchEJBException expected) { //ignore } //re-configure the server default-stateful-bean-session-timeout to 600,000, and then 0 milliseconds, try { writeAttribute(600_000); Assert.assertEquals(600_000, readAttribute().asLong()); } finally { writeAttribute(CONFIGURED_TIMEOUT); } } /** * The server setup task that configures ejb3 subsystem attribute default-stateful-bean-session-timeout. */ public static class ServerSetup extends SnapshotRestoreSetupTask { protected void doSetup(ManagementClient client, String containerId) throws Exception { ModelNode writeDefaultStatefulTimeoutOp = Util.getWriteAttributeOperation(EJB3_ADDRESS, DEFAULT_STATEFUL_TIMEOUT_NAME, CONFIGURED_TIMEOUT); ManagementOperations.executeOperation(client.getControllerClient(), writeDefaultStatefulTimeoutOp); } } }
5,168
39.382813
151
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/timeout/DefaultStatefulTimeoutNegative1TestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ejb.stateful.timeout; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.ManagementOperations; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests that the default stateful timeout value -1 configured in the server works. */ @RunWith(Arquillian.class) @ServerSetup(DefaultStatefulTimeoutNegative1TestCase.ServerSetup.class) public class DefaultStatefulTimeoutNegative1TestCase extends StatefulTimeoutTestBase2 { private static final int CONFIGURED_TIMEOUT = -1; /** * stateful timeout is configured with annotation by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulTimeoutFromAnnotation() throws Exception { Assert.assertEquals(CONFIGURED_TIMEOUT, readAttribute().asLong()); super.testStatefulTimeoutFromAnnotation(); } /** * stateful timeout is configured with annotation by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulTimeoutWithPassivation() throws Exception { super.testStatefulTimeoutWithPassivation(); } /** * stateful timeout is configured with descriptor by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulTimeoutFromDescriptor() throws Exception { super.testStatefulTimeoutFromDescriptor(); } /** * stateful timeout is configured with annotation by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulBeanNotDiscardedWhileInTransaction() throws Exception { super.testStatefulBeanNotDiscardedWhileInTransaction(); } /** * stateful timeout is configured with annotation by application, and the server * default-stateful-bean-session-timeout must not take effect. */ @Test public void testStatefulBeanWithPassivationNotDiscardedWhileInTransaction() throws Exception { super.testStatefulBeanWithPassivationNotDiscardedWhileInTransaction(); } /** * Verifies that a stateful bean that does not configure stateful timeout via annotation or descriptor * will take the configured server default-stateful-bean-session-timeout (-1, no timeout or removal) */ @Test public void testNoTimeoutByApplication() throws Exception { TimeoutNotConfiguredBean timeoutNotConfiguredBean = lookup(TimeoutNotConfiguredBean.class); timeoutNotConfiguredBean.doStuff(); Thread.sleep(2000); timeoutNotConfiguredBean.doStuff(); Assert.assertFalse(TimeoutNotConfiguredBean.preDestroy); } /** * The server setup task that configures ejb3 subsystem attribute default-stateful-bean-session-timeout. */ public static class ServerSetup extends SnapshotRestoreSetupTask { protected void doSetup(ManagementClient client, String containerId) throws Exception { ModelNode writeDefaultStatefulTimeoutOp = Util.getWriteAttributeOperation(EJB3_ADDRESS, DEFAULT_STATEFUL_TIMEOUT_NAME, CONFIGURED_TIMEOUT); ManagementOperations.executeOperation(client.getControllerClient(), writeDefaultStatefulTimeoutOp); } } }
4,726
40.831858
151
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/locking/AccessSerializationTestCase.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.ejb.stateful.locking; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.naming.InitialContext; import org.junit.Assert; 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.Test; import org.junit.runner.RunWith; /** * Tests that multiple calls to a SFSB are serialized correctly in both the presence and the absence of a transaction * * @author Stuart Douglas */ @RunWith(Arquillian.class) public class AccessSerializationTestCase { private static final String ARCHIVE_NAME = "AccessSerializationTestCase"; private static final int NUM_THREADS = 10; public static final int SUM_AMOUNT = 10; @ArquillianResource private InitialContext initialContext; @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addPackage(AccessSerializationTestCase.class.getPackage()); return jar; } @Test public void testConcurrentAccessTransaction() throws Exception { ConcurrencySFSB sfsb = (ConcurrencySFSB)initialContext.lookup("java:module/" + ConcurrencySFSB.class.getSimpleName() ); ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS); Future[] results = new Future[NUM_THREADS]; for(int i = 0; i < NUM_THREADS; ++i) { results[i] = executorService.submit(new CallingClassTransaction(sfsb)); } for(int i = 0; i < NUM_THREADS; ++i) { results[i].get(); } Assert.assertEquals(NUM_THREADS * SUM_AMOUNT, sfsb.getCounter()); } @Test public void testConcurrentAccessNoTransaction() throws Exception { ConcurrencySFSB sfsb = (ConcurrencySFSB)initialContext.lookup("java:module/" + ConcurrencySFSB.class.getSimpleName() ); ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS); Future[] results = new Future[NUM_THREADS]; for(int i = 0; i < NUM_THREADS; ++i) { results[i] = executorService.submit(new CallingClassNoTransaction(sfsb)); } for(int i = 0; i < NUM_THREADS; ++i) { results[i].get(); } Assert.assertEquals(NUM_THREADS * SUM_AMOUNT, sfsb.getCounter()); } private class CallingClassTransaction implements Runnable { private final ConcurrencySFSB sfsb; private CallingClassTransaction(final ConcurrencySFSB sfsb) { this.sfsb = sfsb; } @Override public void run() { try { sfsb.addTx(SUM_AMOUNT); } catch (Exception e) { throw new RuntimeException(e); } } } private class CallingClassNoTransaction implements Runnable { private final ConcurrencySFSB sfsb; private CallingClassNoTransaction(final ConcurrencySFSB sfsb) { this.sfsb = sfsb; } @Override public void run() { try { sfsb.addNoTx(SUM_AMOUNT); } catch (Exception e) { throw new RuntimeException(e); } } } }
4,529
33.318182
127
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/locking/ConcurrencySFSB.java
package org.jboss.as.test.integration.ejb.stateful.locking; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; /** * @author Stuart Douglas */ @Stateful public class ConcurrencySFSB { private int counter; public void addTx(int sum) { counter = counter + sum; } @TransactionAttribute(TransactionAttributeType.NEVER) public void addNoTx(int sum) { counter = counter + sum; } public int getCounter() { return counter; } }
547
18.571429
59
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/locking/reentrant/ReentrantLockTestCase.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.ejb.stateful.locking.reentrant; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; 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.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.inject.Inject; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.transaction.UserTransaction; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Tests that multiple calls to a SFSB in the same TX release the lock correctly. * * @author Stuart Douglas */ @RunWith(Arquillian.class) public class ReentrantLockTestCase { private static final String ARCHIVE_NAME = "ReentrantLockTestCase"; private static InitialContext iniCtx; @Inject private UserTransaction userTransaction; @Inject private SimpleSFSB simpleSFSB; private static final int NUM_THREADS = 5; @BeforeClass public static void beforeClass() throws NamingException { iniCtx = new InitialContext(); } @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addPackage(ReentrantLockTestCase.class.getPackage()); jar.add(EmptyAsset.INSTANCE, "META-INF/beans.xml"); return jar; } @Test public void testStatefulTimeoutFromAnnotation() throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS); Future[] results = new Future[NUM_THREADS]; for(int i = 0; i < NUM_THREADS; ++i) { results[i] = executorService.submit(new CallingClass()); } for(int i = 0; i < NUM_THREADS; ++i) { results[i].get(); } } private class CallingClass implements Runnable { @Override public void run() { try { userTransaction.begin(); simpleSFSB.doStuff(); simpleSFSB.doStuff(); userTransaction.commit(); } catch (Exception e) { throw new RuntimeException(e); } } } }
3,453
29.839286
86
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/locking/reentrant/SimpleSFSB.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.ejb.stateful.locking.reentrant; import jakarta.ejb.AccessTimeout; import jakarta.ejb.Stateful; import java.util.concurrent.TimeUnit; /** * stateful session bean * */ @Stateful @AccessTimeout(value=2, unit = TimeUnit.SECONDS) public class SimpleSFSB { public void doStuff() { } }
1,356
32.097561
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/persistencecontext/StatefulBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ejb.stateful.persistencecontext; import java.io.Serializable; import jakarta.annotation.Resource; import jakarta.ejb.Remove; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateful; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceContextType; import org.jboss.ejb3.annotation.Cache; /** * @author <a href="mailto:[email protected]">Bill Burke</a> */ @Stateful @Cache("distributable") public class StatefulBean implements Serializable, StatefulRemote { private static final long serialVersionUID = 1L; @PersistenceContext(type = PersistenceContextType.EXTENDED) EntityManager manager; @Resource SessionContext ctx; public int doit() { Customer cust = new Customer(); cust.setName("Bill"); manager.persist(cust); return cust.getId(); } public void find(int id) { if (manager.find(Customer.class, id) == null) throw new RuntimeException("not found"); } @Remove @Override public void close() { } }
2,154
30.691176
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/persistencecontext/NonExtendedStatefuBean.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.ejb.stateful.persistencecontext; import java.io.Serializable; import jakarta.ejb.Remove; import jakarta.ejb.Stateful; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import org.jboss.ejb3.annotation.Cache; /** * @author <a href="mailto:[email protected]">Bill Burke</a> */ @Stateful @Cache("distributable") public class NonExtendedStatefuBean implements Serializable, StatefulRemote { private static final long serialVersionUID = 1L; @PersistenceContext EntityManager manager; public int doit() { Customer cust = new Customer(); cust.setName("Bill"); manager.persist(cust); return cust.getId(); } public void find(int id) { if (manager.find(Customer.class, id) == null) throw new RuntimeException("not found"); } @Remove @Override public void close() { } }
1,963
30.677419
77
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/persistencecontext/StatefulTransientBean.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.ejb.stateful.persistencecontext; import java.io.Serializable; import jakarta.ejb.Remove; import jakarta.ejb.Stateful; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceContextType; import jakarta.persistence.Transient; import org.jboss.ejb3.annotation.Cache; /** * @author <a href="mailto:[email protected]">Bill Burke</a> */ @Stateful @Cache("distributable") public class StatefulTransientBean implements Serializable, StatefulRemote { private static final long serialVersionUID = 1L; @Transient @PersistenceContext(type = PersistenceContextType.EXTENDED) EntityManager manager; public int doit() { Customer cust = new Customer(); cust.setName("Bill"); manager.persist(cust); return cust.getId(); } public void find(int id) { if (manager.find(Customer.class, id) == null) throw new RuntimeException("not found"); } @Remove @Override public void close() { } }
2,106
31.415385
76
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/persistencecontext/StatefulRemote.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.ejb.stateful.persistencecontext; import jakarta.ejb.Remote; /** * @author <a href="mailto:[email protected]">Bill Burke</a> */ @Remote public interface StatefulRemote extends AutoCloseable { int doit(); void find(int id); @Override void close(); }
1,329
33.102564
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/persistencecontext/Customer.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.ejb.stateful.persistencecontext; import java.io.Serializable; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; /** * @author <a href="mailto:[email protected]">Bill Burke</a> */ @Entity public class Customer implements Serializable { private static final long serialVersionUID = 1L; private int id; private String name; @Id @GeneratedValue(strategy = GenerationType.AUTO) public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
1,803
29.576271
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/persistencecontext/StatefulUnitTestCase.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.ejb.stateful.persistencecontext; import javax.naming.InitialContext; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; /** * Extended persistent context passivated in SFSB. * Part of the migration of tests from EJB3 testsuite to AS7 testsuite [JBQA-5483]. * * @author Bill Burke, Ondrej Chaloupka */ @RunWith(Arquillian.class) @ServerSetup(StatefulUnitTestCase.StatefulUnitTestCaseSetup.class) public class StatefulUnitTestCase { private static final Logger log = Logger.getLogger(StatefulUnitTestCase.class); private static final int TIME_TO_WAIT_FOR_PASSIVATION_MS = 1000; @ArquillianResource InitialContext ctx; static boolean deployed = false; static int test = 0; @Deployment public static Archive<?> deploy() throws Exception { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "persistentcontext-test.jar"); jar.addPackage(StatefulUnitTestCase.class.getPackage()); jar.addAsManifestResource(StatefulUnitTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); jar.addAsManifestResource(new StringAsset("Dependencies: org.jboss.as.controller-client, org.jboss.dmr, org.jboss.marshalling \n"), "MANIFEST.MF"); return jar; } @Test public void testStateful() throws Exception { try (StatefulRemote remote = (StatefulRemote) ctx.lookup("java:module/" + StatefulBean.class.getSimpleName() + "!" + StatefulRemote.class.getName())) { int id = remote.doit(); try (StatefulRemote remote2 = (StatefulRemote) ctx.lookup("java:module/" + StatefulBean.class.getSimpleName() + "!" + StatefulRemote.class.getName())) { Thread.sleep(TIME_TO_WAIT_FOR_PASSIVATION_MS); remote.find(id); } } } @Test public void testTransientStateful() throws Exception { try (StatefulRemote remote = (StatefulRemote) ctx.lookup("java:module/" + StatefulTransientBean.class.getSimpleName() + "!" + StatefulRemote.class.getName())) { int id = remote.doit(); try (StatefulRemote remote2 = (StatefulRemote) ctx.lookup("java:module/" + StatefulTransientBean.class.getSimpleName() + "!" + StatefulRemote.class.getName())) { Thread.sleep(TIME_TO_WAIT_FOR_PASSIVATION_MS); remote.find(id); } } } @Test public void testNonExtended() throws Exception { try (StatefulRemote remote = (StatefulRemote) ctx.lookup("java:module/" + NonExtendedStatefuBean.class.getSimpleName() + "!" + StatefulRemote.class.getName())) { int id = remote.doit(); try (StatefulRemote remote2 = (StatefulRemote) ctx.lookup("java:module/" + NonExtendedStatefuBean.class.getSimpleName() + "!" + StatefulRemote.class.getName())) { Thread.sleep(TIME_TO_WAIT_FOR_PASSIVATION_MS); remote.find(id); } } } /** * This test originally depended upon manipulatng the passivation-store for the default (passivating) cache. * However, since WFLY-14953, passivation stores have been superceeded by bean-management-providers * i.e. use /subsystem=distributable-ejb/infinispan-bean-management=default instead of /subsystem=ejb3/passicvation-store=infinispan */ static class StatefulUnitTestCaseSetup implements ServerSetupTask { private static final PathAddress INFINISPAN_BEAN_MANAGEMENT_PATH = PathAddress.pathAddress(PathElement.pathElement("subsystem", "distributable-ejb"), PathElement.pathElement("infinispan-bean-management", "default")); /* * Set the max-active-beans attribute of the bean-management provider to 1 to force passivation. */ @Override public void setup(final ManagementClient managementClient, final String containerId) throws Exception { ModelNode operation = Util.getWriteAttributeOperation(INFINISPAN_BEAN_MANAGEMENT_PATH, "max-active-beans", 1); ModelNode result = managementClient.getControllerClient().execute(operation); log.trace("modelnode operation write-attribute max-active-beans=1: " + result); Assert.assertEquals(SUCCESS, result.get(OUTCOME).asString()); ServerReload.reloadIfRequired(managementClient); } /* * Return max-active-beans to its configured value (10,000). * NOTE: the configured default is 10000 but may change over time. */ @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { ModelNode operation = Util.getWriteAttributeOperation(INFINISPAN_BEAN_MANAGEMENT_PATH, "max-active-beans", 10000); ModelNode result = managementClient.getControllerClient().execute(operation); Assert.assertEquals(SUCCESS, result.get(OUTCOME).asString()); ServerReload.reloadIfRequired(managementClient); } } }
7,020
46.761905
174
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/passivation/PassivationEnabledBean.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.ejb.stateful.passivation; import jakarta.ejb.Local; import jakarta.ejb.PostActivate; import jakarta.ejb.PrePassivate; import jakarta.ejb.Remove; import jakarta.ejb.Stateful; import org.jboss.ejb3.annotation.Cache; /** * @author Jaikiran Pai */ @Stateful(passivationCapable = true) @Cache("distributable") @Local(Bean.class) public class PassivationEnabledBean implements Bean { private boolean prePrePassivateInvoked; private boolean postActivateInvoked; @PrePassivate private void beforePassivate() { this.prePrePassivateInvoked = true; } @PostActivate private void afterActivate() { this.postActivateInvoked = true; } @Override public boolean wasPassivated() { return this.prePrePassivateInvoked; } @Override public boolean wasActivated() { return this.postActivateInvoked; } @Remove @Override public void close() { } }
1,999
27.985507
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/passivation/PassivationTestCaseSetup.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.ejb.stateful.passivation; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; 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.PathElement; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.junit.Assert; /** * Setup for passivation test case. * * @author Stuart Douglas, Ondrej Chaloupka * @author Richard Achmatowicz */ public class PassivationTestCaseSetup implements ServerSetupTask { private static final Logger log = Logger.getLogger(PassivationTestCaseSetup.class); /** * This test setup originally depended upon manipulating the passivation-store for the default (passivating) cache. * However, since WFLY-14953, passivation stores have been superceeded by bean-management-providers * (i.e. use /subsystem=distributable-ejb/infinispan-bean-management=default instead of /subsystem=ejb3/passivation-store=infinispan) */ private static final PathAddress INFINISPAN_BEAN_MANAGEMENT_PATH = PathAddress.pathAddress(PathElement.pathElement("subsystem", "distributable-ejb"), PathElement.pathElement("infinispan-bean-management", "default")); /* * Set the max-acive-beans attribute of the bean-management provider to 1 to force passivation. */ @Override public void setup(final ManagementClient managementClient, final String containerId) throws Exception { ModelNode operation = Util.getWriteAttributeOperation(INFINISPAN_BEAN_MANAGEMENT_PATH, "max-active-beans", 1); ModelNode result = managementClient.getControllerClient().execute(operation); log.trace("modelnode operation write-attribute max-active-beans=1: " + result); Assert.assertEquals(SUCCESS, result.get(OUTCOME).asString()); ServerReload.reloadIfRequired(managementClient); } /* * Return max-active-beans to its configured value (10,000). * NOTE: the configured default is 10000 but may change over time. */ @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { ModelNode operation = Util.getWriteAttributeOperation(INFINISPAN_BEAN_MANAGEMENT_PATH, "max-active-beans", 10000); ModelNode result = managementClient.getControllerClient().execute(operation); Assert.assertEquals(SUCCESS, result.get(OUTCOME).asString()); ServerReload.reloadIfRequired(managementClient); } }
3,826
48.064103
153
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/passivation/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.ejb.stateful.passivation; import java.io.Serializable; import jakarta.persistence.Entity; import jakarta.persistence.Id; /** * Employee entity class * * @author Scott Marlow */ @Entity public class Employee implements Serializable { @Id private int id; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
1,601
26.152542
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/passivation/Bean.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.ejb.stateful.passivation; /** * @author Paul Ferraro */ public interface Bean extends AutoCloseable { /** * Returns whether or not this instance has been passivated */ boolean wasPassivated(); /** * Returns whether or not this instance has been activated */ boolean wasActivated(); default void doNothing() { } @Override void close(); }
1,457
31.4
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/passivation/PassivationSuperClass.java
package org.jboss.as.test.integration.ejb.stateful.passivation; import jakarta.annotation.PostConstruct; /** * AS7-3716 * * We also need to make sure that a beans super class is still serialized even when it is not * marked serializable * * @author Stuart Douglas */ public class PassivationSuperClass { private Employee superEmployee; @PostConstruct private void postConstruct() { superEmployee = new Employee(); superEmployee.setName("Super"); } public Employee getSuperEmployee() { return superEmployee; } }
571
20.185185
93
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/stateful/passivation/PassivationFailedTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ejb.stateful.passivation; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.util.PropertyPermission; import jakarta.ejb.NoSuchEJBException; import javax.naming.InitialContext; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.shrinkwrap.api.Archive; 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.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * @author Paul Ferraro */ @RunWith(Arquillian.class) @ServerSetup(PassivationTestCaseSetup.class) public class PassivationFailedTestCase { @ArquillianResource private InitialContext ctx; @Deployment public static Archive<?> deploy() throws Exception { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, PassivationFailedTestCase.class.getSimpleName() + ".jar"); jar.addPackage(PassivationTestCase.class.getPackage()); jar.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); jar.addAsManifestResource(new StringAsset("Dependencies: org.jboss.as.controller-client, org.jboss.dmr \n"), "MANIFEST.MF"); jar.addAsManifestResource(PassivationTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); jar.addAsManifestResource(PassivationTestCase.class.getPackage(), "ejb-jar.xml", "ejb-jar.xml"); jar.addAsManifestResource(createPermissionsXmlAsset(new PropertyPermission("ts.timeout.factor", "read")), "jboss-permissions.xml"); return jar; } /** * Tests passivation of bean that throws exception during serialization. */ @Test public void testPassivationFailure() throws Exception { PassivationInterceptor.reset(); // create first bean try (TestPassivationRemote remote1 = (TestPassivationRemote) ctx.lookup("java:module/" + BeanWithSerializationIssue.class.getSimpleName())) { // make an invocation Assert.assertEquals("Returned remote1 result was not expected", TestPassivationRemote.EXPECTED_RESULT, remote1.returnTrueString()); // create second bean, this should force the first bean to passivate try (TestPassivationRemote remote2 = (TestPassivationRemote) ctx.lookup("java:module/" + BeanWithSerializationIssue.class.getSimpleName())) { // make an invocation Assert.assertEquals("Returned remote2 result was not expected", TestPassivationRemote.EXPECTED_RESULT, remote2.returnTrueString()); // verify that a bean was prePassivated TestPassivationBean target = (TestPassivationBean) PassivationInterceptor.getPrePassivateTarget(); Assert.assertNotNull(target); // verify that bean was not postActivated yet Assert.assertTrue(target.hasBeenPassivated()); // From EJB 4.2.1: // The container may destroy a session bean instance if the instance does not meet the requirements for serialization after PrePassivate. try { // At least one of these invocations should fail remote1.returnTrueString(); Assert.fail("Invocation of pre-passivated EJB should not succeed since passivation failed"); } catch (NoSuchEJBException e) { // Expected } // No EJBs should have activated, since they were unable to passivate Assert.assertTrue(PassivationInterceptor.getPostActivateTarget() == null); } catch (NoSuchEJBException e) { // Expected } } catch (NoSuchEJBException e) { // Expected } PassivationInterceptor.reset(); } }
5,141
46.174312
153
java