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/ws/src/test/java/org/jboss/as/test/integration/ws/basic/InstanceCountEndpointIface.java
|
package org.jboss.as.test.integration.ws.basic;
import jakarta.jws.WebService;
@WebService
public interface InstanceCountEndpointIface {
int getInstanceCount();
String test(String payload);
}
| 203 | 17.545455 | 47 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/authentication/EJBEndpointIface.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.authentication;
import jakarta.jws.WebService;
/**
* @author Rostislav Svoboda
*/
@WebService
public interface EJBEndpointIface {
String hello(String input);
String helloForAll(String input);
String helloForNone(String input);
String helloForRole(String input);
String helloForRoles(String input);
}
| 1,402 | 32.404762 | 70 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/authentication/EJBEndpointSecuredWSDLAccessTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.authentication;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import javax.xml.namespace.QName;
import jakarta.xml.ws.Service;
import jakarta.xml.ws.WebServiceException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.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.security.common.Utils;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.common.iteration.ByteIterator;
/**
* Tests for secured access to WSDL for EJB endpoint
*
* @author Rostislav Svoboda
*/
@RunWith(Arquillian.class)
@RunAsClient
public class EJBEndpointSecuredWSDLAccessTestCase {
@ArquillianResource
URL baseUrl;
@Deployment(testable = false)
public static Archive<?> deployment() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "jaxws-authentication-ejb3-for-wsdl.jar")
.addClasses(EJBEndpointIface.class, EJBEndpointSecuredWSDLAccess.class);
return jar;
}
@Test
public void createService() throws Exception {
QName serviceName = new QName("http://jbossws.org/authenticationForWSDL", "EJB3ServiceForWSDL");
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3-for-wsdl/EJB3ServiceForWSDL?wsdl");
try {
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Assert.fail("Proxy shouldn't be created because WSDL access should be secured");
} catch (WebServiceException e) {
// failure is expected
}
}
@Test
public void accessWSDLWithValidUsernameAndPassword() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3-for-wsdl/EJB3ServiceForWSDL?wsdl");
String encoding = base64Encode("user1:password1");
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet(wsdlURL.toString());
httpget.setHeader("Authorization", "Basic " + encoding);
try (CloseableHttpResponse response = httpClient.execute(httpget)) {
String text = Utils.getContent(response);
Assert.assertTrue("Response doesn't contain wsdl file", text.contains("wsdl:binding"));
}
}
}
@Test
public void accessWSDLWithValidUsernameAndPasswordButInvalidRole() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3-for-wsdl/EJB3ServiceForWSDL?wsdl");
String encoding = base64Encode("user2:password2");
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet(wsdlURL.toString());
httpget.setHeader("Authorization", "Basic " + encoding);
try (CloseableHttpResponse response = httpClient.execute(httpget)) {
Assert.assertEquals(403, response.getStatusLine().getStatusCode());
Utils.getContent(response);
//Assert.assertTrue("Response doesn't contain access denied message", text.contains("Access to the requested resource has been denied"));
}
}
}
@Test
public void accessWSDLWithInvalidUsernameAndPassword() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3-for-wsdl/EJB3ServiceForWSDL?wsdl");
String encoding = base64Encode("user1:password-XZY");
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet(wsdlURL.toString());
httpget.setHeader("Authorization", "Basic " + encoding);
try (CloseableHttpResponse response = httpClient.execute(httpget)) {
Assert.assertEquals(401, response.getStatusLine().getStatusCode());
Utils.getContent(response);
//Assert.assertTrue("Response doesn't contain expected message.", text.contains("This request requires HTTP authentication"));
}
}
}
@Test
public void accessWSDLWithoutUsernameAndPassword() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3-for-wsdl/EJB3ServiceForWSDL?wsdl");
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet(wsdlURL.toString());
try (CloseableHttpResponse response = httpClient.execute(httpget)) {
Assert.assertEquals(401, response.getStatusLine().getStatusCode());
Utils.getContent(response);
//Assert.assertTrue("Response doesn't contain expected message.", text.contains("This request requires HTTP authentication"));
}
}
}
private static String base64Encode(final String original) {
return ByteIterator.ofBytes(original.getBytes(StandardCharsets.UTF_8)).base64Encode().drainToString();
}
}
| 6,514 | 41.305195 | 153 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/authentication/EJBNoCLSAEndpoint.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.authentication;
import org.jboss.ejb3.annotation.SecurityDomain;
import org.jboss.ws.api.annotation.AuthMethod;
import org.jboss.ws.api.annotation.TransportGuarantee;
import org.jboss.ws.api.annotation.WebContext;
import jakarta.annotation.security.DenyAll;
import jakarta.annotation.security.PermitAll;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ejb.Stateless;
import jakarta.jws.WebService;
/**
* Simple EJB3 endpoint
*
* @author Rostislav Svoboda
*/
@WebService(
serviceName = "EJB3NoCLSAAuthService",
targetNamespace = "http://jbossws.org/authentication",
endpointInterface = "org.jboss.as.test.integration.ws.authentication.EJBEndpointIface"
)
@WebContext(
urlPattern = "/EJB3NoCLSAAuthService",
contextRoot = "/jaxws-authentication-no-cla-ejb3",
authMethod = AuthMethod.BASIC,
transportGuarantee = TransportGuarantee.NONE,
secureWSDLAccess = false
)
@Stateless
@SecurityDomain("other")
public class EJBNoCLSAEndpoint implements EJBEndpointIface {
public String hello(String input) {
return "Hello " + input + "!";
}
@PermitAll
public String helloForAll(String input) {
return "Hello " + input + "!";
}
@DenyAll
public String helloForNone(String input) {
return "Hello " + input + "!";
}
@RolesAllowed("Role2")
public String helloForRole(String input) {
return "Hello " + input + "!";
}
@RolesAllowed({"Role1", "Role2"})
public String helloForRoles(String input) {
return "Hello " + input + "!";
}
}
| 2,672 | 32 | 94 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/authentication/EJBEndpointAuthenticationTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.authentication;
import java.net.URL;
import java.util.Map;
import java.util.regex.Pattern;
import javax.xml.namespace.QName;
import jakarta.xml.ws.BindingProvider;
import jakarta.xml.ws.Service;
import jakarta.xml.ws.WebServiceException;
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.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;
/**
* Tests for authentication against EJB endpoint
*
* @author Rostislav Svoboda
*/
@RunWith(Arquillian.class)
@RunAsClient
public class EJBEndpointAuthenticationTestCase {
@ArquillianResource
URL baseUrl;
QName serviceName = new QName("http://jbossws.org/authentication", "EJB3AuthService");
@Deployment(testable = false)
public static Archive<?> deployment() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "jaxws-authentication-ejb.jar")
.addClasses(EJBEndpointIface.class, EJBEndpoint.class);
return jar;
}
// ------------------------------------------------------------------------------
//
// Tests for hello method
//
@Test
public void accessHelloWithoutUsernameAndPassord() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
try {
proxy.hello("World");
Assert.fail("Test should fail, HTTP response '401: Unauthorized' was expected");
} catch (WebServiceException e) {
// failure is expected
Assert.assertTrue("HTTPException '401: Unauthorized' was expected", e.getCause().getMessage().contains("401: Unauthorized"));
}
}
@Test
public void accessHelloWithBadPassword() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user1");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password-XYZ");
try {
proxy.hello("World");
Assert.fail("Test should fail, HTTP response '401: Unauthorized' was expected");
} catch (WebServiceException e) {
// failure is expected
Assert.assertTrue("HTTPException '401: Unauthorized' was expected", e.getCause().getMessage().contains("401: Unauthorized"));
}
}
@Test
public void accessHelloWithUnauthorizedUser() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user2");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password2");
try {
proxy.hello("World");
Assert.fail("Test should fail, user shouldn't be allowed to invoke that method");
} catch (WebServiceException e) {
// failure is expected
checkMessage(e, "hello");
}
}
@Test
public void accessHelloWithValidUser() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user1");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password1");
final String result = proxy.hello("World");
Assert.assertEquals("Hello World!", result);
}
// ------------------------------------------------------------------------------
//
// Tests for helloForRole method
//
@Test
public void accessHelloForRoleWithInvalidRole() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user1");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password1");
try {
proxy.helloForRole("World");
Assert.fail("Test should fail, user shouldn't be allowed to invoke that method");
} catch (WebServiceException e) {
// failure is expected
checkMessage(e, "helloForRole");
}
}
@Test
public void accessHelloForRoleWithValidRole() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user2");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password2");
final String result = proxy.helloForRole("World");
Assert.assertEquals("Hello World!", result);
}
// ------------------------------------------------------------------------------
//
// Tests for helloForRoles method
//
@Test
public void accessHelloForRolesWithValidRole1() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user1");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password1");
final String result = proxy.helloForRoles("World");
Assert.assertEquals("Hello World!", result);
}
@Test
public void accessHelloForRolesWithValidRole2() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user2");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password2");
final String result = proxy.helloForRoles("World");
Assert.assertEquals("Hello World!", result);
}
@Test
public void accessHelloForRolesWithInvalidRole() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "guest");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "guest");
try {
proxy.helloForRoles("World");
Assert.fail("Test should fail, user shouldn't be allowed to invoke that method");
} catch (WebServiceException e) {
// failure is expected
checkMessage(e, "helloForRoles");
}
}
// ------------------------------------------------------------------------------
//
// Tests for helloForAll method
//
@Test
public void accessHelloForAllWithValidRole1() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user1");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password1");
final String result = proxy.helloForAll("World");
Assert.assertEquals("Hello World!", result);
}
@Test
public void accessHelloForAllWithValidRole2() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user2");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password2");
final String result = proxy.helloForAll("World");
Assert.assertEquals("Hello World!", result);
}
@Test
public void accessHelloForAllWithValidRole3() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "guest");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "guest");
final String result = proxy.helloForAll("World");
Assert.assertEquals("Hello World!", result);
}
// ------------------------------------------------------------------------------
//
// Tests for helloForNone method
//
@Test
public void accessHelloForNoneWithValidRole1() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user1");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password1");
try {
proxy.helloForNone("World");
Assert.fail("Test should fail, user shouldn't be allowed to invoke that method");
} catch (WebServiceException e) {
// failure is expected
checkMessage(e, "helloForNone");
}
}
@Test
public void accessHelloForNoneWithValidRole2() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user2");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password2");
try {
proxy.helloForNone("World");
Assert.fail("Test should fail, user shouldn't be allowed to invoke that method");
} catch (WebServiceException e) {
// failure is expected
checkMessage(e, "helloForNone");
}
}
@Test
public void accessHelloForNoneWithValidRole3() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "guest");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "guest");
try {
proxy.helloForNone("World");
Assert.fail("Test should fail, user shouldn't be allowed to invoke that method");
} catch (WebServiceException e) {
// failure is expected
checkMessage(e, "helloForNone");
}
}
private void checkMessage(final Throwable t, final String methodName) {
final Pattern pattern = Pattern.compile("(.*WFLYEJB0364:.*" + methodName + ".*EJBEndpoint.*)");
final String foundMsg = t.getMessage();
Assert.assertTrue(String.format("Expected to find method name %s in error: %s", methodName, foundMsg),
pattern.matcher(t.getMessage()).matches());
}
}
| 14,570 | 39.362881 | 137 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/authentication/EJBEndpointSecuredWSDLAccess.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.authentication;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ejb.Stateless;
import jakarta.jws.WebService;
import org.jboss.ejb3.annotation.SecurityDomain;
import org.jboss.ws.api.annotation.TransportGuarantee;
import org.jboss.ws.api.annotation.AuthMethod;
import org.jboss.ws.api.annotation.WebContext;
/**
* Simple EJB3 endpoint
*
* @author Rostislav Svoboda
*/
@WebService(
serviceName = "EJB3ServiceForWSDL",
targetNamespace = "http://jbossws.org/authenticationForWSDL",
endpointInterface = "org.jboss.as.test.integration.ws.authentication.EJBEndpointIface"
)
@WebContext(
urlPattern = "/EJB3ServiceForWSDL",
contextRoot = "/jaxws-authentication-ejb3-for-wsdl",
authMethod = AuthMethod.BASIC,
transportGuarantee = TransportGuarantee.NONE,
secureWSDLAccess = true
)
@SecurityDomain("other")
@RolesAllowed("Role1")
@Stateless
public class EJBEndpointSecuredWSDLAccess implements EJBEndpointIface {
public String hello(String input) {
return "Hello " + input + "!";
}
public String helloForAll(String input) {
return "Hello " + input + "!";
}
public String helloForNone(String input) {
return "Hello " + input + "!";
}
public String helloForRole(String input) {
return "Hello " + input + "!";
}
public String helloForRoles(String input) {
return "Hello " + input + "!";
}
}
| 2,524 | 32.666667 | 94 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/authentication/EJBEndpoint.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.authentication;
import jakarta.annotation.security.DeclareRoles;
import jakarta.annotation.security.DenyAll;
import jakarta.annotation.security.PermitAll;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ejb.Stateless;
import jakarta.jws.WebService;
import org.jboss.ejb3.annotation.SecurityDomain;
import org.jboss.ws.api.annotation.TransportGuarantee;
import org.jboss.ws.api.annotation.AuthMethod;
import org.jboss.ws.api.annotation.WebContext;
/**
* Simple EJB3 endpoint
*
* @author Rostislav Svoboda
*/
@WebService(
serviceName = "EJB3AuthService",
targetNamespace = "http://jbossws.org/authentication",
endpointInterface = "org.jboss.as.test.integration.ws.authentication.EJBEndpointIface"
)
@WebContext(
urlPattern = "/EJB3AuthService",
contextRoot = "/jaxws-authentication-ejb3",
authMethod = AuthMethod.BASIC,
transportGuarantee = TransportGuarantee.NONE,
secureWSDLAccess = false
)
@Stateless
@SecurityDomain("other")
@DeclareRoles({"Role1", "Role2", "guest"})
@RolesAllowed("Role1")
public class EJBEndpoint implements EJBEndpointIface {
public String hello(String input) {
return "Hello " + input + "!";
}
@PermitAll
public String helloForAll(String input) {
return "Hello " + input + "!";
}
@DenyAll
public String helloForNone(String input) {
return "Hello " + input + "!";
}
@RolesAllowed("Role2")
public String helloForRole(String input) {
return "Hello " + input + "!";
}
@RolesAllowed({"Role1", "Role2"})
public String helloForRoles(String input) {
return "Hello " + input + "!";
}
}
| 2,762 | 31.892857 | 94 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/authentication/PojoEndpointIface.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.authentication;
import jakarta.jws.WebService;
/**
* @author Rostislav Svoboda
*/
@WebService
public interface PojoEndpointIface {
String hello(String input);
}
| 1,242 | 36.666667 | 70 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/authentication/PojoEndpoint.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.authentication;
import jakarta.jws.WebService;
/**
* Simple POJO endpoint
*
* @author Rostislav Svoboda
*/
@WebService(
serviceName = "POJOAuthService",
targetNamespace = "http://jbossws.org/authentication",
endpointInterface = "org.jboss.as.test.integration.ws.authentication.PojoEndpointIface"
)
public class PojoEndpoint implements PojoEndpointIface {
public String hello(String input) {
return "Hello " + input + "!";
}
}
| 1,546 | 35.833333 | 95 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/authentication/EJBEndpointNoClassLevelSecurityAnnotationAuthenticationTestCase.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.ws.authentication;
import static org.hamcrest.CoreMatchers.containsString;
import java.net.URL;
import java.util.Map;
import java.util.regex.Pattern;
import javax.xml.namespace.QName;
import jakarta.xml.ws.BindingProvider;
import jakarta.xml.ws.Service;
import jakarta.xml.ws.WebServiceException;
import org.hamcrest.MatcherAssert;
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.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;
/**
* Tests for authentication against EJB endpoint with no class level security annotation on the endpoint
* https://issues.jboss.org/browse/WFLY-3988
*
* @author Rostislav Svoboda
*/
@RunWith(Arquillian.class)
@RunAsClient
public class EJBEndpointNoClassLevelSecurityAnnotationAuthenticationTestCase {
@ArquillianResource
URL baseUrl;
public static final String deploymentWsdlURL = "/jaxws-authentication-no-cla-ejb3/EJB3NoCLSAAuthService?wsdl";
QName serviceName = new QName("http://jbossws.org/authentication", "EJB3NoCLSAAuthService");
@Deployment(testable = false)
public static Archive<?> deployment() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "jaxws-authentication-no-cla-ejb.jar")
.addClasses(EJBEndpointIface.class, EJBNoCLSAEndpoint.class);
return jar;
}
// ------------------------------------------------------------------------------
//
// Tests for hello method
//
@Test
public void accessHelloWithAuthenticatedUser() throws Exception {
URL wsdlURL = new URL(baseUrl, deploymentWsdlURL);
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user1");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password1");
try {
proxy.hello("World");
Assert.fail("Test should fail, user shouldn't be allowed to invoke hello method");
} catch (WebServiceException e) {
// failure is expected
MatcherAssert.assertThat("Invocation on hello method should not be allowed", e.getCause().getMessage(), containsString("WFLYEJB0364"));
}
}
// ------------------------------------------------------------------------------
//
// Tests for helloForRole method
//
@Test
public void accessHelloForRoleWithInvalidRole() throws Exception {
URL wsdlURL = new URL(baseUrl, deploymentWsdlURL);
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user1");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password1");
try {
proxy.helloForRole("World");
Assert.fail("Test should fail, user shouldn't be allowed to invoke that method");
} catch (WebServiceException e) {
// failure is expected
checkMessage(e, "helloForRole");
}
}
@Test
public void accessHelloForRoleWithValidRole() throws Exception {
URL wsdlURL = new URL(baseUrl, deploymentWsdlURL);
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user2");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password2");
final String result = proxy.helloForRole("World");
Assert.assertEquals("Hello World!", result);
}
// ------------------------------------------------------------------------------
//
// Tests for helloForRoles method
//
@Test
public void accessHelloForRolesWithValidRole1() throws Exception {
URL wsdlURL = new URL(baseUrl, deploymentWsdlURL);
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user1");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password1");
final String result = proxy.helloForRoles("World");
Assert.assertEquals("Hello World!", result);
}
@Test
public void accessHelloForRolesWithValidRole2() throws Exception {
URL wsdlURL = new URL(baseUrl, deploymentWsdlURL);
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user2");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password2");
final String result = proxy.helloForRoles("World");
Assert.assertEquals("Hello World!", result);
}
@Test
public void accessHelloForRolesWithInvalidRole() throws Exception {
URL wsdlURL = new URL(baseUrl, deploymentWsdlURL);
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "guest");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "guest");
try {
proxy.helloForRoles("World");
Assert.fail("Test should fail, user shouldn't be allowed to invoke that method");
} catch (WebServiceException e) {
// failure is expected
checkMessage(e, "helloForRoles");
}
}
// ------------------------------------------------------------------------------
//
// Tests for helloForAll method
//
@Test
public void accessHelloForAllWithValidRole1() throws Exception {
URL wsdlURL = new URL(baseUrl, deploymentWsdlURL);
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user1");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password1");
final String result = proxy.helloForAll("World");
Assert.assertEquals("Hello World!", result);
}
@Test
public void accessHelloForAllWithValidRole2() throws Exception {
URL wsdlURL = new URL(baseUrl, deploymentWsdlURL);
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user2");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password2");
final String result = proxy.helloForAll("World");
Assert.assertEquals("Hello World!", result);
}
@Test
public void accessHelloForAllWithValidRole3() throws Exception {
URL wsdlURL = new URL(baseUrl, deploymentWsdlURL);
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "guest");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "guest");
final String result = proxy.helloForAll("World");
Assert.assertEquals("Hello World!", result);
}
// ------------------------------------------------------------------------------
//
// Tests for helloForNone method
//
@Test
public void accessHelloForNoneWithValidRole1() throws Exception {
URL wsdlURL = new URL(baseUrl, deploymentWsdlURL);
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user1");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password1");
try {
proxy.helloForNone("World");
Assert.fail("Test should fail, user shouldn't be allowed to invoke that method");
} catch (WebServiceException e) {
// failure is expected
checkMessage(e, "helloForNone");
}
}
@Test
public void accessHelloForNoneWithValidRole2() throws Exception {
URL wsdlURL = new URL(baseUrl, deploymentWsdlURL);
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user2");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password2");
try {
proxy.helloForNone("World");
Assert.fail("Test should fail, user shouldn't be allowed to invoke that method");
} catch (WebServiceException e) {
// failure is expected
checkMessage(e, "helloForNone");
}
}
@Test
public void accessHelloForNoneWithValidRole3() throws Exception {
URL wsdlURL = new URL(baseUrl, deploymentWsdlURL);
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "guest");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "guest");
try {
proxy.helloForNone("World");
Assert.fail("Test should fail, user shouldn't be allowed to invoke that method");
} catch (WebServiceException e) {
// failure is expected
checkMessage(e, "helloForNone");
}
}
private void checkMessage(final Throwable t, final String methodName) {
final Pattern pattern = Pattern.compile("(.*WFLYEJB0364:.*" + methodName + ".*EJBNoCLSAEndpoint.*)");
final String foundMsg = t.getMessage();
Assert.assertTrue(String.format("Expected to find method name %s in error: %s", methodName, foundMsg),
pattern.matcher(t.getMessage()).matches());
}
}
| 12,419 | 38.428571 | 147 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/authentication/PojoEndpointAuthenticationTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.authentication;
import java.net.URL;
import java.util.Map;
import javax.xml.namespace.QName;
import jakarta.xml.ws.BindingProvider;
import jakarta.xml.ws.Service;
import jakarta.xml.ws.WebServiceException;
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.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;
/**
* Tests for authentication against POJO endpoint
*
* @author Rostislav Svoboda
*/
@RunWith(Arquillian.class)
@RunAsClient
public class PojoEndpointAuthenticationTestCase {
@ArquillianResource
URL baseUrl;
QName serviceName = new QName("http://jbossws.org/authentication", "POJOAuthService");
@Deployment(testable = false)
public static Archive<?> deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "jaxws-authentication-pojo.war")
.addClasses(PojoEndpointIface.class, PojoEndpoint.class)
.addAsWebInfResource(PojoEndpointAuthenticationTestCase.class.getPackage(), "web.xml", "web.xml")
.addAsWebInfResource(PojoEndpointAuthenticationTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml");
return war;
}
@Test
public void accessHelloWithoutUsernameAndPassord() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-pojo/POJOAuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
PojoEndpointIface proxy = service.getPort(PojoEndpointIface.class);
try {
proxy.hello("World");
Assert.fail("Test should fail, HTTP response '401: Unauthorized' was expected");
} catch (WebServiceException e) {
// failure is expected
Assert.assertTrue("HTTPException '401: Unauthorized' was expected", e.getCause().getMessage().contains("401: Unauthorized"));
}
}
@Test
public void accessHelloWithBadPassword() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-pojo/POJOAuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
PojoEndpointIface proxy = service.getPort(PojoEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user1");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password-XYZ");
try {
proxy.hello("World");
Assert.fail("Test should fail, HTTP response '401: Unauthorized' was expected");
} catch (WebServiceException e) {
// failure is expected
Assert.assertTrue("HTTPException '401: Unauthorized' was expected", e.getCause().getMessage().contains("401: Unauthorized"));
}
}
@Test
public void accessHelloWithValidUser1() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-pojo/POJOAuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
PojoEndpointIface proxy = service.getPort(PojoEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user1");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password1");
final String result = proxy.hello("World");
Assert.assertEquals("Hello World!", result);
}
@Test
public void accessHelloWithValidUser2() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-pojo/POJOAuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
PojoEndpointIface proxy = service.getPort(PojoEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "user2");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password2");
final String result = proxy.hello("World");
Assert.assertEquals("Hello World!", result);
}
@Test
public void accessHelloWithUnauthorizedUser() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-pojo/POJOAuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
PojoEndpointIface proxy = service.getPort(PojoEndpointIface.class);
Map<String, Object> reqContext = ((BindingProvider) proxy).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "guest");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "guest");
try {
proxy.hello("World");
Assert.fail("Test should fail, HTTP response '403: Forbidden' was expected");
} catch (WebServiceException e) {
// failure is expected
Assert.assertTrue("String '403: Forbidden' was expected in " + e.getCause().getMessage(), e.getCause().getMessage().contains("403: Forbidden"));
}
}
}
| 6,372 | 40.653595 | 156 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/anonymouspojos/POJOIface.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.ws.anonymouspojos;
import jakarta.jws.WebService;
import jakarta.jws.soap.SOAPBinding;
/**
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
@WebService
@SOAPBinding
public interface POJOIface {
String echo(String s);
}
| 1,310 | 33.5 | 70 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/anonymouspojos/Usecase1TestCase.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.ws.anonymouspojos;
import java.net.URL;
import org.jboss.logging.Logger;
import javax.xml.namespace.QName;
import jakarta.xml.ws.Service;
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.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* [JBWS-3276] Tests anonymous POJO in web archive that contains web.xml with other endpoint.
*
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
public class Usecase1TestCase {
@ArquillianResource
URL baseUrl;
private static final Logger log = Logger.getLogger(Usecase1TestCase.class.getName());
@Deployment
public static WebArchive createDeployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "anonymous-pojo-usecase1.war");
war.addPackage(AnonymousPOJO.class.getPackage());
war.addClass(AnonymousPOJO.class);
war.addAsWebInfResource(AnonymousPOJO.class.getPackage(), "web.xml", "web.xml");
return war;
}
@Test
public void testAnonymousEndpoint() throws Exception {
final QName serviceName = new QName("org.jboss.as.test.integration.ws.anonymouspojos", "AnonymousPOJOService");
final URL wsdlURL = new URL(baseUrl, "/anonymous-pojo-usecase1/AnonymousPOJOService?wsdl");
final Service service = Service.create(wsdlURL, serviceName);
final POJOIface port = service.getPort(POJOIface.class);
final String result = port.echo("hello");
Assert.assertEquals("hello from anonymous POJO", result);
}
@Test
public void testDeclaredEndpoint() throws Exception {
final QName serviceName = new QName("org.jboss.as.test.integration.ws.anonymouspojos", "POJOImplService");
final URL wsdlURL = new URL(baseUrl, "/anonymous-pojo-usecase1/POJOService?wsdl");
final Service service = Service.create(wsdlURL, serviceName);
final POJOIface port = service.getPort(POJOIface.class);
final String result = port.echo("hello");
Assert.assertEquals("hello from POJO", result);
}
}
| 3,430 | 39.364706 | 119 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/anonymouspojos/AnonymousPOJO.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.ws.anonymouspojos;
import jakarta.jws.WebService;
/**
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
@WebService(
endpointInterface = "org.jboss.as.test.integration.ws.anonymouspojos.POJOIface",
targetNamespace = "org.jboss.as.test.integration.ws.anonymouspojos",
serviceName = "AnonymousPOJOService"
)
public class AnonymousPOJO {
public String echo(final String s) {
return s + " from anonymous POJO";
}
}
| 1,537 | 35.619048 | 88 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/anonymouspojos/POJOImpl.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.ws.anonymouspojos;
import jakarta.jws.WebService;
/**
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
@WebService(
endpointInterface = "org.jboss.as.test.integration.ws.anonymouspojos.POJOIface",
targetNamespace = "org.jboss.as.test.integration.ws.anonymouspojos",
serviceName = "POJOImplService"
)
public class POJOImpl {
public String echo(final String s) {
return s + " from POJO";
}
}
| 1,517 | 35.142857 | 88 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/anonymouspojos/Usecase2TestCase.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.ws.anonymouspojos;
import java.net.URL;
import org.jboss.logging.Logger;
import javax.xml.namespace.QName;
import jakarta.xml.ws.Service;
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.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* [JBWS-3276] Tests anonymous POJO in web archive that is missing web.xml.
*
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
public class Usecase2TestCase {
@ArquillianResource
URL baseUrl;
private static final Logger log = Logger.getLogger(Usecase2TestCase.class.getName());
@Deployment
public static WebArchive createDeployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "anonymous-pojo-usecase2.war");
war.addPackage(AnonymousPOJO.class.getPackage());
war.addClass(AnonymousPOJO.class);
return war;
}
@Test
public void testAnonymousEndpoint() throws Exception {
final QName serviceName = new QName("org.jboss.as.test.integration.ws.anonymouspojos", "AnonymousPOJOService");
final URL wsdlURL = new URL(baseUrl, "/anonymous-pojo-usecase2/AnonymousPOJOService?wsdl");
final Service service = Service.create(wsdlURL, serviceName);
final POJOIface port = service.getPort(POJOIface.class);
final String result = port.echo("hello");
Assert.assertEquals("hello from anonymous POJO", result);
}
}
| 2,801 | 36.864865 | 119 |
java
|
null |
wildfly-main/testsuite/integration/legacy/src/test/java/org/jboss/as/test/integration/messaging/jms/legacy/LegacyJMSTestCase.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.messaging.jms.legacy;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.naming.Context;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.common.jms.JMSOperations;
import org.jboss.as.test.integration.common.jms.JMSOperationsProvider;
import org.jboss.dmr.ModelNode;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test that a legacy (HornetQ) clients can lookup Jakarta Messaging resources managed by the messaging-activemq subsystem
* when they lookup a legacy entry.
*
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc.
*/
@RunWith(Arquillian.class)
@RunAsClient
public class LegacyJMSTestCase {
private static final String QUEUE_NAME = "LegacyJMSTestCase-Queue";
private static final String QUEUE_ENTRY = "java:jboss/exported/jms/" + QUEUE_NAME;
private static final String LEGACY_QUEUE_LOOKUP = "legacy/jms/" + QUEUE_NAME;
private static final String LEGACY_QUEUE_ENTRY = "java:jboss/exported/" + LEGACY_QUEUE_LOOKUP;
private static final String TOPIC_NAME = "LegacyJMSTestCase-Topic";
private static final String TOPIC_ENTRY = "java:jboss/exported/jms/" + TOPIC_NAME;
private static final String LEGACY_TOPIC_LOOKUP = "legacy/jms/" + TOPIC_NAME;
private static final String LEGACY_TOPIC_ENTRY = "java:jboss/exported/" + LEGACY_TOPIC_LOOKUP;
private static final String CF_NAME = "LegacyJMSTestCase-CF";
private static final String LEGACY_CF_LOOKUP = "legacy/jms/" + CF_NAME;
private static final String LEGACY_CF_ENTRY = "java:jboss/exported/" + LEGACY_CF_LOOKUP;
@ContainerResource
private Context remoteContext;
@ContainerResource
private ManagementClient managementClient;
@Before
public void setUp() throws IOException {
JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient());
ModelNode queueAttributes = new ModelNode();
queueAttributes.get("legacy-entries").add(LEGACY_QUEUE_ENTRY);
jmsOperations.createJmsQueue(QUEUE_NAME, QUEUE_ENTRY, queueAttributes);
ModelNode topicAttributes = new ModelNode();
topicAttributes.get("legacy-entries").add(LEGACY_TOPIC_ENTRY);
jmsOperations.createJmsTopic(TOPIC_NAME, TOPIC_ENTRY, topicAttributes);
ModelNode legacyConnectionFactoryAddress = jmsOperations.getServerAddress().clone()
.add("legacy-connection-factory", CF_NAME);
ModelNode addLegacyConnectionFactoryOp = Util.createOperation(ModelDescriptionConstants.ADD, PathAddress.pathAddress(legacyConnectionFactoryAddress));
addLegacyConnectionFactoryOp.get("connectors").add("http-connector");
addLegacyConnectionFactoryOp.get("entries").add(LEGACY_CF_ENTRY);
managementClient.getControllerClient().execute(addLegacyConnectionFactoryOp);
}
@After
public void tearDown() throws IOException {
JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient());
jmsOperations.removeJmsQueue(QUEUE_NAME);
jmsOperations.removeJmsTopic(TOPIC_NAME);
ModelNode legacyConnectionFactoryAddress = jmsOperations.getServerAddress().clone()
.add("legacy-connection-factory", CF_NAME);
ModelNode addLegacyConnectionFactoryOp = Util.createOperation(REMOVE, PathAddress.pathAddress(legacyConnectionFactoryAddress));
managementClient.getControllerClient().execute(addLegacyConnectionFactoryOp);
}
@Test
public void testSendAndReceiveFromLegacyQueue() throws Exception {
doSendAndReceive(LEGACY_CF_LOOKUP, LEGACY_QUEUE_LOOKUP);
}
@Test
public void testSendAndReceiveFromLegacyTopic() throws Exception {
doSendAndReceive(LEGACY_CF_LOOKUP, LEGACY_TOPIC_LOOKUP);
}
private void doSendAndReceive(String connectionFactoryLookup, String destinationLoookup) throws Exception {
Destination destination = (Destination) remoteContext.lookup(destinationLoookup);
assertNotNull(destination);
ConnectionFactory cf = (ConnectionFactory) remoteContext.lookup(connectionFactoryLookup);
assertNotNull(cf);
try (
JMSContext producerContext = cf.createContext("guest", "guest");
JMSContext consumerContext = cf.createContext("guest", "guest")
) {
final CountDownLatch latch = new CountDownLatch(10);
final List<String> result = new ArrayList<String>();
JMSConsumer consumer = consumerContext.createConsumer(destination);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
TextMessage msg = (TextMessage) message;
try {
result.add(msg.getText());
latch.countDown();
} catch (JMSException e) {
e.printStackTrace();
}
}
});
JMSProducer producer = producerContext.createProducer();
for (int i = 0; i < 10; i++) {
String text = "Test" + i;
producer.send(destination, text);
}
assertTrue(latch.await(3, SECONDS));
assertEquals(10, result.size());
for (int i = 0; i < result.size(); i++) {
assertEquals("Test" + i, result.get(i));
}
}
}
}
| 7,613 | 42.261364 | 158 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/timer/database/DatabaseTimerServiceMultiNodeTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.timer.database;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVICE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.test.multinode.ejb.timer.database.DatabaseTimerServiceMultiNodeExecutionDisabledTestCase.getRemoteContext;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FilePermission;
import java.net.SocketPermission;
import java.security.SecurityPermission;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.naming.Context;
import org.h2.tools.Server;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.shared.FileUtils;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests that timers are never doubled up
*
*
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(DatabaseTimerServiceMultiNodeTestCase.DatabaseTimerServiceTestCaseServerSetup.class)
public class DatabaseTimerServiceMultiNodeTestCase {
public static final String ARCHIVE_NAME = "testTimerServiceSimple";
public static final int TIMER_COUNT = 100;
private static Server server;
private static final int TIMER_DELAY = 400;
static final PathAddress ADDR_DATA_SOURCE = PathAddress.pathAddress().append(SUBSYSTEM, "datasources").append("data-source", "MyNewDs");
static final PathAddress ADDR_DATA_STORE = PathAddress.pathAddress().append(SUBSYSTEM, "ejb3").append(SERVICE, "timer-service").append("database-data-store", "dbstore");
@AfterClass
public static void afterClass() {
if(server != null) {
server.stop();
}
}
static class DatabaseTimerServiceTestCaseServerSetup implements ServerSetupTask {
private static final PathAddress ADDR_DATA_SOURCE = PathAddress.pathAddress().append(SUBSYSTEM, "datasources").append("data-source", "MyNewDs");
private static final PathAddress ADDR_TIMER_SERVICE = PathAddress.pathAddress().append(SUBSYSTEM, "ejb3").append("service", "timer-service");
private static final PathAddress ADDR_DATABASE_DATA_STORE = ADDR_TIMER_SERVICE.append("database-data-store", "dbstore");
@Override
public void setup(final ManagementClient managementClient, final String containerId) throws Exception {
if(server == null) {
//we need a TCP server that can be shared between the two servers
//To allow remote connections, start the TCP server using the option -tcpAllowOthers
server = Server.createTcpServer("-tcpAllowOthers", "-ifNotExists").start();
}
final ModelNode compositeOp = new ModelNode();
compositeOp.get(OP).set(COMPOSITE);
compositeOp.get(OP_ADDR).setEmptyList();
ModelNode steps = compositeOp.get(STEPS);
// /subsystem=datasources/data-source=MyNewDs:add(name=MyNewDs,jndi-name=java:jboss/datasources/TimeDs, enabled=true)
ModelNode datasourceAddModelNode = Util.createAddOperation(ADDR_DATA_SOURCE);
datasourceAddModelNode.get("name").set("MyNewDs");
datasourceAddModelNode.get("jndi-name").set("java:jboss/datasources/TimeDs");
datasourceAddModelNode.get("enabled").set(true);
datasourceAddModelNode.get("driver-name").set("h2");
datasourceAddModelNode.get("pool-name").set("MyNewDs_Pool");
datasourceAddModelNode.get("connection-url").set("jdbc:h2:" + server.getURL() + "/mem:testdb;DB_CLOSE_DELAY=-1");
datasourceAddModelNode.get("user-name").set("sa");
datasourceAddModelNode.get("password").set("sa");
steps.add(datasourceAddModelNode);
// /subsystem=ejb3/remoting-profile=test-profile/remoting-ejb-receiver=test-receiver:add(outbound-connection-ref=remote-ejb-connection)
ModelNode databaseDataStoreAddModelNode = Util.createAddOperation(ADDR_DATABASE_DATA_STORE);
databaseDataStoreAddModelNode.get("datasource-jndi-name").set("java:jboss/datasources/TimeDs");
databaseDataStoreAddModelNode.get("database").set("postgresql");
databaseDataStoreAddModelNode.get("refresh-interval").set(100);
steps.add(databaseDataStoreAddModelNode);
Utils.applyUpdates(Collections.singletonList(compositeOp), managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
@Override
public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception {
final ModelNode compositeOp = new ModelNode();
compositeOp.get(OP).set(COMPOSITE);
compositeOp.get(OP_ADDR).setEmptyList();
ModelNode steps = compositeOp.get(STEPS);
ModelNode databaseDataStoreRemoveModelNode = Util.createRemoveOperation(ADDR_DATABASE_DATA_STORE);
// omitting op.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false)
steps.add(databaseDataStoreRemoveModelNode);
ModelNode datasourceRemoveModelNode = Util.createRemoveOperation(ADDR_DATA_SOURCE);
// omitting op.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false)
steps.add(datasourceRemoveModelNode);
Utils.applyUpdates(Collections.singletonList(compositeOp), managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
}
@ContainerResource("multinode-server")
private ManagementClient serverClient;
@ContainerResource("multinode-client")
private ManagementClient clientClient;
@Deployment(name = "server", testable = false)
@TargetsContainer("multinode-server")
public static Archive<?> deployment() {
return createDeployment(false);
}
@Deployment(name = "client", testable = true)
@TargetsContainer("multinode-client")
public static Archive<?> clientDeployment() {
return createDeployment(true);
}
private static Archive<?> createDeployment(boolean client) {
final WebArchive war = ShrinkWrap.create(WebArchive.class, ARCHIVE_NAME + ".war");
war.addClasses(Collector.class, RemoteTimedBean.class, TimedObjectTimerServiceBean.class, TimerData.class, FileUtils.class, StartupSingleton.class);
war.addAsWebInfResource(DatabaseTimerServiceMultiNodeTestCase.class.getPackage(), "jboss-ejb3.xml", "jboss-ejb3.xml");
if(!client) {
war.addClass(CollectionSingleton.class);
}
war.addAsResource(new StringAsset(client ? "client" : "server"), "node.txt");
if (client) {
war.addAsManifestResource(DatabaseTimerServiceMultiNodeExecutionDisabledTestCase.class.getPackage(), "jboss-ejb-client.xml", "jboss-ejb-client.xml");
war.addAsManifestResource(
createPermissionsXmlAsset(
new SocketPermission("*:9092", "connect,resolve"),
new SecurityPermission("putProviderProperty.WildFlyElytron"),
new FilePermission(System.getProperty("jboss.home") + File.separatorChar + "standalone" + File.separatorChar + "tmp" + File.separatorChar + "auth" + File.separatorChar + "-", "read")),
"permissions.xml");
}
return war;
}
@Test
public void testEjbTimeoutOnOtherNode() throws Exception {
Context clientContext = getRemoteContext(clientClient);
try {
RemoteTimedBean clientBean = (RemoteTimedBean) clientContext.lookup(ARCHIVE_NAME + "/" + TimedObjectTimerServiceBean.class.getSimpleName() + "!" + RemoteTimedBean.class.getName());
Set<String> names = new HashSet<>();
long time = System.currentTimeMillis() + TimeoutUtil.adjust(TIMER_DELAY);
for (int i = 0; i < TIMER_COUNT; ++i) {
String name = "timer" + i;
clientBean.scheduleTimer(time, name);
names.add(name);
}
final Context remoteContext = getRemoteContext(serverClient);
try {
Collector serverBean = (Collector) remoteContext.lookup(ARCHIVE_NAME + "/" + CollectionSingleton.class.getSimpleName() + "!" + Collector.class.getName());
List<TimerData> res = serverBean.collect(TIMER_COUNT);
Assert.assertEquals("Expected " + TIMER_COUNT + " was " + res.size() + " " + res, TIMER_COUNT, res.size());
final Set<String> newNames = new HashSet<>(names);
for (TimerData r : res) {
if (!newNames.remove(r.getInfo())) {
if (!names.contains(r.getInfo())) {
throw new RuntimeException("Timer " + r.getInfo() + " not run " + res);
} else {
throw new RuntimeException("Timer " + r.getInfo() + " run twice " + res);
}
}
}
} finally {
remoteContext.close();
}
} finally {
clientContext.close();
}
}
/**
* Verifies that auto timers in a startup singleton bean are properly started,
* and that different nodes should not create duplicate auto timers.
*/
@Test
public void testAutoTimersInSingletonBean() throws Exception {
Context clientContext = getRemoteContext(clientClient);
Context serverContext = getRemoteContext(serverClient);
try {
final String lookupName = ARCHIVE_NAME + "/" + StartupSingleton.class.getSimpleName() + "!" + RemoteTimedBean.class.getName();
RemoteTimedBean clientBean = (RemoteTimedBean) clientContext.lookup(lookupName);
assertTrue(clientBean.hasTimerRun());
RemoteTimedBean serverBean = (RemoteTimedBean) serverContext.lookup(lookupName);
assertTrue(serverBean.hasTimerRun());
} finally {
serverContext.close();
clientContext.close();
}
}
}
| 12,612 | 48.077821 | 212 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/timer/database/RefreshBean1.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2020, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.timer.database;
import jakarta.ejb.ConcurrencyManagement;
import jakarta.ejb.ConcurrencyManagementType;
import jakarta.ejb.Singleton;
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class RefreshBean1 extends RefreshBeanBase implements RefreshIF {
}
| 1,335 | 38.294118 | 73 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/timer/database/RefreshBeanBase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2020, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.timer.database;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import jakarta.annotation.Resource;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Timeout;
import jakarta.ejb.Timer;
import jakarta.ejb.TimerConfig;
import jakarta.ejb.TimerHandle;
import jakarta.ejb.TimerService;
import jakarta.interceptor.Interceptors;
public abstract class RefreshBeanBase implements RefreshIF {
@Resource
TimerService timerService;
@Resource
SessionContext sessionContext;
@SuppressWarnings("unused")
@Timeout
void timeout(Timer timer) {
//noop, all timers will be cancelled before expiry.
}
/**
* {@inheritDoc}
*/
@Override
public byte[] createTimer(final long delay, final Serializable info) {
final Timer timer = timerService.createSingleActionTimer(delay, new TimerConfig(info, true));
if (info == Info.RETURN_HANDLE) {
final TimerHandle handle = timer.getHandle();
try (final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final ObjectOutputStream out = new ObjectOutputStream(bos)) {
out.writeObject(handle);
out.flush();
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException("Failed to serialize timer handle for timer: " + timer, e);
}
} else {
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
@Interceptors(RefreshInterceptor.class)
public List<Serializable> getAllTimerInfoWithRefresh() {
final Collection<Timer> allTimers = timerService.getAllTimers();
return allTimers.stream().map(Timer::getInfo).collect(Collectors.toList());
}
/**
* {@inheritDoc}
*/
@Override
public List<Serializable> getAllTimerInfoWithRefresh2() {
final RefreshIF businessObject = sessionContext.getBusinessObject(RefreshIF.class);
return businessObject.getAllTimerInfoWithRefresh();
}
/**
* {@inheritDoc}
*/
@Override
public List<Serializable> getAllTimerInfoNoRefresh() {
return getAllTimerInfoWithRefresh();
}
/**
* {@inheritDoc}
*/
@Override
public void cancelTimers() {
final Collection<Timer> timers = timerService.getTimers();
for (Timer timer : timers) {
try {
timer.cancel();
} catch (Exception e) {
//ignore
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void cancelTimer(final byte[] handle) {
final TimerHandle timerHandle;
try (final ByteArrayInputStream bis = new ByteArrayInputStream(handle);
final ObjectInputStream in = new ObjectInputStream(bis)) {
timerHandle = (TimerHandle) in.readObject();
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException("Failed to deserialize byte[] to timer handle.", e);
}
final Timer timer = timerHandle.getTimer();
if (timer != null) {
timer.cancel();
} else {
throw new RuntimeException("Failed to get timer from timer handle byte[].");
}
}
}
| 4,570 | 31.65 | 102 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/timer/database/RemoteTimedBean.java
|
package org.jboss.as.test.multinode.ejb.timer.database;
import jakarta.ejb.Remote;
/**
* @author Stuart Douglas
*/
@Remote
public interface RemoteTimedBean {
void scheduleTimer(long date, String info);
boolean hasTimerRun();
}
| 241 | 15.133333 | 55 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/timer/database/DatabaseTimerServiceMultiNodeExecutionDisabledTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.timer.database;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVICE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.h2.tools.Server;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.shared.FileUtils;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.integration.ejb.security.CallbackHandler;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests that a timer created on a node with timeout disabled can be run on a different node in the cluster.
*
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(DatabaseTimerServiceMultiNodeExecutionDisabledTestCase.DatabaseTimerServiceTestCaseServerSetup.class)
public class DatabaseTimerServiceMultiNodeExecutionDisabledTestCase {
public static final String ARCHIVE_NAME = "testTimerServiceSimple";
private static Server server;
static final PathAddress ADDR_DATA_SOURCE = PathAddress.pathAddress().append(SUBSYSTEM, "datasources").append("data-source", "MyNewDs_disabled");
static final PathAddress ADDR_DATA_STORE = PathAddress.pathAddress().append(SUBSYSTEM, "ejb3").append(SERVICE, "timer-service").append("database-data-store", "dbstore");
@AfterClass
public static void afterClass() {
if (server != null) {
server.stop();
}
}
static class DatabaseTimerServiceTestCaseServerSetup implements ServerSetupTask {
private static final PathAddress ADDR_DATA_SOURCE = PathAddress.pathAddress().append(SUBSYSTEM, "datasources").append("data-source", "MyNewDs_disabled");
private static final PathAddress ADDR_TIMER_SERVICE = PathAddress.pathAddress().append(SUBSYSTEM, "ejb3").append("service", "timer-service");
private static final PathAddress ADDR_DATABASE_DATA_STORE = ADDR_TIMER_SERVICE.append("database-data-store", "dbstore");
@Override
public void setup(final ManagementClient managementClient, final String containerId) throws Exception {
if (server == null) {
//we need a TCP server that can be shared between the two servers
//To allow remote connections, start the TCP server using the option -tcpAllowOthers
server = Server.createTcpServer("-tcpAllowOthers", "-ifNotExists").start();
}
final ModelNode compositeOp = new ModelNode();
compositeOp.get(OP).set(COMPOSITE);
compositeOp.get(OP_ADDR).setEmptyList();
ModelNode steps = compositeOp.get(STEPS);
// /subsystem=datasources/data-source=MyNewDs_disabled:add(name=MyNewDs_disabled,jndi-name=java:jboss/datasources/TimeDs_disabled, enabled=true,...)
ModelNode datasourceAddModelNode = Util.createAddOperation(ADDR_DATA_SOURCE);
datasourceAddModelNode.get("name").set("MyNewDs_disabled");
datasourceAddModelNode.get("jndi-name").set("java:jboss/datasources/TimeDs_disabled");
datasourceAddModelNode.get("enabled").set(true);
datasourceAddModelNode.get("driver-name").set("h2");
datasourceAddModelNode.get("pool-name").set("MyNewDs_disabled_Pool");
datasourceAddModelNode.get("connection-url").set("jdbc:h2:" + server.getURL() + "/mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
datasourceAddModelNode.get("user-name").set("sa");
datasourceAddModelNode.get("password").set("sa");
steps.add(datasourceAddModelNode);
// /subsystem=ejb3/service=timer-service/database-data-store=dbstore:add(odatabase-jndi-name=java:jboss/datrasources/TimeDs,...)
ModelNode databaseDataStoreAddModelNode = Util.createAddOperation(ADDR_DATABASE_DATA_STORE);
databaseDataStoreAddModelNode.get("datasource-jndi-name").set("java:jboss/datasources/TimeDs_disabled");
databaseDataStoreAddModelNode.get("database").set("postgresql");
if (containerId.equals("multinode-client")) {
databaseDataStoreAddModelNode.get("allow-execution").set(false);
}
databaseDataStoreAddModelNode.get("refresh-interval").set(100);
steps.add(databaseDataStoreAddModelNode);
Utils.applyUpdates(Collections.singletonList(compositeOp), managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
@Override
public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception {
final ModelNode compositeOp = new ModelNode();
compositeOp.get(OP).set(COMPOSITE);
compositeOp.get(OP_ADDR).setEmptyList();
ModelNode steps = compositeOp.get(STEPS);
ModelNode databaseDataStoreRemoveModelNode = Util.createRemoveOperation(ADDR_DATABASE_DATA_STORE);
// omitting op.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false)
steps.add(databaseDataStoreRemoveModelNode);
ModelNode datasourceRemoveModelNode = Util.createRemoveOperation(ADDR_DATA_SOURCE);
// omitting op.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false)
steps.add(datasourceRemoveModelNode);
Utils.applyUpdates(Collections.singletonList(compositeOp), managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
}
@ContainerResource("multinode-server")
private ManagementClient serverClient;
@ContainerResource("multinode-client")
private ManagementClient clientClient;
@Deployment(name = "server", testable = false)
@TargetsContainer("multinode-server")
public static Archive<?> deployment() {
return createDeployment(false);
}
@Deployment(name = "client", testable = true)
@TargetsContainer("multinode-client")
public static Archive<?> clientDeployment() {
return createDeployment(true);
}
private static Archive<?> createDeployment(boolean client) {
final WebArchive war = ShrinkWrap.create(WebArchive.class, ARCHIVE_NAME + ".war");
war.addClasses(Collector.class, RemoteTimedBean.class, TimedObjectTimerServiceBean.class, TimerData.class, FileUtils.class);
if (!client) {
war.addClass(CollectionSingleton.class);
}
String nodeName = client ? "client" : "server";
war.addAsResource(new StringAsset(nodeName), "node.txt");
war.addAsWebInfResource(DatabaseTimerServiceMultiNodeExecutionDisabledTestCase.class.getPackage(), "jboss-ejb3.xml", "jboss-ejb3.xml");
if (client) {
war.addAsManifestResource(DatabaseTimerServiceMultiNodeExecutionDisabledTestCase.class.getPackage(), "jboss-ejb-client.xml", "jboss-ejb-client.xml");
}
return war;
}
@Test
public void testEjbTimeoutOnOtherNode() throws Exception {
Context clientContext = getRemoteContext(clientClient);
RemoteTimedBean clientBean = (RemoteTimedBean) clientContext.lookup(ARCHIVE_NAME + "/" + TimedObjectTimerServiceBean.class.getSimpleName() + "!" + RemoteTimedBean.class.getName());
clientBean.scheduleTimer(System.currentTimeMillis() + 100, "timer1");
Thread.sleep(200);
Assert.assertFalse(clientBean.hasTimerRun());
clientContext.close();
Collector serverBean = (Collector) getRemoteContext(serverClient).lookup(ARCHIVE_NAME + "/" + CollectionSingleton.class.getSimpleName() + "!" + Collector.class.getName());
List<TimerData> res = serverBean.collect(1);
Assert.assertEquals(1, res.size());
Assert.assertEquals("server", res.get(0).getNode());
Assert.assertEquals("timer1", res.get(0).getInfo());
}
public static Context getRemoteContext(ManagementClient managementClient) throws Exception {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, org.wildfly.naming.client.WildFlyInitialContextFactory.class.getName());
URI webUri = managementClient.getWebUri();
URI namingUri = new URI("remote+http", webUri.getUserInfo(), webUri.getHost(), webUri.getPort(), "", "", "");
env.put(Context.PROVIDER_URL, namingUri.toString());
env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
env.put("jboss.naming.client.security.callback.handler.class", CallbackHandler.class.getName());
env.put("jboss.naming.client.ejb.context", true);
return new InitialContext(env);
}
}
| 11,057 | 48.810811 | 188 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/timer/database/DatabaseTimerServiceRefreshTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2020, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.timer.database;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVICE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.test.multinode.ejb.timer.database.DatabaseTimerServiceMultiNodeExecutionDisabledTestCase.getRemoteContext;
import static org.jboss.as.test.multinode.ejb.timer.database.RefreshIF.Info.CLIENT1;
import static org.jboss.as.test.multinode.ejb.timer.database.RefreshIF.Info.RETURN_HANDLE;
import static org.jboss.as.test.multinode.ejb.timer.database.RefreshIF.Info.SERVER1;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
import java.net.SocketPermission;
import java.security.SecurityPermission;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.naming.Context;
import org.h2.tools.Server;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(DatabaseTimerServiceRefreshTestCase.DatabaseTimerServiceTestCaseServerSetup.class)
public class DatabaseTimerServiceRefreshTestCase {
private static final String ARCHIVE_NAME = "testTimerServiceRefresh";
private static Server server;
private static final long TIMER_DELAY = TimeUnit.MINUTES.toMillis(20);
static final PathAddress ADDR_DATA_SOURCE = PathAddress.pathAddress().append(SUBSYSTEM, "datasources").append("data-source", "MyNewDs");
static final PathAddress ADDR_DATA_STORE = PathAddress.pathAddress().append(SUBSYSTEM, "ejb3").append(SERVICE, "timer-service").append("database-data-store", "dbstore");
@AfterClass
public static void afterClass() {
if (server != null) {
server.stop();
}
}
static class DatabaseTimerServiceTestCaseServerSetup implements ServerSetupTask {
private static final PathAddress ADDR_DATA_SOURCE = PathAddress.pathAddress().append(SUBSYSTEM, "datasources").append("data-source", "MyNewDs");
private static final PathAddress ADDR_TIMER_SERVICE = PathAddress.pathAddress().append(SUBSYSTEM, "ejb3").append("service", "timer-service");
private static final PathAddress ADDR_DATABASE_DATA_STORE = ADDR_TIMER_SERVICE.append("database-data-store", "dbstore");
@Override
public void setup(final ManagementClient managementClient, final String containerId) throws Exception {
if (server == null) {
//we need a TCP server that can be shared between the two servers
//To allow remote connections, start the TCP server using the option -tcpAllowOthers
server = Server.createTcpServer("-tcpAllowOthers", "-ifNotExists").start();
}
final ModelNode compositeOp = new ModelNode();
compositeOp.get(OP).set(COMPOSITE);
compositeOp.get(OP_ADDR).setEmptyList();
ModelNode steps = compositeOp.get(STEPS);
// /subsystem=datasources/data-source=MyNewDs:add(name=MyNewDs,jndi-name=java:jboss/datasources/TimeDs, enabled=true)
ModelNode datasourceAddModelNode = Util.createAddOperation(ADDR_DATA_SOURCE);
datasourceAddModelNode.get("name").set("MyNewDs");
datasourceAddModelNode.get("jndi-name").set("java:jboss/datasources/TimeDs");
datasourceAddModelNode.get("enabled").set(true);
datasourceAddModelNode.get("driver-name").set("h2");
datasourceAddModelNode.get("pool-name").set("MyNewDs_Pool");
datasourceAddModelNode.get("connection-url").set("jdbc:h2:" + server.getURL() + "/mem:testdb;DB_CLOSE_DELAY=-1");
datasourceAddModelNode.get("user-name").set("sa");
datasourceAddModelNode.get("password").set("sa");
steps.add(datasourceAddModelNode);
// /subsystem=ejb3/service=timer-service/database-data-store=dbstore:add(odatabase-jndi-name=java:jboss/datrasources/TimeDs)
ModelNode databaseDataStoreAddModelNode = Util.createAddOperation(ADDR_DATABASE_DATA_STORE);
databaseDataStoreAddModelNode.get("datasource-jndi-name").set("java:jboss/datasources/TimeDs");
databaseDataStoreAddModelNode.get("database").set("postgresql");
databaseDataStoreAddModelNode.get("refresh-interval").set(TimeUnit.MINUTES.toMillis(30));
steps.add(databaseDataStoreAddModelNode);
Utils.applyUpdates(Collections.singletonList(compositeOp), managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
@Override
public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception {
final ModelNode compositeOp = new ModelNode();
compositeOp.get(OP).set(COMPOSITE);
compositeOp.get(OP_ADDR).setEmptyList();
ModelNode steps = compositeOp.get(STEPS);
ModelNode databaseDataStoreRemoveModelNode = Util.createRemoveOperation(ADDR_DATABASE_DATA_STORE);
// omitting op.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false)
steps.add(databaseDataStoreRemoveModelNode);
ModelNode datasourceRemoveModelNode = Util.createRemoveOperation(ADDR_DATA_SOURCE);
// omitting op.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false)
steps.add(datasourceRemoveModelNode);
Utils.applyUpdates(Collections.singletonList(compositeOp), managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
}
@ContainerResource("multinode-server")
private ManagementClient serverClient;
@ContainerResource("multinode-client")
private ManagementClient clientClient;
@Deployment(name = "server", testable = false)
@TargetsContainer("multinode-server")
public static Archive<?> deployment() {
return createDeployment(false);
}
@Deployment(name = "client", testable = true)
@TargetsContainer("multinode-client")
public static Archive<?> clientDeployment() {
return createDeployment(true);
}
private static Archive<?> createDeployment(boolean client) {
final WebArchive war = ShrinkWrap.create(WebArchive.class, ARCHIVE_NAME + ".war");
war.addClasses(RefreshInterceptor.class, RefreshIF.class, RefreshBeanBase.class, RefreshBean1.class, RefreshBean2.class);
war.addAsWebInfResource(DatabaseTimerServiceRefreshTestCase.class.getPackage(), "jboss-ejb3.xml", "jboss-ejb3.xml");
if (client) {
war.addAsManifestResource(DatabaseTimerServiceRefreshTestCase.class.getPackage(), "jboss-ejb-client-refresh-test.xml", "jboss-ejb-client.xml");
war.addAsManifestResource(
createPermissionsXmlAsset(
new SocketPermission("*:9092", "connect,resolve"),
new SecurityPermission("putProviderProperty.WildFlyElytron")),
"permissions.xml");
}
return war;
}
/**
* Verifies that application can programmatically refresh timers across different nodes,
* when programmatic refresh is enabled through interceptor.
*/
@Test
public void testTimerProgrammaticRefresh() throws Exception {
Context clientContext = null;
Context serverContext = null;
try {
clientContext = getRemoteContext(clientClient);
serverContext = getRemoteContext(serverClient);
RefreshIF bean1Client = (RefreshIF) clientContext.lookup(ARCHIVE_NAME + "/" + RefreshBean1.class.getSimpleName() + "!" + RefreshIF.class.getName());
RefreshIF bean2Client = (RefreshIF) clientContext.lookup(ARCHIVE_NAME + "/" + RefreshBean2.class.getSimpleName() + "!" + RefreshIF.class.getName());
RefreshIF bean1Server = (RefreshIF) serverContext.lookup(ARCHIVE_NAME + "/" + RefreshBean1.class.getSimpleName() + "!" + RefreshIF.class.getName());
RefreshIF bean2Server = (RefreshIF) serverContext.lookup(ARCHIVE_NAME + "/" + RefreshBean2.class.getSimpleName() + "!" + RefreshIF.class.getName());
RefreshIF[] serverBeans = {bean1Server, bean2Server};
RefreshIF[] clientBeans = {bean1Client, bean2Client};
// client bean 1 creates a timer in client node
// both client beans will see this newly-created timer
bean1Client.createTimer(TIMER_DELAY, CLIENT1);
for (RefreshIF b : clientBeans) {
verifyTimerInfo(b.getAllTimerInfoNoRefresh(), 1, CLIENT1);
}
// without refresh, both server beans see no timer
for (RefreshIF b : serverBeans) {
verifyTimerInfo(b.getAllTimerInfoNoRefresh(), 0);
}
// after server bean 1 refreshes, both server beans see the timer created in client node
verifyTimerInfo(bean1Server.getAllTimerInfoWithRefresh(), 1, CLIENT1);
verifyTimerInfo(bean2Server.getAllTimerInfoNoRefresh(), 1, CLIENT1);
// after cancelling the timer, client beans see no timer
// but both server beans still see 1 obsolete timer
bean1Client.cancelTimers();
for (RefreshIF b : clientBeans) {
verifyTimerInfo(b.getAllTimerInfoNoRefresh(), 0);
}
for (RefreshIF b : serverBeans) {
verifyTimerInfo(b.getAllTimerInfoNoRefresh(), 1, CLIENT1);
}
// after server bean 2 refreshes, both server beans see no timer
verifyTimerInfo(bean2Server.getAllTimerInfoWithRefresh2(), 0);
verifyTimerInfo(bean1Server.getAllTimerInfoNoRefresh(), 0);
// after server bean 1 creates a timer, both client beans see no timer
// after client bean 2 refreshes, both client beans see this timer
bean1Server.createTimer(TIMER_DELAY, SERVER1);
for (RefreshIF b : clientBeans) {
verifyTimerInfo(b.getAllTimerInfoNoRefresh(), 0);
}
verifyTimerInfo(bean2Client.getAllTimerInfoWithRefresh(), 1, SERVER1);
verifyTimerInfo(bean1Client.getAllTimerInfoNoRefresh(), 1, SERVER1);
// server bean 1 cancels this timer
// after refresh, both client beans see no timer
bean1Server.cancelTimers();
verifyTimerInfo(bean1Client.getAllTimerInfoWithRefresh2(), 0);
verifyTimerInfo(bean2Client.getAllTimerInfoNoRefresh(), 0);
// after server bean 1 creates a timer, both client beans see no timer,
// but client bean 1 should still be able to cancel this timer.
final byte[] handle = bean1Server.createTimer(TIMER_DELAY, RETURN_HANDLE);
try {
bean1Client.cancelTimer(handle);
verifyTimerInfo(bean1Server.getAllTimerInfoWithRefresh(), 0);
verifyTimerInfo(bean1Client.getAllTimerInfoWithRefresh(), 0);
} finally {
//clean up (cancel in the active node) in case the timer was not cancelled by client bean 1
try {
bean1Server.cancelTimers();
} catch (Exception ignore) {
}
}
} finally {
if (clientContext != null) {
clientContext.close();
}
if (serverContext != null) {
serverContext.close();
}
}
}
private void verifyTimerInfo(List<Serializable> infoList, int expectedSize, Serializable... expectedInfo) {
assertEquals(expectedSize, infoList.size());
for (Serializable e : expectedInfo) {
assertTrue("Expecting timer info: " + e + " not found in timer info list: " + infoList, infoList.contains(e));
}
}
}
| 14,291 | 50.042857 | 173 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/timer/database/RefreshIF.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2020, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.timer.database;
import java.io.Serializable;
import java.util.List;
import jakarta.ejb.Remote;
@Remote
public interface RefreshIF {
/**
* Used to indicate in which node and by which bean the timer is created.
*/
enum Info {
/**
* The timer is created in the client node and by bean 1.
*/
CLIENT1,
/**
* The timer is created in the server node and by bean 1.
*/
SERVER1,
/**
* Indicates that a timer handle should be returned
*/
RETURN_HANDLE
}
/**
* Creates a timer to expire {@code delay} milliseconds later, with {@code info}
* as the timer info.
*
* @param delay number of milliseconds after which the timer is set to expire
* @param info timer info
* @return timer handle for the new timer
*/
byte[] createTimer(long delay, Serializable info);
/**
* Gets all timers after programmatic refresh. Any implementation method
* should be configured to have an interceptor that enables programmatic
* timer refresh.
*
* @return list of timer info
*/
List<Serializable> getAllTimerInfoWithRefresh();
/**
* Gets all timers after programmatic refresh. Any implementation method
* should be configured to have an interceptor that enables programmatic
* timer refresh.
* <p>
* This method demonstrates that a bean class can invoke its own business
* method that enables programmatic timer refresh, without replying on an
* external client invocation.
*
* @return list of timer info
*/
List<Serializable> getAllTimerInfoWithRefresh2();
/**
* Gets all timers without programmatic refresh. Any implementation method
* should NOT be configured to have an interceptor that enables programmatic
* timer refresh.
*
* @return list of timer info
*/
List<Serializable> getAllTimerInfoNoRefresh();
/**
* Cancels timers of this bean.
*/
void cancelTimers();
/**
* Cancels a timer by its timer handle.
* @param handle the timer handle for the timer to be cancelled
*/
void cancelTimer(byte[] handle);
}
| 3,291 | 30.961165 | 84 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/timer/database/CollectionSingleton.java
|
package org.jboss.as.test.multinode.ejb.timer.database;
import jakarta.ejb.ConcurrencyManagement;
import jakarta.ejb.ConcurrencyManagementType;
import jakarta.ejb.Singleton;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
/**
* @author Stuart Douglas
*/
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class CollectionSingleton implements Collector {
private final LinkedBlockingDeque<TimerData> timerDatas = new LinkedBlockingDeque<>();
@Override
public void timerRun(String nodeName, String info) {
timerDatas.add(new TimerData(nodeName, info));
}
@Override
public List<TimerData> collect(int expectedCount) {
long end = System.currentTimeMillis() + 30000; //10 seconds
List<TimerData> ret = new ArrayList<>();
for (; ; ) {
if (ret.size() == expectedCount) {
break;
}
if (System.currentTimeMillis() > end) {
break;
}
try {
TimerData res = timerDatas.poll(end - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
if (res != null) {
ret.add(res);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
return ret;
}
}
| 1,435 | 28.306122 | 105 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/timer/database/Collector.java
|
package org.jboss.as.test.multinode.ejb.timer.database;
import jakarta.ejb.Remote;
import java.util.List;
/**
* @author Stuart Douglas
*/
@Remote
public interface Collector {
void timerRun(final String nodeName, String info);
List<TimerData> collect(final int expectedCount);
}
| 293 | 16.294118 | 55 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/timer/database/RefreshBean2.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2020, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.timer.database;
import jakarta.ejb.Stateless;
@Stateless
public class RefreshBean2 extends RefreshBeanBase implements RefreshIF {
}
| 1,192 | 37.483871 | 73 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/timer/database/RefreshInterceptor.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2020, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.timer.database;
import jakarta.interceptor.AroundInvoke;
import jakarta.interceptor.Interceptor;
import jakarta.interceptor.InvocationContext;
/**
* An interceptor to enable programmatic timer refresh across multiple nodes.
*/
@Interceptor
public class RefreshInterceptor {
@AroundInvoke
public Object intercept(InvocationContext context) throws Exception {
context.getContextData().put("wildfly.ejb.timer.refresh.enabled", Boolean.TRUE);
return context.proceed();
}
}
| 1,558 | 37.975 | 88 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/timer/database/TimedObjectTimerServiceBean.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.timer.database;
import org.jboss.as.test.shared.FileUtils;
import jakarta.annotation.Resource;
import jakarta.ejb.EJB;
import jakarta.ejb.Stateless;
import jakarta.ejb.TimedObject;
import jakarta.ejb.Timer;
import jakarta.ejb.TimerConfig;
import jakarta.ejb.TimerService;
import java.util.Date;
/**
* @author Stuart Douglas
*/
@Stateless
public class TimedObjectTimerServiceBean implements TimedObject, RemoteTimedBean {
@Resource
private TimerService timerService;
private volatile boolean run = false;
@EJB(lookup = "ejb:/testTimerServiceSimple/CollectionSingleton!org.jboss.as.test.multinode.ejb.timer.database.Collector")
private Collector collector;
private static final String NODE;
static {
NODE = FileUtils.readFile(TimedObjectTimerServiceBean.class.getClassLoader().getResource("node.txt"));
}
@Override
public void scheduleTimer(long date, String info) {
timerService.createSingleActionTimer(new Date(date), new TimerConfig(info, true));
}
@Override
public boolean hasTimerRun() {
return run;
}
@Override
public void ejbTimeout(final Timer timer) {
run = true;
collector.timerRun(NODE, (String) timer.getInfo());
}
}
| 2,305 | 31.027778 | 125 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/timer/database/StartupSingleton.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2021, 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.multinode.ejb.timer.database;
import java.io.Serializable;
import java.util.Collection;
import jakarta.annotation.Resource;
import jakarta.ejb.ConcurrencyManagement;
import jakarta.ejb.ConcurrencyManagementType;
import jakarta.ejb.Schedule;
import jakarta.ejb.Schedules;
import jakarta.ejb.Singleton;
import jakarta.ejb.Startup;
import jakarta.ejb.Timer;
import jakarta.ejb.TimerService;
import jakarta.ejb.TransactionManagement;
import jakarta.ejb.TransactionManagementType;
@Singleton
@Startup
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
@TransactionManagement(TransactionManagementType.BEAN)
public class StartupSingleton implements RemoteTimedBean {
@Resource
private TimerService timerService;
@Override
public void scheduleTimer(final long date, final String info) {
throw new UnsupportedOperationException();
}
@Override
public boolean hasTimerRun() {
final Collection<Timer> timers = timerService.getTimers();
if (timers.size() != 2) {
throw new IllegalStateException("Expected 2 timers for StartupSingleton, but got " + timers.size());
}
for (Timer t : timers) {
final Serializable info = t.getInfo();
if (!info.equals("ZERO") && !info.equals("ONE")) {
throw new IllegalStateException("Unexpected timer info: " + info);
}
}
return true;
}
@Schedules({
@Schedule(dayOfMonth = "*", second = "*", minute = "*", hour = "*", year="9999", persistent = true, info = "ZERO", timezone = "America/New_York")
})
private void schedule0() {
}
@Schedules({
@Schedule(dayOfMonth = "*", second = "*", minute = "*", hour = "*", year="9999", persistent = true, info = "ONE")
})
private void schedule1(Timer timer) {
}
}
| 2,864 | 34.8125 | 149 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/timer/database/TimerData.java
|
package org.jboss.as.test.multinode.ejb.timer.database;
import java.io.Serializable;
/**
* @author Stuart Douglas
*/
public class TimerData implements Serializable {
private final String node;
private final String info;
public TimerData(String node, String info) {
this.node = node;
this.info = info;
}
public String getNode() {
return node;
}
public String getInfo() {
return info;
}
@Override
public String toString() {
return "{" +
"node='" + node + '\'' +
", info='" + info + '\'' +
'}';
}
}
| 637 | 17.764706 | 55 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/http/EjbOverHttpDescriptorTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.http;
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.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.naming.InitialContext;
import java.net.SocketPermission;
import java.util.Arrays;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createFilePermission;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
/**
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
@RunWith(Arquillian.class)
public class EjbOverHttpDescriptorTestCase {
private static final Logger log = Logger.getLogger(EjbOverHttpDescriptorTestCase.class);
public static final String ARCHIVE_NAME_SERVER = "ejboverhttp-test-server";
public static final String ARCHIVE_NAME_CLIENT = "ejboverhttp--descriptor-test-client";
public static final int NO_EJB_RETURN_CODE = -1;
private static final int serverPort = 8180;
@ArquillianResource
private Deployer deployer;
@Deployment(name = "server", managed = false)
@TargetsContainer("multinode-server")
public static Archive<?> deployment0() {
JavaArchive jar = createJar(ARCHIVE_NAME_SERVER);
return jar;
}
@Deployment(name = "client")
@TargetsContainer("multinode-client")
public static Archive<?> deployment1() {
JavaArchive clientJar = createClientJar();
return clientJar;
}
private static JavaArchive createJar(String archiveName) {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, archiveName + ".jar");
jar.addClasses(StatelessBean.class, StatelessLocal.class, StatelessRemote.class);
return jar;
}
private static JavaArchive createClientJar() {
JavaArchive jar = createJar(EjbOverHttpDescriptorTestCase.ARCHIVE_NAME_CLIENT);
jar.addClasses(EjbOverHttpDescriptorTestCase.class);
jar.addAsManifestResource("META-INF/jboss-ejb-client-http-connections.xml", "jboss-ejb-client.xml")
.addAsManifestResource("ejb-http-wildfly-config.xml", "wildfly-config.xml")
.addAsManifestResource(
createPermissionsXmlAsset(
createFilePermission("read,write,delete",
"jbossas.multinode.client", Arrays.asList("standalone", "data", "ejb-xa-recovery", "-")),
new SocketPermission(TestSuiteEnvironment.formatPossibleIpv6Address(System.getProperty("node0")) + ":" + serverPort,
"connect,resolve")),
"permissions.xml");
return jar;
}
@Test
@OperateOnDeployment("client")
public void testBasicInvocation(@ArquillianResource InitialContext ctx) throws Exception {
deployer.deploy("server");
StatelessRemote bean = (StatelessRemote) ctx.lookup("java:module/" + StatelessBean.class.getSimpleName() + "!"
+ StatelessRemote.class.getName());
Assert.assertNotNull(bean);
// initial discovery
int methodCount = bean.remoteCall();
Assert.assertEquals(1, methodCount);
deployer.undeploy("server");
// failed discovery after undeploying server deployment
int returnValue = bean.remoteCall();
Assert.assertEquals(NO_EJB_RETURN_CODE, returnValue);
deployer.deploy("server");
// rediscovery after redeployment
methodCount = bean.remoteCall();
Assert.assertEquals(1, methodCount);
}
}
| 5,166 | 41.702479 | 148 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/http/EjbOverHttpTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.http;
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.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
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.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.naming.InitialContext;
import java.net.SocketPermission;
import java.util.Arrays;
import java.util.Collections;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createFilePermission;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
/**
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
@RunWith(Arquillian.class)
@ServerSetup(EjbOverHttpTestCase.EjbOverHttpTestCaseServerSetup.class)
public class EjbOverHttpTestCase {
private static final Logger log = Logger.getLogger(EjbOverHttpTestCase.class);
public static final String ARCHIVE_NAME_SERVER = "ejboverhttp-test-server";
public static final String ARCHIVE_NAME_CLIENT = "ejboverhttp-test-client";
public static final int NO_EJB_RETURN_CODE = -1;
private static final int serverPort = 8180;
@ArquillianResource
private Deployer deployer;
static class EjbOverHttpTestCaseServerSetup implements ServerSetupTask {
private static final PathAddress ADDR_REMOTING_PROFILE = PathAddress.pathAddress().append(SUBSYSTEM, "ejb3").append("remoting-profile", "test-profile");
private static final PathAddress ADDR_REMOTE_HTTP_CONNECTION = ADDR_REMOTING_PROFILE.append("remote-http-connection", "remote-connection");
@Override
public void setup(final ManagementClient managementClient, final String containerId) throws Exception {
final ModelNode compositeOp = new ModelNode();
compositeOp.get(OP).set(COMPOSITE);
compositeOp.get(OP_ADDR).setEmptyList();
ModelNode steps = compositeOp.get(STEPS);
// /subsystem=ejb3/remoting-profile=test-profile:add()
ModelNode remotingProfileAddModelNode = Util.createAddOperation(ADDR_REMOTING_PROFILE);
steps.add(remotingProfileAddModelNode);
// /subsystem=ejb3/remoting-profile=test-profile/remoting-ejb-receiver=test-connection:add(remote-http-connection=remote-ejb-connection)
ModelNode ejbReceiverAddModelNode = Util.createAddOperation(ADDR_REMOTE_HTTP_CONNECTION);
ejbReceiverAddModelNode.get("uri").set("http://localhost:8180/wildfly-services");
steps.add(ejbReceiverAddModelNode);
Utils.applyUpdates(Collections.singletonList(compositeOp), managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
@Override
public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception {
ModelNode remotingProfileRemoveModelNode = Util.createRemoveOperation(ADDR_REMOTING_PROFILE);
//remotingProfileRemoveModelNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
Utils.applyUpdates(Collections.singletonList(remotingProfileRemoveModelNode), managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
}
@BeforeClass
public static void printSysProps() {
log.trace("System properties:\n" + System.getProperties());
}
@Deployment(name = "server", managed = false)
@TargetsContainer("multinode-server")
public static Archive<?> deployment0() {
JavaArchive jar = createJar(ARCHIVE_NAME_SERVER);
return jar;
}
@Deployment(name = "client")
@TargetsContainer("multinode-client")
public static Archive<?> deployment1() {
JavaArchive clientJar = createClientJar();
return clientJar;
}
private static JavaArchive createJar(String archiveName) {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, archiveName + ".jar");
jar.addClasses(StatelessBean.class, StatelessLocal.class, StatelessRemote.class);
return jar;
}
private static JavaArchive createClientJar() {
JavaArchive jar = createJar(EjbOverHttpTestCase.ARCHIVE_NAME_CLIENT);
jar.addClasses(EjbOverHttpTestCase.class);
jar.addAsManifestResource("META-INF/jboss-ejb-client-profile.xml", "jboss-ejb-client.xml")
.addAsManifestResource("ejb-http-wildfly-config.xml", "wildfly-config.xml")
.addAsManifestResource(
createPermissionsXmlAsset(
createFilePermission("read,write,delete",
"jbossas.multinode.client", Arrays.asList("standalone", "data", "ejb-xa-recovery", "-")),
new SocketPermission(TestSuiteEnvironment.formatPossibleIpv6Address(System.getProperty("node0")) + ":" + serverPort,
"connect,resolve")),
"permissions.xml");
return jar;
}
@Test
@OperateOnDeployment("client")
public void testBasicInvocation(@ArquillianResource InitialContext ctx) throws Exception {
deployer.deploy("server");
StatelessRemote bean = (StatelessRemote) ctx.lookup("java:module/" + StatelessBean.class.getSimpleName() + "!"
+ StatelessRemote.class.getName());
Assert.assertNotNull(bean);
// initial discovery
int methodCount = bean.remoteCall();
Assert.assertEquals(1, methodCount);
deployer.undeploy("server");
// failed discovery after undeploying server deployment
int returnValue = bean.remoteCall();
Assert.assertEquals(NO_EJB_RETURN_CODE, returnValue);
deployer.deploy("server");
// rediscovery after redeployment
methodCount = bean.remoteCall();
Assert.assertEquals(1, methodCount);
}
}
| 8,288 | 45.567416 | 160 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/http/EjbOverHttpWrongCredentialsTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.http;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createFilePermission;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.net.SocketPermission;
import java.util.Arrays;
import javax.naming.InitialContext;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* EJB over HTTP remote call should fail with incorrect wildfly-config.xml credentials
*
* @author <a href="mailto:[email protected]">Sultan Zhantemirov</a>
*/
@RunWith(Arquillian.class)
@ServerSetup(EjbOverHttpTestCase.EjbOverHttpTestCaseServerSetup.class)
public class EjbOverHttpWrongCredentialsTestCase {
public static final String ARCHIVE_NAME_SERVER = "ejboverhttp-test-server";
public static final String ARCHIVE_NAME_CLIENT_WRONG_CREDENTIALS = "ejboverhttp-test-client-wrong-credentials";
private static final int serverPort = 8180;
@Deployment(name = "server")
@TargetsContainer("multinode-server")
public static Archive<?> deployment0() {
JavaArchive jar = createJar(ARCHIVE_NAME_SERVER);
return jar;
}
@Deployment(name = "client-wrong-credentials")
@TargetsContainer("multinode-client")
public static Archive<?> deployment1() {
JavaArchive jar = createClientJar();
return jar;
}
private static JavaArchive createJar(String archiveName) {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, archiveName + ".jar");
jar.addClasses(StatelessBean.class, StatelessLocal.class, StatelessRemote.class);
return jar;
}
private static JavaArchive createClientJar() {
JavaArchive jar = createJar(EjbOverHttpWrongCredentialsTestCase.ARCHIVE_NAME_CLIENT_WRONG_CREDENTIALS);
jar.addClasses(EjbOverHttpTestCase.class);
jar.addAsManifestResource("META-INF/jboss-ejb-client-profile.xml", "jboss-ejb-client.xml")
.addAsManifestResource("ejb-http-wildfly-config-wrong.xml", "wildfly-config.xml")
.addAsManifestResource(
createPermissionsXmlAsset(
createFilePermission("read,write,delete",
"jbossas.multinode.client", Arrays.asList("standalone", "data", "ejb-xa-recovery", "-")),
new SocketPermission(TestSuiteEnvironment.formatPossibleIpv6Address(System.getProperty("node0")) + ":" + serverPort,
"connect,resolve")),
"permissions.xml");
return jar;
}
@Test
@OperateOnDeployment("client-wrong-credentials")
public void testBasicInvocationWithWrongCredentials(@ArquillianResource InitialContext ctx) throws Exception {
StatelessRemote bean = (StatelessRemote) ctx.lookup("java:module/" + StatelessBean.class.getSimpleName() + "!"
+ StatelessRemote.class.getName());
Assert.assertNotNull(bean);
try {
int methodCount = bean.remoteCall();
Assert.assertEquals(EjbOverHttpTestCase.NO_EJB_RETURN_CODE, methodCount);
} catch (javax.naming.AuthenticationException e) {
// expected
}
}
}
| 4,866 | 44.485981 | 148 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/http/StatelessRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.http;
/**
* @author <a href="mailto:[email protected]">William DeCoste</a>
*/
public interface StatelessRemote extends jakarta.ejb.EJBObject {
int remoteCall() throws Exception;
int method() throws Exception;
}
| 1,296 | 39.53125 | 70 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/http/StatelessBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.http;
import org.jboss.logging.Logger;
import jakarta.ejb.Local;
import jakarta.ejb.NoSuchEJBException;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;
@Stateless
@Local(StatelessLocal.class)
@Remote(StatelessRemote.class)
public class StatelessBean {
private static final Logger log = Logger.getLogger(StatelessBean.class);
private static int methodCount = 0;
private InitialContext getInitialContext() throws NamingException {
final Properties props = new Properties();
// setup the Jakarta Enterprise Beans: namespace URL factory
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
return new InitialContext(props);
}
public int remoteCall() throws Exception {
++methodCount;
InitialContext jndiContext = getInitialContext();
log.trace("Calling Remote... " + jndiContext.getEnvironment());
StatelessRemote stateless = (StatelessRemote) jndiContext.lookup("ejb:/" +EjbOverHttpTestCase.ARCHIVE_NAME_SERVER
+ "//" + StatelessBean.class.getSimpleName() + "!" + StatelessRemote.class.getName());
try {
return stateless.method();
} catch (NoSuchEJBException e) {
return EjbOverHttpTestCase.NO_EJB_RETURN_CODE;
}
}
public int method() throws Exception {
++methodCount;
log.trace("Method called " + methodCount);
return methodCount;
}
}
| 2,652 | 36.9 | 121 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/ejb/http/StatelessLocal.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.ejb.http;
public interface StatelessLocal extends jakarta.ejb.EJBLocalObject {
int method() throws Exception;
}
| 1,186 | 41.392857 | 70 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/StatefulLocal.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.remotecall;
/**
* @author <a href="mailto:[email protected]">William DeCoste</a>
*/
public interface StatefulLocal extends jakarta.ejb.EJBLocalObject {
void localCall() throws Exception;
void localHomeCall() throws Exception;
int remoteCall() throws Exception;
int remoteHomeCall() throws Exception;
int method() throws Exception;
int homeMethod() throws Exception;
}
| 1,470 | 34.878049 | 70 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/StatefulBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.remotecall;
import java.util.Properties;
import jakarta.ejb.Local;
import jakarta.ejb.LocalHome;
import jakarta.ejb.Remote;
import jakarta.ejb.RemoteHome;
import jakarta.ejb.Stateful;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.logging.Logger;
/**
* @author William DeCoste
*/
@Stateful
@Local(StatefulLocal.class)
@LocalHome(StatefulLocalHome.class)
@Remote(StatefulRemote.class)
@RemoteHome(StatefulRemoteHome.class)
public class StatefulBean {
private static final Logger log = Logger.getLogger(StatefulBean.class);
private static int methodCount = 0;
private static int homeMethodCount = 0;
private InitialContext getInitialContext() throws NamingException {
final Properties props = new Properties();
// setup the Jakarta Enterprise Beans: namespace URL factory
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
return new InitialContext(props);
}
public void localCall() throws Exception {
InitialContext jndiContext = getInitialContext();
log.trace("Calling Local remotely... " + jndiContext.getEnvironment());
StatelessLocal stateless = (StatelessLocal) jndiContext.lookup("ejb:/" + RemoteLocalCallTestCase.ARCHIVE_NAME_SERVER
+ "//" + StatelessBean.class.getSimpleName() + "!" + StatelessLocal.class.getName());
stateless.method();
}
public void localHomeCall() throws Exception {
InitialContext jndiContext = getInitialContext();
log.trace("Calling LocalHome remotely... " + jndiContext.getEnvironment());
StatelessLocalHome statelessHome = (StatelessLocalHome) jndiContext.lookup("ejb:/"
+ RemoteLocalCallTestCase.ARCHIVE_NAME_SERVER + "//" + StatelessBean.class.getSimpleName() + "!"
+ StatelessLocalHome.class.getName());
StatelessLocal stateless = statelessHome.create();
stateless.homeMethod();
}
public int remoteCall() throws Exception {
++methodCount;
InitialContext jndiContext = getInitialContext();
log.trace("Calling Remote... " + jndiContext.getEnvironment());
StatefulRemote stateful = (StatefulRemote) jndiContext.lookup("ejb:/" + RemoteLocalCallTestCase.ARCHIVE_NAME_SERVER
+ "//" + StatefulBean.class.getSimpleName() + "!" + StatefulRemote.class.getName() + "?stateful");
log.trace("We have got statefulbean...");
return stateful.method();
}
public int remoteHomeCall() throws Exception {
++homeMethodCount;
InitialContext jndiContext = new InitialContext();
log.trace("Calling RemoteHome... " + jndiContext.getEnvironment());
StatefulRemoteHome statefulHome = (StatefulRemoteHome) jndiContext.lookup("ejb:/"
+ RemoteLocalCallTestCase.ARCHIVE_NAME_SERVER + "//" + StatefulBean.class.getSimpleName() + "!"
+ StatefulRemoteHome.class.getName());
StatefulRemote stateful = statefulHome.create();
return stateful.homeMethod();
}
public int method() throws Exception {
++methodCount;
log.trace("Method called " + methodCount);
return methodCount;
}
public int homeMethod() throws Exception {
log.trace("Before adding ++ is homeMethodCount: " + homeMethodCount);
++homeMethodCount;
log.trace("HomeMethod called " + homeMethodCount);
return homeMethodCount;
}
public void ejbCreate() throws java.rmi.RemoteException, jakarta.ejb.CreateException {
log.debug("Creating method for home interface...");
}
}
| 4,739 | 39.862069 | 124 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/StatefulRemoteHome.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.remotecall;
import jakarta.ejb.EJBHome;
/**
* @author <a href="mailto:[email protected]">William DeCoste</a>
*/
public interface StatefulRemoteHome extends EJBHome {
StatefulRemote create() throws java.rmi.RemoteException, jakarta.ejb.CreateException;
}
| 1,332 | 39.393939 | 89 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/StatefulRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.remotecall;
/**
* @author <a href="mailto:[email protected]">William DeCoste</a>
*/
public interface StatefulRemote extends jakarta.ejb.EJBObject {
void localCall() throws Exception;
void localHomeCall() throws Exception;
int remoteCall() throws Exception;
int remoteHomeCall() throws Exception;
int method() throws Exception;
int homeMethod() throws Exception;
}
| 1,466 | 34.780488 | 70 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/StatelessRemoteHome.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.remotecall;
import jakarta.ejb.EJBHome;
/**
* @author <a href="mailto:[email protected]">William DeCoste</a>
*/
public interface StatelessRemoteHome extends EJBHome {
StatelessRemote create() throws java.rmi.RemoteException, jakarta.ejb.CreateException;
}
| 1,334 | 39.454545 | 90 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/StatelessRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.remotecall;
/**
* @author <a href="mailto:[email protected]">William DeCoste</a>
*/
public interface StatelessRemote extends jakarta.ejb.EJBObject {
void localCall() throws Exception;
void localHomeCall() throws Exception;
int remoteCall() throws Exception;
int remoteHomeCall() throws Exception;
int method() throws Exception;
int homeMethod() throws Exception;
}
| 1,467 | 34.804878 | 70 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/StatelessLocalHome.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.remotecall;
import jakarta.ejb.EJBHome;
/**
* @author <a href="mailto:[email protected]">William DeCoste</a>
*/
public interface StatelessLocalHome extends EJBHome {
StatelessLocal create() throws java.rmi.RemoteException, jakarta.ejb.CreateException;
}
| 1,333 | 38.235294 | 89 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/RemoteLocalCallTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.remotecall;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createFilePermission;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.security.SecurityPermission;
import java.util.Arrays;
import jakarta.ejb.EJBException;
import javax.naming.InitialContext;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
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.spec.JavaArchive;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Testing multinode communication - calling Stateless and Stateful beans (via remote and local and home interfaces).
*
* @author William DeCoste, Ondrej Chaloupka
*/
@RunWith(Arquillian.class)
public class RemoteLocalCallTestCase {
private static final Logger log = Logger.getLogger(RemoteLocalCallTestCase.class);
public static final String ARCHIVE_NAME_CLIENT = "remotelocalcall-test-client";
public static final String ARCHIVE_NAME_SERVER = "remotelocalcall-test-server";
@BeforeClass
public static void printSysProps() {
log.trace("System properties:\n" + System.getProperties());
}
@Deployment(name = "server")
@TargetsContainer("multinode-server")
public static Archive<?> deployment0() {
JavaArchive jar = createJar(ARCHIVE_NAME_SERVER);
return jar;
}
@Deployment(name = "client")
@TargetsContainer("multinode-client")
public static Archive<?> deployment1() {
JavaArchive jar = createJar(ARCHIVE_NAME_CLIENT);
jar.addClasses(RemoteLocalCallTestCase.class);
jar.addAsManifestResource("META-INF/jboss-ejb-client-receivers.xml", "jboss-ejb-client.xml");
jar.addAsManifestResource(
createPermissionsXmlAsset(
createFilePermission("delete",
"jbossas.multinode.client", Arrays.asList("standalone", "data", "ejb-xa-recovery", "-")),
createFilePermission("read",
"jboss.home", Arrays.asList("standalone", "tmp", "auth", "-")),
new SecurityPermission("putProviderProperty.WildFlyElytron")),
"permissions.xml");
return jar;
}
private static JavaArchive createJar(String archiveName) {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, archiveName + ".jar");
jar.addClasses(StatefulBean.class, StatefulLocal.class, StatefulLocalHome.class, StatefulRemote.class,
StatefulRemoteHome.class, StatelessBean.class, StatelessLocal.class, StatelessLocalHome.class,
StatelessRemote.class, StatelessRemoteHome.class);
return jar;
}
@Test
@OperateOnDeployment("client")
public void testStatelessLocalFromRemote(@ArquillianResource InitialContext ctx) throws Exception {
StatefulRemote bean = (StatefulRemote) ctx.lookup("java:module/" + StatefulBean.class.getSimpleName() + "!"
+ StatefulRemote.class.getName());
Assert.assertNotNull(bean);
try {
bean.localCall();
Assert.fail("should not be allowed to call local interface remotely");
} catch (EJBException e) {
// it's OK
} catch (Exception ee) {
if(!(ee.getCause() instanceof EJBException)) {
Assert.fail("should be " + EJBException.class.getName());
}
}
}
@Test
@OperateOnDeployment("client")
public void testStatelessLocalHomeFromRemoteHome(@ArquillianResource InitialContext ctx) throws Exception {
StatefulRemoteHome home = (StatefulRemoteHome) ctx.lookup("java:module/" + StatefulBean.class.getSimpleName() + "!"
+ StatefulRemoteHome.class.getName());
StatefulRemote bean = home.create();
Assert.assertNotNull(bean);
try {
bean.localHomeCall();
Assert.fail("should not be allowed to call local interface remotely");
} catch (EJBException e) {
// it's OK
} catch (Exception ee) {
if(!(ee.getCause() instanceof EJBException)) {
Assert.fail("should be " + EJBException.class.getName());
}
}
}
@Test
@OperateOnDeployment("client")
public void testStatelessRemoteFromRemote(@ArquillianResource InitialContext ctx) throws Exception {
StatefulRemote bean = (StatefulRemote) ctx.lookup("java:module/" + StatefulBean.class.getSimpleName() + "!"
+ StatefulRemote.class.getName());
Assert.assertNotNull(bean);
int methodCount = bean.remoteCall();
Assert.assertEquals(1, methodCount);
}
@Test
@OperateOnDeployment("client")
public void testStatelessRemoteHomeFromRemoteHome(@ArquillianResource InitialContext ctx) throws Exception {
StatefulRemoteHome home = (StatefulRemoteHome) ctx.lookup("java:module/" + StatefulBean.class.getSimpleName() + "!"
+ StatefulRemoteHome.class.getName());
StatefulRemote bean = home.create();
Assert.assertNotNull(bean);
int methodCount = bean.remoteHomeCall();
Assert.assertEquals(1, methodCount);
}
@Test
@OperateOnDeployment("client")
public void testStatefulRemoteFromRemote(@ArquillianResource InitialContext ctx) throws Exception {
StatelessRemote bean = (StatelessRemote) ctx.lookup("java:module/" + StatelessBean.class.getSimpleName() + "!"
+ StatelessRemote.class.getName());
Assert.assertNotNull(bean);
int methodCount = bean.remoteCall();
Assert.assertEquals(1, methodCount);
}
@Test
@OperateOnDeployment("client")
public void testStatefulRemoteHomeFromRemoteHome(@ArquillianResource InitialContext ctx) throws Exception {
StatelessRemoteHome home = (StatelessRemoteHome) ctx.lookup("java:module/" + StatelessBean.class.getSimpleName() + "!"
+ StatelessRemoteHome.class.getName());
StatelessRemote bean = home.create();
Assert.assertNotNull(bean);
int methodCount = bean.remoteHomeCall();
Assert.assertEquals(1, methodCount);
}
@Test
@OperateOnDeployment("client")
public void testStatefulLocalFromRemote(@ArquillianResource InitialContext ctx) throws Exception {
InitialContext jndiContext = new InitialContext();
StatelessRemote bean = (StatelessRemote) jndiContext.lookup("java:module/" + StatelessBean.class.getSimpleName() + "!"
+ StatelessRemote.class.getName());
Assert.assertNotNull(bean);
try {
bean.localCall();
Assert.fail("should not be allowed to call local interface remotely");
} catch (EJBException e) {
// it's OK
} catch (Exception ee) {
if(!(ee.getCause() instanceof EJBException)) {
Assert.fail("should be " + EJBException.class.getName());
}
}
}
@Test
@OperateOnDeployment("client")
public void testStatefulLocalHomeFromRemoteHome(@ArquillianResource InitialContext ctx) throws Exception {
InitialContext jndiContext = new InitialContext();
StatelessRemoteHome home = (StatelessRemoteHome) jndiContext.lookup("java:module/"
+ StatelessBean.class.getSimpleName() + "!" + StatelessRemoteHome.class.getName());
StatelessRemote bean = home.create();
Assert.assertNotNull(bean);
try {
bean.localHomeCall();
Assert.fail("should not be allowed to call local interface remotely");
} catch (EJBException e) {
// it's OK
} catch (Exception ee) {
if(!(ee.getCause() instanceof EJBException)) {
Assert.fail("should be " + EJBException.class.getName());
}
}
}
}
| 9,359 | 41.545455 | 126 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/StatelessBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.remotecall;
import java.util.Properties;
import jakarta.ejb.Local;
import jakarta.ejb.LocalHome;
import jakarta.ejb.Remote;
import jakarta.ejb.RemoteHome;
import jakarta.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.logging.Logger;
/**
* @author <a href="mailto:[email protected]">William DeCoste</a>
*/
@Stateless
@Local(StatelessLocal.class)
@LocalHome(StatelessLocalHome.class)
@Remote(StatelessRemote.class)
@RemoteHome(StatelessRemoteHome.class)
public class StatelessBean {
private static final Logger log = Logger.getLogger(StatelessBean.class);
private static int methodCount = 0;
private static int homeMethodCount = 0;
private InitialContext getInitialContext() throws NamingException {
final Properties props = new Properties();
// setup the Jakarta Enterprise Beans: namespace URL factory
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
return new InitialContext(props);
}
public void localCall() throws Exception {
InitialContext jndiContext = getInitialContext();
log.trace("Calling Local remotely... " + jndiContext.getEnvironment());
StatefulLocal stateful = (StatefulLocal) jndiContext.lookup("ejb:/" + RemoteLocalCallTestCase.ARCHIVE_NAME_SERVER
+ "//" + StatefulBean.class.getSimpleName() + "!" + StatefulLocal.class.getName());
stateful.method();
}
public void localHomeCall() throws Exception {
InitialContext jndiContext = getInitialContext();
log.trace("Calling LocalHome remotely... " + jndiContext.getEnvironment());
StatefulLocalHome statefulHome = (StatefulLocalHome) jndiContext.lookup("ejb:/" + StatefulBean.class.getSimpleName()
+ "!" + StatefulLocalHome.class.getName());
StatefulLocal stateful = statefulHome.create();
stateful.homeMethod();
}
public int remoteCall() throws Exception {
++methodCount;
InitialContext jndiContext = getInitialContext();
log.trace("Calling Remote... " + jndiContext.getEnvironment());
StatelessRemote stateless = (StatelessRemote) jndiContext.lookup("ejb:/" + RemoteLocalCallTestCase.ARCHIVE_NAME_SERVER
+ "//" + StatelessBean.class.getSimpleName() + "!" + StatelessRemote.class.getName());
return stateless.method();
}
public int remoteHomeCall() throws Exception {
++homeMethodCount;
InitialContext jndiContext = getInitialContext();
StatelessRemoteHome statelessHome = (StatelessRemoteHome) jndiContext.lookup("ejb:/"
+ RemoteLocalCallTestCase.ARCHIVE_NAME_SERVER + "//" + StatelessBean.class.getSimpleName() + "!"
+ StatelessRemoteHome.class.getName());
StatelessRemote stateless = statelessHome.create();
return stateless.homeMethod();
}
public int method() throws Exception {
++methodCount;
log.trace("Method called " + methodCount);
return methodCount;
}
public int homeMethod() throws Exception {
++homeMethodCount;
log.trace("HomeMethod called " + homeMethodCount);
return homeMethodCount;
}
public void ejbCreate() throws java.rmi.RemoteException, jakarta.ejb.CreateException {
log.debug("Creating method for home interface...");
}
}
| 4,496 | 39.513514 | 126 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/StatelessLocal.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.remotecall;
/**
* @author <a href="mailto:[email protected]">William DeCoste</a>
*/
public interface StatelessLocal extends jakarta.ejb.EJBLocalObject {
int method() throws Exception;
int homeMethod() throws Exception;
}
| 1,303 | 38.515152 | 70 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/StatefulLocalHome.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.remotecall;
import jakarta.ejb.EJBHome;
/**
* @author <a href="mailto:[email protected]">William DeCoste</a>
*/
public interface StatefulLocalHome extends EJBHome {
StatefulLocal create() throws java.rmi.RemoteException, jakarta.ejb.CreateException;
}
| 1,330 | 39.333333 | 88 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/RemoteLocalCallProfileTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.multinode.remotecall;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createFilePermission;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.util.Arrays;
import java.util.Collections;
import jakarta.ejb.EJBException;
import javax.naming.InitialContext;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.security.common.Utils;
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.spec.JavaArchive;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Testing multinode communication - calling Stateless and Stateful beans (via remote and local and home interfaces).
*
* @author William DeCoste, Ondrej Chaloupka
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
@RunWith(Arquillian.class)
@ServerSetup(RemoteLocalCallProfileTestCase.RemoteLocalCallProfileTestCaseServerSetup.class)
public class RemoteLocalCallProfileTestCase {
private static final Logger log = Logger.getLogger(RemoteLocalCallProfileTestCase.class);
public static final String ARCHIVE_NAME_CLIENT = "remotelocalcall-test-client";
public static final String ARCHIVE_NAME_SERVER = "remotelocalcall-test-server";
static class RemoteLocalCallProfileTestCaseServerSetup implements ServerSetupTask {
private static final PathAddress ADDR_REMOTING_PROFILE = PathAddress.pathAddress().append(SUBSYSTEM, "ejb3").append("remoting-profile", "test-profile");
private static final PathAddress ADDR_REMOTING_EJB_RECEIVER = ADDR_REMOTING_PROFILE.append("remoting-ejb-receiver", "test-receiver");
@Override
public void setup(final ManagementClient managementClient, final String containerId) throws Exception {
final ModelNode compositeOp = new ModelNode();
compositeOp.get(OP).set(COMPOSITE);
compositeOp.get(OP_ADDR).setEmptyList();
ModelNode steps = compositeOp.get(STEPS);
// /subsystem=ejb3/remoting-profile=test-profile:add()
ModelNode remotingProfileAddModelNode = Util.createAddOperation(ADDR_REMOTING_PROFILE);
steps.add(remotingProfileAddModelNode);
// /subsystem=ejb3/remoting-profile=test-profile/remoting-ejb-receiver=test-receiver:add(outbound-connection-ref=remote-ejb-connection)
ModelNode ejbReceiverAddModelNode = Util.createAddOperation(ADDR_REMOTING_EJB_RECEIVER);
ejbReceiverAddModelNode.get("outbound-connection-ref").set("remote-ejb-connection");
steps.add(ejbReceiverAddModelNode);
Utils.applyUpdates(Collections.singletonList(compositeOp), managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
@Override
public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception {
ModelNode remotingProfileRemoveModelNode = Util.createRemoveOperation(ADDR_REMOTING_PROFILE);
//remotingProfileRemoveModelNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
Utils.applyUpdates(Collections.singletonList(remotingProfileRemoveModelNode), managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
}
@BeforeClass
public static void printSysProps() {
log.trace("System properties:\n" + System.getProperties());
}
@Deployment(name = "server")
@TargetsContainer("multinode-server")
public static Archive<?> deployment0() {
JavaArchive jar = createJar(ARCHIVE_NAME_SERVER);
return jar;
}
@Deployment(name = "client")
@TargetsContainer("multinode-client")
public static Archive<?> deployment1() {
JavaArchive jar = createJar(ARCHIVE_NAME_CLIENT);
jar.addClasses(RemoteLocalCallProfileTestCase.class);
jar.addAsManifestResource("META-INF/jboss-ejb-client-profile.xml", "jboss-ejb-client.xml");
jar.addAsManifestResource(
createPermissionsXmlAsset(
createFilePermission("delete",
"jbossas.multinode.client", Arrays.asList("standalone", "data", "ejb-xa-recovery", "-")),
createFilePermission("read",
"jboss.home", Arrays.asList("standalone", "tmp", "auth", "-"))),
"permissions.xml");
return jar;
}
private static JavaArchive createJar(String archiveName) {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, archiveName + ".jar");
jar.addClasses(StatefulBean.class, StatefulLocal.class, StatefulLocalHome.class, StatefulRemote.class,
StatefulRemoteHome.class, StatelessBean.class, StatelessLocal.class, StatelessLocalHome.class,
StatelessRemote.class, StatelessRemoteHome.class);
return jar;
}
@Test
@OperateOnDeployment("client")
public void testStatelessLocalFromRemote(@ArquillianResource InitialContext ctx) throws Exception {
StatefulRemote bean = (StatefulRemote) ctx.lookup("java:module/" + StatefulBean.class.getSimpleName() + "!"
+ StatefulRemote.class.getName());
Assert.assertNotNull(bean);
try {
bean.localCall();
Assert.fail("should not be allowed to call local interface remotely");
} catch (EJBException e) {
// it's OK
} catch (Exception ee) {
if(!(ee.getCause() instanceof EJBException)) {
Assert.fail("should be " + EJBException.class.getName());
}
}
}
@Test
@OperateOnDeployment("client")
public void testStatelessLocalHomeFromRemoteHome(@ArquillianResource InitialContext ctx) throws Exception {
StatefulRemoteHome home = (StatefulRemoteHome) ctx.lookup("java:module/" + StatefulBean.class.getSimpleName() + "!"
+ StatefulRemoteHome.class.getName());
StatefulRemote bean = home.create();
Assert.assertNotNull(bean);
try {
bean.localHomeCall();
Assert.fail("should not be allowed to call local interface remotely");
} catch (EJBException e) {
// it's OK
} catch (Exception ee) {
if(!(ee.getCause() instanceof EJBException)) {
Assert.fail("should be " + EJBException.class.getName());
}
}
}
@Test
@OperateOnDeployment("client")
public void testStatelessRemoteFromRemote(@ArquillianResource InitialContext ctx) throws Exception {
StatefulRemote bean = (StatefulRemote) ctx.lookup("java:module/" + StatefulBean.class.getSimpleName() + "!"
+ StatefulRemote.class.getName());
Assert.assertNotNull(bean);
int methodCount = bean.remoteCall();
Assert.assertEquals(1, methodCount);
}
@Test
@OperateOnDeployment("client")
public void testStatelessRemoteHomeFromRemoteHome(@ArquillianResource InitialContext ctx) throws Exception {
StatefulRemoteHome home = (StatefulRemoteHome) ctx.lookup("java:module/" + StatefulBean.class.getSimpleName() + "!"
+ StatefulRemoteHome.class.getName());
StatefulRemote bean = home.create();
Assert.assertNotNull(bean);
int methodCount = bean.remoteHomeCall();
Assert.assertEquals(1, methodCount);
}
@Test
@OperateOnDeployment("client")
public void testStatefulRemoteFromRemote(@ArquillianResource InitialContext ctx) throws Exception {
StatelessRemote bean = (StatelessRemote) ctx.lookup("java:module/" + StatelessBean.class.getSimpleName() + "!"
+ StatelessRemote.class.getName());
Assert.assertNotNull(bean);
int methodCount = bean.remoteCall();
Assert.assertEquals(1, methodCount);
}
@Test
@OperateOnDeployment("client")
public void testStatefulRemoteHomeFromRemoteHome(@ArquillianResource InitialContext ctx) throws Exception {
StatelessRemoteHome home = (StatelessRemoteHome) ctx.lookup("java:module/" + StatelessBean.class.getSimpleName() + "!"
+ StatelessRemoteHome.class.getName());
StatelessRemote bean = home.create();
Assert.assertNotNull(bean);
int methodCount = bean.remoteHomeCall();
Assert.assertEquals(1, methodCount);
}
@Test
@OperateOnDeployment("client")
public void testStatefulLocalFromRemote(@ArquillianResource InitialContext ctx) throws Exception {
InitialContext jndiContext = new InitialContext();
StatelessRemote bean = (StatelessRemote) jndiContext.lookup("java:module/" + StatelessBean.class.getSimpleName() + "!"
+ StatelessRemote.class.getName());
Assert.assertNotNull(bean);
try {
bean.localCall();
Assert.fail("should not be allowed to call local interface remotely");
} catch (EJBException e) {
// it's OK
} catch (Exception ee) {
if(!(ee.getCause() instanceof EJBException)) {
Assert.fail("should be " + EJBException.class.getName());
}
}
}
@Test
@OperateOnDeployment("client")
public void testStatefulLocalHomeFromRemoteHome(@ArquillianResource InitialContext ctx) throws Exception {
InitialContext jndiContext = new InitialContext();
StatelessRemoteHome home = (StatelessRemoteHome) jndiContext.lookup("java:module/"
+ StatelessBean.class.getSimpleName() + "!" + StatelessRemoteHome.class.getName());
StatelessRemote bean = home.create();
Assert.assertNotNull(bean);
try {
bean.localHomeCall();
Assert.fail("should not be allowed to call local interface remotely");
} catch (EJBException e) {
// it's OK
} catch (Exception ee) {
if(!(ee.getCause() instanceof EJBException)) {
Assert.fail("should be " + EJBException.class.getName());
}
}
}
}
| 12,366 | 44.803704 | 160 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/scoped/context/StatefulBeanA.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.multinode.remotecall.scoped.context;
import org.jboss.ejb3.annotation.Cache;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.ejb.CreateException;
import jakarta.ejb.LocalBean;
import jakarta.ejb.PostActivate;
import jakarta.ejb.PrePassivate;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateful;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
/**
* @author Jaikiran Pai
*/
@Stateful
@Remote(LocalServerStatefulRemote.class)
@LocalBean
@Cache("distributable") // reference to the passivating cache configuration which comes shipped in Enterprise Beans 3 subsystem
public class StatefulBeanA implements LocalServerStatefulRemote {
@Resource(name = "other-server-remoting-port")
private String otherServerRemotingPort;
@Resource(name = "other-server-host-address")
private String otherServerHostAddress;
@Resource(name = "other-server-auth-user-name")
private String otherServerAuthUserName;
@Resource(name = "other-server-auth-password")
private String otherServerAuthPassword;
private StatefulRemoteOnOtherServer statefulBeanOnOtherServer;
private StatelessRemoteOnOtherServer statelessRemoteOnOtherServer;
private StatefulRemoteHomeForBeanOnOtherServer statefulRemoteHomeForBeanOnOtherServer;
private transient CountDownLatch passivationNotificationLatch;
private boolean postActivateInvoked;
@PostConstruct
void onConstruct() throws Exception {
final Properties jndiProps = this.getInitialContextProperties();
final Context context = new InitialContext(jndiProps);
// lookup and set the SFSB from remote server
this.statefulBeanOnOtherServer = (StatefulRemoteOnOtherServer) context.lookup("ejb:/deployment-on-other-server//StatefulBeanOnOtherServer!" + StatefulRemoteOnOtherServer.class.getName() + "?stateful");
// lookup and set the SLSB from remote server
this.statelessRemoteOnOtherServer = (StatelessRemoteOnOtherServer) context.lookup("ejb:/deployment-on-other-server//StatelessBeanOnOtherServer!" + StatelessRemoteOnOtherServer.class.getName());
// Enterprise Beans 2.x remote home view of bean on other server
this.statefulRemoteHomeForBeanOnOtherServer = (StatefulRemoteHomeForBeanOnOtherServer) context.lookup("ejb:/deployment-on-other-server//StatefulBeanOnOtherServer!" + StatefulRemoteHomeForBeanOnOtherServer.class.getName());
}
@Override
public int getCountByInvokingOnRemoteServerBean() {
// invoke the SFSB which resides on a remote server and was looked up via JNDI
// using the scoped Jakarta Enterprise Beans client context feature
return this.statefulBeanOnOtherServer.getCount();
}
@Override
public int incrementCountByInvokingOnRemoteServerBean() {
// invoke the SFSB which resides on a remote server and was looked up via JNDI
// using the scoped Jakarta Enterprise Beans client context feature
return this.statefulBeanOnOtherServer.incrementCount();
}
@Override
public String getEchoByInvokingOnRemoteServerBean(final String msg) {
// invoke the SLSB which resides on a remote server and was looked up via JNDI
// using the scoped Jakarta Enterprise Beans client context feature
return this.statelessRemoteOnOtherServer.echo(msg);
}
public int getStatefulBeanCountUsingEJB2xHomeView() {
final StatefulRemoteOnOtherServer bean;
try {
bean = this.statefulRemoteHomeForBeanOnOtherServer.create();
} catch (CreateException e) {
throw new RuntimeException(e);
}
return bean.getCount();
}
public int getStatefulBeanCountUsingEJB2xHomeViewDifferentWay() {
final StatefulRemoteOnOtherServer bean;
try {
bean = this.statefulRemoteHomeForBeanOnOtherServer.createDifferentWay();
} catch (CreateException e) {
throw new RuntimeException(e);
}
return bean.getCount();
}
public int getStatefulBeanCountUsingEJB2xHomeViewYetAnotherWay(int initialCount) {
final StatefulRemoteOnOtherServer bean;
try {
bean = this.statefulRemoteHomeForBeanOnOtherServer.createYetAnotherWay(initialCount);
} catch (CreateException e) {
throw new RuntimeException(e);
}
return bean.getCount();
}
@Override
public void registerPassivationNotificationLatch(final CountDownLatch latch) {
this.passivationNotificationLatch = latch;
}
@Override
public boolean wasPostActivateInvoked() {
return this.postActivateInvoked;
}
@Override
public StatefulRemoteOnOtherServer getSFSBCreatedWithScopedEJBClientContext() {
return this.statefulBeanOnOtherServer;
}
@Override
public StatelessRemoteOnOtherServer getSLSBCreatedWithScopedEJBClientContext() {
return this.statelessRemoteOnOtherServer;
}
@PrePassivate
private void prePassivate() {
this.postActivateInvoked = false;
if (this.passivationNotificationLatch != null) {
this.passivationNotificationLatch.countDown();
}
}
@PostActivate
private void postActivate() {
this.postActivateInvoked = true;
}
private Properties getInitialContextProperties() {
final Properties jndiProps = new Properties();
// Property to enable scoped Jakarta Enterprise Beans client context which will be tied to the JNDI context
jndiProps.put("org.jboss.ejb.client.scoped.context", true);
// Property which will handle the ejb: namespace during JNDI lookup
jndiProps.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
final String connectionName = "foo-bar-connection";
jndiProps.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false");
// add a property which lists the connections that we are configuring. In
// this example, we are just configuring a single connection named "foo-bar-connection"
jndiProps.put("remote.connections", connectionName);
// add a property which points to the host server of the "foo-bar-connection"
jndiProps.put("remote.connection." + connectionName + ".host", this.otherServerHostAddress);
// add a property which points to the port on which the server is listening for Jakarta Enterprise Beans invocations
jndiProps.put("remote.connection." + connectionName + ".port", this.otherServerRemotingPort);
// add the username and password properties which will be used to establish this connection
jndiProps.put("remote.connection." + connectionName + ".username", this.otherServerAuthUserName);
jndiProps.put("remote.connection." + connectionName + ".password", this.otherServerAuthPassword);
return jndiProps;
}
}
| 8,059 | 42.101604 | 230 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/scoped/context/StatefulRemoteHomeForBeanOnOtherServer.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.multinode.remotecall.scoped.context;
import jakarta.ejb.CreateException;
import jakarta.ejb.EJBHome;
/**
* @author Jaikiran Pai
*/
public interface StatefulRemoteHomeForBeanOnOtherServer extends EJBHome {
StatefulRemoteOnOtherServer create() throws CreateException;
StatefulRemoteOnOtherServer createDifferentWay() throws CreateException;
StatefulRemoteOnOtherServer createYetAnotherWay(int initialCount) throws CreateException;
}
| 1,500 | 37.487179 | 93 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/scoped/context/StatefulRemoteOnOtherServer.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.multinode.remotecall.scoped.context;
/**
* @author Jaikiran Pai
*/
public interface StatefulRemoteOnOtherServer {
int getCount();
int incrementCount();
}
| 1,217 | 34.823529 | 70 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/scoped/context/StatelessBeanOnOtherServer.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.multinode.remotecall.scoped.context;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateless;
/**
* @author Jaikiran Pai
*/
@Stateless
@Remote (StatelessRemoteOnOtherServer.class)
public class StatelessBeanOnOtherServer implements StatelessRemoteOnOtherServer {
@Override
public String echo(String msg) {
return msg;
}
}
| 1,395 | 34.794872 | 81 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/scoped/context/PassivationConfigurationSetup.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.multinode.remotecall.scoped.context;
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;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
/**
* Setup for passivation test case.
*
* @author Jaikiran Pai
* @author Richard Achmatowicz
*/
public class PassivationConfigurationSetup implements ServerSetupTask {
private static final Logger log = Logger.getLogger(PassivationConfigurationSetup.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-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);
}
}
| 3,816 | 47.935897 | 153 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/scoped/context/LocalServerStatefulRemote.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.multinode.remotecall.scoped.context;
import java.util.concurrent.CountDownLatch;
/**
* @author Jaikiran Pai
*/
public interface LocalServerStatefulRemote {
int getCountByInvokingOnRemoteServerBean();
int incrementCountByInvokingOnRemoteServerBean();
String getEchoByInvokingOnRemoteServerBean(final String msg);
void registerPassivationNotificationLatch(final CountDownLatch latch);
boolean wasPostActivateInvoked();
StatefulRemoteOnOtherServer getSFSBCreatedWithScopedEJBClientContext();
StatelessRemoteOnOtherServer getSLSBCreatedWithScopedEJBClientContext();
}
| 1,653 | 34.956522 | 76 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/scoped/context/StatefulBeanOnOtherServer.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.multinode.remotecall.scoped.context;
import jakarta.ejb.Remote;
import jakarta.ejb.RemoteHome;
import jakarta.ejb.Stateful;
/**
* @author Jaikiran Pai
*/
@Stateful
@Remote(StatefulRemoteOnOtherServer.class)
@RemoteHome(StatefulRemoteHomeForBeanOnOtherServer.class)
public class StatefulBeanOnOtherServer implements StatefulRemoteOnOtherServer {
private int count;
@Override
public int getCount() {
return this.count;
}
@Override
public int incrementCount() {
this.count++;
return this.count;
}
public void ejbCreate() {
}
public void ejbCreateDifferentWay() {
}
public void ejbCreateYetAnotherWay(final int initialCount) {
this.count = initialCount;
}
}
| 1,799 | 28.508197 | 79 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/scoped/context/StatelessRemoteOnOtherServer.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.multinode.remotecall.scoped.context;
/**
* @author Jaikiran Pai
*/
public interface StatelessRemoteOnOtherServer {
String echo(String msg);
}
| 1,200 | 36.53125 | 70 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/remotecall/scoped/context/DynamicJNDIContextEJBInvocationTestCase.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.multinode.remotecall.scoped.context;
import org.junit.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.naming.InitialContext;
import java.io.FilePermission;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
/**
* A test case for testing the feature introduced in https://issues.jboss.org/browse/EJBCLIENT-34 which
* allows applications to pass JNDI context properties during JNDI context creation for (scoped) Jakarta Enterprise Beans client
* context creation
*
* @author Jaikiran Pai
*/
@RunWith(Arquillian.class)
@ServerSetup(PassivationConfigurationSetup.class)
public class DynamicJNDIContextEJBInvocationTestCase {
private static final Logger logger = Logger.getLogger(DynamicJNDIContextEJBInvocationTestCase.class);
private static final String LOCAL_DEPLOYMENT_NAME = "dynamic-jndi-context-ejb-invocation-test";
private static final String REMOTE_SERVER_DEPLOYMENT_NAME = "deployment-on-other-server";
@Deployment(name = "local-server-deployment")
@TargetsContainer("multinode-client")
public static Archive<?> createLocalDeployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, LOCAL_DEPLOYMENT_NAME + ".jar");
jar.addClasses(StatefulBeanA.class, LocalServerStatefulRemote.class,PassivationConfigurationSetup.class, DynamicJNDIContextEJBInvocationTestCase.class, StatefulRemoteOnOtherServer.class, StatelessRemoteOnOtherServer.class);
jar.addClasses(StatefulRemoteHomeForBeanOnOtherServer.class);
jar.addAsManifestResource(DynamicJNDIContextEJBInvocationTestCase.class.getPackage(), "MANIFEST.MF", "MANIFEST.MF");
jar.addAsManifestResource(DynamicJNDIContextEJBInvocationTestCase.class.getPackage(), "ejb-jar.xml", "ejb-jar.xml");
jar.addAsManifestResource(createPermissionsXmlAsset(
new FilePermission(System.getProperty("jbossas.multinode.server") + "/standalone/tmp/auth/*", "read")),
"permissions.xml"
);
return jar;
}
@Deployment(name = "remote-server-deployment", testable = false)
@TargetsContainer("multinode-server")
public static Archive<?> createDeploymentForRemoteServer() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, REMOTE_SERVER_DEPLOYMENT_NAME + ".jar");
jar.addClasses(StatefulRemoteOnOtherServer.class, StatelessRemoteOnOtherServer.class, StatefulRemoteHomeForBeanOnOtherServer.class);
jar.addClasses(StatefulBeanOnOtherServer.class, StatelessBeanOnOtherServer.class);
return jar;
}
/**
* Tests that a SFSB hosted on server X can lookup and invoke a SFSB and SLSB hosted on a different server,
* by using a JNDI context which was created by passing the Jakarta Enterprise Beans client context creation properties
*
* @throws Exception
*/
@Test
@OperateOnDeployment("local-server-deployment")
public void testServerToServerSFSBInvocation() throws Exception {
final StatefulBeanA sfsbOnLocalServer = InitialContext.doLookup("java:module/" + StatefulBeanA.class.getSimpleName() + "!" + StatefulBeanA.class.getName());
final int initialCount = sfsbOnLocalServer.getCountByInvokingOnRemoteServerBean();
Assert.assertEquals("Unexpected initial count from stateful bean", 0, initialCount);
// just increment a few times
final int NUM_TIMES = 5;
for (int i = 0; i < NUM_TIMES; i++) {
sfsbOnLocalServer.incrementCountByInvokingOnRemoteServerBean();
}
final int countAfterIncrement = sfsbOnLocalServer.getCountByInvokingOnRemoteServerBean();
Assert.assertEquals("Unexpected count after increment, from stateful bean", NUM_TIMES, countAfterIncrement);
// let the SFSB invoke an SLSB on a remote server
final String message = "foo";
final String firstEcho = sfsbOnLocalServer.getEchoByInvokingOnRemoteServerBean(message);
Assert.assertEquals("Unexpected echo from remote server SLSB", message, firstEcho);
}
/**
* Tests that a SFSB Foo hosted on server X can lookup and store a SFSB and a SLSB hosted on a different server Y,
* by using a JNDI context which was created by passing the Jakarta Enterprise Beans client context creation properties. The SFSB Foo
* on server X is then allowed to passivate and after activation the invocations on the SFSB and SLSB members held
* as state by SFSB Foo are expected to correcty end up on the remote server Y and return the correct state information
*
* @throws Exception
*/
@Test
@OperateOnDeployment("local-server-deployment")
public void testSFSBPassivationWithScopedEJBProxyMemberInstances() throws Exception {
final StatefulBeanA sfsbOnLocalServer = InitialContext.doLookup("java:module/" + StatefulBeanA.class.getSimpleName() + "!" + StatefulBeanA.class.getName());
final int initialCount = sfsbOnLocalServer.getCountByInvokingOnRemoteServerBean();
Assert.assertEquals("Unexpected initial count from stateful bean", 0, initialCount);
// just increment a few times
final int NUM_TIMES_BEFORE_PASSIVATION = 5;
for (int i = 0; i < NUM_TIMES_BEFORE_PASSIVATION; i++) {
sfsbOnLocalServer.incrementCountByInvokingOnRemoteServerBean();
}
final int countAfterIncrement = sfsbOnLocalServer.getCountByInvokingOnRemoteServerBean();
Assert.assertEquals("Unexpected count after increment, from stateful bean", NUM_TIMES_BEFORE_PASSIVATION, countAfterIncrement);
// let the SFSB invoke an SLSB on a remote server
final String message = "foo";
final String firstEcho = sfsbOnLocalServer.getEchoByInvokingOnRemoteServerBean(message);
Assert.assertEquals("Unexpected echo from remote server SLSB", message, firstEcho);
// now let's wait for passivation of the SFSB on local server
final CountDownLatch passivationLatch = new CountDownLatch(1);
sfsbOnLocalServer.registerPassivationNotificationLatch(passivationLatch);
logger.trace("Triggering passivation of " + StatefulBeanA.class.getSimpleName() + " bean");
InitialContext.doLookup("java:module/" + StatefulBeanA.class.getSimpleName() + "!" + StatefulBeanA.class.getName());
final boolean passivated = passivationLatch.await(2, TimeUnit.SECONDS);
if (passivated) {
logger.trace("pre-passivate invoked on " + StatefulBeanA.class.getSimpleName() + " bean");
} else {
Assert.fail(sfsbOnLocalServer + " was not passivated");
}
// just wait a little while longer since the acknowledgement that the pre-passivate was invoked
// doesn't mean the passivation process is complete
Thread.sleep(1000);
// let's activate the passivated SFSB on local server
final int countAfterActivate = sfsbOnLocalServer.getCountByInvokingOnRemoteServerBean();
Assert.assertEquals("Unexpected count from stateful bean after it was activated", NUM_TIMES_BEFORE_PASSIVATION, countAfterActivate);
// just make sure @PostActivate was invoked
Assert.assertTrue("Post-activate method was not invoked on bean " + StatefulBeanA.class.getSimpleName(), sfsbOnLocalServer.wasPostActivateInvoked());
// now increment on the remote server SFSB via the local server SFSB
final int NUM_TIMES_AFTER_ACTIVATION = 2;
for (int i = 0; i < NUM_TIMES_AFTER_ACTIVATION; i++) {
sfsbOnLocalServer.incrementCountByInvokingOnRemoteServerBean();
}
final int counterAfterIncrementOnPostActivate = sfsbOnLocalServer.getCountByInvokingOnRemoteServerBean();
Assert.assertEquals("Unexpected count after increment, on the post activated stateful bean", NUM_TIMES_BEFORE_PASSIVATION + NUM_TIMES_AFTER_ACTIVATION, counterAfterIncrementOnPostActivate);
// let's also invoke on the remote server SLSB via the local server SFSB
final String echoAfterPostActivate = sfsbOnLocalServer.getEchoByInvokingOnRemoteServerBean(message);
Assert.assertEquals("Unexpected echo message from remote server SLSB", message, echoAfterPostActivate);
}
/**
* Tests that a SFSB hosted on server X can lookup and invoke a SFSB hosted on a different server, through the Enterprise Beans 2.x
* home view, by using a JNDI context which was created by passing the Jakarta Enterprise Beans client context creation properties
* @see https://issues.jboss.org/browse/EJBCLIENT-51
*
* @throws Exception
*/
@Test
@OperateOnDeployment("local-server-deployment")
public void testServerToServerSFSBUsingEJB2xHomeView() throws Exception {
final StatefulBeanA sfsbOnLocalServer = InitialContext.doLookup("java:module/" + StatefulBeanA.class.getSimpleName() + "!" + StatefulBeanA.class.getName());
final int countUsingEJB2xHomeView = sfsbOnLocalServer.getStatefulBeanCountUsingEJB2xHomeView();
Assert.assertEquals("Unexpected initial count from stateful bean", 0, countUsingEJB2xHomeView);
// now try the other create... method on the remote home
final int countUsingEJB2xHomeViewDifferentWay = sfsbOnLocalServer.getStatefulBeanCountUsingEJB2xHomeViewDifferentWay();
Assert.assertEquals("Unexpected initial count from stateful bean", 0, countUsingEJB2xHomeViewDifferentWay);
// yet another create method
final int initialCount = 54;
final int countUsingEJB2xHomeViewYetAnotherWay = sfsbOnLocalServer.getStatefulBeanCountUsingEJB2xHomeViewYetAnotherWay(initialCount);
Assert.assertEquals("Unexpected initial count from stateful bean", initialCount, countUsingEJB2xHomeViewYetAnotherWay);
}
}
| 11,401 | 56.01 | 231 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/clientinterceptor/StatelessRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.multinode.clientinterceptor;
/**
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
public interface StatelessRemote {
int method() throws Exception;
}
| 1,236 | 38.903226 | 70 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/clientinterceptor/ClientInterceptor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.multinode.clientinterceptor;
import org.jboss.ejb.client.EJBClientInterceptor;
import org.jboss.ejb.client.EJBClientInvocationContext;
import java.util.concurrent.CountDownLatch;
/**
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
public class ClientInterceptor implements EJBClientInterceptor {
public static CountDownLatch invocationLatch = new CountDownLatch(1);
public static CountDownLatch resultLatch = new CountDownLatch(1);
@Override
public void handleInvocation(EJBClientInvocationContext context) throws Exception {
invocationLatch.countDown();
context.sendRequest();
}
@Override
public Object handleInvocationResult(EJBClientInvocationContext context) throws Exception {
resultLatch.countDown();
return context.getResult();
}
}
| 1,891 | 36.84 | 95 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/clientinterceptor/StatelessBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.multinode.clientinterceptor;
import org.jboss.logging.Logger;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateless;
/**
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
@Stateless
@Remote(StatelessRemote.class)
public class StatelessBean implements StatelessRemote {
private static final Logger log = Logger.getLogger(StatelessBean.class);
private static int methodCount = 0;
public int method() throws Exception {
++methodCount;
log.trace("Method called " + methodCount);
return methodCount;
}
}
| 1,627 | 33.638298 | 76 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/clientinterceptor/RemoteCallClientInterceptorTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.multinode.clientinterceptor;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.io.File;
import java.io.FilePermission;
import java.security.SecurityPermission;
import java.util.Collections;
import java.util.List;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.shared.integration.ejb.security.Util;
import org.jboss.as.test.shared.integration.interceptor.clientside.AbstractClientInterceptorsSetupTask;
import org.jboss.as.test.shared.integration.interceptor.clientside.InterceptorModule;
import org.jboss.as.test.shared.util.ClientInterceptorUtil;
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]">Tomasz Adamski</a>
*/
@RunWith(Arquillian.class)
@ServerSetup({RemoteCallClientInterceptorTestCase.SetupTask.class})
public class RemoteCallClientInterceptorTestCase {
private static final String ARCHIVE_NAME_CLIENT = "remotelocalcall-test-client";
private static final String ARCHIVE_NAME_SERVER = "remotelocalcall-test-server";
private static final String moduleName = "remote-call-interceptor-module";
@Deployment(name = AbstractClientInterceptorsSetupTask.DEPLOYMENT_NAME_SERVER)
@TargetsContainer(AbstractClientInterceptorsSetupTask.TARGER_CONTAINER_SERVER)
public static Archive<?> deployment0() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME_SERVER + ".jar");
jar.addClasses(StatelessBean.class, StatelessRemote.class);
return jar;
}
@Deployment(name = AbstractClientInterceptorsSetupTask.DEPLOYMENT_NAME_CLIENT)
@TargetsContainer(AbstractClientInterceptorsSetupTask.TARGER_CONTAINER_CLIENT)
public static Archive<?> deployment1() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME_CLIENT + ".jar");
jar.addClasses(Util.class, ClientInterceptorUtil.class);
jar.addClasses(StatelessBean.class, StatelessRemote.class);
jar.addClasses(RemoteCallClientInterceptorTestCase.class, ClientInterceptor.class);
jar.addPackage(AbstractClientInterceptorsSetupTask.class.getPackage());
jar.addAsManifestResource("META-INF/jboss-ejb-client-receivers.xml", "jboss-ejb-client.xml");
jar.addAsManifestResource(
createPermissionsXmlAsset(
new SecurityPermission("putProviderProperty.WildFlyElytron"),
new FilePermission(System.getProperty("jboss.home") + File.separatorChar + "standalone" + File.separatorChar + "tmp" + File.separatorChar + "auth" + File.separatorChar + "-", "read")),
"permissions.xml");
return jar;
}
@Test
@OperateOnDeployment("client")
public void testStateless() throws Exception {
StatelessRemote bean = ClientInterceptorUtil.lookupStatelessRemote(ARCHIVE_NAME_SERVER, StatelessBean.class, StatelessRemote.class);
Assert.assertNotNull(bean);
int methodCount = bean.method();
Assert.assertEquals(1, methodCount);
Assert.assertEquals(0, ClientInterceptor.invocationLatch.getCount());
Assert.assertEquals(0, ClientInterceptor.resultLatch.getCount());
}
static class SetupTask extends AbstractClientInterceptorsSetupTask.SetupTask {
@Override
public List<InterceptorModule> getModules() {
return Collections.singletonList(new InterceptorModule(
ClientInterceptor.class,
moduleName,
"module.xml",
RemoteCallClientInterceptorTestCase.class.getResource("module.xml"),
"client-side-interceptor.jar"
));
}
}
}
| 5,205 | 46.761468 | 208 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/clientinterceptor/multiple/MultipleClientInterceptorTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.multinode.clientinterceptor.multiple;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.fail;
import java.security.SecurityPermission;
import java.util.Arrays;
import java.util.List;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.multinode.clientinterceptor.ClientInterceptor;
import org.jboss.as.test.multinode.clientinterceptor.StatelessBean;
import org.jboss.as.test.multinode.clientinterceptor.StatelessRemote;
import org.jboss.as.test.shared.integration.ejb.security.Util;
import org.jboss.as.test.shared.integration.interceptor.clientside.AbstractClientInterceptorsSetupTask;
import org.jboss.as.test.shared.integration.interceptor.clientside.InterceptorModule;
import org.jboss.as.test.shared.util.ClientInterceptorUtil;
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;
/**
* A test case verifying:
* 1. Multiple client-side interceptors execution
* 2. An exception thrown in an interceptor is propagated.
* See https://issues.jboss.org/browse/WFLY-6144 for more details.
*
* @author <a href="mailto:[email protected]">Sultan Zhantemirov</a> (c) 2019 Red Hat, inc.
*/
@RunWith(Arquillian.class)
@ServerSetup(MultipleClientInterceptorTestCase.SetupTask.class)
public class MultipleClientInterceptorTestCase {
private static final String ARCHIVE_NAME_CLIENT = "multiple-interceptors-test-client";
private static final String ARCHIVE_NAME_SERVER = "multiple-interceptors-test-server";
private static final String firstModuleName = "interceptor-first-module";
private static final String secondModuleName = "interceptor-second-module";
@Deployment(name = AbstractClientInterceptorsSetupTask.DEPLOYMENT_NAME_SERVER)
@TargetsContainer(AbstractClientInterceptorsSetupTask.TARGER_CONTAINER_SERVER)
public static Archive<?> deployment0() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME_SERVER + ".jar");
jar.addClasses(StatelessBean.class, StatelessRemote.class);
return jar;
}
@Deployment(name = AbstractClientInterceptorsSetupTask.DEPLOYMENT_NAME_CLIENT)
@TargetsContainer(AbstractClientInterceptorsSetupTask.TARGER_CONTAINER_CLIENT)
public static Archive<?> deployment1() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME_CLIENT + ".jar");
jar.addClasses(Util.class, ClientInterceptorUtil.class);
jar.addClasses(StatelessBean.class, StatelessRemote.class);
jar.addClasses(MultipleClientInterceptorTestCase.class, ClientInterceptor.class, ExceptionClientInterceptor.class);
jar.addPackage(AbstractClientInterceptorsSetupTask.class.getPackage());
jar.addAsManifestResource("META-INF/jboss-ejb-client-receivers.xml", "jboss-ejb-client.xml");
jar.addAsManifestResource(
createPermissionsXmlAsset(
new SecurityPermission("putProviderProperty.WildFlyElytron")),
"permissions.xml");
return jar;
}
@Test
@OperateOnDeployment(AbstractClientInterceptorsSetupTask.DEPLOYMENT_NAME_CLIENT)
public void testMultiple() throws Exception {
StatelessRemote bean = ClientInterceptorUtil.lookupStatelessRemote(ARCHIVE_NAME_SERVER, StatelessBean.class, StatelessRemote.class);
Assert.assertNotNull(bean);
try {
bean.method();
fail("Client interceptor should have thrown an IllegalArgumentException");
} catch (Exception e) {
// expected
Assert.assertTrue(e instanceof IllegalArgumentException);
Assert.assertEquals(0, ClientInterceptor.invocationLatch.getCount());
Assert.assertEquals(0, ClientInterceptor.resultLatch.getCount());
}
}
static class SetupTask extends AbstractClientInterceptorsSetupTask.SetupTask {
@Override
public List<InterceptorModule> getModules() {
InterceptorModule firstModule = new InterceptorModule(
ClientInterceptor.class,
firstModuleName,
"first-module.xml",
MultipleClientInterceptorTestCase.class.getResource("first-module.xml"),
"first-client-side-interceptor.jar"
);
InterceptorModule secondModule = new InterceptorModule(
ExceptionClientInterceptor.class,
secondModuleName,
"second-module.xml",
MultipleClientInterceptorTestCase.class.getResource("second-module.xml"),
"second-client-side-interceptor.jar"
);
return Arrays.asList(firstModule, secondModule);
}
}
}
| 6,231 | 46.572519 | 140 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/clientinterceptor/multiple/ExceptionClientInterceptor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.multinode.clientinterceptor.multiple;
import org.jboss.ejb.client.EJBClientInterceptor;
import org.jboss.ejb.client.EJBClientInvocationContext;
/**
* Simple interceptor throwing an exception during invocation result handing.
*/
public class ExceptionClientInterceptor implements EJBClientInterceptor {
@Override
public void handleInvocation(EJBClientInvocationContext context) throws Exception {
context.sendRequest();
}
@Override
public Object handleInvocationResult(EJBClientInvocationContext context) throws Exception {
throw new IllegalArgumentException("Throwing an exception from client-side interceptor");
}
}
| 1,721 | 40 | 97 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/clientinterceptor/protocol/ProtocolSampleClientInterceptor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.multinode.clientinterceptor.protocol;
import org.jboss.ejb.client.EJBClientInterceptor;
import org.jboss.ejb.client.EJBClientInvocationContext;
public class ProtocolSampleClientInterceptor implements EJBClientInterceptor {
static final int COUNT = 10;
@Override
public void handleInvocation(EJBClientInvocationContext context) throws Exception {
context.sendRequest();
}
@Override
public Object handleInvocationResult(EJBClientInvocationContext context) throws Exception {
Object result = context.getResult();
if (result instanceof Integer) {
return COUNT + (int) result;
}
return result;
}
}
| 1,735 | 38.454545 | 95 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/clientinterceptor/protocol/RemoteProtocolChangeClientInterceptorTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.multinode.clientinterceptor.protocol;
import static org.jboss.as.test.shared.TestSuiteEnvironment.getSystemProperty;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.io.File;
import java.io.FilePermission;
import java.security.SecurityPermission;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.PropertyPermission;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.multinode.clientinterceptor.StatelessBean;
import org.jboss.as.test.multinode.clientinterceptor.StatelessRemote;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.as.test.shared.integration.ejb.security.Util;
import org.jboss.as.test.shared.integration.interceptor.clientside.AbstractClientInterceptorsSetupTask;
import org.jboss.as.test.shared.integration.interceptor.clientside.InterceptorModule;
import org.jboss.as.test.shared.util.ClientInterceptorUtil;
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;
/**
* A test case verifying client-side interceptor execution after changing JBoss Remoting protocol.
*
* @author Sultan Zhantemirov
*/
@RunWith(Arquillian.class)
@ServerSetup(RemoteProtocolChangeClientInterceptorTestCase.SetupTask.class)
public class RemoteProtocolChangeClientInterceptorTestCase {
private static final String ARCHIVE_NAME_CLIENT = "remote-protocol-test-client";
private static final String ARCHIVE_NAME_SERVER = "remote-protocol-test-server";
private static final String moduleName = "protocol-change-interceptor-module";
@Deployment(name = AbstractClientInterceptorsSetupTask.DEPLOYMENT_NAME_SERVER)
@TargetsContainer(AbstractClientInterceptorsSetupTask.TARGER_CONTAINER_SERVER)
public static Archive<?> deployment0() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME_SERVER + ".jar");
jar.addClasses(StatelessBean.class, StatelessRemote.class);
return jar;
}
@Deployment(name = AbstractClientInterceptorsSetupTask.DEPLOYMENT_NAME_CLIENT)
@TargetsContainer(AbstractClientInterceptorsSetupTask.TARGER_CONTAINER_CLIENT)
public static Archive<?> deployment1() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME_CLIENT + ".jar");
jar.addClasses(Util.class, ClientInterceptorUtil.class);
jar.addClasses(StatelessBean.class, StatelessRemote.class, ProtocolSampleClientInterceptor.class);
jar.addClasses(RemoteProtocolChangeClientInterceptorTestCase.class, TestSuiteEnvironment.class);
jar.addPackage(AbstractClientInterceptorsSetupTask.class.getPackage());
jar.addAsManifestResource(RemoteProtocolChangeClientInterceptorTestCase.class.getPackage(), "jboss-ejb-client.xml", "jboss-ejb-client.xml");
jar.addAsManifestResource(
createPermissionsXmlAsset(
new SecurityPermission("putProviderProperty.WildFlyElytron"),
new PropertyPermission("management.address", "read"),
new PropertyPermission("node0", "read"),
new PropertyPermission("jboss.http.port", "read"),
new PropertyPermission("jboss.socket.binding.port-offset", "read"),
new FilePermission(System.getProperty("jboss.home") + File.separatorChar + "standalone" + File.separatorChar + "tmp" + File.separatorChar + "auth" + File.separatorChar + "-", "read")),
"permissions.xml");
return jar;
}
@Test
@InSequence(1)
@OperateOnDeployment("client")
public void testDefaultProtocol() throws Exception {
final Hashtable<String, String> props = new Hashtable<>();
props.put(Context.URL_PKG_PREFIXES, "org.wildfly.naming.client");
StatelessRemote bean = getRemote(new InitialContext(props));
Assert.assertNotNull(bean);
// StatelessBean.methodCount field should equal 1 after first invoking
Assert.assertEquals(ProtocolSampleClientInterceptor.COUNT + 1, bean.method());
}
@Test
@InSequence(2)
@OperateOnDeployment("client")
public void testHttpRemotingProtocol() throws Exception {
final Hashtable<String, String> props = new Hashtable<>();
props.put(Context.URL_PKG_PREFIXES, "org.wildfly.naming.client");
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.wildfly.naming.client.WildFlyInitialContextFactory");
props.put(Context.PROVIDER_URL, "http-remoting://" + TestSuiteEnvironment.getServerAddress() + ":"
+ (TestSuiteEnvironment.getHttpPort() + Integer.parseInt(getSystemProperty("jboss.socket.binding.port-offset", "100"))));
StatelessRemote bean = getRemote(new InitialContext(props));
Assert.assertNotNull(bean);
// StatelessBean.methodCount field should equal 2 after second invoking (methodCount is a static field and is shared within a single JVM)
Assert.assertEquals(ProtocolSampleClientInterceptor.COUNT + 2, bean.method());
}
private StatelessRemote getRemote(InitialContext ctx) throws NamingException {
return (StatelessRemote) ctx.lookup("ejb:/" + RemoteProtocolChangeClientInterceptorTestCase.ARCHIVE_NAME_SERVER + "/" + "" + "/" + "StatelessBean" + "!" + StatelessRemote.class.getName());
}
static class SetupTask extends AbstractClientInterceptorsSetupTask.SetupTask {
@Override
public List<InterceptorModule> getModules() {
return Collections.singletonList(new InterceptorModule(
ProtocolSampleClientInterceptor.class,
moduleName,
"module.xml",
RemoteProtocolChangeClientInterceptorTestCase.class.getResource("module.xml"),
"client-side-interceptor.jar"
));
}
}
}
| 7,498 | 49.328859 | 208 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/clientinterceptor/secured/SecuredBeanClientInterceptorTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.multinode.clientinterceptor.secured;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.io.File;
import java.io.FilePermission;
import java.security.SecurityPermission;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import jakarta.ejb.EJBAccessException;
import javax.security.auth.AuthPermission;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.integration.security.common.AbstractSecurityDomainSetup;
import org.jboss.as.test.shared.integration.ejb.security.Util;
import org.jboss.as.test.shared.integration.interceptor.clientside.AbstractClientInterceptorsSetupTask;
import org.jboss.as.test.shared.integration.interceptor.clientside.InterceptorModule;
import org.jboss.as.test.shared.util.ClientInterceptorUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.security.permission.ElytronPermission;
/**
* A test case verifying client-side interceptor execution while accessing an EJB with @RolesAllowed, @DenyAll and @PermitAll security annotations.
* See https://issues.jboss.org/browse/WFLY-6144 for more details.
*
* @author <a href="mailto:[email protected]">Sultan Zhantemirov</a> (c) 2019 Red Hat, inc.
*/
@RunWith(Arquillian.class)
@ServerSetup({SecuredBeanClientInterceptorTestCase.SetupTask.class, EjbSecurityDomainSetup.class})
public class SecuredBeanClientInterceptorTestCase {
private static final String ARCHIVE_NAME_CLIENT = "secured-bean-test-client";
private static final String ARCHIVE_NAME_SERVER = "secured-bean-test-server";
private static final String moduleName = "secured-bean-interceptor-module";
@Deployment(name = "server")
@TargetsContainer("multinode-server")
public static Archive<?> deployment0() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME_SERVER + ".jar");
jar.addClasses(Secured.class, SecuredBean.class);
return jar;
}
@Deployment(name = "client")
@TargetsContainer("multinode-client")
public static Archive<?> deployment1() {
final Package currentPackage = SecuredBeanClientInterceptorTestCase.class.getPackage();
WebArchive war = ShrinkWrap.create(WebArchive.class, ARCHIVE_NAME_CLIENT + ".war");
war.addClasses(Util.class, ClientInterceptorUtil.class);
war.addClasses(AbstractSecurityDomainSetup.class, EjbSecurityDomainSetup.class);
war.addClasses(SecuredBeanClientInterceptorTestCase.class, SampleSecureInterceptor.class, Secured.class, SecuredBean.class);
war.addPackage(AbstractClientInterceptorsSetupTask.class.getPackage());
war.addAsManifestResource("META-INF/jboss-ejb-client-receivers.xml", "jboss-ejb-client.xml");
war.addAsWebInfResource(currentPackage, "jboss-web.xml", "jboss-web.xml");
war.addAsManifestResource(new StringAsset("Manifest-Version: 1.0\nDependencies: org.jboss.as.controller-client,org.jboss.dmr\n"), "MANIFEST.MF");
war.addAsManifestResource(
createPermissionsXmlAsset(
new SecurityPermission("putProviderProperty.WildFlyElytron"),
new ElytronPermission("getSecurityDomain"),
new ElytronPermission("authenticate"),
new RuntimePermission("getProtectionDomain"),
new AuthPermission("modifyPrincipals"),
new FilePermission(System.getProperty("jboss.home") + File.separatorChar + "standalone" +
File.separatorChar + "tmp" + File.separatorChar + "auth" + File.separatorChar + "-", "read")),
"permissions.xml");
return war;
}
@Test
@InSequence(1)
@OperateOnDeployment("client")
public void securedBeanAccessCheck() throws Exception {
Secured bean = ClientInterceptorUtil.lookupStatelessRemote(ARCHIVE_NAME_SERVER, SecuredBean.class, Secured.class);
Assert.assertNotNull(bean);
String result = bean.permitAll("permitAll");
Assert.assertNotNull(result);
try {
bean.denyAll("denyAll");
Assert.fail("it was supposed to throw EJBAccessException");
}
catch (EJBAccessException ie){
// expected
}
}
@Test
@InSequence(2)
@OperateOnDeployment("client")
public void securedBeanRoleCheck() throws Exception {
final Callable<Void> callable = () -> {
Secured bean = ClientInterceptorUtil.lookupStatelessRemote(ARCHIVE_NAME_SERVER, SecuredBean.class, Secured.class);
try {
bean.roleEcho("role1access");
} catch (EJBAccessException ignored) {
}
try {
bean.role2Echo("access");
} catch (EJBAccessException e) {
// expected
}
Assert.assertEquals(0, SampleSecureInterceptor.latch.getCount());
return null;
};
Util.switchIdentity("user1", "password1", callable);
}
static class SetupTask extends AbstractClientInterceptorsSetupTask.SetupTask {
@Override
public List<InterceptorModule> getModules() {
return Collections.singletonList(new InterceptorModule(
SampleSecureInterceptor.class,
moduleName,
"module.xml",
SecuredBeanClientInterceptorTestCase.class.getResource("module.xml"),
"client-side-interceptor-secured.jar"
));
}
}
}
| 7,244 | 44.28125 | 153 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/clientinterceptor/secured/Secured.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.multinode.clientinterceptor.secured;
public interface Secured {
String permitAll(String message);
void denyAll(String message);
String roleEcho(String message);
String role2Echo(String message);
}
| 1,275 | 37.666667 | 70 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/clientinterceptor/secured/SampleSecureInterceptor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.multinode.clientinterceptor.secured;
import java.util.concurrent.CountDownLatch;
import org.jboss.ejb.client.EJBClientInterceptor;
import org.jboss.ejb.client.EJBClientInvocationContext;
public class SampleSecureInterceptor implements EJBClientInterceptor {
public static final CountDownLatch latch = new CountDownLatch(4);
@Override
public void handleInvocation(EJBClientInvocationContext context) throws Exception {
latch.countDown();
context.sendRequest();
}
@Override
public Object handleInvocationResult(EJBClientInvocationContext context) throws Exception {
latch.countDown();
return context.getResult();
}
}
| 1,738 | 38.522727 | 95 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/clientinterceptor/secured/SecuredBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, 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.multinode.clientinterceptor.secured;
import jakarta.annotation.Resource;
import jakarta.annotation.security.DenyAll;
import jakarta.annotation.security.PermitAll;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ejb.Remote;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Stateless;
@Stateless
@Remote(Secured.class)
public class SecuredBean implements Secured {
@Resource
private SessionContext sessionContext;
@PermitAll
public String permitAll(String message) {
return message;
}
@DenyAll
public void denyAll(String message) {
}
@RolesAllowed("Role1")
public String roleEcho(final String message) {
return message;
}
@RolesAllowed("Role2")
public String role2Echo(final String message) {
return message;
}
}
| 1,878 | 30.847458 | 70 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/clientinterceptor/secured/EjbSecurityDomainSetup.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.multinode.clientinterceptor.secured;
import java.io.File;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.integration.security.common.AbstractSecurityDomainSetup;
import org.wildfly.test.security.common.elytron.EjbElytronDomainSetup;
import org.wildfly.test.security.common.elytron.ElytronDomainSetup;
import org.wildfly.test.security.common.elytron.ServletElytronDomainSetup;
/**
* Utility methods to create/remove simple security domains
*
* @author <a href="mailto:[email protected]">Marcus Moyses</a>
*/
public class EjbSecurityDomainSetup extends AbstractSecurityDomainSetup {
protected static final String DEFAULT_SECURITY_DOMAIN_NAME = "ejb3-tests";
private ElytronDomainSetup elytronDomainSetup;
private EjbElytronDomainSetup ejbElytronDomainSetup;
private ServletElytronDomainSetup servletElytronDomainSetup;
@Override
protected String getSecurityDomainName() {
return DEFAULT_SECURITY_DOMAIN_NAME;
}
protected String getUsersFile() {
return new File(EjbSecurityDomainSetup.class.getResource("users.properties").getFile()).getAbsolutePath();
}
protected String getGroupsFile() {
return new File(EjbSecurityDomainSetup.class.getResource("roles.properties").getFile()).getAbsolutePath();
}
public boolean isUsersRolesRequired() {
return true;
}
@Override
public void setup(final ManagementClient managementClient, final String containerId) throws Exception {
elytronDomainSetup = new ElytronDomainSetup(getUsersFile(), getGroupsFile(), getSecurityDomainName());
ejbElytronDomainSetup = new EjbElytronDomainSetup(getSecurityDomainName());
servletElytronDomainSetup = new ServletElytronDomainSetup(getSecurityDomainName());
elytronDomainSetup.setup(managementClient, containerId);
ejbElytronDomainSetup.setup(managementClient, containerId);
servletElytronDomainSetup.setup(managementClient, containerId);
}
@Override
public void tearDown(final ManagementClient managementClient, final String containerId) {
}
}
| 3,174 | 40.233766 | 114 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/batch/stoprestart/Batchlet1.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2021, 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.multinode.batch.stoprestart;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import jakarta.batch.api.BatchProperty;
import jakarta.batch.api.Batchlet;
import jakarta.enterprise.context.Dependent;
import jakarta.inject.Inject;
import jakarta.inject.Named;
@Named
@Dependent
public class Batchlet1 implements Batchlet {
private final AtomicBoolean stopRequested = new AtomicBoolean();
@Inject
@BatchProperty
long seconds;
@Inject
@BatchProperty
int interval;
@Override
public String process() throws Exception {
if (seconds > 0) {
long startTime = System.currentTimeMillis();
long targetDuration = seconds * 1000;
long sleepAmount;
while((sleepAmount = System.currentTimeMillis() - startTime) < targetDuration && !stopRequested.get()) {
Thread.sleep(interval);
}
return "Slept " + TimeUnit.MILLISECONDS.toSeconds(sleepAmount) + " seconds";
}
return "Direct return no sleep";
}
@Override
public void stop() throws Exception {
stopRequested.set(true);
}
}
| 2,214 | 33.076923 | 116 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/batch/stoprestart/BatchClientIF.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2021, 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.multinode.batch.stoprestart;
import java.util.Properties;
import jakarta.batch.runtime.BatchStatus;
import jakarta.ejb.Remote;
@Remote
public interface BatchClientIF {
long start(String jobName, Properties jobParams);
void stop(long jobExecutionId);
long restart(long jobExecutionId, Properties restartParams);
BatchStatus getJobStatus(long jobExecutionId);
}
| 1,425 | 34.65 | 73 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/batch/stoprestart/StopFromDifferentNodeTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2021, 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.multinode.batch.stoprestart;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.test.multinode.ejb.timer.database.DatabaseTimerServiceMultiNodeExecutionDisabledTestCase.getRemoteContext;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.assertEquals;
import java.net.SocketPermission;
import java.security.SecurityPermission;
import java.util.Collections;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import jakarta.batch.runtime.BatchStatus;
import javax.naming.Context;
import org.h2.tools.Server;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.security.common.Utils;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(StopFromDifferentNodeTestCase.StopFromDifferentNodeTestCaseSetup.class)
public class StopFromDifferentNodeTestCase {
private static final Logger log = Logger.getLogger(StopFromDifferentNodeTestCase.class.getName());
private static final String ARCHIVE_NAME = "stopFromDifferentNode";
private static final String BATCHLET1_JOB = "batchlet1.xml";
private static final String BATCH_CLIENT_BEAN_LOOKUP = ARCHIVE_NAME + "/" + BatchClientBean.class.getSimpleName() + "!" + BatchClientIF.class.getName();
/**
* Number of seconds {@link Batchlet1#process()} method sleeps. The batchlet
* needs to sleep long enough so that when a client stops it, it is still in
* running state.
*/
private static final long BATCHLET_DELAY_SECONDS = TimeoutUtil.adjust(10);
/**
* Interval in milliseconds with which a client polls the status of a job execution.
*/
private static final int CHECK_STATUS_INTERVAL_MILLIS = TimeoutUtil.adjust(200);
private static Server h2Server;
@AfterClass
public static void afterClass() {
if (h2Server != null) {
h2Server.stop();
}
}
static class StopFromDifferentNodeTestCaseSetup implements ServerSetupTask {
static final PathAddress ADDR_DATA_SOURCE = PathAddress.pathAddress().append(SUBSYSTEM, "datasources").append("data-source", "MyNewDs");
static final PathAddress ADDR_BATCH_SUBSYSTEM = PathAddress.pathAddress().append(SUBSYSTEM, "batch-jberet");
static final PathAddress ADDR_JDBC_JOB_REPOSITORY = ADDR_BATCH_SUBSYSTEM.append("jdbc-job-repository", "jdbc");
String savedDefaultJobRepository = null;
@Override
public void setup(final ManagementClient managementClient, final String containerId) throws Exception {
if (h2Server == null) {
//We need a TCP server that can be shared between the two servers.
//To allow remote connections, start the TCP server using the option -tcpAllowOthers
h2Server = Server.createTcpServer("-tcpAllowOthers", "-ifNotExists").start();
}
if (savedDefaultJobRepository == null) {
final ModelNode readAttributeOperation = Util.getReadAttributeOperation(ADDR_BATCH_SUBSYSTEM, "default-job-repository");
final ModelNode defaultJobRepository = managementClient.getControllerClient().execute(readAttributeOperation);
savedDefaultJobRepository = defaultJobRepository.get("result").asString("in-memory");
}
final ModelNode compositeOp = new ModelNode();
compositeOp.get(OP).set(COMPOSITE);
compositeOp.get(OP_ADDR).setEmptyList();
ModelNode steps = compositeOp.get(STEPS);
// /subsystem=datasources/data-source=MyNewDs:add(name=MyNewDs,jndi-name=java:jboss/datasources/MyNewDs, enabled=true)
ModelNode datasourceAddModelNode = Util.createAddOperation(ADDR_DATA_SOURCE);
datasourceAddModelNode.get("name").set("MyNewDs");
datasourceAddModelNode.get("jndi-name").set("java:jboss/datasources/MyNewDs");
datasourceAddModelNode.get("enabled").set(true);
datasourceAddModelNode.get("driver-name").set("h2");
datasourceAddModelNode.get("pool-name").set("MyNewDs_Pool");
datasourceAddModelNode.get("connection-url").set("jdbc:h2:" + h2Server.getURL() + "/mem:testdb;DB_CLOSE_DELAY=-1");
datasourceAddModelNode.get("user-name").set("sa");
datasourceAddModelNode.get("password").set("sa");
steps.add(datasourceAddModelNode);
// /subsystem=batch-jberet/jdbc-job-repository=jdbc:add(data-source=MyNewDs)
ModelNode jdbcJobRepositoryAddModelNode = Util.createAddOperation(ADDR_JDBC_JOB_REPOSITORY);
jdbcJobRepositoryAddModelNode.get("data-source").set("MyNewDs");
steps.add(jdbcJobRepositoryAddModelNode);
ModelNode setJobRepositoryModelNode = Util.getWriteAttributeOperation(ADDR_BATCH_SUBSYSTEM, "default-job-repository", "jdbc");
steps.add(setJobRepositoryModelNode);
Utils.applyUpdates(Collections.singletonList(compositeOp), managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
@Override
public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception {
final ModelNode compositeOp = new ModelNode();
compositeOp.get(OP).set(COMPOSITE);
compositeOp.get(OP_ADDR).setEmptyList();
ModelNode steps = compositeOp.get(STEPS);
ModelNode setJobRepositoryModelNode = Util.getWriteAttributeOperation(ADDR_BATCH_SUBSYSTEM, "default-job-repository", savedDefaultJobRepository);
steps.add(setJobRepositoryModelNode);
ModelNode jdbcJobRepositoryRemoveModelNode = Util.createRemoveOperation(ADDR_JDBC_JOB_REPOSITORY);
steps.add(jdbcJobRepositoryRemoveModelNode);
ModelNode datasourceRemoveModelNode = Util.createRemoveOperation(ADDR_DATA_SOURCE);
steps.add(datasourceRemoveModelNode);
Utils.applyUpdates(Collections.singletonList(compositeOp), managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
}
@ContainerResource("multinode-server")
private ManagementClient client1;
@ContainerResource("multinode-client")
private ManagementClient client2;
@Deployment(name = "server", testable = false)
@TargetsContainer("multinode-server")
public static Archive<?> deployment() {
return createDeployment();
}
@Deployment(name = "client", testable = false)
@TargetsContainer("multinode-client")
public static Archive<?> clientDeployment() {
return createDeployment();
}
private static Archive<?> createDeployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, ARCHIVE_NAME + ".war");
war.addClasses(Batchlet1.class, BatchClientIF.class, BatchClientBean.class);
war.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
war.addAsWebInfResource(StopFromDifferentNodeTestCase.class.getPackage(), BATCHLET1_JOB, "classes/META-INF/batch-jobs/" + BATCHLET1_JOB);
war.addAsManifestResource(
createPermissionsXmlAsset(
new SocketPermission("*:9092", "connect,resolve"),
new SecurityPermission("putProviderProperty.WildFlyElytron")),
"permissions.xml");
return war;
}
/**
* Verifies that a running batch job execution can be stopped from a different node.
* This test starts a batch job in node 1, stop it in node 2, and restart it in node 2.
*/
@Test()
@InSequence(0)
public void testStartStopRestart122() throws Exception {
testStartStopRestart(122);
}
/**
* Verifies that a running batch job execution can be stopped from a different node.
* This test starts a batch job in node 1, stop it in node 2, and restart it in node 1.
*/
@Test
@InSequence(1)
public void testStartStopRestart121() throws Exception {
testStartStopRestart(121);
}
/**
* Starts a job execution, stops it from a different node, and then restart it.
*
* @param sequence if 121, the restart will be from the same node where the job was initially started;
* if 122, the restart will be from the same node where the job was stopped.
* @throws Exception on any exception
*/
private void testStartStopRestart(int sequence) throws Exception {
Context context1 = null;
Context context2 = null;
try {
context1 = getRemoteContext(client1);
context2 = getRemoteContext(client2);
BatchClientIF bean1 = (BatchClientIF) context1.lookup(BATCH_CLIENT_BEAN_LOOKUP);
BatchClientIF bean2 = (BatchClientIF) context2.lookup(BATCH_CLIENT_BEAN_LOOKUP);
//start the job in node 1
final Properties jobParams = new Properties();
jobParams.setProperty("seconds", String.valueOf(BATCHLET_DELAY_SECONDS));
jobParams.setProperty("interval", String.valueOf(CHECK_STATUS_INTERVAL_MILLIS));
final long jobExecutionId = bean1.start(BATCHLET1_JOB, jobParams);
//make sure the job execution has started
final BatchStatus startedFromNode1 = waitForBatchStatus(bean1, jobExecutionId, BatchStatus.STARTED);
assertEquals(BatchStatus.STARTED, startedFromNode1);
//stop the job execution from node 2
bean2.stop(jobExecutionId);
//check job status from node 1
final BatchStatus stoppedFromNode1 = waitForBatchStatus(bean1, jobExecutionId, BatchStatus.STOPPED);
assertEquals(BatchStatus.STOPPED, stoppedFromNode1);
//check job status from node 2
final BatchStatus stoppedFromNode2 = waitForBatchStatus(bean2, jobExecutionId, BatchStatus.STOPPED);
assertEquals(BatchStatus.STOPPED, stoppedFromNode2);
//restart from node 1 or node 2, depending on sequence parameter.
BatchClientIF beanUsedToRestart = sequence == 121 ? bean1 : bean2;
//do not wait in the batchlet when restarting.
jobParams.setProperty("seconds", String.valueOf(0));
jobParams.setProperty("interval", String.valueOf(0));
final long restartExecutionId = beanUsedToRestart.restart(jobExecutionId, jobParams);
//check job status from the node which originated the restart operation
final BatchStatus restartStatusFromNode1 = waitForBatchStatus(beanUsedToRestart, restartExecutionId, BatchStatus.COMPLETED);
assertEquals(BatchStatus.COMPLETED, restartStatusFromNode1);
} finally {
if (context2 != null) {
context2.close();
}
if (context1 != null) {
context1.close();
}
}
}
private static BatchStatus waitForBatchStatus(BatchClientIF bean, long jobExecutionId, BatchStatus batchStatus) throws Exception {
final long endTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(BATCHLET_DELAY_SECONDS);
BatchStatus finalStatus = null;
Exception exception = null;
do {
Thread.sleep(CHECK_STATUS_INTERVAL_MILLIS);
try {
finalStatus = bean.getJobStatus(jobExecutionId);
} catch (Exception e) {
exception = e;
}
} while (finalStatus != batchStatus && System.currentTimeMillis() < endTime);
if (exception != null) {
log.warnf(exception, "batch status is still null after wait timeout.");
}
return finalStatus;
}
}
| 14,196 | 46.801347 | 157 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/batch/stoprestart/BatchClientBean.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2021, 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.multinode.batch.stoprestart;
import java.util.Properties;
import jakarta.batch.operations.JobOperator;
import jakarta.batch.runtime.BatchRuntime;
import jakarta.batch.runtime.BatchStatus;
import jakarta.batch.runtime.JobExecution;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionManagement;
import jakarta.ejb.TransactionManagementType;
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class BatchClientBean implements BatchClientIF {
private final JobOperator jobOperator = BatchRuntime.getJobOperator();
@Override
public long start(String jobName, Properties jobParams) {
return jobOperator.start(jobName, jobParams);
}
@Override
public void stop(long jobExecutionId) {
jobOperator.stop(jobExecutionId);
}
@Override
public long restart(long jobExecutionId, Properties restartParams) {
return jobOperator.restart(jobExecutionId, restartParams);
}
@Override
public BatchStatus getJobStatus(long jobExecutionId) {
final JobExecution jobExecution = jobOperator.getJobExecution(jobExecutionId);
return jobExecution.getBatchStatus();
}
}
| 2,211 | 35.866667 | 86 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/TransactionalStatelessBean.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.multinode.transaction;
import jakarta.annotation.Resource;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionAttribute;
import jakarta.ejb.TransactionAttributeType;
import jakarta.transaction.TransactionSynchronizationRegistry;
/**
* @author Stuart Douglas
* @author Ivo Studensky
*/
@Remote(TransactionalRemote.class)
@Stateless
public class TransactionalStatelessBean implements TransactionalRemote {
@Resource
private TransactionSynchronizationRegistry transactionSynchronizationRegistry;
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public int transactionStatus() {
return transactionSynchronizationRegistry.getTransactionStatus();
}
}
| 1,774 | 35.979167 | 82 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/TransactionalRemote.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.multinode.transaction;
import java.rmi.RemoteException;
/**
* @author Stuart Douglas
*/
public interface TransactionalRemote {
int transactionStatus() throws RemoteException;
}
| 1,235 | 36.454545 | 70 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/TransactionalStatefulBean.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.multinode.transaction;
import jakarta.annotation.Resource;
import jakarta.ejb.EJBException;
import jakarta.ejb.Remote;
import jakarta.ejb.SessionContext;
import jakarta.ejb.SessionSynchronization;
import jakarta.ejb.Stateful;
import jakarta.ejb.TransactionAttribute;
import jakarta.ejb.TransactionAttributeType;
import jakarta.transaction.TransactionSynchronizationRegistry;
import java.rmi.RemoteException;
/**
* @author Stuart Douglas
* @author Ivo Studensky
*/
@Remote(TransactionalStatefulRemote.class)
@Stateful
public class TransactionalStatefulBean implements SessionSynchronization, TransactionalStatefulRemote {
private Boolean commitSucceeded;
private boolean beforeCompletion = false;
private Object transactionKey = null;
private boolean rollbackOnlyBeforeCompletion = false;
@Resource
private SessionContext sessionContext;
@Resource
private TransactionSynchronizationRegistry transactionSynchronizationRegistry;
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public int transactionStatus() {
return transactionSynchronizationRegistry.getTransactionStatus();
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void resetStatus() {
commitSucceeded = null;
beforeCompletion = false;
transactionKey = null;
}
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public void setRollbackOnlyBeforeCompletion(boolean rollbackOnlyBeforeCompletion) throws RemoteException {
this.rollbackOnlyBeforeCompletion = rollbackOnlyBeforeCompletion;
}
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void sameTransaction(boolean first) throws RemoteException {
if (first) {
transactionKey = transactionSynchronizationRegistry.getTransactionKey();
} else {
if (!transactionKey.equals(transactionSynchronizationRegistry.getTransactionKey())) {
throw new RemoteException("Transaction on second call was not the same as on first call");
}
}
}
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void rollbackOnly() throws RemoteException {
this.sessionContext.setRollbackOnly();
}
public void ejbCreate() {
}
public void afterBegin() throws EJBException, RemoteException {
}
public void beforeCompletion() throws EJBException, RemoteException {
beforeCompletion = true;
if (rollbackOnlyBeforeCompletion) {
this.sessionContext.setRollbackOnly();
}
}
public void afterCompletion(final boolean committed) throws EJBException, RemoteException {
commitSucceeded = committed;
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public Boolean getCommitSucceeded() {
return commitSucceeded;
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public boolean isBeforeCompletion() {
return beforeCompletion;
}
}
| 4,086 | 33.635593 | 110 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/TransactionInvocationTestCase.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.multinode.transaction;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import java.io.IOException;
import java.util.Arrays;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createFilePermission;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
/**
* A simple Jakarta Enterprise Beans Remoting transaction context propagation in JTS style from one AS7 server to another.
*
* @author Stuart Douglas
* @author Ivo Studensky
*/
@RunWith(Arquillian.class)
public class TransactionInvocationTestCase {
public static final String SERVER_DEPLOYMENT = "server";
public static final String CLIENT_DEPLOYMENT = "client";
@Deployment(name = "server", testable = false)
@TargetsContainer("multinode-server")
public static Archive<?> deployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, SERVER_DEPLOYMENT + ".jar");
jar.addClasses(TransactionalStatelessBean.class, TransactionalRemote.class,
TransactionalStatefulRemote.class, TransactionalStatefulBean.class);
return jar;
}
@Deployment(name = "client", testable = true)
@TargetsContainer("multinode-client")
public static Archive<?> clientDeployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, CLIENT_DEPLOYMENT + ".jar");
jar.addClasses(ClientEjb.class, TransactionalRemote.class, TransactionInvocationTestCase.class,
TransactionalStatefulRemote.class);
jar.addAsManifestResource("META-INF/jboss-ejb-client-receivers.xml", "jboss-ejb-client.xml");
jar.addAsManifestResource(
createPermissionsXmlAsset(
createFilePermission("delete",
"jbossas.multinode.client", Arrays.asList("standalone", "data", "ejb-xa-recovery", "-")),
createFilePermission("read",
"jboss.home", Arrays.asList("standalone", "tmp", "auth", "-"))),
"permissions.xml");
return jar;
}
@Test
@OperateOnDeployment("client")
public void testRemoteInvocation() throws IOException, NamingException, NotSupportedException, SystemException {
final ClientEjb ejb = getClient();
ejb.basicTransactionPropagationTest();
}
@Test
@OperateOnDeployment("client")
public void testRollbackOnly() throws IOException, NamingException, NotSupportedException, SystemException {
final ClientEjb ejb = getClient();
ejb.testRollbackOnly();
}
@Test
@OperateOnDeployment("client")
public void testRollbackOnlyBeforeCompletion() throws IOException, NamingException, NotSupportedException, SystemException, HeuristicMixedException, HeuristicRollbackException {
final ClientEjb ejb = getClient();
ejb.testRollbackOnlyBeforeCompletion();
}
@Test
@OperateOnDeployment("client")
public void testSameTransactionEachCall() throws IOException, NamingException, NotSupportedException, SystemException {
final ClientEjb ejb = getClient();
ejb.testSameTransactionEachCall();
}
@Test
@OperateOnDeployment("client")
public void testSynchronizationSucceeded() throws IOException, NamingException, NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
final ClientEjb ejb = getClient();
ejb.testSynchronization(true);
}
@Test
@OperateOnDeployment("client")
public void testSynchronizationFailed() throws IOException, NamingException, NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
final ClientEjb ejb = getClient();
ejb.testSynchronization(false);
}
private ClientEjb getClient() throws NamingException {
final InitialContext context = new InitialContext();
return (ClientEjb) context.lookup("java:module/" + ClientEjb.class.getSimpleName());
}
}
| 5,836 | 41.919118 | 196 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/TransactionalStatefulRemote.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.multinode.transaction;
import java.rmi.RemoteException;
/**
* @author Stuart Douglas
*/
public interface TransactionalStatefulRemote {
int transactionStatus() throws RemoteException;
Boolean getCommitSucceeded() throws RemoteException;
boolean isBeforeCompletion() throws RemoteException;
void resetStatus() throws RemoteException;
void sameTransaction(boolean first) throws RemoteException;
void rollbackOnly() throws RemoteException;
void setRollbackOnlyBeforeCompletion(boolean rollbackOnlyInBeforeCompletion) throws RemoteException;
}
| 1,628 | 34.413043 | 104 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/ClientEjb.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.multinode.transaction;
import org.junit.Assert;
import jakarta.annotation.Resource;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionManagement;
import jakarta.ejb.TransactionManagementType;
import javax.naming.Context;
import javax.naming.NamingException;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.transaction.UserTransaction;
import java.rmi.RemoteException;
import java.util.Hashtable;
/**
* @author Stuart Douglas
* @author Ivo Studensky
*/
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class ClientEjb {
@Resource
private UserTransaction userTransaction;
private TransactionalRemote getRemote() throws NamingException {
final Hashtable props = new Hashtable();
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
final Context context = new javax.naming.InitialContext(props);
final TransactionalRemote remote = (TransactionalRemote) context.lookup("ejb:/" + TransactionInvocationTestCase.SERVER_DEPLOYMENT + "/" + "" + "/" + "TransactionalStatelessBean" + "!" + TransactionalRemote.class.getName());
return remote;
}
private TransactionalStatefulRemote getStatefulRemote() throws NamingException {
final Hashtable props = new Hashtable();
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
final Context context = new javax.naming.InitialContext(props);
final TransactionalStatefulRemote statefulRemote = (TransactionalStatefulRemote) context.lookup("ejb:/" + TransactionInvocationTestCase.SERVER_DEPLOYMENT + "/" + "" + "/" + "TransactionalStatefulBean" + "!" + TransactionalStatefulRemote.class.getName() + "?stateful");
return statefulRemote;
}
public void basicTransactionPropagationTest() throws RemoteException, SystemException, NotSupportedException, NamingException {
final TransactionalRemote remote = getRemote();
Assert.assertEquals("No transaction expected!", Status.STATUS_NO_TRANSACTION, remote.transactionStatus());
userTransaction.begin();
try {
Assert.assertEquals("Active transaction expected!", Status.STATUS_ACTIVE, remote.transactionStatus());
} finally {
userTransaction.rollback();
}
}
public void testSameTransactionEachCall() throws RemoteException, SystemException, NotSupportedException, NamingException {
final TransactionalStatefulRemote statefulRemote = getStatefulRemote();
userTransaction.begin();
try {
statefulRemote.sameTransaction(true);
statefulRemote.sameTransaction(false);
} finally {
userTransaction.rollback();
}
}
public void testSynchronization(final boolean succeeded) throws RemoteException, SystemException, NotSupportedException, RollbackException, HeuristicRollbackException, HeuristicMixedException, NamingException {
final TransactionalStatefulRemote statefulRemote = getStatefulRemote();
userTransaction.begin();
try {
statefulRemote.sameTransaction(true);
statefulRemote.sameTransaction(false);
} finally {
if (succeeded) {
userTransaction.commit();
} else {
userTransaction.rollback();
}
}
Assert.assertEquals("The beforeCompletion method invalid invocation!", succeeded, statefulRemote.isBeforeCompletion());
Assert.assertEquals("The result of the transaction does not match the input of afterCompletion!", (Boolean) succeeded, statefulRemote.getCommitSucceeded());
}
public void testRollbackOnly() throws RemoteException, SystemException, NotSupportedException, NamingException {
final TransactionalStatefulRemote statefulRemote = getStatefulRemote();
userTransaction.begin();
try {
Assert.assertEquals("Active transaction expected!", Status.STATUS_ACTIVE, statefulRemote.transactionStatus());
statefulRemote.rollbackOnly();
Assert.assertEquals("Rollback-only marked transaction expected!", Status.STATUS_MARKED_ROLLBACK, statefulRemote.transactionStatus());
} finally {
userTransaction.rollback();
}
Assert.assertFalse("The beforeCompletion method invoked even in case of rollback-only transaction!", statefulRemote.isBeforeCompletion());
Assert.assertFalse("The result of the transaction does not match the input of afterCompletion!", statefulRemote.getCommitSucceeded());
}
public void testRollbackOnlyBeforeCompletion() throws RemoteException, SystemException, NotSupportedException, HeuristicRollbackException, HeuristicMixedException, NamingException {
final TransactionalStatefulRemote statefulRemote = getStatefulRemote();
userTransaction.begin();
try {
Assert.assertEquals("Active transaction expected!", Status.STATUS_ACTIVE, statefulRemote.transactionStatus());
statefulRemote.setRollbackOnlyBeforeCompletion(true);
userTransaction.commit();
} catch (RollbackException expected) {
} finally {
if (userTransaction.getStatus() == Status.STATUS_ACTIVE) {
userTransaction.rollback();
}
}
Assert.assertFalse("The result of the transaction does not match the input of afterCompletion!", statefulRemote.getCommitSucceeded());
Assert.assertEquals("No transaction expected!", Status.STATUS_NO_TRANSACTION, statefulRemote.transactionStatus());
}
}
| 6,887 | 47.507042 | 276 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/nooutbound/ProviderUrlData.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.multinode.transaction.nooutbound;
import org.jboss.as.test.shared.TestSuiteEnvironment;
public class ProviderUrlData {
private final String protocol, host;
private final int port;
public ProviderUrlData(String protocol, String host, int port) {
this.protocol = protocol;
this.host = host;
this.port = port;
}
public String getProviderUrl() {
String host = TestSuiteEnvironment.formatPossibleIpv6Address(this.host);
int port = this.port;
return String.format("%s://%s:%s%s", protocol, host, port,
protocol.startsWith("http") ? "/wildfly-services" : "");
}
public String toString() {
return getProviderUrl();
}
}
| 1,770 | 35.895833 | 80 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/nooutbound/ServerMandatoryStatelessBean.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.multinode.transaction.nooutbound;
import jakarta.annotation.Resource;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionAttribute;
import jakarta.ejb.TransactionAttributeType;
import jakarta.transaction.TransactionSynchronizationRegistry;
@Remote(ServerStatelessRemote.class)
@Stateless
public class ServerMandatoryStatelessBean implements ServerStatelessRemote {
@Resource
private TransactionSynchronizationRegistry transactionSynchronizationRegistry;
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public int transactionStatus() {
return transactionSynchronizationRegistry.getTransactionStatus();
}
}
| 1,734 | 37.555556 | 82 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/nooutbound/TransactionContextRemoteCallTestCase.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.multinode.transaction.nooutbound;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createFilePermission;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.net.SocketPermission;
import java.util.Arrays;
import java.util.PropertyPermission;
import jakarta.ejb.EJBException;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* A simple Jakarta Enterprise Beans Remoting transaction context propagation.
*/
@RunWith(Arquillian.class)
public class TransactionContextRemoteCallTestCase {
private static final String CLIENT_CONTAINER = "multinode-client";
public static final String CLIENT_DEPLOYMENT = "client";
private static final String SERVER_CONTAINER = "multinode-server";
public static final String SERVER_DEPLOYMENT = "server";
private static final int serverPort = 8180;
@Inject
private ClientStatelessBean clientBean;
@Deployment(name = CLIENT_DEPLOYMENT, testable = true)
@TargetsContainer(CLIENT_CONTAINER)
public static Archive<?> clientDeployment() {
return ShrinkWrap.create(JavaArchive.class, CLIENT_DEPLOYMENT + ".jar")
.addClasses(ClientStatelessBean.class, ServerStatelessRemote.class, ProviderUrlData.class, TestSuiteEnvironment.class,
ServerMandatoryStatelessBean.class, ServerNeverStatelessBean.class,
TransactionContextRemoteCallTestCase.class)
.addAsManifestResource(new StringAsset("Dependencies: org.wildfly.http-client.transaction\n"), "MANIFEST.MF")
.addAsManifestResource(createPermissionsXmlAsset(
createFilePermission("delete", "jbossas.multinode.client", Arrays.asList("standalone", "data", "ejb-xa-recovery", "-")),
new SocketPermission(TestSuiteEnvironment.formatPossibleIpv6Address(System.getProperty("node0")) + ":" + serverPort, "connect,resolve"),
new PropertyPermission("node1", "read")
), "permissions.xml");
}
@Deployment(name = SERVER_DEPLOYMENT, testable = false)
@TargetsContainer(SERVER_CONTAINER)
public static Archive<?> deployment() {
return ShrinkWrap.create(JavaArchive.class, SERVER_DEPLOYMENT + ".jar")
.addClasses(ServerMandatoryStatelessBean.class, ServerNeverStatelessBean.class, ServerStatelessRemote.class);
}
@Test
@OperateOnDeployment(CLIENT_DEPLOYMENT)
public void remotePlusHttpMandatoryBean() {
ProviderUrlData providerUrl = new ProviderUrlData("remote+http", TestSuiteEnvironment.getServerAddressNode1(), serverPort);
clientBean.call(providerUrl, ServerMandatoryStatelessBean.class.getSimpleName());
}
@Test
@OperateOnDeployment(CLIENT_DEPLOYMENT)
public void remotePlusHttpNeverBean() {
try {
ProviderUrlData providerUrl = new ProviderUrlData("remote+http", TestSuiteEnvironment.getServerAddressNode1(), serverPort);
clientBean.call(providerUrl, ServerNeverStatelessBean.class.getSimpleName());
Assert.fail(EJBException.class.getName() + " expected, transaction context propagated to TransactionAttributeType.NEVER");
} catch (EJBException expected) {
}
}
@Test
@OperateOnDeployment(CLIENT_DEPLOYMENT)
public void httpMandatoryBean() {
ProviderUrlData providerUrl = new ProviderUrlData("http", TestSuiteEnvironment.getServerAddressNode1(), serverPort);
clientBean.call(providerUrl, ServerMandatoryStatelessBean.class.getSimpleName());
}
@Test
@OperateOnDeployment(CLIENT_DEPLOYMENT)
public void httpNeverBean() {
try {
ProviderUrlData providerUrl = new ProviderUrlData("http", TestSuiteEnvironment.getServerAddressNode1(), serverPort);
clientBean.call(providerUrl, ServerNeverStatelessBean.class.getSimpleName());
Assert.fail(EJBException.class.getName() + " expected, transaction context propagated to TransactionAttributeType.NEVER");
} catch (EJBException expected) {
}
}
}
| 5,700 | 45.729508 | 156 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/nooutbound/ServerStatelessRemote.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.multinode.transaction.nooutbound;
import java.rmi.RemoteException;
public interface ServerStatelessRemote {
int transactionStatus() throws RemoteException;
}
| 1,214 | 39.5 | 70 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/nooutbound/ServerNeverStatelessBean.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.multinode.transaction.nooutbound;
import jakarta.annotation.Resource;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionAttribute;
import jakarta.ejb.TransactionAttributeType;
import jakarta.transaction.TransactionSynchronizationRegistry;
@Remote(ServerStatelessRemote.class)
@Stateless
public class ServerNeverStatelessBean implements ServerStatelessRemote {
@Resource
private TransactionSynchronizationRegistry transactionSynchronizationRegistry;
@TransactionAttribute(TransactionAttributeType.NEVER)
public int transactionStatus() {
return transactionSynchronizationRegistry.getTransactionStatus();
}
}
| 1,726 | 37.377778 | 82 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/nooutbound/ClientStatelessBean.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.multinode.transaction.nooutbound;
import java.rmi.RemoteException;
import java.util.Properties;
import java.util.function.BiFunction;
import java.util.function.Function;
import jakarta.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.logging.Logger;
import org.junit.Assert;
import org.wildfly.naming.client.WildFlyInitialContextFactory;
@Stateless
public class ClientStatelessBean {
private static final Logger log = Logger.getLogger(ClientStatelessBean.class);
Function<ProviderUrlData, InitialContext> initialContextGetter = (providerUrl) -> {
Properties jndiProperties = new Properties();
jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, WildFlyInitialContextFactory.class.getName());
jndiProperties.put(javax.naming.Context.PROVIDER_URL, providerUrl.getProviderUrl());
jndiProperties.put(Context.SECURITY_PRINCIPAL, "user1");
jndiProperties.put(Context.SECURITY_CREDENTIALS, "password1");
// the authentication is forced to go through remote MD5 authentication
jndiProperties.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS", "JBOSS-LOCAL-USER");
try {
return new InitialContext(jndiProperties);
} catch (NamingException ne) {
throw new IllegalStateException("Cannot create initial context for '" + providerUrl + "'", ne);
}
};
BiFunction<ProviderUrlData, String, Integer> remoteCall = (providerUrl, beanName) -> {
InitialContext ctx = initialContextGetter.apply(providerUrl);
try {
ServerStatelessRemote bean = (ServerStatelessRemote) ctx.lookup("ejb:/" +
TransactionContextRemoteCallTestCase.SERVER_DEPLOYMENT + "/" + beanName + "!" + ServerStatelessRemote.class.getName());
return bean.transactionStatus();
} catch (NamingException | RemoteException nre) {
throw new IllegalStateException("Cannot do remote bean call '" + beanName + "' with context " + ctx, nre);
} finally {
try {
ctx.close();
} catch (NamingException closeNamingException) {
log.warn("Cannot close context after remote call", closeNamingException);
}
}
};
public void call(ProviderUrlData providerUrl, String beanName) {
Assert.assertEquals(new Integer(0),
remoteCall.apply(providerUrl, beanName));
}
}
| 3,577 | 44.291139 | 135 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/async/TransactionalRemote.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.multinode.transaction.async;
import java.util.concurrent.Future;
import jakarta.ejb.Remote;
/**
* Remote interface for testing beans being called.
*
* @author Ondrej Chaloupka
*/
@Remote
public interface TransactionalRemote {
Future<Integer> transactionStatus();
Future<Integer> asyncWithRequired();
}
| 1,366 | 34.973684 | 70 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/async/TransactionalStatusByManager.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.multinode.transaction.async;
import java.util.concurrent.Future;
import jakarta.annotation.Resource;
import jakarta.ejb.AsyncResult;
import jakarta.ejb.Asynchronous;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionAttribute;
import jakarta.ejb.TransactionAttributeType;
import jakarta.transaction.SystemException;
import jakarta.transaction.TransactionManager;
/**
* Asynchronously invoked bean where we expect that transaction manager returns
* no active status for "current" transaction as propagation should not occur.
*
* @author Ondrej Chaloupka
*/
@Stateless
public class TransactionalStatusByManager implements TransactionalRemote {
@Resource(lookup = "java:/TransactionManager")
private TransactionManager txnManager;
@Asynchronous
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public Future<Integer> transactionStatus() {
try {
return new AsyncResult<Integer>(txnManager.getStatus());
} catch (SystemException se) {
throw new RuntimeException("Can't get transaction status", se);
}
}
@Override
@Asynchronous
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Future<Integer> asyncWithRequired() {
throw new RuntimeException("Throw RuntimeException on purpose to cause the transaction rollback");
}
}
| 2,404 | 37.174603 | 106 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/async/TransactionalStatusByRegistry.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.multinode.transaction.async;
import java.util.concurrent.Future;
import jakarta.annotation.Resource;
import jakarta.ejb.AsyncResult;
import jakarta.ejb.Asynchronous;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionAttribute;
import jakarta.ejb.TransactionAttributeType;
import jakarta.transaction.TransactionSynchronizationRegistry;
/**
* Asynchronously invoked bean where we expect that transaction registry returns
* no active status for "current" transaction as propagation should not occur.
*
* @author Ondrej Chaloupka
*/
@Stateless
@Asynchronous
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public class TransactionalStatusByRegistry implements TransactionalRemote {
@Resource
private TransactionSynchronizationRegistry transactionSynchronizationRegistry;
public Future<Integer> transactionStatus() {
return new AsyncResult<Integer>(transactionSynchronizationRegistry.getTransactionStatus());
}
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Future<Integer> asyncWithRequired() {
throw new RuntimeException("Throw RuntimeException on purpose to cause the transaction rollback");
}
}
| 2,247 | 38.438596 | 106 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/async/TransactionalMandatory.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.multinode.transaction.async;
import java.util.concurrent.Future;
import jakarta.ejb.AsyncResult;
import jakarta.ejb.Asynchronous;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionAttribute;
import jakarta.ejb.TransactionAttributeType;
/**
* Bean invoked asynchronously where {@link TransactionAttributeType#MANDATORY} suggests
* that call to this bean will fail.
*
* @author Ondrej Chaloupka
*/
@Stateless
@Asynchronous
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public class TransactionalMandatory implements TransactionalRemote {
public Future<Integer> transactionStatus() {
return new AsyncResult<Integer>(-1);
}
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Future<Integer> asyncWithRequired() {
throw new RuntimeException("Throw RuntimeException on purpose to cause the transaction rollback");
}
}
| 1,955 | 36.615385 | 106 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/async/TransactionPropagationTestCase.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.multinode.transaction.async;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createFilePermission;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.util.Arrays;
import javax.naming.InitialContext;
/**
* <p>
* Testing transaction propagation to a remote server when bean method is annotated
* as asynchronous.
* <p>
* Specification says at such case that no transaction context is provided
* <p>
* Jakarta Enterprise Beans 3.2 4.5.3 Transactions<br>
* The client’s transaction context does not propagate with an asynchronous method invocation. From the
* Bean Provider’s point of view, there is never a transaction context flowing in from the client. This
* means, for example, that the semantics of the REQUIRED transaction attribute on an asynchronous
* method are exactly the same as REQUIRES_NEW.
*
* @author Ondrej Chaloupka
*/
@RunWith(Arquillian.class)
public class TransactionPropagationTestCase {
public static final String CLIENT_DEPLOYMENT = "client-txt-propag-async";
public static final String SERVER_DEPLOYMENT = "server-txt-propag-async";
@Deployment(name = CLIENT_DEPLOYMENT, testable = true)
@TargetsContainer("multinode-client")
public static Archive<?> clientDeployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, CLIENT_DEPLOYMENT + ".jar");
jar.addPackage(TransactionPropagationTestCase.class.getPackage());
jar.addAsManifestResource("META-INF/jboss-ejb-client-receivers.xml", "jboss-ejb-client.xml");
jar.addAsManifestResource(
createPermissionsXmlAsset(
createFilePermission("read",
"jboss.home", Arrays.asList("standalone", "tmp", "auth", "-"))),
"permissions.xml");
return jar;
}
@Deployment(name = SERVER_DEPLOYMENT, testable = false)
@TargetsContainer("multinode-server")
public static Archive<?> deployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, SERVER_DEPLOYMENT + ".jar");
jar.addClasses(TransactionalMandatory.class, TransactionalStatusByManager.class, TransactionalStatusByRegistry.class,
TransactionalRemote.class);
return jar;
}
@Test
@OperateOnDeployment(CLIENT_DEPLOYMENT)
public void testRemoteInvocation() throws Exception {
final ClientBean ejb = getClient();
ejb.callToMandatory();
}
@Test
@OperateOnDeployment(CLIENT_DEPLOYMENT)
public void testRemoteWithStatusAtRegistry() throws Exception {
final ClientBean ejb = getClient();
ejb.callToStatusByRegistry();
}
@Test
@OperateOnDeployment(CLIENT_DEPLOYMENT)
public void testRemoteWithStatusAtTransactionManager() throws Exception {
final ClientBean ejb = getClient();
ejb.callToStatusByTransactionmanager();
}
@Test
@OperateOnDeployment(CLIENT_DEPLOYMENT)
public void testRemoteWithRequired() throws Exception {
final ClientBean ejb = getClient();
ejb.callToRequired();
}
private ClientBean getClient() throws Exception {
final InitialContext context = new InitialContext();
final ClientBean lookupResult = (ClientBean) context.lookup("java:module/" + ClientBean.class.getSimpleName());
context.close();
return lookupResult;
}
}
| 4,946 | 39.54918 | 125 |
java
|
null |
wildfly-main/testsuite/integration/multinode/src/test/java/org/jboss/as/test/multinode/transaction/async/ClientBean.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.multinode.transaction.async;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Hashtable;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionManagement;
import jakarta.ejb.TransactionManagementType;
import javax.naming.Context;
import javax.naming.NamingException;
import jakarta.transaction.Status;
import jakarta.transaction.UserTransaction;
/**
* Client bean which lookups for a remote bean on other server and do the call.
*
* @author Ondrej Chaloupka
*/
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class ClientBean {
@Resource
private UserTransaction userTransaction;
private Context namingContext;
@PostConstruct
private void postConstruct() {
final Hashtable<String,String> props = new Hashtable<>();
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
try {
namingContext = new javax.naming.InitialContext(props);
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
@PreDestroy
private void preDestroy() {
if (namingContext != null) {
try {
namingContext.close();
} catch (NamingException e) {
//ignore
}
}
}
private TransactionalRemote getRemote(Class<?> beanClass) throws NamingException {
return (TransactionalRemote) namingContext.lookup(String.format("ejb:/%s//%s!%s",
TransactionPropagationTestCase.SERVER_DEPLOYMENT, beanClass.getSimpleName(), TransactionalRemote.class.getName()));
}
public void callToMandatory() throws Exception {
final TransactionalRemote remote = getRemote(TransactionalMandatory.class);
userTransaction.begin();
try {
remote.transactionStatus().get();
fail("Expecting exception being thrown as async call does not provide transaction context");
} catch (java.util.concurrent.ExecutionException ee) {
// ignored - bean with transaction attribute mandatory
// but async call does not provide transactional context thus the exception is expected
} finally {
userTransaction.rollback();
}
}
public void callToStatusByRegistry() throws Exception {
final TransactionalRemote remote = getRemote(TransactionalStatusByRegistry.class);
userTransaction.begin();
try {
assertEquals("No transaction expected as async call does not pass txn context",
(Integer) Status.STATUS_NO_TRANSACTION, remote.transactionStatus().get());
} finally {
userTransaction.rollback();
}
}
public void callToStatusByTransactionmanager() throws Exception {
final TransactionalRemote remote = getRemote(TransactionalStatusByManager.class);
userTransaction.begin();
try {
assertEquals("No transaction expected as async call does not pass txn context",
(Integer) Status.STATUS_NO_TRANSACTION, remote.transactionStatus().get());
} finally {
userTransaction.rollback();
}
}
/**
* Verifies async method invocation with REQUIRED transaction attribute.
* The client transaction context should not be propagated to the invoked async method.
* The invoked async method should execute in a new, separate transaction context.
*/
public void callToRequired() throws Exception {
final TransactionalRemote remote = getRemote(TransactionalStatusByManager.class);
userTransaction.begin();
// asyncWithRequired() will throw RuntimeException and cause its transaction to rollback.
// But it has no bearing on the transaction here, which should be able to commit okay.
try {
remote.asyncWithRequired().get();
} catch (java.util.concurrent.ExecutionException e) {
// This is expected since the invoked async method throws a RuntimeException
}
userTransaction.commit();
}
}
| 5,278 | 38.103704 | 125 |
java
|
null |
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/autoignore/TestClass.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.autoignore;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
*
* @author <a href="[email protected]">Kabir Khan</a>
*/
public class TestClass implements TestClassMBean {
String path;
@Override
public void setPath(String path) {
this.path = path;
}
@Override
public void start() {
try {
Files.write(Paths.get(path), "Test\n".getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
| 1,665 | 29.851852 | 84 |
java
|
null |
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/autoignore/TestClassMBean.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.autoignore;
/**
*
* @author <a href="[email protected]">Kabir Khan</a>
*/
public interface TestClassMBean {
void setPath(String path);
void start();
}
| 1,227 | 37.375 | 70 |
java
|
null |
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/EEConcurrencyExecutorShutdownTestCase.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.domain;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.helpers.domain.DomainClient;
import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil;
import org.jboss.as.test.integration.domain.management.util.DomainTestSupport;
import org.jboss.as.test.shared.RetryTaskExecutor;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CONTENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ENABLED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PRIMARY;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_CONFIG;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STATUS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STOP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TIMEOUT;
import static org.jboss.as.controller.operations.common.Util.createAddOperation;
import static org.jboss.as.controller.operations.common.Util.createEmptyOperation;
import static org.jboss.as.test.integration.domain.management.util.DomainTestSupport.cleanFile;
import static org.jboss.as.test.integration.domain.management.util.DomainTestUtils.executeForResult;
import static org.junit.Assert.fail;
/**
* The test case schedules an instance of task ReSchedulingTask.
* Each instance of ReSchedulingTask sleeps for 10 seconds and then re-schedules another instance of its own class.
* After the CLI command /host=primary/server-config=server-one:stop() is invoked the server should stop.
* Test for [ WFCORE-3868 ].
*
* @author Daniel Cihak
*/
public class EEConcurrencyExecutorShutdownTestCase {
private static final String ARCHIVE_FILE_NAME = "test.war";
private static final PathAddress ROOT_DEPLOYMENT_ADDRESS = PathAddress.pathAddress(DEPLOYMENT, ARCHIVE_FILE_NAME);
private static final PathAddress MAIN_SERVER_GROUP_ADDRESS = PathAddress.pathAddress(SERVER_GROUP, "main-server-group");
private static final PathAddress MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS = MAIN_SERVER_GROUP_ADDRESS.append(DEPLOYMENT, ARCHIVE_FILE_NAME);
public static final String FIRST_SERVER_NAME = "main-one";
private static DomainTestSupport testSupport;
public static DomainLifecycleUtil domainPrimaryLifecycleUtil;
private static File tmpDir;
private static DomainClient primaryClient;
@BeforeClass
public static void setupDomain() {
testSupport = createAndStartDefaultEESupport(EEConcurrencyExecutorShutdownTestCase.class.getSimpleName());
domainPrimaryLifecycleUtil = testSupport.getDomainPrimaryLifecycleUtil();
primaryClient = domainPrimaryLifecycleUtil.getDomainClient();
}
private static DomainTestSupport createAndStartDefaultEESupport(final String testName) {
try {
final DomainTestSupport.Configuration configuration;
if (Boolean.getBoolean("wildfly.primary.debug")) {
configuration = DomainTestSupport.Configuration.createDebugPrimary(testName,
"domain-configs/domain-standard-ee.xml", "host-configs/host-primary.xml", null);
} else if (Boolean.getBoolean("wildfly.secondary.debug")) {
configuration = DomainTestSupport.Configuration.createDebugSecondary(testName,
"domain-configs/domain-standard-ee.xml", "host-configs/host-primary.xml", null);
} else {
configuration = DomainTestSupport.Configuration.create(testName,
"domain-configs/domain-standard-ee.xml", "host-configs/host-primary.xml", null);
}
final DomainTestSupport testSupport = DomainTestSupport.create(configuration);
testSupport.start();
return testSupport;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Before
public void createDeployment() {
WebArchive testDeployment = ShrinkWrap.create(WebArchive.class, ARCHIVE_FILE_NAME);
testDeployment.addClasses(TaskSchedulerServletContextListener.class);
tmpDir = new File("target/deployments/" + this.getClass().getSimpleName());
new File(tmpDir, "archives").mkdirs();
testDeployment.as(ZipExporter.class).exportTo(new File(tmpDir, "archives/" + ARCHIVE_FILE_NAME), true);
}
@AfterClass
public static void tearDownDomain() {
try {
testSupport.stop();
domainPrimaryLifecycleUtil = null;
} finally {
cleanFile(tmpDir);
}
}
/**
* Tests if the server with running ConcurrencyExecutor can be stopped using cli command
* /host=primary/server-config=server-one:stop(timeout=0)
*
* @throws Exception
*/
@Test
public void testConcurrencyExecutorShutdown() throws Exception {
ModelNode content = new ModelNode();
content.get("archive").set(true);
content.get("path").set(new File(tmpDir, "archives/" + ARCHIVE_FILE_NAME).getAbsolutePath());
ModelNode deploymentOpMain = createDeploymentOperation(content, MAIN_SERVER_GROUP_DEPLOYMENT_ADDRESS);
executeForResult(deploymentOpMain, primaryClient);
this.stopServer(FIRST_SERVER_NAME);
}
private ModelNode createDeploymentOperation(ModelNode content, PathAddress... serverGroupAddressses) {
ModelNode composite = createEmptyOperation(COMPOSITE, PathAddress.EMPTY_ADDRESS);
ModelNode steps = composite.get(STEPS);
ModelNode step1 = steps.add();
step1.set(createAddOperation(ROOT_DEPLOYMENT_ADDRESS));
step1.get(CONTENT).add(content);
for (PathAddress serverGroup : serverGroupAddressses) {
ModelNode sg = steps.add();
sg.set(createAddOperation(serverGroup));
sg.get(ENABLED).set(true);
}
return composite;
}
/**
* Stops the given server and waits until STOPPED status
*
* @param serverName
* @throws Exception
*/
private void stopServer(final String serverName) {
ModelNode op = new ModelNode();
op.get(OP_ADDR).add(HOST, PRIMARY);
op.get(OP_ADDR).add(SERVER_CONFIG, FIRST_SERVER_NAME);
op.get(OP).set(STOP);
op.get(TIMEOUT).set(0);
domainPrimaryLifecycleUtil.executeForResult(op);
try {
waitUntilState(FIRST_SERVER_NAME, "STOPPED");
} catch (TimeoutException e) {
fail("After \"stop(timeout=0)\" was called sever never reached the desired STOPPED state.");
}
}
/**
* Checks the status of he given server until given state is reached.
*
* @param serverName
* @param state
* @throws TimeoutException
*/
private static void waitUntilState(final String serverName, final String state) throws TimeoutException {
RetryTaskExecutor<Void> taskExecutor = new RetryTaskExecutor<Void>();
taskExecutor.retryTask(new Callable<Void>() {
public Void call() throws Exception {
String serverStatus = this.checkServerStatus();
if (!serverStatus.equals(state)) throw new Exception("Server not in state " + state);
return null;
}
private String checkServerStatus() {
ModelNode op = new ModelNode();
op.get(OP_ADDR).add(HOST, PRIMARY);
op.get(OP_ADDR).add(SERVER_CONFIG, serverName);
op.get(OP).set(READ_ATTRIBUTE_OPERATION);
op.get(NAME).set(STATUS);
return domainPrimaryLifecycleUtil.executeForResult(op).asString();
}
});
}
}
| 9,999 | 46.169811 | 140 |
java
|
null |
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/BuildConfigurationTestBase.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.domain;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.jboss.as.test.integration.domain.management.util.WildFlyManagedConfiguration;
import org.jboss.as.test.shared.TestSuiteEnvironment;
/**
* Base class for tests that use the standard AS configuration files.
*
* @author Emanuel Muckenhuber
* @author Brian Stansberry (c) 2013 Red Hat Inc.
*/
public abstract class BuildConfigurationTestBase {
static final String PRIMARY_ADDRESS = System.getProperty("jboss.test.host.primary.address", "localhost");
static final String PRIMARY_HOST_NAME = "primary";
static final File CONFIG_DIR = new File("target/wildfly/domain/configuration/");
static WildFlyManagedConfiguration createConfiguration(final String domainXmlName, final String hostXmlName, final String testConfiguration) {
return createConfiguration(domainXmlName, hostXmlName, testConfiguration, PRIMARY_HOST_NAME, PRIMARY_ADDRESS, 9990);
}
static WildFlyManagedConfiguration createConfiguration(final String domainXmlName, final String hostXmlName,
final String testConfiguration, final String hostName,
final String hostAddress, final int hostPort) {
final WildFlyManagedConfiguration configuration = new WildFlyManagedConfiguration();
configuration.setHostControllerManagementAddress(hostAddress);
configuration.setHostControllerManagementPort(hostPort);
configuration.setHostControllerManagementProtocol("remote+http");
configuration.setHostCommandLineProperties("-Djboss.domain.primary.address=" + PRIMARY_ADDRESS +
" -Djboss.management.http.port=" + hostPort);
configuration.setDomainConfigFile(hackFixDomainConfig(new File(CONFIG_DIR, domainXmlName)).getAbsolutePath());
configuration.setHostConfigFile(hackFixHostConfig(new File(CONFIG_DIR, hostXmlName), hostName, hostAddress).getAbsolutePath());
//configuration.setHostConfigFile(new File(CONFIG_DIR, hostXmlName).getAbsolutePath());
configuration.setHostName(hostName); // TODO this shouldn't be needed
final File output = new File("target" + File.separator + "domains" + File.separator + testConfiguration + File.separator + hostName);
new File(output, "configuration").mkdirs(); // TODO this should not be necessary
configuration.setDomainDirectory(output.getAbsolutePath());
return configuration;
}
private static File hackFixHostConfig(File hostConfigFile, String hostName, String hostAddress) {
final Path file;
try {
file = Files.createTempFile(hostConfigFile.toPath().getParent(),"host", ".xml");
} catch (IOException e) {
throw new RuntimeException(e);
}
try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)){
List<String> lines = Files.readAllLines(hostConfigFile.toPath(), StandardCharsets.UTF_8);
boolean processedOpt = false;
for (String line : lines) {
int start = line.indexOf("<host");
if (start >= 0 && !line.contains(" name=")) {
StringBuilder sb = new StringBuilder();
sb.append("<host name=\"");
sb.append(hostName);
sb.append('"');
sb.append(line.substring(start + 5));
writer.write(sb.toString());
} else {
start = line.indexOf("<inet-address value=\"");
if (start >= 0) {
StringBuilder sb = new StringBuilder();
sb.append(line, 0, start)
.append("<inet-address value=\"")
.append(hostAddress)
.append("\"/>");
writer.write(sb.toString());
} else {
start = line.indexOf("<option value=\"");
if (start >= 0 && !processedOpt) {
StringBuilder sb = new StringBuilder();
sb.append(line, 0, start);
List<String> opts = new ArrayList<String>();
TestSuiteEnvironment.getIpv6Args(opts);
for (String opt : opts) {
sb.append("<option value=\"")
.append(opt)
.append("\"/>");
}
writer.write(sb.toString());
processedOpt = true;
} else if (!line.contains("java.net.")) {
writer.write(line);
}
}
writer.write("\n");
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return file.toFile();
}
private static File hackFixDomainConfig(File domainConfigFile) {
final File file;
try {
file = File.createTempFile("domain", ".xml", domainConfigFile.getAbsoluteFile().getParentFile());
file.deleteOnExit();
} catch (IOException e) {
throw new RuntimeException(e);
}
try (BufferedWriter writer = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8)) {
List<String> lines = Files.readAllLines(domainConfigFile.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
if (line.contains("<security-setting name=\"#\">")) { //super duper hackish, just IO optimization
writer.write(" <journal type=\"NIO\" file-size=\"1024\" />");
writer.newLine();
}
int start = line.indexOf("java.net.preferIPv4Stack");
if (start < 0) {
writer.write(line);
}
writer.newLine();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return file;
}
}
| 7,529 | 45.481481 | 146 |
java
|
null |
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/DefaultConfigSmokeTestCase.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.domain;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_DESCRIPTION_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RECURSIVE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil;
import org.jboss.as.test.integration.domain.management.util.WildFlyManagedConfiguration;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.logging.Logger;
import org.junit.Assert;
import org.junit.Test;
/**
* Ensures the default domain.xml and host.xml start.
*
* @author Brian Stansberry (c) 2013 Red Hat Inc.
*/
public class DefaultConfigSmokeTestCase extends BuildConfigurationTestBase {
private static final Logger LOGGER = Logger.getLogger(DefaultConfigSmokeTestCase.class);
public static final String secondaryAddress = System.getProperty("jboss.test.host.secondary.address", "127.0.0.1");
@Test
public void testStandardHost() throws Exception {
final WildFlyManagedConfiguration config = createConfiguration("domain.xml", "host.xml", getClass().getSimpleName());
final DomainLifecycleUtil utils = new DomainLifecycleUtil(config);
try {
utils.start();
// Double-check server status by confirming server-one can accept a web request to the root
URLConnection connection = new URL("http://" + TestSuiteEnvironment.formatPossibleIpv6Address(PRIMARY_ADDRESS) + ":8080").openConnection();
connection.connect();
if (Boolean.getBoolean("expression.audit")) {
writeExpressionAudit(utils);
}
} finally {
utils.stop(); // Stop
}
}
@Test
public void testPrimaryAndSecondary() throws Exception {
final WildFlyManagedConfiguration primaryConfig = createConfiguration("domain.xml", "host-primary.xml", getClass().getSimpleName());
final DomainLifecycleUtil primaryUtils = new DomainLifecycleUtil(primaryConfig);
final WildFlyManagedConfiguration secondaryConfig = createConfiguration("domain.xml", "host-secondary.xml", getClass().getSimpleName(),
"secondary", secondaryAddress, 19990);
final DomainLifecycleUtil secondaryUtils = new DomainLifecycleUtil(secondaryConfig);
try {
primaryUtils.start();
secondaryUtils.start();
// Double-check server status by confirming server-one can accept a web request to the root
URLConnection connection = new URL("http://" + TestSuiteEnvironment.formatPossibleIpv6Address(secondaryAddress) + ":8080").openConnection();
connection.connect();
} finally {
try {
secondaryUtils.stop();
} finally {
primaryUtils.stop();
}
}
}
private void writeExpressionAudit(final DomainLifecycleUtil utils) throws IOException {
final ModelNode operation = new ModelNode();
operation.get(OP).set(READ_RESOURCE_DESCRIPTION_OPERATION);
operation.get(OP_ADDR).setEmptyList();
operation.get(RECURSIVE).set(true);
final ModelNode result = utils.getDomainClient().execute(operation);
Assert.assertEquals(SUCCESS, result.get(OUTCOME).asString());
Assert.assertTrue(result.hasDefined(RESULT));
PathAddress pa = PathAddress.EMPTY_ADDRESS;
writeExpressionAudit(pa, result.get(RESULT));
}
private static void writeExpressionAudit(PathAddress pa, ModelNode resourceDescription) {
String paString = getPaString(pa);
if (LOGGER.isTraceEnabled()) {
if (resourceDescription.hasDefined(ModelDescriptionConstants.ATTRIBUTES)) {
for (Property property : resourceDescription.get(ModelDescriptionConstants.ATTRIBUTES).asPropertyList()) {
ModelNode attrdesc = property.getValue();
if (!attrdesc.hasDefined(ModelDescriptionConstants.STORAGE) ||
AttributeAccess.Storage.CONFIGURATION.name().toLowerCase().equals(attrdesc.get(ModelDescriptionConstants.STORAGE).asString().toLowerCase())) {
StringBuilder sb = new StringBuilder(paString);
sb.append(",").append(property.getName());
sb.append(",").append(attrdesc.get(ModelDescriptionConstants.TYPE).asString());
sb.append(",").append(attrdesc.get(ModelDescriptionConstants.EXPRESSIONS_ALLOWED).asBoolean(false));
sb.append(",").append(attrdesc.get(ModelDescriptionConstants.DESCRIPTION).asString());
LOGGER.trace(sb.toString());
}
}
}
}
if (resourceDescription.hasDefined(ModelDescriptionConstants.CHILDREN)) {
for (Property childTypeProp : resourceDescription.get(ModelDescriptionConstants.CHILDREN).asPropertyList()) {
String childType = childTypeProp.getName();
ModelNode childTypeDesc = childTypeProp.getValue();
if (childTypeDesc.hasDefined(ModelDescriptionConstants.MODEL_DESCRIPTION)) {
for (Property childInstanceProp : childTypeDesc.get(ModelDescriptionConstants.MODEL_DESCRIPTION).asPropertyList()) {
PathAddress childAddress = pa.append(childType, childInstanceProp.getName());
writeExpressionAudit(childAddress, childInstanceProp.getValue());
}
}
}
}
}
private static String getPaString(PathAddress pa) {
if (pa.size() == 0) {
return "/";
}
StringBuilder sb = new StringBuilder();
for (PathElement pe : pa) {
sb.append("/").append(pe.getKey()).append("=").append(pe.getValue());
}
return sb.toString();
}
}
| 7,774 | 47.59375 | 170 |
java
|
null |
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/OrderedChildResourcesTestCase.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.domain;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.*;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.helpers.domain.DomainClient;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil;
import org.jboss.as.test.integration.domain.management.util.DomainTestUtils;
import org.jboss.as.test.integration.domain.management.util.WildFlyManagedConfiguration;
import org.jboss.as.test.integration.management.util.MgmtOperationException;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.junit.Assert;
import org.junit.Test;
/**
* Checks that the child resources that should be ordered are in fact so on a secondary reconnect.
* At the moment this is only jgroups protocols. Although we have good tests for the indexed adds
* working on reconnect in core, this is here as a sanity that no special describe handler is used
* overriding the default mechanism.
*
* @author Kabir Khan
*/
public class OrderedChildResourcesTestCase extends BuildConfigurationTestBase {
private static final String SECONDARY_ADDRESS = System.getProperty("jboss.test.host.secondary.address", "127.0.0.1");
private static final String SECONDARY_HOST_NAME = "secondary";
private static final int ADJUSTED_SECOND = TimeoutUtil.adjust(1000);
private static final String TARGET_PROTOCOL = "pbcast.STABLE";
@Test
public void testOrderedChildResources() throws Exception {
String testConfiguration = this.getClass().getSimpleName();
final WildFlyManagedConfiguration primaryConfig = createConfiguration("domain.xml", "host-primary.xml", testConfiguration);
final WildFlyManagedConfiguration secondaryConfig = createConfiguration("domain.xml", "host-secondary.xml", testConfiguration, SECONDARY_HOST_NAME, SECONDARY_ADDRESS, 19990);
try (DomainLifecycleUtil primaryUtil = new DomainLifecycleUtil(primaryConfig);
DomainLifecycleUtil secondaryUtil = new DomainLifecycleUtil(secondaryConfig)) {
primaryUtil.start();
secondaryUtil.start();
PathAddress stackAddress = PathAddress.pathAddress(PROFILE, "full-ha")
.append(SUBSYSTEM, "jgroups")
.append("stack", "tcp");
final ModelNode originalPrimaryStack = readResource(primaryUtil.getDomainClient(), stackAddress);
final ModelNode originalSecondaryStack = readResource(secondaryUtil.getDomainClient(), stackAddress);
Assert.assertEquals(originalPrimaryStack, originalSecondaryStack);
int index = -1;
Iterator<Property> it = originalPrimaryStack.get(PROTOCOL).asPropertyList().iterator();
for (int i = 0; it.hasNext(); i++) {
Property property = it.next();
if (property.getName().equals(TARGET_PROTOCOL)) {
index = i;
break;
}
}
//Make sure that we found the protocol and that it is not at the end
Assert.assertTrue(0 <= index);
Assert.assertTrue(index < originalPrimaryStack.get(PROTOCOL).keys().size() - 2);
PathAddress targetProtocolAddress = stackAddress.append(PROTOCOL, TARGET_PROTOCOL);
//Remove the protocol
DomainTestUtils.executeForResult(Util.createRemoveOperation(targetProtocolAddress),
primaryUtil.getDomainClient());
//Reload the primary into admin-only and re-add the protocol
reloadPrimary(primaryUtil, true);
ModelNode add = Util.createAddOperation(targetProtocolAddress, index);
DomainTestUtils.executeForResult(add, primaryUtil.getDomainClient());
//Reload the primary into normal mode and check the protocol is in the right place on the secondary
reloadPrimary(primaryUtil, false);
ModelNode secondaryStack = readResource(secondaryUtil.getDomainClient(), stackAddress);
Assert.assertEquals(originalPrimaryStack, secondaryStack);
//Check that :read-operation-description has add-index defined; WFLY-6782
ModelNode rodOp = Util.createOperation(READ_OPERATION_DESCRIPTION_OPERATION, targetProtocolAddress);
rodOp.get(NAME).set(ADD);
ModelNode result = DomainTestUtils.executeForResult(rodOp, primaryUtil.getDomainClient());
Assert.assertTrue(result.get(REQUEST_PROPERTIES).hasDefined(ADD_INDEX));
}
}
private static ModelNode readResource(DomainClient client, PathAddress pathAddress) throws IOException, MgmtOperationException {
ModelNode rr = Util.createEmptyOperation(READ_RESOURCE_OPERATION, pathAddress);
ModelNode result = DomainTestUtils.executeForResult(rr, client);
result.protect();
return result;
}
private static void reloadPrimary(DomainLifecycleUtil primaryUtil, boolean adminOnly) throws Exception{
ModelNode restartAdminOnly = Util.createEmptyOperation(RELOAD, PathAddress.pathAddress(HOST, PRIMARY_HOST_NAME));
restartAdminOnly.get(ADMIN_ONLY).set(adminOnly);
primaryUtil.executeAwaitConnectionClosed(restartAdminOnly);
primaryUtil.connect();
primaryUtil.awaitHostController(System.currentTimeMillis());
if (!adminOnly) {
//Wait for the secondary to reconnect, look for the secondary in the list of hosts
long end = System.currentTimeMillis() + 20 * ADJUSTED_SECOND;
boolean reconnected = false;
do {
Thread.sleep(ADJUSTED_SECOND);
reconnected = checkSecondaryReconnected(primaryUtil.getDomainClient());
} while (!reconnected && System.currentTimeMillis() < end);
}
}
private static boolean checkSecondaryReconnected(DomainClient primaryClient) throws Exception {
ModelNode op = Util.createEmptyOperation(READ_CHILDREN_NAMES_OPERATION, PathAddress.EMPTY_ADDRESS);
op.get(CHILD_TYPE).set(HOST);
try {
ModelNode ret = DomainTestUtils.executeForResult(op, primaryClient);
List<ModelNode> list = ret.asList();
if (list.size() == 2) {
for (ModelNode entry : list) {
if (SECONDARY_HOST_NAME.equals(entry.asString())){
return true;
}
}
}
} catch (Exception e) {
}
return false;
}
}
| 7,782 | 48.259494 | 182 |
java
|
null |
wildfly-main/testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/HostExcludesTestCase.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.domain;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILD_TYPE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXCLUDED_EXTENSIONS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST_EXCLUDE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_RESOURCES_OPERATION;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import org.jboss.as.controller.client.helpers.domain.DomainClient;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil;
import org.jboss.as.test.integration.domain.management.util.DomainTestUtils;
import org.jboss.as.test.integration.domain.management.util.WildFlyManagedConfiguration;
import org.jboss.as.test.integration.management.util.MgmtOperationException;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.logging.Logger;
import org.jboss.modules.LocalModuleLoader;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleLoadException;
import org.jboss.modules.Resource;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* This test verifies it is possible to get the list of previous release extensions using the host-excludes definition
* included in the current domain.xml.
* <p>
* The test fails if it finds a missing extension in the excluded-extensions section, there is a host-exclude name
* in domain.xml undefined in this test or we are excluding more extensions than the necessary.
* <p>
* It also maintains the configuration of the current release, see ExtensionConf.CURRENT. When an extension is added or
* removed on the current release, that extension must be tracked down on the ExtensionConf.CURRENT object. Once the
* current release moves to the next mayor, if the ExtensionConf.CURRENT has extensions added or removed during the
* current development cycle, the test will fail, forcing us to create new ExtensionConf objects for each previous
* releases not defined in the test and point out ExtensionConf.CURRENT to the new current release without any
* additional / removed extensions.
*
* @author Yeray Borges
*/
public class HostExcludesTestCase extends BuildConfigurationTestBase {
private static DomainLifecycleUtil primaryUtils;
private static DomainClient primaryClient;
private static WildFlyManagedConfiguration primaryConfig;
private static final BiFunction<Set<String>, Set<String>, Set<String>> diff = (a, b) -> a.stream().filter(e -> !b.contains(e)).collect(Collectors.toSet());
private final boolean isFullDistribution = AssumeTestGroupUtil.isFullDistribution();
private final boolean isPreviewGalleonPack = AssumeTestGroupUtil.isWildFlyPreview();
private static final String MAJOR = "29.";
/**
* Maintains the list of expected extensions for each host-exclude name for previous releases.
* Each enum entry represents the list of extensions that are available on the excluded host.
* It assumes that the hosts builds are always full builds, including the MP extensions if they exist.
* This must be corrected on each new host-exclude id added on the current release.
*/
private enum ExtensionConf {
WILDFLY_10_0("WildFly10.0", null, Arrays.asList(
"org.jboss.as.appclient",
"org.jboss.as.clustering.infinispan",
"org.jboss.as.clustering.jgroups",
"org.jboss.as.cmp",
"org.jboss.as.configadmin",
"org.jboss.as.connector",
"org.jboss.as.deployment-scanner",
"org.jboss.as.ee",
"org.jboss.as.ejb3",
"org.jboss.as.jacorb",
"org.jboss.as.jaxrs",
"org.jboss.as.jaxr",
"org.jboss.as.jdr",
"org.jboss.as.jmx",
"org.jboss.as.jpa",
"org.jboss.as.jsf",
"org.jboss.as.jsr77",
"org.jboss.as.logging",
"org.jboss.as.mail",
"org.jboss.as.messaging",
"org.jboss.as.modcluster",
"org.jboss.as.naming",
"org.jboss.as.pojo",
"org.jboss.as.remoting",
"org.jboss.as.sar",
"org.jboss.as.security",
"org.jboss.as.threads",
"org.jboss.as.transactions",
"org.jboss.as.web",
"org.jboss.as.webservices",
"org.jboss.as.weld",
"org.jboss.as.xts",
"org.keycloak.keycloak-adapter-subsystem",
"org.wildfly.extension.batch.jberet",
"org.wildfly.extension.bean-validation",
"org.wildfly.extension.clustering.singleton",
"org.wildfly.extension.io",
"org.wildfly.extension.messaging-activemq",
"org.wildfly.extension.mod_cluster",
"org.wildfly.extension.picketlink",
"org.wildfly.extension.request-controller",
"org.wildfly.extension.rts",
"org.wildfly.extension.security.manager",
"org.wildfly.extension.undertow",
"org.wildfly.iiop-openjdk"
), false),
WILDFLY_10_1("WildFly10.1", WILDFLY_10_0, false),
WILDFLY_11_0("WildFly11.0", WILDFLY_10_1, Arrays.asList(
"org.wildfly.extension.core-management",
"org.wildfly.extension.discovery",
"org.wildfly.extension.elytron"
), false),
WILDFLY_12_0("WildFly12.0", WILDFLY_11_0, false),
WILDFLY_13_0("WildFly13.0", WILDFLY_12_0, List.of(
"org.wildfly.extension.ee-security"
), false),
WILDFLY_14_0("WildFly14.0", WILDFLY_13_0, Arrays.asList(
"org.wildfly.extension.datasources-agroal",
"org.wildfly.extension.microprofile.config-smallrye",
"org.wildfly.extension.microprofile.health-smallrye",
"org.wildfly.extension.microprofile.opentracing-smallrye"
), false),
WILDFLY_15_0("WildFly15.0", WILDFLY_14_0, List.of(
"org.wildfly.extension.microprofile.metrics-smallrye"
), false),
WILDFLY_16_0("WildFly16.0", WILDFLY_15_0, List.of(
// This extension was added in WF17, however we add it here because WF16/WF17/WF18 use the same management
// kernel API, which is 10.0.0. Adding a host-exclusion for this extension on WF16 could affect to WF17/WF18
// We decided to add the host-exclusion only for WF15 and below. It means potentially a DC running on WF17
// with an WF16 as secondary will not exclude this extension. It is not a problem at all since mixed domains in
// WildFly is not supported.
"org.wildfly.extension.clustering.web"
), false),
WILDFLY_17_0("WildFly17.0", WILDFLY_16_0, false),
WILDFLY_18_0("WildFly18.0", WILDFLY_17_0, false),
WILDFLY_19_0("WildFly19.0", WILDFLY_18_0, Arrays.asList(
"org.wildfly.extension.microprofile.fault-tolerance-smallrye",
"org.wildfly.extension.microprofile.jwt-smallrye",
"org.wildfly.extension.microprofile.openapi-smallrye"
), false),
WILDFLY_20_0("WildFly20.0", WILDFLY_19_0, false),
WILDFLY_21_0("WildFly21.0", WILDFLY_20_0, false),
WILDFLY_22_0("WildFly22.0", WILDFLY_21_0, Arrays.asList(
"org.wildfly.extension.health",
"org.wildfly.extension.metrics"
), false),
WILDFLY_23_0("WildFly23.0", WILDFLY_22_0, Arrays.asList(
"org.wildfly.extension.microprofile.reactive-messaging-smallrye",
"org.wildfly.extension.microprofile.reactive-streams-operators-smallrye"
), false),
WILDFLY_24_0("WildFly24.0", WILDFLY_23_0, true),
WILDFLY_25_0("WildFly25.0", WILDFLY_24_0, Arrays.asList(
"org.wildfly.extension.elytron-oidc-client",
"org.wildfly.extension.opentelemetry"
), true),
WILDFLY_26_0("WildFly26.0", WILDFLY_25_0, null, Arrays.asList(
"org.jboss.as.cmp",
"org.jboss.as.jaxr",
"org.jboss.as.configadmin"
), true),
WILDFLY_27_0("WildFly27.0", WILDFLY_26_0, Arrays.asList(
"org.wildfly.extension.clustering.ejb",
"org.wildfly.extension.datasources-agroal"
), true),
WILDFLY_28_0("WildFly28.0", WILDFLY_27_0, Arrays.asList(
"org.wildfly.extension.micrometer",
"org.wildfly.extension.microprofile.lra-coordinator",
"org.wildfly.extension.microprofile.lra-participant",
"org.wildfly.extension.microprofile.telemetry"
), true),
CURRENT(MAJOR, WILDFLY_28_0, getCurrentAddedExtensions(), getCurrentRemovedExtensions(), true);
private static List<String> getCurrentAddedExtensions() {
// If an extension is added to this list, also check if it is supplied only by wildfly-galleon-pack. If so, add it also
// to the internal mpExtensions Set defined on this class.
// Don't add here extensions supplied only by the wildfly-preview-feature-pack because we are not tracking different releases
// of wildfly preview. In such a case, add them to previewExtensions set defined below.
return Collections.emptyList();
}
private static List<String> getCurrentRemovedExtensions() {
// TODO If we decide to remove these modules from WFP, uncomment this.
// See https://issues.redhat.com/browse/WFLY-16686
/*
if (AssumeTestGroupUtil.isWildFlyPreview()) {
return Arrays.asList(
"org.jboss.as.jsr77",
"org.wildfly.extension.picketlink",
"org.jboss.as.security"
);
}
*/
return Arrays.asList("org.jboss.as.jacorb", "org.jboss.as.messaging", "org.jboss.as.web");
}
private final String name;
private final Set<String> extensions = new HashSet<>();
private final Set<String> removed = new HashSet<>();
private static final Map<String, ExtensionConf> MAP;
private final boolean modified;
private final boolean supported;
// List of extensions added by the wildfly-galleon-pack
private final Set<String> mpExtensions = new HashSet<>(Arrays.asList(
"org.wildfly.extension.micrometer",
"org.wildfly.extension.microprofile.config-smallrye",
"org.wildfly.extension.microprofile.health-smallrye",
"org.wildfly.extension.microprofile.metrics-smallrye",
"org.wildfly.extension.microprofile.fault-tolerance-smallrye",
"org.wildfly.extension.microprofile.jwt-smallrye",
"org.wildfly.extension.microprofile.openapi-smallrye",
"org.wildfly.extension.microprofile.reactive-messaging-smallrye",
"org.wildfly.extension.microprofile.reactive-streams-operators-smallrye",
"org.wildfly.extension.microprofile.lra-coordinator",
"org.wildfly.extension.microprofile.lra-participant",
"org.wildfly.extension.microprofile.telemetry"
));
// List of extensions added only by the WildFly Preview
// We do not track changes between different versions of WildFly Preview.
// From the point of view of this test, all extensions added in WildFly Preview are always extensions
// added in the latest release of WildFly Preview. It is out of the scope of Host Exclusion test
// to compute on which WildFly Preview was added such a new extension and track the Host Exclusions between
// different WildFly Preview releases.
private final Set<String> previewExtensions = new HashSet<>(Arrays.asList(
));
ExtensionConf(String name, ExtensionConf parent, boolean supported) {
this(name, parent, null, null, supported);
}
ExtensionConf(String name, ExtensionConf parent, List<String> addedExtensions, boolean supported) {
this(name, parent, addedExtensions, null, supported);
}
/**
* Main constructor
* @param name Host exclude name to define
* @param parent A parent extension definition
* @param addedExtensions Extensions added on the server release referred by this host exclude name
* @param removedExtensions Extensions removed on the server release referred by this host exclude name
* @param supported whether the given release is supported as a secondary host in a mixed domain
*/
ExtensionConf(String name, ExtensionConf parent, List<String> addedExtensions, List<String> removedExtensions, boolean supported) {
this.name = name;
this.modified = (addedExtensions != null && !addedExtensions.isEmpty()) || (removedExtensions != null && !removedExtensions.isEmpty());
if (addedExtensions != null) {
this.extensions.addAll(addedExtensions);
}
if (parent != null) {
this.extensions.addAll(parent.extensions);
this.removed.addAll(parent.removed);
}
if (removedExtensions != null) {
this.extensions.removeAll(removedExtensions);
this.removed.addAll(removedExtensions);
}
this.supported = supported;
}
static {
final Map<String, ExtensionConf> map = new HashMap<>();
for (ExtensionConf element : values()) {
final String name = element.name;
if (name != null) map.put(name, element);
}
MAP = map;
}
public static ExtensionConf forName(String name) {
return MAP.get(name);
}
public Set<String> getRemovedExtensions() {
return removed;
}
public Set<String> getExtensions(boolean isFullDistribution, boolean isPreview) {
if (this.name.equals(MAJOR) && isPreview) {
this.extensions.addAll(previewExtensions);
}
if (!isFullDistribution && !isPreview) {
return diff.apply(extensions, mpExtensions);
}
return extensions;
}
public boolean isModified() {
return modified;
}
public boolean isSupported() {
return supported;
}
public String getName() {
return name;
}
}
@BeforeClass
public static void setUp() throws IOException {
primaryConfig = createConfiguration("domain.xml", "host-primary.xml", HostExcludesTestCase.class.getSimpleName());
primaryUtils = new DomainLifecycleUtil(primaryConfig);
primaryUtils.start();
primaryClient = primaryUtils.getDomainClient();
}
@AfterClass
public static void tearDown() {
if (primaryUtils != null) {
primaryUtils.stop();
}
}
@Test
public void testHostExcludes() throws IOException, MgmtOperationException {
Set<String> availableExtensions = retrieveAvailableExtensions();
ModelNode op = Util.getEmptyOperation(READ_CHILDREN_RESOURCES_OPERATION, null);
op.get(CHILD_TYPE).set(EXTENSION);
ModelNode result = DomainTestUtils.executeForResult(op, primaryClient);
Set<String> currentExtensions = new HashSet<>();
for (Property prop : result.asPropertyList()) {
currentExtensions.add(prop.getName());
}
//Check we are able to retrieve at minimum all the extensions defined for the current server
if (!availableExtensions.containsAll(currentExtensions)) {
currentExtensions.removeAll(availableExtensions);
fail(String.format("The following extensions defined in domain.xml cannot be retrieved by this test %s . " +
"It could lead in a false negative test result, check HostExcludesTestCase.retrieveAvailableExtensions method", currentExtensions));
}
// Check that the list of all available extensions is in the ExtensionConf.CURRENT configuration
Set<String> current = ExtensionConf.forName(MAJOR).getExtensions(isFullDistribution, isPreviewGalleonPack);
if (!current.equals(availableExtensions)) {
Set<String> extensionsAdded = diff.apply(current, availableExtensions);
Set<String> extensionsRemoved = diff.apply(availableExtensions, current);
fail(String.format("The following extensions %s have been removed on the current release. Remove them on ExtensionConf.CURRENT object defined in this test. " +
"The following extensions %s have been added on the current release. Add them to ExtensionConf.CURRENT object defined in this test.", extensionsAdded, extensionsRemoved));
}
// If the ExtensionConf.CURRENT has extensions removed / added and the version it represents no longer
// points out to the actual, then we need to create new ExtensionConf(s) for each of the previous releases
// not included in this test.
if (ExtensionConf.CURRENT.isModified()) {
op = Util.getReadAttributeOperation(null, "product-version");
result = DomainTestUtils.executeForResult(op, primaryClient);
if (!result.asString().startsWith(ExtensionConf.CURRENT.getName())) {
fail(String.format("The ExtensionConf.CURRENT has extensions added or removed but it no longer points to the current release. " +
"Modify this test adding new ExtensionConf enums for each previous releases undefined in this test by using the list of extensions added or removed on ExtensionConf.CURRENT." +
"Then remove all the extensions from ExtensionConf.CURRENT enum and correct the MAJOR number accordingly to point out to the current release."));
}
}
op = Util.getEmptyOperation(READ_CHILDREN_RESOURCES_OPERATION, null);
op.get(CHILD_TYPE).set(HOST_EXCLUDE);
result = DomainTestUtils.executeForResult(op, primaryClient);
Set<String> processedExclusionsIds = new HashSet<>();
for (Property prop : result.asPropertyList()) {
String name = prop.getName();
List<String> excludedExtensions = prop.getValue().get(EXCLUDED_EXTENSIONS)
.asListOrEmpty()
.stream()
.map(p -> p.asString())
.collect(Collectors.toList());
//check duplicated extensions
Assert.assertTrue(String.format (
"There are duplicated extensions declared for %s host-exclude", name),
excludedExtensions.size() == new HashSet<>(excludedExtensions).size()
);
//check we have defined the current host-exclude configuration in the test
ExtensionConf confPrevRelease = ExtensionConf.forName(name);
Assert.assertNotNull(String.format(
"This host-exclude name is not defined in this test: %s", name),
confPrevRelease);
//check that available extensions - excluded extensions = expected extensions in a previous release - removed
Set<String> expectedExtensions = ExtensionConf.forName(name).getExtensions(isFullDistribution, isPreviewGalleonPack);
expectedExtensions.removeAll(ExtensionConf.forName(MAJOR).getRemovedExtensions());
Set<String> extensionsUnderTest = new HashSet<>(availableExtensions);
extensionsUnderTest.removeAll(excludedExtensions);
if (expectedExtensions.size() > extensionsUnderTest.size()) {
expectedExtensions.removeAll(extensionsUnderTest);
fail(String.format("These extensions are expected to be available after applying the %s host-exclude configuration to the extensions supplied by this server release: %s", name, expectedExtensions));
}
if ( extensionsUnderTest.size() != expectedExtensions.size() ){
extensionsUnderTest.removeAll(expectedExtensions);
fail(String.format("These extensions are missing on the %s host-exclude: %s", name, extensionsUnderTest));
}
processedExclusionsIds.add(name);
}
// Verifies all the exclusions Id added as configurations for this test are defined as host exclusions in the current server release
for(ExtensionConf extensionConf : ExtensionConf.values()) {
if (extensionConf != ExtensionConf.CURRENT && extensionConf.isSupported() && !processedExclusionsIds.contains(extensionConf.getName())) {
Set<String> extensions = extensionConf.getExtensions(isFullDistribution, isPreviewGalleonPack);
extensions.removeAll(ExtensionConf.forName(MAJOR).getRemovedExtensions());
if (!extensions.equals(availableExtensions)) {
fail(String.format("The %s exclusion id is not defined as host exclusion for the current release.", extensionConf.getName()));
}
}
}
}
/**
* Retrieve the list of all modules which export locally a resource that implements org.jboss.as.controller.Extension.
* This list is considered the list of all available extensions that can be added to a server.
*
* It is assumed that the module which is added as an extension has the org.jboss.as.controller.Extension service as
* a local resource.
*/
private Set<String> retrieveAvailableExtensions() throws IOException {
final Set<String> result = new HashSet<>();
LocalModuleLoader ml = new LocalModuleLoader(getModuleRoots());
Iterator<String> moduleNames = ml.iterateModules((String) null, true);
while (moduleNames.hasNext()) {
String moduleName = moduleNames.next();
Module module;
try {
module = ml.loadModule(moduleName);
List<Resource> resources = module.getClassLoader().loadResourceLocal("META-INF/services/org.jboss.as.controller.Extension");
if (!resources.isEmpty()) {
result.add(moduleName);
}
} catch (ModuleLoadException e) {
Logger.getLogger(HostExcludesTestCase.class).warn("Failed to load module " + moduleName +
" to check if it is an extension", e);
}
}
return result;
}
private static File[] getModuleRoots() throws IOException {
Path layersRoot = Paths.get(primaryConfig.getModulePath()) .resolve("system").resolve("layers");
DirectoryStream.Filter<Path> filter = entry -> {
File f = entry.toFile();
return f.isDirectory() && !f.isHidden();
};
List<File> result = new ArrayList<>();
for (Path path : Files.newDirectoryStream(layersRoot, filter)) {
result.add(path.toFile());
}
return result.toArray(new File[0]);
}
}
| 25,345 | 49.692 | 214 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.