repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/lifecycle/servlet/LifecycleCallbackBinding.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ee.lifecycle.servlet; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.interceptor.InterceptorBinding; @Target({ TYPE }) @Retention(RUNTIME) @Documented @InterceptorBinding public @interface LifecycleCallbackBinding { }
1,479
36.948718
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/lifecycle/servlet/RemoteListener.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.ee.lifecycle.servlet; import jakarta.servlet.ServletRequestEvent; import jakarta.servlet.ServletRequestListener; import jakarta.servlet.annotation.WebListener; @LifecycleCallbackBinding @WebListener public class RemoteListener implements ServletRequestListener { @Override public void requestDestroyed(ServletRequestEvent sre) { } @Override public void requestInitialized(ServletRequestEvent sre) { } }
1,492
36.325
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/lifecycle/servlet/InfoServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ee.lifecycle.servlet; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @SuppressWarnings("serial") @WebServlet(urlPatterns = "/InfoServlet") public class InfoServlet extends HttpServlet { // sign whether LifecycleCallbackInterceptor's @PreDestroy method intercepting RemoteServlet was invoked private volatile int preDestroyInvocations; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String event = request.getParameter("event"); if ("preDestroyNotify".equals(event)) { preDestroyInvocations++; } else if ("preDestroyVerify".equals(event)) { response.getWriter().append("" + preDestroyInvocations); } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } }
2,117
38.962264
121
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/lifecycle/servlet/ListenerLifecycleCallbackInterceptionTestCase.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.ee.lifecycle.servlet; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.URL; import java.net.URLEncoder; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author Matus Abaffy */ @RunAsClient @RunWith(Arquillian.class) public class ListenerLifecycleCallbackInterceptionTestCase extends LifecycleInterceptionTestCase { @Deployment(name = REMOTE, managed = false, testable = false) public static WebArchive createRemoteTestArchive() { return createRemoteTestArchiveBase().addClasses(RemoteListener.class, RemoteListenerServlet.class); } @Deployment(testable = false) public static WebArchive createMainTestArchive() { return createMainTestArchiveBase(); } /** * This is not a real test method. */ @Test @InSequence(1) public void deployRemoteArchive() { // In order to use @ArquillianResource URL from the unmanaged deployment we need to deploy the test archive first deployer.deploy(REMOTE); } @Test @InSequence(2) public void testListenerPostConstructInterception( @ArquillianResource @OperateOnDeployment(REMOTE) URL remoteContextPath) throws IOException, ExecutionException, TimeoutException { assertEquals("PostConstruct interceptor method not invoked for listener", "1", doGetRequest(remoteContextPath + "/RemoteListenerServlet?event=postConstructVerify")); } @Test @InSequence(3) public void testListenerPreDestroyInterception( @ArquillianResource(InitServlet.class) @OperateOnDeployment(REMOTE) URL remoteContextPath) throws IOException, ExecutionException, TimeoutException { // set the context in InfoClient so that it can send request to InfoServlet doGetRequest(remoteContextPath + "/InitServlet?url=" + URLEncoder.encode(infoContextPath.toExternalForm(), "UTF-8")); deployer.undeploy(REMOTE); assertEquals("PreDestroy interceptor method not invoked for listener", "1", doGetRequest(infoContextPath + "/InfoServlet?event=preDestroyVerify")); } }
3,699
38.784946
125
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/lifecycle/servlet/ServletLifecycleCallbackInterceptionTestCase.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.ee.lifecycle.servlet; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.URL; import java.net.URLEncoder; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author Matus Abaffy */ @RunAsClient @RunWith(Arquillian.class) public class ServletLifecycleCallbackInterceptionTestCase extends LifecycleInterceptionTestCase { @Deployment(name = REMOTE, managed = false, testable = false) public static WebArchive createRemoteTestArchive() { return createRemoteTestArchiveBase().addClass(RemoteServlet.class); } @Deployment(testable = false) public static WebArchive createMainTestArchive() { return createMainTestArchiveBase(); } /** * This is not a real test method. */ @Test @InSequence(1) public void deployRemoteArchive() { // In order to use @ArquillianResource URL from the unmanaged deployment we need to deploy the test archive first deployer.deploy(REMOTE); } @Test @InSequence(2) public void testServletPostConstructInterception( @ArquillianResource @OperateOnDeployment(REMOTE) URL remoteContextPath) throws IOException, ExecutionException, TimeoutException { assertEquals("PostConstruct interceptor method not invoked for servlet", "1", doGetRequest(remoteContextPath + "/RemoteServlet?event=postConstructVerify")); } @Test @InSequence(3) public void testServletPreDestroyInterception( @ArquillianResource @OperateOnDeployment(REMOTE) URL remoteContextPath) throws IOException, ExecutionException, TimeoutException { // set the context in InfoClient so that it can send request to InfoServlet doGetRequest(remoteContextPath + "/InitServlet?url=" + URLEncoder.encode(infoContextPath.toExternalForm(), "UTF-8")); deployer.undeploy(REMOTE); assertEquals("PreDestroy interceptor method not invoked for servlet", "1", doGetRequest(infoContextPath + "/InfoServlet?event=preDestroyVerify")); } }
3,635
38.096774
125
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/lifecycle/servlet/InitServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ee.lifecycle.servlet; import java.io.IOException; import java.net.URLDecoder; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @SuppressWarnings("serial") @WebServlet(urlPatterns = "/InitServlet") public class InitServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = request.getParameter("url"); if (url != null) { InfoClient.setInfoContext(URLDecoder.decode(url, "UTF-8")); } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } }
1,873
37.244898
121
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/lifecycle/servlet/RemoteListenerServlet.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.ee.lifecycle.servlet; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @SuppressWarnings("serial") @WebServlet("/RemoteListenerServlet") public class RemoteListenerServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String event = req.getParameter("event"); resp.setContentType("text/plain"); if ("postConstructVerify".equals(event)) { resp.setContentType("text/plain"); resp.getWriter().append("" + LifecycleCallbackInterceptor.getPostConstructIncations()); } else { resp.setStatus(404); } } }
1,952
38.06
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/lifecycle/servlet/LifecycleCallbackInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ee.lifecycle.servlet; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.annotation.Priority; import jakarta.interceptor.Interceptor; import jakarta.interceptor.InvocationContext; @Interceptor @LifecycleCallbackBinding @Priority(Interceptor.Priority.APPLICATION) public class LifecycleCallbackInterceptor { private static volatile int postConstructInvocations = 0; @PostConstruct public Object postConstruct(InvocationContext ctx) throws Exception { postConstructInvocations++; return ctx.proceed(); } @PreDestroy public Object preDestroy(InvocationContext ctx) throws Exception { InfoClient.notify("preDestroyNotify"); return ctx.proceed(); } public static int getPostConstructIncations() { return postConstructInvocations; } }
1,915
35.150943
73
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/lifecycle/servlet/LifecycleInterceptionTestCase.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.ee.lifecycle.servlet; import java.io.IOException; import java.net.SocketPermission; import java.net.URL; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; /** * @author Matus Abaffy */ public abstract class LifecycleInterceptionTestCase { protected static final String REMOTE = "remote"; private static final String BEANS_XML = "beans.xml"; protected static WebArchive createRemoteTestArchiveBase() { return ShrinkWrap.create(WebArchive.class, "remote.war") .addClasses(LifecycleCallbackBinding.class, LifecycleCallbackInterceptor.class, InfoClient.class, InitServlet.class) .addAsWebInfResource(EmptyAsset.INSTANCE, BEANS_XML) // InfoClient requires SocketPermission .addAsManifestResource( createPermissionsXmlAsset(new SocketPermission(TestSuiteEnvironment.getServerAddress() + ":" + TestSuiteEnvironment.getHttpPort(), "connect,resolve")), "permissions.xml"); } protected static WebArchive createMainTestArchiveBase() { return ShrinkWrap.create(WebArchive.class, "main.war") .addClass(InfoServlet.class) .addAsWebInfResource(EmptyAsset.INSTANCE, BEANS_XML); } @ArquillianResource Deployer deployer; @ArquillianResource//(InfoServlet.class) URL infoContextPath; protected String doGetRequest(String path) throws IOException, ExecutionException, TimeoutException { return HttpRequest.get(path, 10, TimeUnit.SECONDS); } }
3,194
40.493506
175
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/lifecycle/servlet/InfoClient.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.ee.lifecycle.servlet; import java.net.URL; import java.net.URLConnection; public final class InfoClient { private static String infoContext = null; public static void setInfoContext(String infoContext) { InfoClient.infoContext = infoContext; } public static void notify(String event) { try { URLConnection connection = new URL(infoContext + "InfoServlet" + "?event=" + event).openConnection(); connection.getInputStream().close(); } catch (Exception e) { throw new RuntimeException(e); } } }
1,646
36.431818
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/lifecycle/servlet/RemoteServlet.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.ee.lifecycle.servlet; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @SuppressWarnings("serial") @LifecycleCallbackBinding @WebServlet("/RemoteServlet") public class RemoteServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String event = req.getParameter("event"); if ("postConstructVerify".equals(event)) { resp.setContentType("text/plain"); resp.getWriter().append("" + LifecycleCallbackInterceptor.getPostConstructIncations()); } else { resp.setStatus(404); } } }
1,919
37.4
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/altdd/AltDDEjb.java
package org.jboss.as.test.integration.ee.altdd; import jakarta.ejb.Stateless; /** * @author Stuart Douglas */ @Stateless public class AltDDEjb { private String value; public String getValue() { return value; } }
239
12.333333
47
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/altdd/AltDDTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ee.altdd; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests that the alt-dd element of application.xml is respected */ @RunWith(Arquillian.class) public class AltDDTestCase { @Deployment public static Archive<?> deployment() { final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "altdd.ear"); ear.addAsManifestResource(AltDDTestCase.class.getPackage(), "application.xml", "application.xml"); ear.addAsResource(AltDDTestCase.class.getPackage(), "alt-ejb-jar.xml", "alt-ejb-jar.xml"); final JavaArchive ejbs = ShrinkWrap.create(JavaArchive.class,"ejb.jar"); ejbs.addClasses(AltDDTestCase.class, AltDDEjb.class); ejbs.addAsManifestResource(AltDDTestCase.class.getPackage(), "ejb-jar.xml", "ejb-jar.xml"); ear.addAsModule(ejbs); return ear; } @Test public void testAlternateDeploymentDescriptor() throws NamingException { final AltDDEjb bean = (AltDDEjb) new InitialContext().lookup("java:module/" + AltDDEjb.class.getSimpleName()); Assert.assertEquals("alternate", bean.getValue()); } }
2,596
40.222222
118
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/initializeinorder/MyServlet.java
package org.jboss.as.test.integration.ee.initializeinorder; import java.io.IOException; import jakarta.annotation.PostConstruct; import jakarta.servlet.Servlet; import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.annotation.WebServlet; /** * @author Stuart Douglas */ @WebServlet(name = "MyServlet", urlPatterns = {"/test"}, loadOnStartup = 1) public class MyServlet implements Servlet { @PostConstruct public void postConstruct() { //we wait a second, to make sure that the EJB is actually waiting for us to start, and it is not just //the normal random init order try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } InitializeInOrderTestCase.recordInit(MyServlet.class.getSimpleName()); } @Override public void init(final ServletConfig config) throws ServletException { } @Override public ServletConfig getServletConfig() { return null; } @Override public void service(final ServletRequest req, final ServletResponse res) throws ServletException, IOException { } @Override public String getServletInfo() { return null; } @Override public void destroy() { } }
1,405
24.563636
115
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/initializeinorder/InitializeInOrderTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ee.initializeinorder; import java.util.ArrayList; import java.util.List; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; 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; /** * Tests that <initialize-in-order> works as expected. * * @author Stuart Douglas */ @RunWith(Arquillian.class) public class InitializeInOrderTestCase { private static final List<String> initOrder = new ArrayList<String>(); @Deployment public static Archive<?> deployment() { final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "init.ear"); ear.addAsResource(InitializeInOrderTestCase.class.getPackage(), "application.xml", "application.xml"); final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "ejb.jar"); jar.addClasses(MyEjb.class, InitializeInOrderTestCase.class); ear.addAsModule(jar); final WebArchive war = ShrinkWrap.create(WebArchive.class, "web.war"); war.addClass(MyServlet.class); ear.addAsModule(war); return ear; } @Test public void testPostConstruct() throws NamingException { Assert.assertEquals(2, initOrder.size()); Assert.assertEquals("MyServlet", initOrder.get(0)); Assert.assertEquals("MyEjb", initOrder.get(1)); } public static void recordInit(final String clazz) { initOrder.add(clazz); } }
2,804
35.428571
110
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/initializeinorder/MyEjb.java
package org.jboss.as.test.integration.ee.initializeinorder; import jakarta.annotation.PostConstruct; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; /** * @author Stuart Douglas */ @Singleton @Startup public class MyEjb { @PostConstruct public void postConstruct() { InitializeInOrderTestCase.recordInit(MyEjb.class.getSimpleName()); } }
373
18.684211
74
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/interceptors/exceptions/ExceptionsFromInterceptorsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ee.interceptors.exceptions; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="mailto:[email protected]">Carlo de Wolf</a> */ @RunWith(Arquillian.class) public class ExceptionsFromInterceptorsTestCase { @Deployment public static JavaArchive deployment() { return ShrinkWrap.create(JavaArchive.class, "interceptors-exceptions.jar") .addPackage(ExceptionsFromInterceptorsTestCase.class.getPackage()); } private static <T> T lookup(final String name, final Class<T> cls) throws NamingException { InitialContext ctx = new InitialContext(); try { return cls.cast(ctx.lookup(name)); } finally { ctx.close(); } } @Test public void testUndeclared() throws Exception { try { lookup("java:global/interceptors-exceptions/PitcherBean", PitcherBean.class).fastball(); fail("Should have thrown a (Runtime)Exception"); } catch (Exception e) { assertTrue("Did not declare exception - " + e, e instanceof RuntimeException); } } }
2,551
35.985507
100
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/interceptors/exceptions/PitcherBean.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ee.interceptors.exceptions; import jakarta.ejb.Stateless; import jakarta.interceptor.Interceptors; /** * @author <a href="mailto:[email protected]">Carlo de Wolf</a> */ @Stateless public class PitcherBean { @Interceptors(ThrowingClassCastExceptionInterceptor.class) public void curveball() { // do nothing } @Interceptors(ThrowingUndeclaredExceptionInterceptor.class) public void fastball() { // do nothing } }
1,522
35.261905
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/interceptors/exceptions/ThrowingClassCastExceptionInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ee.interceptors.exceptions; import jakarta.interceptor.AroundInvoke; import jakarta.interceptor.InvocationContext; /** * @author <a href="mailto:[email protected]">Carlo de Wolf</a> */ public class ThrowingClassCastExceptionInterceptor { @AroundInvoke public Object aroundInvoke(final InvocationContext ctx) throws Exception { throw new ClassCastException("test"); } }
1,459
39.555556
78
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/interceptors/exceptions/ThrowingUndeclaredExceptionInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ee.interceptors.exceptions; import jakarta.interceptor.AroundInvoke; import jakarta.interceptor.InvocationContext; /** * @author <a href="mailto:[email protected]">Carlo de Wolf</a> */ public class ThrowingUndeclaredExceptionInterceptor { public static class SurpriseException extends Exception { public SurpriseException(String message) { super(message); } } @AroundInvoke public Object aroundInvoke(InvocationContext ctx) throws Exception { throw new SurpriseException("didn't expect this"); } }
1,625
37.714286
72
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/suspend/EEConcurrencySuspendTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 2110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ee.suspend; 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.READ_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUSPEND_STATE; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.io.IOException; import java.net.HttpURLConnection; import java.net.SocketPermission; import java.net.URL; import java.io.FilePermission; import java.util.PropertyPermission; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.remoting3.security.RemotingPermission; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests for suspend/resume functionality with EE concurrency */ @RunWith(Arquillian.class) public class EEConcurrencySuspendTestCase { protected static Logger log = Logger.getLogger(EEConcurrencySuspendTestCase.class); @ArquillianResource private ManagementClient managementClient; @Deployment public static WebArchive deployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, "ee-suspend.war"); war.addPackage(EEConcurrencySuspendTestCase.class.getPackage()); war.addPackage(HttpRequest.class.getPackage()); war.addClass(TestSuiteEnvironment.class); war.addAsResource(new StringAsset("Dependencies: org.jboss.dmr, org.jboss.as.controller, org.jboss.remoting \n"), "META-INF/MANIFEST.MF"); war.addAsManifestResource(createPermissionsXmlAsset( new RuntimePermission("modifyThread"), new PropertyPermission("management.address", "read"), new PropertyPermission("node0", "read"), new PropertyPermission("jboss.http.port", "read"), new RemotingPermission("createEndpoint"), new RemotingPermission("connect"), new FilePermission(System.getProperty("jboss.inst") + "/standalone/tmp/auth/*", "read"), new SocketPermission(TestSuiteEnvironment.getServerAddress() + ":" + TestSuiteEnvironment.getHttpPort(), "connect,resolve")), "permissions.xml"); return war; } @Test public void testRequestInShutdown() throws Exception { final String address = "http://" + TestSuiteEnvironment.getServerAddress() + ":" + TestSuiteEnvironment.getHttpPort() + "/ee-suspend/ShutdownServlet"; ExecutorService executorService = Executors.newSingleThreadExecutor(); boolean suspended = false; try { Future<Object> result = executorService.submit(new Callable<Object>() { @Override public Object call() throws Exception { return HttpRequest.get(address, 60, TimeUnit.SECONDS); } }); Thread.sleep(1000); //nasty, but we need to make sure the HTTP request has started Assert.assertEquals(ShutdownServlet.TEXT, result.get()); ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.OP).set("suspend"); execute(managementClient.getControllerClient(), op); op = new ModelNode(); op.get(OP).set(READ_ATTRIBUTE_OPERATION); op.get(NAME).set(SUSPEND_STATE); waitUntilSuspendStateResult(op, "SUSPENDING"); ShutdownServlet.requestLatch.countDown(); op = new ModelNode(); op.get(OP).set(READ_ATTRIBUTE_OPERATION); op.get(NAME).set(SUSPEND_STATE); waitUntilSuspendStateResult(op, "SUSPENDED"); //server is now suspended,check we get 503 http status code final HttpURLConnection conn = (HttpURLConnection) new URL(address).openConnection(); try { conn.setDoInput(true); int responseCode = conn.getResponseCode(); Assert.assertEquals(503, responseCode); } finally { conn.disconnect(); } suspended = true; } finally { ShutdownServlet.requestLatch.countDown(); executorService.shutdown(); if (suspended){ //if suspended, test if it is resumed ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.OP).set("resume"); execute(managementClient.getControllerClient(), op); op = new ModelNode(); op.get(OP).set(READ_ATTRIBUTE_OPERATION); op.get(NAME).set(SUSPEND_STATE); Assert.assertEquals("server-state is not <RUNNING> after resume operation. ", "RUNNING", executeForStringResult(managementClient.getControllerClient(), op)); } } } private void waitUntilSuspendStateResult(ModelNode op, String expectedResult) throws IOException, InterruptedException { final long deadline = System.currentTimeMillis() + 4000; while (true) { String result = executeForStringResult(managementClient.getControllerClient(), op); if (result.equals(expectedResult)) { break; } if (System.currentTimeMillis() > deadline) { Assert.fail("Server suspend-state is not in " + expectedResult + " after " + deadline + " milliseconds."); } TimeUnit.MILLISECONDS.sleep(500); } } static ModelNode execute(final ModelControllerClient client, final ModelNode op) throws IOException { ModelNode result = client.execute(op); if (!Operations.isSuccessfulOutcome(result)) { Assert.fail(Operations.getFailureDescription(result).asString()); } return result; } static String executeForStringResult(final ModelControllerClient client, final ModelNode op) throws IOException { return execute(client,op).get(RESULT).asString(); } }
8,135
42.508021
173
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ee/suspend/ShutdownServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 2110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.ee.suspend; import java.io.IOException; import java.util.concurrent.CountDownLatch; import jakarta.annotation.Resource; import jakarta.enterprise.concurrent.ManagedExecutorService; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @WebServlet(name = "ShutdownServlet", urlPatterns = { "/ShutdownServlet" }) public class ShutdownServlet extends HttpServlet { private static final long serialVersionUID = -5891682551205336273L; public static final CountDownLatch requestLatch = new CountDownLatch(1); public static final String TEXT = "Running Request"; @Resource private ManagedExecutorService executorService; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { executorService.execute(new Runnable() { @Override public void run() { try { requestLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); response.getWriter().write(TEXT); response.getWriter().close(); } }
2,397
37.677419
121
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/json/JSONPServlet.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.json; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonObject; import jakarta.json.stream.JsonCollectors; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; /** * JSON-P 1.1 sample servlet - using JsonCollectors.toJsonArray() * * @author Rostislav Svoboda */ @WebServlet("/json") public class JSONPServlet extends HttpServlet { @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); JsonArray array = this.list. stream(). collect(JsonCollectors.toJsonArray()); PrintWriter out = response.getWriter(); out.print(array); out.flush(); } private List<JsonObject> list; @Override public void init() throws ServletException { this.list = Arrays.asList(next(), next()); } private JsonObject next() { return Json.createObjectBuilder(). add("number", System.currentTimeMillis()). build(); } }
2,452
33.549296
133
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/json/JSONPTestCase.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.json; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonReader; import java.io.StringReader; import java.net.URL; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; /** * JSON-P 1.1 smoke test * * @author Rostislav Svoboda */ @RunWith(Arquillian.class) @RunAsClient public class JSONPTestCase { @ArquillianResource private URL url; @Deployment(testable = false) public static Archive<?> deploy() { return ShrinkWrap.create(WebArchive.class, "jsonp11-test.war").addClasses(JSONPServlet.class); } @Test public void testJsonServlet() throws Exception { final String result = HttpRequest.get(url + "json", 5, TimeUnit.SECONDS); JsonReader jsonReader = Json.createReader(new StringReader(result)); JsonArray array = jsonReader.readArray(); jsonReader.close(); assertEquals(2, array.size()); } }
2,477
32.945205
102
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/json/JsonTestCase.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.json; import java.io.StringReader; import java.net.URL; import java.util.concurrent.TimeUnit; import jakarta.json.Json; import jakarta.json.stream.JsonParser; import jakarta.json.stream.JsonParser.Event; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunWith(Arquillian.class) @RunAsClient public class JsonTestCase { @Deployment(testable = false) public static Archive<?> deploy() { return ShrinkWrap.create(WebArchive.class, "jsonp-test.war") .addClasses(JsonTestCase.class, JsonServlet.class); } @ArquillianResource private URL url; @Test public void testJsonServlet() throws Exception { final String result = HttpRequest.get(url + "json", 10, TimeUnit.SECONDS); final JsonParser parser = Json.createParser(new StringReader(result)); String key = null; String value = null; while (parser.hasNext()) { final Event event = parser.next(); switch (event) { case KEY_NAME: key = parser.getString(); break; case VALUE_STRING: value = parser.getString(); break; } } parser.close(); Assert.assertEquals("Key should be \"name\"", "name", key); Assert.assertEquals("Value should be \"value\"", "value", value); } }
2,977
35.317073
82
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/json/JSONBTestCase.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.json; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import java.net.URL; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; /** * JSON-B 1.0 smoke test * * @author Rostislav Svoboda */ @RunWith(Arquillian.class) @RunAsClient public class JSONBTestCase { @ArquillianResource private URL url; @Deployment(testable = false) public static Archive<?> deploy() { return ShrinkWrap.create(WebArchive.class, "jsonb10-test.war").addClasses(JSONBServlet.class); } @Test public void testJsonbServlet() throws Exception { final String result = HttpRequest.get(url + "jsonb", 5, TimeUnit.SECONDS); assertEquals("{\"name\":\"foo\",\"surname\":\"bar\"}", result); } }
2,238
33.446154
102
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/json/JSONBServlet.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.json; import jakarta.json.bind.JsonbBuilder; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * JSON-B 1.0 sample servlet - using JsonbBuilder * * @author Rostislav Svoboda */ @WebServlet("/jsonb") public class JSONBServlet extends HttpServlet { @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.print(JsonbBuilder.create().toJson(new Person("foo", "bar"))); out.flush(); } public static class Person { public String name; public String surname; public Person(String name, String surname) { this.name = name; this.surname = surname; } } }
2,133
34.566667
133
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/json/JsonServlet.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.json; import java.io.IOException; import jakarta.json.Json; import jakarta.json.stream.JsonGenerator; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @WebServlet("/json") public class JsonServlet extends HttpServlet { @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); final JsonGenerator generator = Json.createGenerator(response.getWriter()); generator.writeStartObject(); generator.write("name", "value"); generator.writeEnd(); generator.close(); } }
1,967
38.36
133
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/NoCdiTestCase.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.batch; import jakarta.batch.operations.JobOperator; import jakarta.batch.runtime.BatchRuntime; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="mailto:[email protected]">Brent Douglas</a> * @since 9.0 */ @RunWith(Arquillian.class) public class NoCdiTestCase extends Assert { @Deployment public static Archive<?> deploy() { return ShrinkWrap.create(JavaArchive.class, NoCdiTestCase.class.getSimpleName() + ".jar") .addClass(NoCdiTestCase.class); } @Test public void testJobOperatorIsAvailable() throws Exception { final JobOperator operator = BatchRuntime.getJobOperator(); assertNotNull(operator); } }
2,039
35.428571
97
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/chunk/ChunkPartitionCollector.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.batch.chunk; import java.io.Serializable; import jakarta.batch.api.partition.PartitionCollector; import jakarta.inject.Named; @Named public final class ChunkPartitionCollector implements PartitionCollector { @Override public Serializable collectPartitionData() throws Exception { return Thread.currentThread().getId(); } }
1,407
38.111111
74
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/chunk/ChunkPartitionTestCase.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.batch.chunk; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.io.FilePermission; import java.net.URL; import java.util.Properties; import java.util.PropertyPermission; import jakarta.batch.operations.JobOperator; import jakarta.batch.operations.NoSuchJobExecutionException; import jakarta.batch.runtime.BatchRuntime; import jakarta.batch.runtime.BatchStatus; import jakarta.batch.runtime.JobExecution; import jakarta.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.batch.common.AbstractBatchTestCase; import org.jboss.as.test.integration.batch.common.CountingItemWriter; import org.jboss.as.test.integration.batch.common.JobExecutionMarshaller; import org.jboss.as.test.integration.batch.common.StartBatchServlet; import org.jboss.remoting3.security.RemotingPermission; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunWith(Arquillian.class) public class ChunkPartitionTestCase extends AbstractBatchTestCase { @ArquillianResource private ManagementClient managementClient; @Inject private CountingItemWriter countingItemWriter; @Deployment public static WebArchive createDeployment() { return createDefaultWar("batch-chunk-partition.war", ChunkPartitionTestCase.class.getPackage(), "chunkPartition.xml", "chunk-suspend.xml") .addPackage(ChunkPartitionTestCase.class.getPackage()) .addClass(Operations.class) .addAsResource(new StringAsset("Dependencies: org.jboss.dmr, org.jboss.as.controller, org.jboss.remoting\n"), "META-INF/MANIFEST.MF") .addAsManifestResource(createPermissionsXmlAsset( new RemotingPermission("createEndpoint"), new RemotingPermission("connect"), new PropertyPermission("ts.timeout.factor", "read"), new FilePermission(System.getProperty("jboss.inst") + "/standalone/tmp/auth/*", "read") ), "permissions.xml"); } @RunAsClient @Test public void chunks(@ArquillianResource final URL url) throws Exception { for (int i = 10; i >= 8; i--) { final UrlBuilder builder = UrlBuilder.of(url, "start"); builder.addParameter(StartBatchServlet.JOB_XML_PARAMETER, "chunkPartition"); builder.addParameter("thread.count", i); builder.addParameter("writer.sleep.time", 100); final String result = performCall(builder.build()); final JobExecution jobExecution = JobExecutionMarshaller.unmarshall(result); Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getBatchStatus()); // final String exitStatus = stepExecution0.getExitStatus(); // Assert.assertTrue(exitStatus.startsWith("PASS")); } final UrlBuilder builder = UrlBuilder.of(url, "start"); builder.addParameter(StartBatchServlet.JOB_XML_PARAMETER, "chunkPartition"); builder.addParameter("thread.count", 1); builder.addParameter("skip.thread.check", "true"); builder.addParameter("writer.sleep.time", 0); final String result = performCall(builder.build()); final JobExecution jobExecution = JobExecutionMarshaller.unmarshall(result); Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getBatchStatus()); } @Test public void testSuspend() throws Exception { try { final Properties jobProperties = new Properties(); jobProperties.setProperty("reader.end", "10"); final JobOperator jobOperator = BatchRuntime.getJobOperator(); // Start the first job long executionId = jobOperator.start("chunk-suspend", jobProperties); JobExecution jobExecution = jobOperator.getJobExecution(executionId); // Wait until the job is complete for a maximum of 5 seconds waitForTermination(jobExecution, 5); Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getBatchStatus()); // Check that count Assert.assertEquals(10, countingItemWriter.getWrittenItemSize()); // Suspend the server managementClient.getControllerClient().execute(Operations.createOperation("suspend")); // Submit another job which should be queued, should be safe with an InMemoryJobRepository (the default) executionId = jobOperator.start("chunk-suspend", jobProperties); // The job should not exist yet as the server is suspended try { jobOperator.getJobExecution(executionId); } catch (NoSuchJobExecutionException expected) { Assert.fail("Job should not exist as the server is suspended: " + executionId); } // Resume the server which should kick of queued jobs managementClient.getControllerClient().execute(Operations.createOperation("resume")); // Get the execution jobExecution = jobOperator.getJobExecution(executionId); // Wait until the job is complete for a maximum of 5 seconds waitForTermination(jobExecution, 5); Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getBatchStatus()); // Check that count Assert.assertEquals(20, countingItemWriter.getWrittenItemSize()); } finally { managementClient.getControllerClient().execute(Operations.createOperation("resume")); } } }
7,162
43.76875
149
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/chunk/ChunkPartitionAnalyzer.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.batch.chunk; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import jakarta.batch.api.BatchProperty; import jakarta.batch.api.partition.PartitionAnalyzer; import jakarta.batch.runtime.BatchStatus; import jakarta.batch.runtime.context.StepContext; import jakarta.inject.Inject; import jakarta.inject.Named; @Named public final class ChunkPartitionAnalyzer implements PartitionAnalyzer { @Inject private StepContext stepContext; @Inject @BatchProperty(name = "thread.count") private int threadCount; @Inject @BatchProperty(name = "skip.thread.check") private boolean skipThreadCheck; private final Set<Long> childThreadIds = new HashSet<Long>(); private int numOfCompletedPartitions; @Override public void analyzeCollectorData(final Serializable data) throws Exception { childThreadIds.add((Long) data); } @Override public void analyzeStatus(final BatchStatus batchStatus, final String exitStatus) throws Exception { //the check for number of threads used is not very accurate. The underlying thread pool //may choose a cold thread even when a warm thread has already been returned to pool and available. //especially when thread.count is 1, there may be 2 or more threads being used, but at one point, //there should be only 1 active thread running partition. numOfCompletedPartitions++; if(numOfCompletedPartitions == 3 && !skipThreadCheck) { //partitions in job xml if (childThreadIds.size() <= threadCount) { //threads in job xml stepContext.setExitStatus(String.format("PASS: Max allowable thread count %s, actual threads %s", threadCount, childThreadIds.size())); } else { stepContext.setExitStatus(String.format("FAIL: Expecting max thread count %s, but got %s", threadCount, childThreadIds.size())); } } } }
3,051
41.388889
113
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/StartBatchServlet.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.batch.common; import java.io.IOException; import java.util.Arrays; import java.util.Properties; import java.util.concurrent.TimeUnit; import jakarta.batch.runtime.JobExecution; import jakarta.inject.Inject; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.jboss.as.test.shared.TimeoutUtil; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @WebServlet("/start") public class StartBatchServlet extends AbstractBatchServlet { protected static final int DEFAULT_TIMEOUT = 60000; protected static final String TIMEOUT_PARAM = "timeout"; public static final String WAIT_FOR_COMPLETION = "wait"; @Inject private BatchExecutionService service; @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { // Get the batch file name final String jobXml = req.getParameter(JOB_XML_PARAMETER); final String timeoutString = req.getParameter(TIMEOUT_PARAM); final String wait = req.getParameter(WAIT_FOR_COMPLETION); if (jobXml == null) { throw new IllegalStateException(String.format("%s is a required parameter", JOB_XML_PARAMETER)); } final Properties params = parseParams(req, Arrays.asList(TIMEOUT_PARAM, WAIT_FOR_COMPLETION)); final JobExecution jobExecution = service.start(jobXml, params); long timeout = TimeoutUtil.adjust(timeoutString == null ? DEFAULT_TIMEOUT : Integer.parseInt(timeoutString)); long sleep = 100L; final boolean waitForCompletion = (wait == null || Boolean.parseBoolean(wait)); boolean b = waitForCompletion; while (b) { switch (jobExecution.getBatchStatus()) { case STARTED: case STARTING: case STOPPING: try { TimeUnit.MILLISECONDS.sleep(sleep); } catch (InterruptedException e) { throw new RuntimeException(e); } timeout -= sleep; sleep = Math.max(sleep / 2, 100L); break; default: b = false; break; } if (timeout <= 0) { throw new IllegalStateException(String.format("Batch job '%s' did not complete within allotted time.", jobXml)); } } if (waitForCompletion) write(resp, jobExecution); } }
3,741
38.389474
128
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/JobListener1.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.batch.common; import jakarta.batch.api.BatchProperty; import jakarta.batch.api.listener.AbstractJobListener; import jakarta.batch.api.listener.JobListener; import jakarta.batch.runtime.context.JobContext; import jakarta.inject.Inject; import jakarta.inject.Named; import org.junit.Assert; import org.wildfly.security.manager.WildFlySecurityManager; @Named("L1") public class JobListener1 extends AbstractJobListener implements JobListener { @Inject @BatchProperty(name="job-prop") private String jobProp; //nothing is injected @Inject @BatchProperty(name = "listener-prop") private String listenerProp; //injected @Inject @BatchProperty(name = "reference-job-prop") private String referenceJobProp; @Inject @BatchProperty(name="reference-job-param") private String referenceJobParam; @Inject @BatchProperty(name="reference-system-property") private String referenceSystemProperty; @Inject private JobContext jobContext; @Override public void beforeJob() throws Exception { Assert.assertEquals(null, jobProp); Assert.assertEquals("listener-prop", listenerProp); Assert.assertEquals("job-prop", referenceJobProp); Assert.assertEquals("job-param", referenceJobParam); Assert.assertEquals(WildFlySecurityManager.getPropertyPrivileged("java.version", ""), referenceSystemProperty); Assert.assertEquals(2, jobContext.getProperties().size()); Assert.assertEquals("job-prop", jobContext.getProperties().get("job-prop")); } @Override public void afterJob() throws Exception { } }
2,674
36.676056
119
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/Counter.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.batch.common; import jakarta.inject.Named; import jakarta.inject.Singleton; import java.io.Serializable; import java.util.concurrent.atomic.AtomicInteger; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @Named @Singleton public class Counter implements Serializable { private final AtomicInteger counter = new AtomicInteger(0); public int increment() { return counter.incrementAndGet(); } public int increment(final int i) { return counter.addAndGet(i); } public int get() { return counter.get(); } }
1,650
31.372549
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/JobListener2.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.batch.common; import jakarta.batch.api.BatchProperty; import jakarta.batch.api.listener.JobListener; import jakarta.batch.runtime.context.JobContext; import jakarta.inject.Inject; import jakarta.inject.Named; import org.junit.Assert; @Named("L2") public class JobListener2 implements JobListener { @Inject @BatchProperty(name="job-prop") private String jobProp = "L2"; //unmatched property @Inject @BatchProperty(name = "listener-prop") private String listenerProp; //nothing is injected @Inject @BatchProperty(name = "reference-job-prop") private String referencedProp; //nothing is injected @Inject private JobContext jobContext; @Override public void beforeJob() throws Exception { //Assert.assertEquals("L2", jobProp); should be null or "L2"? Assert.assertEquals(null, listenerProp); Assert.assertEquals(null, referencedProp); Assert.assertEquals(2, jobContext.getProperties().size()); Assert.assertEquals("job-prop", jobContext.getProperties().get("job-prop")); } @Override public void afterJob() throws Exception { } }
2,195
35.6
84
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/CountingItemWriter.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.batch.common; import java.io.Serializable; import java.util.List; import java.util.concurrent.TimeUnit; import jakarta.batch.api.BatchProperty; import jakarta.batch.api.chunk.ItemWriter; import jakarta.inject.Inject; import jakarta.inject.Named; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @Named //@Singleton public class CountingItemWriter implements ItemWriter { @Inject private Counter counter; @Inject @BatchProperty(name = "writer.sleep.time") private long sleep; @Override public void open(final Serializable checkpoint) throws Exception { } @Override public void close() throws Exception { } @Override public void writeItems(final List<Object> items) throws Exception { counter.increment(items.size()); if (sleep > 0) { TimeUnit.MILLISECONDS.sleep(sleep); } } @Override public Serializable checkpointInfo() throws Exception { return counter; } public int getWrittenItemSize() { return counter.get(); } }
2,144
28.791667
71
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/JobExecutionMarshaller.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.batch.common; import java.io.StringReader; import java.io.StringWriter; import java.util.Date; import java.util.Properties; import jakarta.batch.runtime.BatchStatus; import jakarta.batch.runtime.JobExecution; import jakarta.json.Json; import jakarta.json.stream.JsonGenerator; import jakarta.json.stream.JsonParser; import jakarta.json.stream.JsonParser.Event; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class JobExecutionMarshaller { static final String ID = "id"; static final String NAME = "name"; static final String STATUS = "status"; static final String EXIT_STATUS = "exitStatus"; static final String CREATE_TIME = "createTime"; static final String END_TIME = "endTime"; static final String LAST_UPDATE_TIME = "lastUpdateTime"; static final String START_TIME = "startTime"; static final String PROPERTIES = "properties"; public static String marshall(final JobExecution jobExecution) { final StringWriter writer = new StringWriter(); final JsonGenerator generator = Json.createGenerator(writer); generator.writeStartObject() .write(ID, jobExecution.getExecutionId()) .write(NAME, jobExecution.getJobName()) .write(STATUS, jobExecution.getBatchStatus().toString()) .write(EXIT_STATUS, jobExecution.getExitStatus()) .write(CREATE_TIME, jobExecution.getCreateTime().getTime()) .write(END_TIME, jobExecution.getEndTime().getTime()) .write(LAST_UPDATE_TIME, jobExecution.getLastUpdatedTime().getTime()) .write(START_TIME, jobExecution.getStartTime().getTime()); // Write out properties generator.writeStartObject(PROPERTIES); final Properties params = jobExecution.getJobParameters(); for (String key : params.stringPropertyNames()) { generator.write(key, params.getProperty(key)); } generator.writeEnd(); // End main object generator.writeEnd(); generator.close(); return writer.toString(); } public static JobExecution unmarshall(final String json) { final JsonParser parser = Json.createParser(new StringReader(json)); final JobExecutionBuilder builder = JobExecutionBuilder.create(); String key = null; while (parser.hasNext()) { final Event event = parser.next(); switch (event) { case KEY_NAME: key = parser.getString(); break; case VALUE_FALSE: case VALUE_NULL: case VALUE_NUMBER: case VALUE_STRING: case VALUE_TRUE: final String value = parser.getString(); if (key == null) { throw new IllegalStateException(String.format("No key for value '%s'. Parsing position: %s%n\t%s", value, parser.getLocation(), json)); } switch (key) { case ID: if (value != null) { builder.setId(Long.parseLong(value)); } break; case NAME: builder.setName(value); break; case STATUS: if (value != null) { builder.setStatus(BatchStatus.valueOf(value)); } break; case EXIT_STATUS: builder.setExitStatus(value); break; case CREATE_TIME: if (value != null) { builder.setCreateTime(Long.parseLong(value)); } break; case END_TIME: if (value != null) { builder.setEndTime(Long.parseLong(value)); } break; case LAST_UPDATE_TIME: if (value != null) { builder.setLastUpdatedTime(Long.parseLong(value)); } break; case START_TIME: if (value != null) { builder.setStartTime(Long.parseLong(value)); } break; case PROPERTIES: String k = null; while (parser.hasNext()) { final Event e = parser.next(); switch (e) { case KEY_NAME: k = parser.getString(); break; case VALUE_FALSE: case VALUE_NULL: case VALUE_NUMBER: case VALUE_STRING: case VALUE_TRUE: if (k != null) { builder.addParameter(k, parser.getString()); } break; } } break; } break; } } parser.close(); return builder.build(); } static class JobExecutionBuilder { private long id; private String name; private BatchStatus status; private long startTime; private long endTime; private String exitStatus; private long createTime; private long lastUpdatedTime; private final Properties params; private JobExecutionBuilder() { id = -1L; name = null; status = null; startTime = 0L; endTime = 0L; exitStatus = null; createTime = 0L; lastUpdatedTime = 0L; params = new Properties(); } public static JobExecutionBuilder create() { return new JobExecutionBuilder(); } public JobExecutionBuilder setId(final long id) { this.id = id; return this; } public JobExecutionBuilder setName(final String name) { this.name = name; return this; } public JobExecutionBuilder setStatus(final BatchStatus status) { this.status = status; return this; } public JobExecutionBuilder setStartTime(final long startTime) { this.startTime = startTime; return this; } public JobExecutionBuilder setEndTime(final long endTime) { this.endTime = endTime; return this; } public JobExecutionBuilder setExitStatus(final String exitStatus) { this.exitStatus = exitStatus; return this; } public JobExecutionBuilder setCreateTime(final long createTime) { this.createTime = createTime; return this; } public JobExecutionBuilder setLastUpdatedTime(final long lastUpdatedTime) { this.lastUpdatedTime = lastUpdatedTime; return this; } public JobExecutionBuilder addParameter(final String key, final String value) { params.setProperty(key, value); return this; } public JobExecution build() { final long id = this.id; final String name = this.name; final BatchStatus status = this.status; final long startTime = this.startTime; final long endTime = this.endTime; final String exitStatus = this.exitStatus; final long createTime = this.createTime; final long lastUpdatedTime = this.lastUpdatedTime; final Properties params = new Properties(); params.putAll(this.params); return new JobExecution() { @Override public long getExecutionId() { return id; } @Override public String getJobName() { return name; } @Override public BatchStatus getBatchStatus() { return status; } @Override public Date getStartTime() { return new Date(startTime); } @Override public Date getEndTime() { return new Date(endTime); } @Override public String getExitStatus() { return exitStatus; } @Override public Date getCreateTime() { return new Date(createTime); } @Override public Date getLastUpdatedTime() { return new Date(lastUpdatedTime); } @Override public Properties getJobParameters() { return params; } @Override public String toString() { final StringBuilder sb = new StringBuilder("JobExecutionBuilder{"); sb.append("id=").append(id); sb.append(", name='").append(name).append('\''); sb.append(", status=").append(status); sb.append(", startTime=").append(startTime); sb.append(", endTime=").append(endTime); sb.append(", exitStatus='").append(exitStatus).append('\''); sb.append(", createTime=").append(createTime); sb.append(", lastUpdatedTime=").append(lastUpdatedTime); sb.append(", params=").append(params); sb.append('}'); return sb.toString(); } }; } } }
11,676
36.546624
159
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/CountingItemReader.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.batch.common; import java.io.Serializable; import java.util.concurrent.atomic.AtomicInteger; import jakarta.batch.api.BatchProperty; import jakarta.batch.api.chunk.ItemReader; import jakarta.inject.Inject; import jakarta.inject.Named; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @Named public class CountingItemReader implements ItemReader { @Inject @BatchProperty(name = "reader.start") private int start; @Inject @BatchProperty(name = "reader.end") private int end; private final AtomicInteger counter = new AtomicInteger(); @Override public void open(final Serializable checkpoint) throws Exception { if (end == 0) { end = 10; } counter.set(start); } @Override public void close() throws Exception { counter.set(0); } @Override public Object readItem() throws Exception { final int result = counter.incrementAndGet(); if (result > end) { return null; } return result; } @Override public Serializable checkpointInfo() throws Exception { return counter.get(); } }
2,241
28.893333
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/StepExecutionMarshaller.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.batch.common; 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.io.StringReader; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import jakarta.batch.runtime.BatchStatus; import jakarta.batch.runtime.Metric; import jakarta.batch.runtime.Metric.MetricType; import jakarta.batch.runtime.StepExecution; import jakarta.json.Json; import jakarta.json.stream.JsonGenerator; import jakarta.json.stream.JsonParser; import jakarta.json.stream.JsonParser.Event; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public class StepExecutionMarshaller { static final String ID = "id"; static final String NAME = "name"; static final String STATUS = "status"; static final String START_TIME = "startTime"; static final String END_TIME = "endTime"; static final String EXIT_STATUS = "exitStatus"; static final String PERSISTENT_USER_DATA = "persistentUserData"; static final String METRICS = "METRICS"; private static final String METRIC = "metric"; private static final String METRIC_TYPE = "type"; private static final String METRIC_VALUE = "value"; public static String marshall(final StepExecution stepExecution) throws IOException { final StringWriter writer = new StringWriter(); final JsonGenerator generator = Json.createGenerator(writer); generator.writeStartObject() .write(ID, stepExecution.getStepExecutionId()) .write(NAME, stepExecution.getStepName()) .write(STATUS, stepExecution.getBatchStatus().toString()) .write(START_TIME, stepExecution.getStartTime().getTime()) .write(END_TIME, stepExecution.getEndTime().getTime()) .write(EXIT_STATUS, stepExecution.getExitStatus()) .write(PERSISTENT_USER_DATA, serialize(stepExecution.getPersistentUserData())); generator.writeStartObject(METRICS); for (Metric metric : stepExecution.getMetrics()) { generator.writeStartObject(METRIC); generator.write(METRIC_TYPE, metric.getType().toString()); generator.write(METRIC_VALUE, metric.getValue()); generator.writeEnd(); } generator.writeEnd(); // End main object generator.writeEnd(); generator.close(); return writer.toString(); } public static StepExecution unmarshall(final String json) throws IOException, ClassNotFoundException { final JsonParser parser = Json.createParser(new StringReader(json)); final StepExecutionBuilder builder = StepExecutionBuilder.create(); String key = null; while (parser.hasNext()) { final Event event = parser.next(); switch (event) { case KEY_NAME: key = parser.getString(); break; case VALUE_FALSE: case VALUE_NULL: case VALUE_NUMBER: case VALUE_STRING: case VALUE_TRUE: final String value = parser.getString(); if (key == null) { throw new IllegalStateException(String.format("No key for value '%s'. Parsing position: %s%n\t%s", value, parser.getLocation(), json)); } switch (key) { case ID: if (value != null) { builder.setId(Long.parseLong(value)); } break; case NAME: builder.setName(value); break; case STATUS: if (value != null) { builder.setStatus(BatchStatus.valueOf(value)); } break; case EXIT_STATUS: builder.setExitStatus(value); break; case END_TIME: if (value != null) { builder.setEndTime(Long.parseLong(value)); } break; case START_TIME: if (value != null) { builder.setStartTime(Long.parseLong(value)); } break; case PERSISTENT_USER_DATA: builder.setPersistentUserData(deserialize(value)); case METRICS: String k = null; String metricType = null; String metricValue = null; while (parser.hasNext()) { final Event e = parser.next(); switch (e) { case KEY_NAME: k = parser.getString(); break; case VALUE_FALSE: case VALUE_NULL: case VALUE_NUMBER: case VALUE_STRING: case VALUE_TRUE: if (k == null) { throw new IllegalStateException(String.format("No key for value '%s'. Parsing position: %s%n\t%s", value, parser.getLocation(), json)); } switch (k) { case METRIC_TYPE: metricType = parser.getString(); break; case METRIC_VALUE: metricValue = parser.getString(); break; } if (metricType != null && metricValue != null) { final MetricType type = MetricType.valueOf(metricType); final long v = Long.parseLong(parser.getString()); final Metric m = new Metric() { @Override public MetricType getType() { return type; } @Override public long getValue() { return v; } }; builder.addMetric(m); } break; } } break; } break; } } parser.close(); return builder.build(); } private static String serialize(final Serializable serializable) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(serializable); out.flush(); return baos.toString(); } private static Serializable deserialize(final String data) throws IOException, ClassNotFoundException { if (data == null) { return null; } final ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); final ObjectInputStream in = new ObjectInputStream(bais); return (Serializable) in.readObject(); } static class StepExecutionBuilder { private long id; private String name; private BatchStatus status; private long startTime; private long endTime; private String exitStatus; private Serializable persistentUserData; private final Collection<Metric> metrics; private StepExecutionBuilder() { id = -1L; name = null; status = null; startTime = 0L; endTime = 0L; exitStatus = null; persistentUserData = null; metrics = new ArrayList<Metric>(); } public static StepExecutionBuilder create() { return new StepExecutionBuilder(); } public StepExecutionBuilder setId(final long id) { this.id = id; return this; } public StepExecutionBuilder setName(final String name) { this.name = name; return this; } public StepExecutionBuilder setStatus(final BatchStatus status) { this.status = status; return this; } public StepExecutionBuilder setStartTime(final long startTime) { this.startTime = startTime; return this; } public StepExecutionBuilder setEndTime(final long endTime) { this.endTime = endTime; return this; } public StepExecutionBuilder setExitStatus(final String exitStatus) { this.exitStatus = exitStatus; return this; } public StepExecutionBuilder setPersistentUserData(final Serializable persistentUserData) { this.persistentUserData = persistentUserData; return this; } public StepExecutionBuilder addMetric(final Metric metric) { metrics.add(metric); return this; } public StepExecution build() { final long id = this.id; final String name = this.name; final BatchStatus status = this.status; final long startTime = this.startTime; final long endTime = this.endTime; final String exitStatus = this.exitStatus; final Serializable persistentUserData = this.persistentUserData; final Metric[] metrics = this.metrics.toArray(new Metric[this.metrics.size()]); return new StepExecution() { @Override public long getStepExecutionId() { return id; } @Override public String getStepName() { return name; } @Override public BatchStatus getBatchStatus() { return status; } @Override public Date getStartTime() { return new Date(startTime); } @Override public Date getEndTime() { return new Date(endTime); } @Override public String getExitStatus() { return exitStatus; } @Override public Serializable getPersistentUserData() { return persistentUserData; } @Override public Metric[] getMetrics() { return Arrays.copyOf(metrics, metrics.length); } }; } } }
13,146
39.082317
179
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/AbstractBatchTestCase.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.batch.common; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.PropertyPermission; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import jakarta.batch.runtime.JobExecution; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.descriptor.api.Descriptors; import org.jboss.shrinkwrap.descriptor.api.spec.se.manifest.ManifestDescriptor; import org.junit.Assert; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public abstract class AbstractBatchTestCase { static final String ENCODING = "utf-8"; public static WebArchive createDefaultWar(final String warName, final Package pkg, final String... jobXmls) { final WebArchive deployment = ShrinkWrap.create(WebArchive.class, warName) .addPackage(AbstractBatchTestCase.class.getPackage()) .addClasses(TimeoutUtil.class) .addAsWebInfResource(new StringAsset("<beans bean-discovery-mode=\"all\"></beans>"), "beans.xml") .setManifest(new StringAsset( Descriptors.create(ManifestDescriptor.class) .attribute("Dependencies", "org.jboss.msc,org.wildfly.security.manager") .exportAsString())) .addAsManifestResource(createPermissionsXmlAsset(new PropertyPermission("ts.timeout.factor", "read")), "permissions.xml"); for (String jobXml : jobXmls) { addJobXml(pkg, deployment, jobXml); } return deployment; } protected static String performCall(final String url) throws ExecutionException, IOException, TimeoutException { return performCall(url, 10); } protected static String performCall(final String url, final int timeout) throws ExecutionException, IOException, TimeoutException { return HttpRequest.get(url, TimeoutUtil.adjust(timeout), TimeUnit.SECONDS); } protected static WebArchive addJobXml(final Package pkg, final WebArchive deployment, final String jobXml) { return addJobXml(pkg, deployment, jobXml, jobXml); } protected static WebArchive addJobXml(final Package pkg, final WebArchive deployment, final String fileName, final String jobXml) { return deployment.addAsWebInfResource(pkg, fileName, "classes/META-INF/batch-jobs/" + jobXml); } protected static WebArchive addJobXml(final WebArchive deployment, final Asset asset, final String jobXml) { return deployment.addAsWebInfResource(asset, "classes/META-INF/batch-jobs/" + jobXml); } protected static WebArchive addJobXml(final WebArchive deployment, final String jobName) { return deployment.addAsWebInfResource(createJobXml(jobName), "classes/META-INF/batch-jobs/" + jobName + ".xml"); } protected static JavaArchive addJobXml(final JavaArchive deployment, final String jobName) { return deployment.addAsResource(createJobXml(jobName), "META-INF/batch-jobs/" + jobName + ".xml"); } static Asset createJobXml(final String jobName) { final String xml = "<job id=\"" + jobName + "\" xmlns=\"http://xmlns.jcp.org/xml/ns/javaee\" version=\"1.0\">\n" + " <step id=\"step1\">\n" + " <chunk item-count=\"3\">\n" + " <reader ref=\"countingItemReader\">\n" + " <properties>\n" + " <property name=\"reader.start\" value=\"#{jobParameters['reader.start']}\"/>\n" + " <property name=\"reader.end\" value=\"#{jobParameters['reader.end']}\"/>\n" + " </properties>\n" + " </reader>\n" + " <writer ref=\"countingItemWriter\">\n" + " <properties>\n" + " <property name=\"writer.sleep.time\" value=\"#{jobParameters['writer.sleep.time']}\"/>\n" + " </properties>\n" + " </writer>\n" + " </chunk>\n" + " </step>\n" + "</job>"; return new StringAsset(xml); } public static void waitForTermination(final JobExecution jobExecution, final int timeout) { long waitTimeout = TimeoutUtil.adjust(timeout * 1000); long sleep = 100L; while (true) { switch (jobExecution.getBatchStatus()) { case STARTED: case STARTING: case STOPPING: try { TimeUnit.MILLISECONDS.sleep(sleep); } catch (InterruptedException e) { throw new RuntimeException(e); } waitTimeout -= sleep; sleep = Math.max(sleep / 2, 100L); break; default: return; } if (waitTimeout <= 0) { throw new IllegalStateException("Batch job did not complete within allotted time."); } } } public static class UrlBuilder { private final URL url; private final String[] paths; private final Map<String, String> params; private UrlBuilder(final URL url, final String... paths) { this.url = url; this.paths = paths; params = new HashMap<String, String>(); } public static UrlBuilder of(final URL url, final String... paths) { return new UrlBuilder(url, paths); } public UrlBuilder addParameter(final String key, final int value) { return addParameter(key, Integer.toString(value)); } public UrlBuilder addParameter(final String key, final String value) { params.put(key, value); return this; } public String build() throws UnsupportedEncodingException { final StringBuilder result = new StringBuilder(url.toExternalForm()); if (paths != null) { for (String path : paths) { result.append('/').append(path); } } boolean isFirst = true; for (Map.Entry<String, String> entry : params.entrySet()) { if (isFirst) { result.append('?'); } else { result.append('&'); } result.append(URLEncoder.encode(entry.getKey(), ENCODING)).append('=').append(URLEncoder.encode(entry.getValue(), ENCODING)); isFirst = false; } return result.toString(); } } public static class LoggingSetup implements ServerSetupTask { static final ModelNode WELD_BOOTSTRAP_LOGGER_ADDRESS; static { WELD_BOOTSTRAP_LOGGER_ADDRESS = new ModelNode().setEmptyList(); WELD_BOOTSTRAP_LOGGER_ADDRESS.add(ModelDescriptionConstants.SUBSYSTEM, "logging"); WELD_BOOTSTRAP_LOGGER_ADDRESS.add("logger", "org.jboss.weld.Bootstrap"); WELD_BOOTSTRAP_LOGGER_ADDRESS.protect(); } @Override public void setup(final ManagementClient managementClient, final String containerId) throws Exception { final ModelControllerClient client = managementClient.getControllerClient(); // Create the weld bootstrap logger ModelNode op = Operations.createAddOperation(WELD_BOOTSTRAP_LOGGER_ADDRESS); op.get("level").set("DEBUG"); execute(client, op); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { final ModelControllerClient client = managementClient.getControllerClient(); // Remove the weld bootstrap logger ModelNode op = Operations.createRemoveOperation(WELD_BOOTSTRAP_LOGGER_ADDRESS); execute(client, op); } static ModelNode execute(final ModelControllerClient client, final ModelNode op) throws IOException { ModelNode result = client.execute(op); if (!Operations.isSuccessfulOutcome(result)) { Assert.assertTrue(Operations.getFailureDescription(result).toString(), false); } return result; } } }
10,447
42.89916
141
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/IntegerArrayWriter.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.batch.common; import java.util.List; import jakarta.batch.api.chunk.ItemWriter; import jakarta.inject.Named; @Named("integerArrayWriter") public final class IntegerArrayWriter extends IntegerArrayReaderWriterBase implements ItemWriter { @Override public void writeItems(final List<Object> items) throws Exception { if (items == null) { return; } /*if (Metric.getMetric(stepContext, Metric.MetricType.WRITE_COUNT) + items.size() >= writerFailAt && writerFailAt >= 0) { throw new ArithmeticException("Failing at writer.fail.at point " + writerFailAt); }*/ if (writerSleepTime > 0) { Thread.sleep(writerSleepTime); } for (final Object o : items) { data[cursor] = (Integer) o; cursor++; } } @Override protected void initData() { super.initData(); cursor = partitionStart; } }
2,018
35.053571
105
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/IntegerArrayReader.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.batch.common; import jakarta.batch.api.chunk.ItemReader; import jakarta.inject.Named; @Named("integerArrayReader") public final class IntegerArrayReader extends IntegerArrayReaderWriterBase implements ItemReader { @Override public Object readItem() throws Exception { if (cursor > partitionEnd || cursor < partitionStart) { return null; } if (cursor == readerFailAt) { throw new ArithmeticException("Failing at reader.fail.at point " + readerFailAt); } final Integer result = data[cursor]; cursor++; return result; } @Override protected void initData() { super.initData(); for (int i = 0; i < dataCount; i++) { data[i] = i; } //position the cursor according to partition start cursor = partitionStart; } }
1,927
35.377358
98
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/Decider1.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.batch.common; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import jakarta.batch.api.BatchProperty; import jakarta.batch.api.Decider; import jakarta.batch.runtime.StepExecution; import jakarta.batch.runtime.context.JobContext; import jakarta.inject.Inject; import jakarta.inject.Named; import org.hamcrest.MatcherAssert; import org.junit.Assert; import org.wildfly.security.manager.WildFlySecurityManager; @Named public class Decider1 implements Decider { @Inject @BatchProperty(name = "decision-prop") private String decisionProp; @Inject @BatchProperty(name="reference-job-prop") private String referencingJobProp; @Inject @BatchProperty(name="reference-step-prop") private String referencingStepProp; //not injected @Inject @BatchProperty(name = "reference-system-prop") private String referencingSystemProp; @Inject @BatchProperty(name = "reference-job-param") private String referencingJobParam; @Inject private JobContext jobContext; @Override public String decide(final StepExecution[] stepExecutions) throws Exception { Assert.assertEquals("decision-prop", decisionProp); Assert.assertEquals("job-prop", referencingJobProp); MatcherAssert.assertThat(referencingStepProp, not(equalTo("step-prop"))); Assert.assertEquals(WildFlySecurityManager.getPropertyPrivileged("java.version", ""), referencingSystemProp); Assert.assertEquals("job-param", referencingJobParam); return "next"; } }
2,620
36.985507
117
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/PostConstructPreDestroyBase.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.batch.common; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.batch.runtime.context.JobContext; import jakarta.batch.runtime.context.StepContext; import jakarta.inject.Inject; public abstract class PostConstructPreDestroyBase { @Inject protected JobContext jobContext; @Inject protected StepContext stepContext; private boolean allowAddToJobExitStatus; //set in job-level property add.to.job.exit.status in job xml @PostConstruct private void ps() { final String p = jobContext.getProperties().getProperty("add.to.job.exit.status"); allowAddToJobExitStatus = Boolean.parseBoolean(p); addToJobExitStatus("PostConstructPreDestroyBase.ps"); } @PreDestroy private void pd() { addToJobExitStatus("PostConstructPreDestroyBase.pd"); } protected void addToJobExitStatus(final String s) { if (allowAddToJobExitStatus) { final String jes = jobContext.getExitStatus(); if (jes == null) { jobContext.setExitStatus(s); } else { jobContext.setExitStatus(jes + " " + s); } } } }
2,260
34.888889
107
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/AbstractBatchServlet.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.batch.common; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.Properties; import jakarta.batch.runtime.JobExecution; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ public abstract class AbstractBatchServlet extends HttpServlet { public static final String JOB_XML_PARAMETER = "jobXml"; protected Properties parseParams(final HttpServletRequest request, final Collection<String> ignore) { final Collection<String> localIgnore = new ArrayList<String>(Arrays.asList(JOB_XML_PARAMETER)); localIgnore.addAll(ignore); final Properties params = new Properties(); final Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { final String name = e.nextElement(); if (localIgnore.contains(name)) continue; final String value = request.getParameter(name); params.setProperty(name, value); } return params; } protected void write(final HttpServletResponse response, final JobExecution jobExecution) throws IOException { response.setContentType("application/json"); response.getWriter().write(JobExecutionMarshaller.marshall(jobExecution)); } }
2,544
40.048387
114
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/BatchExecutionService.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.batch.common; import java.util.Properties; import jakarta.batch.operations.JobOperator; import jakarta.batch.runtime.BatchRuntime; import jakarta.batch.runtime.JobExecution; import jakarta.inject.Singleton; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @Singleton public class BatchExecutionService { private final JobOperator jobOperator; public BatchExecutionService() { jobOperator = BatchRuntime.getJobOperator(); } public JobOperator getJobOperator() { return jobOperator; } public JobExecution start(final String jobXml, final Properties params) { final long id = jobOperator.start(jobXml, params); return jobOperator.getJobExecution(id); } }
1,808
33.788462
77
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/BatchletNoNamed.java
/* * Copyright (c) 2012-2013 Red Hat, Inc. and/or its affiliates. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Cheng Fang - Initial API and implementation */ package org.jboss.as.test.integration.batch.common; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.batch.api.BatchProperty; import jakarta.batch.api.Batchlet; import jakarta.inject.Inject; public class BatchletNoNamed extends PostConstructPreDestroyBase implements Batchlet { @Inject @BatchProperty(name = "batchlet-prop") protected String batchletProp; @Inject @BatchProperty(name = "reference-job-prop") protected String referencingJobProp; @Inject @BatchProperty(name = "reference-system-prop") protected String referencingSystemProp; @Inject @BatchProperty(name = "reference-job-param") protected String referencingJobParam; @Override public String process() throws Exception { return "Processed"; } @Override public void stop() throws Exception { } @PostConstruct void ps() { addToJobExitStatus("BatchletNoNamed.ps"); } @PreDestroy void pd() { addToJobExitStatus("BatchletNoNamed.pd"); } }
1,460
24.189655
86
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/IntegerArrayReaderWriterBase.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.batch.common; import java.io.Serializable; import jakarta.batch.api.BatchProperty; import jakarta.batch.runtime.context.StepContext; import jakarta.inject.Inject; public abstract class IntegerArrayReaderWriterBase { @Inject protected StepContext stepContext; @Inject @BatchProperty(name = "data.count") protected Integer dataCount; @Inject @BatchProperty(name = "partition.start") protected int partitionStart; @Inject @BatchProperty(name = "partition.end") protected Integer partitionEnd; @Inject @BatchProperty(name = "reader.fail.at") protected Integer readerFailAt; @Inject @BatchProperty(name = "writer.fail.at") protected Integer writerFailAt; @Inject @BatchProperty(name = "writer.sleep.time") protected long writerSleepTime; protected Integer[] data; protected int cursor; /** * Creates the data array without filling the data. */ protected void initData() { if (dataCount == null) { throw new IllegalStateException("data.count property is not injected."); } data = new Integer[dataCount]; if (readerFailAt == null) { readerFailAt = -1; } if (writerFailAt == null) { writerFailAt = -1; } if (partitionEnd == null) { partitionEnd = dataCount - 1; } } public void open(final Serializable checkpoint) throws Exception { if (data == null) { initData(); } cursor = checkpoint == null ? partitionStart : (Integer) checkpoint; } public Serializable checkpointInfo() throws Exception { return cursor; } public void close() throws Exception { } }
2,819
29
84
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/common/Batchlet0.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.batch.common; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.inject.Named; @Named public class Batchlet0 extends BatchletNoNamed { @PostConstruct void ps() { addToJobExitStatus("Batchlet0.ps"); } @PreDestroy void pd() { addToJobExitStatus("Batchlet0.pd"); } }
1,412
33.463415
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/deployment/DeploymentResourceTestCase.java
/* * Copyright 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.batch.deployment; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.stream.Collectors; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.batch.common.AbstractBatchTestCase; import org.jboss.as.test.integration.batch.common.CountingItemReader; import org.jboss.as.test.integration.batch.common.CountingItemWriter; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests the start, stop and restart functionality for deployments. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunWith(Arquillian.class) @RunAsClient public class DeploymentResourceTestCase extends AbstractBatchTestCase { private static final String DEPLOYMENT_NAME_1 = "test-batch-1.war"; private static final String DEPLOYMENT_NAME_2 = "test-batch-2.war"; @ArquillianResource // @OperateOnDeployment is required until WFARQ-13 is resolved @OperateOnDeployment(DEPLOYMENT_NAME_1) private ManagementClient managementClient; @Deployment(name = DEPLOYMENT_NAME_1) public static WebArchive createDeployment1() { final Package pkg = DeploymentResourceTestCase.class.getPackage(); final WebArchive deployment = createDefaultWar(DEPLOYMENT_NAME_1, pkg) .addClasses(CountingItemReader.class, CountingItemWriter.class); addJobXml(pkg, deployment, "test-chunk.xml"); addJobXml(pkg, deployment, "test-chunk.xml", "same-test-chunk.xml"); return deployment; } @Deployment(name = DEPLOYMENT_NAME_2) public static WebArchive createDeployment2() { final Package pkg = DeploymentResourceTestCase.class.getPackage(); final WebArchive deployment = createDefaultWar(DEPLOYMENT_NAME_2, pkg) .addClasses(CountingItemReader.class, CountingItemWriter.class); addJobXml(pkg, deployment, "test-chunk.xml"); addJobXml(pkg, deployment, "test-chunk.xml", "same-test-chunk.xml"); addJobXml(pkg, deployment, "test-chunk-other.xml"); addJobXml(deployment, EmptyAsset.INSTANCE, "invalid.xml"); return deployment; } @Test public void testRootResourceJobXmlListing() throws Exception { // First deployment should only have two available XML descriptors validateJobXmlNames(DEPLOYMENT_NAME_1, "test-chunk.xml", "same-test-chunk.xml"); // Second deployment should have 3 available descriptors and one missing descriptor as it's invalid validateJobXmlNames(DEPLOYMENT_NAME_2, Arrays.asList("test-chunk.xml", "same-test-chunk.xml", "test-chunk-other.xml"), Collections.singleton("invalid.xml")); } @Test public void testDeploymentJobXmlListing() throws Exception { // First deployment should have two available XML descriptors on the single job ModelNode address = Operations.createAddress("deployment", DEPLOYMENT_NAME_1, "subsystem", "batch-jberet", "job", "test-chunk"); validateJobXmlNames(address, "test-chunk.xml", "same-test-chunk.xml"); // Second deployment should have two available jobs. The first job should have two available XML descriptors the // second job should only have one descriptor. address = Operations.createAddress("deployment", DEPLOYMENT_NAME_2, "subsystem", "batch-jberet", "job", "test-chunk"); validateJobXmlNames(address, "test-chunk.xml", "same-test-chunk.xml"); address = Operations.createAddress("deployment", DEPLOYMENT_NAME_2, "subsystem", "batch-jberet", "job", "test-chunk-other"); validateJobXmlNames(address, "test-chunk-other.xml"); } @Test public void testEmptyResources() throws Exception { final ModelNode address = Operations.createAddress("deployment", DEPLOYMENT_NAME_2, "subsystem", "batch-jberet"); final ModelNode op = Operations.createReadResourceOperation(address, true); op.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true); final ModelNode result = executeOperation(op); final ModelNode otherJob = result.get("job", "test-chunk-other"); Assert.assertTrue("Expected the test-chunk-other job resource to exist", otherJob.isDefined()); Assert.assertEquals(0, otherJob.get("instance-count").asInt()); Assert.assertEquals(0, otherJob.get("running-executions").asInt()); Assert.assertFalse(otherJob.get("executions").isDefined()); } private void validateJobXmlNames(final String deploymentName, final String... expectedDescriptors) throws IOException { validateJobXmlNames(deploymentName, Arrays.asList(expectedDescriptors), Collections.emptyList()); } private void validateJobXmlNames(final ModelNode address, final String... expectedDescriptors) throws IOException { validateJobXmlNames(address, Arrays.asList(expectedDescriptors), Collections.emptyList()); } private void validateJobXmlNames(final String deploymentName, final Collection<String> expectedDescriptors, final Collection<String> unexpectedDescriptors) throws IOException { final ModelNode address = Operations.createAddress("deployment", deploymentName, "subsystem", "batch-jberet"); validateJobXmlNames(address, expectedDescriptors, unexpectedDescriptors); } private void validateJobXmlNames(final ModelNode address, final Collection<String> expectedDescriptors, final Collection<String> unexpectedDescriptors) throws IOException { final ModelNode op = Operations.createReadAttributeOperation(address, "job-xml-names"); final ModelNode result = executeOperation(op); final Collection<String> jobNames = result.asList() .stream() .map(ModelNode::asString) .collect(Collectors.toSet()); Assert.assertEquals(expectedDescriptors.size(), jobNames.size()); for (String xmlDescriptor : expectedDescriptors) { Assert.assertTrue(String.format("Expected %s to be in the list of job-xml-names.", xmlDescriptor), jobNames.contains(xmlDescriptor)); } for (String xmlDescriptor : unexpectedDescriptors) { Assert.assertFalse(String.format("Expected %s to NOT be in the list of job-xml-names.", xmlDescriptor), jobNames.contains(xmlDescriptor)); } } @SuppressWarnings("Duplicates") private ModelNode executeOperation(final ModelNode op) throws IOException { final ModelControllerClient client = managementClient.getControllerClient(); final ModelNode result = client.execute(op); if (Operations.isSuccessfulOutcome(result)) { return Operations.readResult(result); } Assert.fail(Operations.getFailureDescription(result).asString()); // Should never be reached return new ModelNode(); } }
8,258
48.753012
165
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/deployment/DeploymentDescriptorTestCase.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.batch.deployment; import jakarta.batch.runtime.BatchStatus; import jakarta.batch.runtime.JobExecution; import java.io.IOException; import java.net.URL; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.client.helpers.Operations.CompositeOperationBuilder; import org.jboss.as.test.integration.batch.common.AbstractBatchTestCase; import org.jboss.as.test.integration.batch.common.CountingItemReader; import org.jboss.as.test.integration.batch.common.CountingItemWriter; import org.jboss.as.test.integration.batch.common.JobExecutionMarshaller; import org.jboss.as.test.integration.batch.common.StartBatchServlet; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Runs tests with a {@code jboss-all.xml} deployment descriptor. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunAsClient @RunWith(Arquillian.class) @ServerSetup(DeploymentDescriptorTestCase.JdbcJobRepositorySetUp.class) public class DeploymentDescriptorTestCase extends AbstractBatchTestCase { // in-memory deployment names private static final String NAMED_IN_MEMORY_DEPLOYMENT = "batch-named-in-memory.war"; private static final String DEFINED_IN_MEMORY_DEPLOYMENT = "batch-defined-in-memory.war"; // JDBC deployment names private static final String NAMED_JDBC_DEPLOYMENT = "batch-named-jdbc.war"; private static final String DEFINED_JDBC_DEPLOYMENT = "batch-defined-jdbc.war"; @Deployment(name = NAMED_IN_MEMORY_DEPLOYMENT) public static WebArchive createNamedInMemoryDeployment() { return createDefaultWar(NAMED_IN_MEMORY_DEPLOYMENT, DeploymentDescriptorTestCase.class.getPackage(), "test-chunk.xml") .addClasses(CountingItemReader.class, CountingItemWriter.class) .addAsManifestResource(DeploymentDescriptorTestCase.class.getPackage(), "named-in-memory-jboss-all.xml", "jboss-all.xml"); } @Deployment(name = DEFINED_IN_MEMORY_DEPLOYMENT) public static WebArchive createDefinedInMemoryDeployment() { return createDefaultWar(DEFINED_IN_MEMORY_DEPLOYMENT, DeploymentDescriptorTestCase.class.getPackage(), "test-chunk.xml") .addClasses(CountingItemReader.class, CountingItemWriter.class) .addAsManifestResource(DeploymentDescriptorTestCase.class.getPackage(), "defined-in-memory-jboss-all.xml", "jboss-all.xml"); } @Deployment(name = NAMED_JDBC_DEPLOYMENT) public static WebArchive createNamedJdbcDeployment() { return createDefaultWar(NAMED_JDBC_DEPLOYMENT, DeploymentDescriptorTestCase.class.getPackage(), "test-chunk.xml") .addClasses(CountingItemReader.class, CountingItemWriter.class) .addAsManifestResource(DeploymentDescriptorTestCase.class.getPackage(), "named-jdbc-jboss-all.xml", "jboss-all.xml"); } @Deployment(name = DEFINED_JDBC_DEPLOYMENT) public static WebArchive createDefinedJdbcDeployment() { return createDefaultWar(DEFINED_JDBC_DEPLOYMENT, DeploymentDescriptorTestCase.class.getPackage(), "test-chunk.xml") .addClasses(CountingItemReader.class, CountingItemWriter.class) .addAsManifestResource(DeploymentDescriptorTestCase.class.getPackage(), "defined-jdbc-jboss-all.xml", "jboss-all.xml"); } @OperateOnDeployment(NAMED_IN_MEMORY_DEPLOYMENT) @Test public void namedInMemoryTest(@ArquillianResource final URL url) throws Exception { // Test the default batch defined, ExampleDS, repository is isolated testCompletion(1L, url); testCompletion(2L, url); } @OperateOnDeployment(DEFINED_IN_MEMORY_DEPLOYMENT) @Test public void definedInMemoryTest(@ArquillianResource final URL url) throws Exception { // Test that a newly named testCompletion(1L, url); testCompletion(2L, url); } @OperateOnDeployment(NAMED_JDBC_DEPLOYMENT) @Test @InSequence(1) public void namedJdbcTest(@ArquillianResource final URL url) throws Exception { // This test runs after definedJdbcTest, and the two tests share the same data source. testCompletion(3L, url); testCompletion(4L, url); } @OperateOnDeployment(DEFINED_JDBC_DEPLOYMENT) @Test public void definedJdbcTest(@ArquillianResource final URL url) throws Exception { testCompletion(1L, url); testCompletion(2L, url); } private void testCompletion(final long expectedExecutionId, final URL url) throws IOException, ExecutionException, TimeoutException { final UrlBuilder builder = UrlBuilder.of(url, "start"); builder.addParameter(StartBatchServlet.JOB_XML_PARAMETER, "test-chunk"); builder.addParameter("reader.end", 10); final String result = performCall(builder.build()); final JobExecution jobExecution = JobExecutionMarshaller.unmarshall(result); Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getBatchStatus()); Assert.assertEquals(expectedExecutionId, jobExecution.getExecutionId()); } static class JdbcJobRepositorySetUp extends SnapshotRestoreSetupTask { @Override public void doSetup(final ManagementClient managementClient, final String containerId) throws Exception { final CompositeOperationBuilder operationBuilder = CompositeOperationBuilder.create(); // Add a new data-source ModelNode address = Operations.createAddress("subsystem", "datasources", "data-source", "batch-ds"); ModelNode op = Operations.createAddOperation(address); op.get("driver-name").set("h2"); op.get("jndi-name").set("java:jboss/datasources/batch"); op.get("connection-url").set("jdbc:h2:mem:batch-test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); operationBuilder.addStep(op); // Add a new JDBC job repository with the new data-source address = Operations.createAddress("subsystem", "batch-jberet", "jdbc-job-repository", "batch-ds"); op = Operations.createAddOperation(address); op.get("data-source").set("batch-ds"); operationBuilder.addStep(op); // Add a new in-memory repository address = Operations.createAddress("subsystem", "batch-jberet", "in-memory-job-repository", "batch-in-mem"); operationBuilder.addStep(Operations.createAddOperation(address)); // Add a new thread-pool address = Operations.createAddress("subsystem", "batch-jberet", "thread-pool", "deployment-thread-pool"); op = Operations.createAddOperation(address); op.get("max-threads").set(5L); final ModelNode keepAlive = op.get("keepalive-time"); keepAlive.get("time").set(200L); keepAlive.get("unit").set(TimeUnit.MILLISECONDS.toString()); operationBuilder.addStep(op); execute(managementClient.getControllerClient(), operationBuilder.build()); } static ModelNode execute(final ModelControllerClient client, final Operation op) throws IOException { final ModelNode result = client.execute(op); if (!Operations.isSuccessfulOutcome(result)) { Assert.fail(Operations.getFailureDescription(result).toString()); } return result; } static ModelNode execute(final ModelControllerClient client, final ModelNode op) throws IOException { return execute(client, Operation.Factory.create(op)); } } }
9,477
47.357143
140
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/deployment/SimpleEJB.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.batch.deployment; import jakarta.ejb.Singleton; /** * Pointless EJB that exists only to convert a jar to an EJB archive. */ @Singleton public class SimpleEJB { public void noop() { // do nothing } }
1,282
33.675676
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/deployment/JobControlTestCase.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.batch.deployment; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.io.FilePermission; import java.io.IOException; import java.util.PropertyPermission; import jakarta.batch.operations.JobOperator; import jakarta.batch.runtime.BatchRuntime; import jakarta.batch.runtime.BatchStatus; import jakarta.batch.runtime.JobExecution; import jakarta.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.batch.common.AbstractBatchTestCase; import org.jboss.as.test.integration.batch.common.CountingItemReader; import org.jboss.as.test.integration.batch.common.CountingItemWriter; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.remoting3.security.RemotingPermission; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests the start, stop and restart functionality for deployments. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunWith(Arquillian.class) @ServerSetup(JobControlTestCase.DebugLoggingSetup.class) public class JobControlTestCase extends AbstractBatchTestCase { private static final String DEPLOYMENT_NAME = "test-batch.war"; @ArquillianResource private ManagementClient managementClient; @Inject private CountingItemWriter countingItemWriter; private int currentCount = 0; @Deployment(name = DEPLOYMENT_NAME) public static WebArchive createNamedInMemoryDeployment() { return createDefaultWar(DEPLOYMENT_NAME, DeploymentDescriptorTestCase.class.getPackage(), "test-chunk.xml") .addClasses(CountingItemReader.class, CountingItemWriter.class) .addClass(Operations.class) .addAsResource(new StringAsset("Dependencies: org.jboss.dmr, org.jboss.as.controller, org.jboss.remoting\n"), "META-INF/MANIFEST.MF") .addAsManifestResource(createPermissionsXmlAsset( new RemotingPermission("createEndpoint"), new RemotingPermission("connect"), new PropertyPermission("ts.timeout.factor", "read"), new FilePermission(System.getProperty("jboss.inst") + "/standalone/tmp/auth/*", "read") ), "permissions.xml"); } @Test public void testStart() throws Exception { final ModelNode address = Operations.createAddress("deployment", DEPLOYMENT_NAME, "subsystem", "batch-jberet"); final ModelNode op = Operations.createOperation("start-job", address); op.get("job-xml-name").set("test-chunk"); final ModelNode properties = op.get("properties"); properties.get("reader.end").set("5"); final ModelNode result = executeOperation(op); currentCount += 5; final long executionId = result.asLong(); Assert.assertTrue("Execution id should be greater than 0", executionId > 0L); // Validate that the job as executed final JobOperator jobOperator = BatchRuntime.getJobOperator(); final JobExecution execution = jobOperator.getJobExecution(executionId); Assert.assertNotNull(execution); // Wait for 3 seconds max for the execution to finish. waitForTermination(execution, 3); // Check that we have 5 items Assert.assertEquals(currentCount, countingItemWriter.getWrittenItemSize()); } @Test public void testStop() throws Exception { final ModelNode address = Operations.createAddress("deployment", DEPLOYMENT_NAME, "subsystem", "batch-jberet"); ModelNode op = Operations.createOperation("start-job", address); op.get("job-xml-name").set("test-chunk"); final ModelNode properties = op.get("properties"); properties.get("reader.end").set("20"); // We're adding a long wait time to ensure we can stop, 1 seconds should be okay properties.get("writer.sleep.time").set(Integer.toString(TimeoutUtil.adjust(1000))); final ModelNode result = executeOperation(op); final long executionId = result.asLong(); Assert.assertTrue("Execution id should be greater than 0", executionId > 0L); // Test the stop operation op = Operations.createOperation("stop-job", address); op.get("execution-id").set(executionId); executeOperation(op); // Validate that the job as executed final JobOperator jobOperator = BatchRuntime.getJobOperator(); final JobExecution execution = jobOperator.getJobExecution(executionId); Assert.assertNotNull(execution); // Wait for 1 seconds max for the execution to finish. waitForTermination(execution, 3); // Reset the counter as we're not sure how many were actually written currentCount = countingItemWriter.getWrittenItemSize(); // Check that the status is stopped Assert.assertEquals(BatchStatus.STOPPED, execution.getBatchStatus()); } @Test public void testStopOnExecutionResource() throws Exception { final ModelNode address = Operations.createAddress("deployment", DEPLOYMENT_NAME, "subsystem", "batch-jberet"); ModelNode op = Operations.createOperation("start-job", address); op.get("job-xml-name").set("test-chunk"); final ModelNode properties = op.get("properties"); properties.get("reader.end").set("20"); // We're adding a long wait time to ensure we can stop, 1 seconds should be okay properties.get("writer.sleep.time").set(Integer.toString(TimeoutUtil.adjust(1000))); final ModelNode result = executeOperation(op); final long executionId = result.asLong(); Assert.assertTrue("Execution id should be greater than 0", executionId > 0L); // Test the stop operation final ModelNode executionAddress = Operations.createAddress("deployment", DEPLOYMENT_NAME, "subsystem", "batch-jberet", "job", "test-chunk", "execution", Long.toString(executionId)); executeOperation(Operations.createOperation("stop-job", executionAddress)); // Validate that the job as executed final JobOperator jobOperator = BatchRuntime.getJobOperator(); final JobExecution execution = jobOperator.getJobExecution(executionId); Assert.assertNotNull(execution); // Wait for 1 seconds max for the execution to finish. waitForTermination(execution, 3); // Reset the counter as we're not sure how many were actually written currentCount = countingItemWriter.getWrittenItemSize(); // Check that the status is stopped Assert.assertEquals(BatchStatus.STOPPED, execution.getBatchStatus()); } @Test public void testRestart() throws Exception { final ModelNode address = Operations.createAddress("deployment", DEPLOYMENT_NAME, "subsystem", "batch-jberet"); ModelNode op = Operations.createOperation("start-job", address); op.get("job-xml-name").set("test-chunk"); ModelNode properties = op.get("properties"); properties.get("reader.end").set("20"); // We're adding a long wait time to ensure we can stop, 1 seconds should be okay properties.get("writer.sleep.time").set(Integer.toString(TimeoutUtil.adjust(2000))); ModelNode result = executeOperation(op); long executionId = result.asLong(); Assert.assertTrue("Execution id should be greater than 0", executionId > 0L); // Test the stop operation op = Operations.createOperation("stop-job", address); op.get("execution-id").set(executionId); executeOperation(op); // Validate that the job as executed final JobOperator jobOperator = BatchRuntime.getJobOperator(); JobExecution execution = jobOperator.getJobExecution(executionId); Assert.assertNotNull(execution); // Wait for 5 seconds max for the execution to finish. waitForTermination(execution, 5); // Reset the counter as we're not sure how many were actually written currentCount = countingItemWriter.getWrittenItemSize(); // Check that the status is stopped Assert.assertEquals(BatchStatus.STOPPED, execution.getBatchStatus()); // Restart the execution op = Operations.createOperation("restart-job", address); op.get("execution-id").set(executionId); properties = op.get("properties"); properties.get("reader.end").set("10"); properties.get("writer.sleep.time").set("0"); result = executeOperation(op); executionId = result.asLong(); Assert.assertTrue("Execution id should be greater than 0", executionId > 0L); execution = jobOperator.getJobExecution(executionId); Assert.assertNotNull(execution); // Wait for 5 seconds max for the execution to finish. waitForTermination(execution, 5); // Check that the status is stopped Assert.assertEquals(BatchStatus.COMPLETED, execution.getBatchStatus()); } @Test public void testRestartOnExecutionResource() throws Exception { final ModelNode address = Operations.createAddress("deployment", DEPLOYMENT_NAME, "subsystem", "batch-jberet"); ModelNode op = Operations.createOperation("start-job", address); op.get("job-xml-name").set("test-chunk"); ModelNode properties = op.get("properties"); properties.get("reader.end").set("20"); // We're adding a long wait time to ensure we can stop, 1 seconds should be okay properties.get("writer.sleep.time").set(Integer.toString(TimeoutUtil.adjust(1000))); ModelNode result = executeOperation(op); long executionId = result.asLong(); Assert.assertTrue("Execution id should be greater than 0", executionId > 0L); // Test the stop operation final ModelNode executionAddress = Operations.createAddress("deployment", DEPLOYMENT_NAME, "subsystem", "batch-jberet", "job", "test-chunk", "execution", Long.toString(executionId)); executeOperation(Operations.createOperation("stop-job", executionAddress)); // Validate that the job as executed final JobOperator jobOperator = BatchRuntime.getJobOperator(); JobExecution execution = jobOperator.getJobExecution(executionId); Assert.assertNotNull(execution); // Wait for 1 seconds max for the execution to finish. waitForTermination(execution, 3); // Reset the counter as we're not sure how many were actually written currentCount = countingItemWriter.getWrittenItemSize(); // Check that the status is stopped Assert.assertEquals(BatchStatus.STOPPED, execution.getBatchStatus()); // Restart the execution op = Operations.createOperation("restart-job", executionAddress); properties = op.get("properties"); properties.get("reader.end").set("10"); properties.get("writer.sleep.time").set("0"); result = executeOperation(op); executionId = result.asLong(); Assert.assertTrue("Execution id should be greater than 0", executionId > 0L); execution = jobOperator.getJobExecution(executionId); Assert.assertNotNull(execution); // Wait for 3 seconds max for the execution to finish. waitForTermination(execution, 3); // Check that the status is stopped Assert.assertEquals(BatchStatus.COMPLETED, execution.getBatchStatus()); } private ModelNode executeOperation(final ModelNode op) throws IOException { final ModelControllerClient client = managementClient.getControllerClient(); final ModelNode result = client.execute(op); if (Operations.isSuccessfulOutcome(result)) { return Operations.readResult(result); } Assert.fail(Operations.getFailureDescription(result).asString()); // Should never be reached return new ModelNode(); } static class DebugLoggingSetup implements ServerSetupTask { @Override public void setup(final ManagementClient managementClient, final String containerId) throws Exception { // Enable debug logging for org.wildfly.extension.batch final ModelNode address = Operations.createAddress("subsystem", "logging", "logger", "org.wildfly.extension.batch"); final ModelNode op = Operations.createAddOperation(address); op.get("level").set("DEBUG"); execute(managementClient.getControllerClient(), op); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { execute(managementClient.getControllerClient(), Operations.createRemoveOperation(Operations.createAddress("subsystem", "logging", "logger", "org.wildfly.extension.batch"))); } static ModelNode execute(final ModelControllerClient client, final ModelNode op) throws IOException { final ModelNode result = client.execute(op); if (!Operations.isSuccessfulOutcome(result)) { Assert.fail(Operations.getFailureDescription(result).toString()); } return result; } } }
14,881
46.244444
190
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/deployment/JobXmlVisibilityTestCase.java
/* * Copyright 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.batch.deployment; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import java.util.stream.Collectors; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.batch.common.AbstractBatchTestCase; import org.jboss.as.test.integration.batch.common.CountingItemReader; import org.jboss.as.test.integration.batch.common.CountingItemWriter; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunAsClient @RunWith(Arquillian.class) public class JobXmlVisibilityTestCase extends AbstractBatchTestCase { private static final String EAR = "test-visibility.ear"; private static final String EAR_ISOLATED = "test-visibility-isolated.ear"; private static final String EAR_WITH_LIB = "test-with-lib.ear"; private static final String EAR_WITH_LIB_ISOLATED = "test-isolated-with-lib.ear"; private static final String WAR_WITH_LIB = "test-war-with-lib.war"; @ArquillianResource // @OperateOnDeployment is required until WFARQ-13 is resolved, any deployment should suffice though @OperateOnDeployment(EAR) private ManagementClient managementClient; @Deployment(name = EAR) public static EnterpriseArchive visibleEarDeployment() { return createEar(EAR, "visible"); } @Deployment(name = EAR_ISOLATED) public static EnterpriseArchive isolatedEarDeployment() { return createEar(EAR_ISOLATED, "isolated") .addAsManifestResource(new StringAsset( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<jboss-deployment-structure>\n" + " <ear-subdeployments-isolated>true</ear-subdeployments-isolated>\n" + "</jboss-deployment-structure>" ), "jboss-deployment-structure.xml"); } @Deployment(name = EAR_WITH_LIB) public static EnterpriseArchive earWithLibDeployment() { return createEar(EAR_WITH_LIB, "with-lib") .addAsLibrary(createJar("lib-in-ear.jar")); } @Deployment(name = EAR_WITH_LIB_ISOLATED) public static EnterpriseArchive isolatedEarWithLibDeployment() { return createEar(EAR_WITH_LIB_ISOLATED, "isolated-with-lib") .addAsLibrary(createJar("lib-in-ear.jar")) .addAsManifestResource(new StringAsset( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<jboss-deployment-structure>\n" + " <ear-subdeployments-isolated>true</ear-subdeployments-isolated>\n" + "</jboss-deployment-structure>" ), "jboss-deployment-structure.xml"); } @Deployment(name = WAR_WITH_LIB) public static WebArchive warWithLibDeployment() { return createWar(WAR_WITH_LIB) .addClasses(CountingItemReader.class, CountingItemWriter.class) .addAsLibrary(createJar("lib-in-war.jar")); } /** * Tests that all job XML files are visible from the WAR. */ @Test public void testJobXmlIsVisible() throws Exception { validateJobXmlNames(deploymentAddress(EAR, "war-in-ear-visible.war"), Arrays.asList("test-war.xml", "test-ejb.xml")); } /** * Tests that the WAR can only see the job XML from the WAR and the EJB can only see the job XML from the EJB. */ @Test public void testJobXmlIsIsolated() throws Exception { validateJobXmlNames(deploymentAddress(EAR_ISOLATED, "war-in-ear-isolated.war"), Collections.singleton("test-war.xml")); validateJobXmlNames(deploymentAddress(EAR_ISOLATED, "ejb-in-ear-isolated.jar"), Collections.singleton("test-ejb.xml")); } /** * Tests that the WAR can see the job XML from the WAR itself, the EJB and the EAR's global dependency. The EJB * should be able to see the job XML from the EJB itself and the EAR's global dependency. */ @Test public void testJobXmlIsVisibleJar() throws Exception { validateJobXmlNames(deploymentAddress(EAR_WITH_LIB, "war-in-ear-with-lib.war"), Arrays.asList("test-war.xml", "test-ejb.xml", "test-jar.xml")); validateJobXmlNames(deploymentAddress(EAR_WITH_LIB, "ejb-in-ear-with-lib.jar"), Arrays.asList("test-ejb.xml", "test-jar.xml")); } /** * Tests that the WAR can see the job XML from the WAR itself and the EAR's global dependency. The EJB * should be able to see the job XML from the EJB itself and the EAR's global dependency. */ @Test public void testJobXmlIsIsolatedJar() throws Exception { validateJobXmlNames(deploymentAddress(EAR_WITH_LIB_ISOLATED, "war-in-ear-isolated-with-lib.war"), Arrays.asList("test-war.xml", "test-jar.xml")); validateJobXmlNames(deploymentAddress(EAR_WITH_LIB_ISOLATED, "ejb-in-ear-isolated-with-lib.jar"), Arrays.asList("test-ejb.xml", "test-jar.xml")); } /** * Test that a WAR will see the job XML from a direct dependency. */ @Test public void testJobXmlInWar() throws Exception { validateJobXmlNames(deploymentAddress(WAR_WITH_LIB, null), Arrays.asList("test-war.xml", "test-jar.xml")); } private void validateJobXmlNames(final ModelNode address, final Collection<String> expected) throws IOException { Set<String> jobXmlNames = getJobXmlNames(address); Assert.assertEquals(expected.size(), jobXmlNames.size()); Assert.assertTrue("Expected the following job XML names: " + expected, jobXmlNames.containsAll(expected)); final Collection<String> expectedJobNames = new LinkedHashSet<>(); for (String jobXmlName : expected) { final int end = jobXmlName.indexOf(".xml"); expectedJobNames.add(jobXmlName.substring(0, end)); } final Set<String> jobNames = getJobNames(address); Assert.assertEquals(expectedJobNames.size(), jobNames.size()); Assert.assertTrue("Expected the following job names: " + expectedJobNames, jobNames.containsAll(expectedJobNames)); } private Set<String> getJobXmlNames(final ModelNode address) throws IOException { final ModelNode op = Operations.createReadAttributeOperation(address, "job-xml-names"); final ModelNode result = executeOperation(op); return result.asList() .stream() .map(ModelNode::asString) .collect(Collectors.toSet()); } private Set<String> getJobNames(final ModelNode address) throws IOException { final ModelNode op = Operations.createOperation(ClientConstants.READ_CHILDREN_NAMES_OPERATION, address); op.get(ClientConstants.CHILD_TYPE).set("job"); final ModelNode result = executeOperation(op); return result.asList() .stream() .map(ModelNode::asString) .collect(Collectors.toSet()); } @SuppressWarnings("Duplicates") private ModelNode executeOperation(final ModelNode op) throws IOException { final ModelControllerClient client = managementClient.getControllerClient(); final ModelNode result = client.execute(op); if (Operations.isSuccessfulOutcome(result)) { return Operations.readResult(result); } Assert.fail(Operations.getFailureDescription(result).asString()); // Should never be reached return new ModelNode(); } private static EnterpriseArchive createEar(final String name, final String suffix) { return ShrinkWrap.create(EnterpriseArchive.class, name) .addAsModule(createEjb("ejb-in-ear-" + suffix + ".jar")) .addAsModule(createWar("war-in-ear-" + suffix + ".war")); } private static WebArchive createWar(final String name) { final WebArchive war = ShrinkWrap.create(WebArchive.class, name) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); addJobXml(war, "test-war"); return war; } private static JavaArchive createEjb(final String name) { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, name) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") // Add at least one EJB annotated class to make this an EJB JAR .addClasses(CountingItemReader.class, CountingItemWriter.class, SimpleEJB.class); addJobXml(jar, "test-ejb"); return jar; } private static JavaArchive createJar(final String name) { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, name) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addClasses(AbstractBatchTestCase.class); addJobXml(jar, "test-jar"); return jar; } private static ModelNode deploymentAddress(final String deploymentName, final String subDeploymentName) { if (subDeploymentName == null) { return Operations.createAddress( "deployment", deploymentName, "subsystem", "batch-jberet" ); } return Operations.createAddress( "deployment", deploymentName, "subdeployment", subDeploymentName, "subsystem", "batch-jberet" ); } }
11,058
43.236
153
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/analyzer/transactiontimeout/TestWriter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.batch.analyzer.transactiontimeout; import jakarta.batch.api.chunk.AbstractItemWriter; import jakarta.inject.Named; @Named public class TestWriter extends AbstractItemWriter { public void writeItems(java.util.List<Object> items) throws Exception { // do nothing - if the items are delivered to writer test passes } }
1,396
40.088235
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/analyzer/transactiontimeout/TransactionTimeoutSetupStep.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.batch.analyzer.transactiontimeout; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADDRESS; 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.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import java.io.IOException; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.ManagementOperations; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; class TransactionTimeoutSetupStep extends SnapshotRestoreSetupTask { @Override public void doSetup(ManagementClient managementClient, String serverId) throws Exception { setTimeout(managementClient, 5); ServerReload.executeReloadAndWaitForCompletion(managementClient); } private void setTimeout(ManagementClient managementClient, int timeout) throws IOException, MgmtOperationException { ModelNode op = new ModelNode(); op.get(OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(ADDRESS).add(SUBSYSTEM); op.get(ADDRESS).add("transactions"); op.get(NAME).set("default-timeout"); op.get(VALUE).set(timeout); ManagementOperations.executeOperation(managementClient.getControllerClient(), op); } }
2,774
46.844828
120
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/analyzer/transactiontimeout/AnalyzerTransactionTimeoutTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.batch.analyzer.transactiontimeout; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.batch.common.AbstractBatchTestCase; import org.jboss.as.test.integration.batch.common.JobExecutionMarshaller; import org.jboss.as.test.integration.batch.common.StartBatchServlet; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.batch.runtime.JobExecution; import java.net.URL; import static org.junit.Assert.assertEquals; /** * Test for JBEAP-4862 * * - uses the {@link TransactionTimeoutSetupStep} to set up small transaction timeout. * - the batch job is slow and takes more then the timeout failing the analyzer * - using jberet.analyzer.txDisabled makes the test pass */ @RunWith(Arquillian.class) @ServerSetup(TransactionTimeoutSetupStep.class) public class AnalyzerTransactionTimeoutTestCase extends AbstractBatchTestCase { @Deployment public static WebArchive createDeployment() { return createDefaultWar("timeout-analyzer.war", AnalyzerTransactionTimeoutTestCase.class.getPackage(), "analyzer-job.xml") .addPackage(AnalyzerTransactionTimeoutTestCase.class.getPackage()) .addAsResource(new StringAsset("Dependencies: org.jboss.dmr, org.jboss.as.controller\n"), "META-INF/MANIFEST.MF"); } @Test @RunAsClient public void testTransactionTimeoutDisabled(@ArquillianResource URL url) throws Exception { final UrlBuilder builder = UrlBuilder.of(url, "start"); builder.addParameter(StartBatchServlet.JOB_XML_PARAMETER, "analyzer-job"); final String result = performCall(builder.build(), 20); final JobExecution jobExecution = JobExecutionMarshaller.unmarshall(result); assertEquals("COMPLETED", jobExecution.getBatchStatus().name()); } }
3,188
41.52
130
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/analyzer/transactiontimeout/TestPartitionAnalyzer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.batch.analyzer.transactiontimeout; import jakarta.batch.api.partition.PartitionAnalyzer; import jakarta.batch.runtime.BatchStatus; import jakarta.inject.Named; import java.io.Serializable; @Named public class TestPartitionAnalyzer implements PartitionAnalyzer { @Override public void analyzeCollectorData(Serializable serializable) throws Exception { } @Override public void analyzeStatus(BatchStatus batchStatus, String s) throws Exception { } }
1,538
35.642857
83
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/analyzer/transactiontimeout/TestReader.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.batch.analyzer.transactiontimeout; import jakarta.batch.api.chunk.AbstractItemReader; import jakarta.inject.Named; @Named public class TestReader extends AbstractItemReader { private int numItems = 10; @Override public Object readItem() throws Exception { if (numItems > 0) { numItems--; Thread.sleep(1000); return numItems; } return null; } }
1,486
33.581395
72
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/repository/JobRepositoryTestUtils.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.batch.repository; import org.jberet.repository.JobRepository; import org.jboss.as.test.integration.batch.common.AbstractBatchTestCase; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.junit.Assert; import jakarta.batch.operations.JobOperator; import jakarta.batch.runtime.BatchRuntime; import jakarta.batch.runtime.BatchStatus; import jakarta.batch.runtime.JobExecution; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; public final class JobRepositoryTestUtils { public static void testGetJobExecutionsWithLimit(ServiceContainer serviceContainer, String repositoryName) { final JobOperator jobOperator = BatchRuntime.getJobOperator(); final Properties jobProperties = new Properties(); jobProperties.setProperty("reader.end", "10"); jobProperties.setProperty("writer.sleep.time", "0"); long latestExecutionId = 0; for (int i = 0; i < 5; i++) { // Start the first job latestExecutionId = jobOperator.start("test-chunk", jobProperties); JobExecution jobExecution = jobOperator.getJobExecution(latestExecutionId); // Wait until the job is complete for a maximum of 5 seconds AbstractBatchTestCase.waitForTermination(jobExecution, 5); // Check the job as completed and the expected execution id should be 1 Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getBatchStatus()); } serviceContainer.dumpServices(); ServiceController<?> service = serviceContainer.getService(ServiceName.of("org", "wildfly", "batch", "job", "repository", repositoryName)); Assert.assertNotNull(String.format("MSC service for the %s job repository not found. Services found: %s", repositoryName, serviceContainer.getServiceNames().stream() .map(ServiceName::toString) .filter(n -> n.contains("jdbc")) .collect(Collectors.joining("\n"))), service); JobRepository repositoryService = (JobRepository) service.getValue(); List<Long> list = repositoryService.getJobExecutionsByJob("test-chunk"); Assert.assertEquals(2, list.size()); // the last two executions are supposed to be obtained Assert.assertEquals(latestExecutionId, (long) list.get(0)); Assert.assertEquals(latestExecutionId - 1, (long) list.get(1)); // override the limit and verify that all executions were retrieved list = repositoryService.getJobExecutionsByJob("test-chunk", 10); Assert.assertEquals(5, list.size()); } }
3,391
44.226667
147
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/repository/InMemoryRepositoryTestCase.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.batch.repository; import org.jberet.repository.JobRepository; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.batch.common.AbstractBatchTestCase; import org.jboss.as.test.integration.batch.common.CountingItemReader; import org.jboss.as.test.integration.batch.common.CountingItemWriter; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.descriptor.api.Descriptors; import org.jboss.shrinkwrap.descriptor.api.spec.se.manifest.ManifestDescriptor; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.batch.operations.JobOperator; import jakarta.batch.runtime.BatchRuntime; import jakarta.batch.runtime.BatchStatus; import jakarta.batch.runtime.JobExecution; import java.util.List; import java.util.Properties; @RunWith(Arquillian.class) public class InMemoryRepositoryTestCase extends AbstractBatchTestCase { private static final String DEPLOYMENT_NAME = "jdbc-batch.war"; @ArquillianResource private ServiceContainer serviceContainer; @Deployment(name = DEPLOYMENT_NAME) public static WebArchive createNamedJdbcDeployment() { return createDefaultWar(DEPLOYMENT_NAME, InMemoryRepositoryTestCase.class.getPackage(), "test-chunk.xml") .addClasses(CountingItemReader.class, CountingItemWriter.class, JobRepositoryTestUtils.class) .setManifest(new StringAsset( Descriptors.create(ManifestDescriptor.class) .attribute("Dependencies", "org.jboss.msc,org.wildfly.security.manager,org.wildfly.extension.batch.jberet") .exportAsString())); } @Test public void testGetJobExecutions() { final JobOperator jobOperator = BatchRuntime.getJobOperator(); final Properties jobProperties = new Properties(); jobProperties.setProperty("reader.end", "10"); jobProperties.setProperty("writer.sleep.time", "0"); long latestExecutionId = 0; for (int i = 0; i < 5; i++) { // Start the first job latestExecutionId = jobOperator.start("test-chunk", jobProperties); JobExecution jobExecution = jobOperator.getJobExecution(latestExecutionId); // Wait until the job is complete for a maximum of 5 seconds AbstractBatchTestCase.waitForTermination(jobExecution, 5); // Check the job as completed and the expected execution id should be 1 Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getBatchStatus()); } ServiceController<?> service = serviceContainer.getService(ServiceName.of("org", "wildfly", "batch", "job", "repository", "in-memory")); JobRepository repositoryService = (JobRepository) service.getValue(); List<Long> list = repositoryService.getJobExecutionsByJob("test-chunk"); Assert.assertEquals(5, list.size()); // executions should be retrieved in the order from latest to the oldest Assert.assertEquals(latestExecutionId, (long) list.get(0)); Assert.assertEquals(latestExecutionId - 1, (long) list.get(1)); Assert.assertEquals(latestExecutionId - 2, (long) list.get(2)); Assert.assertEquals(latestExecutionId - 3, (long) list.get(3)); Assert.assertEquals(latestExecutionId - 4, (long) list.get(4)); } }
4,328
45.548387
144
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/repository/H2JdbcJobRepositorySetUp.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.batch.repository; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; import org.junit.Assert; import java.io.IOException; class H2JdbcJobRepositorySetUp extends SnapshotRestoreSetupTask { static final String REPOSITORY_NAME = "jdbc"; @Override public void doSetup(final ManagementClient managementClient, final String containerId) throws Exception { final Operations.CompositeOperationBuilder operationBuilder = Operations.CompositeOperationBuilder.create(); // Add a new JDBC job repository with the new data-source ModelNode op = Operations.createAddOperation(Operations.createAddress("subsystem", "batch-jberet", "jdbc-job-repository", REPOSITORY_NAME)); configureJobRepository(op); operationBuilder.addStep(op); operationBuilder.addStep(Operations.createWriteAttributeOperation( Operations.createAddress("subsystem", "batch-jberet"), "default-job-repository", REPOSITORY_NAME)); execute(managementClient.getControllerClient(), operationBuilder.build()); ServerReload.reloadIfRequired(managementClient); } @SuppressWarnings("unused") protected void configureJobRepository(ModelNode op) { op.get("data-source").set("ExampleDS"); } private static void execute(final ModelControllerClient client, final Operation op) throws IOException { final ModelNode result = client.execute(op); if (!Operations.isSuccessfulOutcome(result)) { Assert.fail(Operations.getFailureDescription(result).toString()); } Operations.readResult(result); } }
2,590
38.257576
148
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/repository/JdbcRepositoryExecutionsLimitTestCase.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.batch.repository; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.batch.common.AbstractBatchTestCase; import org.jboss.as.test.integration.batch.common.CountingItemReader; import org.jboss.as.test.integration.batch.common.CountingItemWriter; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.ServiceContainer; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.descriptor.api.Descriptors; import org.jboss.shrinkwrap.descriptor.api.spec.se.manifest.ManifestDescriptor; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.extension.batch.jberet.job.repository.JdbcJobRepositoryService; @RunWith(Arquillian.class) @ServerSetup(JdbcRepositoryExecutionsLimitTestCase.JdbcRepositorySetup.class) public class JdbcRepositoryExecutionsLimitTestCase extends AbstractBatchTestCase { private static final String DEPLOYMENT_NAME = "jdbc-batch.war"; @ArquillianResource private ServiceContainer serviceContainer; @Deployment(name = DEPLOYMENT_NAME) public static WebArchive createNamedJdbcDeployment() { return createDefaultWar(DEPLOYMENT_NAME, JdbcRepositoryExecutionsLimitTestCase.class.getPackage(), "test-chunk.xml") .addClasses(CountingItemReader.class, CountingItemWriter.class, JdbcJobRepositoryService.class, JobRepositoryTestUtils.class, H2JdbcJobRepositorySetUp.class) .setManifest(new StringAsset( Descriptors.create(ManifestDescriptor.class) .attribute("Dependencies", "org.jboss.msc,org.wildfly.security.manager,org.wildfly.extension.batch.jberet") .exportAsString())); } @Test public void testGetJobExecutionsWithLimit() { JobRepositoryTestUtils.testGetJobExecutionsWithLimit(serviceContainer, "jdbc"); } static class JdbcRepositorySetup extends H2JdbcJobRepositorySetUp { @Override protected void configureJobRepository(ModelNode op) { super.configureJobRepository(op); op.get("execution-records-limit").set(2); } } }
3,026
41.041667
139
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/repository/JdbcRepositoryTestCase.java
/* * Copyright 2018 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.batch.repository; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.Properties; import jakarta.annotation.Resource; import jakarta.batch.operations.JobOperator; import jakarta.batch.runtime.BatchRuntime; import jakarta.batch.runtime.BatchStatus; import jakarta.batch.runtime.JobExecution; import javax.sql.DataSource; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.batch.common.AbstractBatchTestCase; import org.jboss.as.test.integration.batch.common.CountingItemReader; import org.jboss.as.test.integration.batch.common.CountingItemWriter; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunWith(Arquillian.class) @ServerSetup(JdbcRepositoryTestCase.AgroalJdbcJobRepositorySetUp.class) public class JdbcRepositoryTestCase extends AbstractBatchTestCase { private static final String DEPLOYMENT_NAME = "jdbc-batch.war"; private static final String REPOSITORY_NAME = "jdbc"; @Resource(lookup = "java:jboss/datasources/batch") private DataSource dataSource; @Deployment(name = DEPLOYMENT_NAME) public static WebArchive createNamedJdbcDeployment() { return createDefaultWar(DEPLOYMENT_NAME, JdbcRepositoryTestCase.class.getPackage(), "test-chunk.xml") .addClasses(CountingItemReader.class, CountingItemWriter.class); } /** * This tests that the correct default-jdbc-repository was set. */ @RunAsClient @Test public void checkCorrectJobRepository(@ArquillianResource ManagementClient client) throws Exception { final ModelNode address = Operations.createAddress("subsystem", "batch-jberet"); final ModelNode op = Operations.createReadAttributeOperation(address, "default-job-repository"); final ModelNode result = client.getControllerClient().execute(op); if (!Operations.isSuccessfulOutcome(result)) { Assert.fail(Operations.getFailureDescription(result).toString()); } final String foundName = Operations.readResult(result).asString(); Assert.assertEquals( String.format("Expected the default-job-repository to be set to %s but was %s. See previously logged errors", REPOSITORY_NAME, foundName), REPOSITORY_NAME, foundName); } @Test public void testAgroalBackedRepository() throws Exception { final JobOperator jobOperator = BatchRuntime.getJobOperator(); final Properties jobProperties = new Properties(); jobProperties.setProperty("reader.end", "10"); // Start the first job long executionId = jobOperator.start("test-chunk", jobProperties); JobExecution jobExecution = jobOperator.getJobExecution(executionId); // Wait until the job is complete for a maximum of 5 seconds waitForTermination(jobExecution, 5); // Check the job as completed and the expected execution id should be 1 Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getBatchStatus()); // Query the actual DB and ensure we're using the correct repository Assert.assertNotNull(dataSource); try (Connection connection = dataSource.getConnection()) { final Statement stmt = connection.createStatement(); final ResultSet rs = stmt.executeQuery("SELECT JOBEXECUTIONID, BATCHSTATUS FROM JOB_EXECUTION ORDER BY JOBEXECUTIONID DESC"); Assert.assertTrue("Expected a single entry for the query", rs.next()); Assert.assertEquals(jobExecution.getExecutionId(), rs.getLong("JOBEXECUTIONID")); Assert.assertEquals(BatchStatus.COMPLETED.toString(), rs.getString("BATCHSTATUS")); } } static class AgroalJdbcJobRepositorySetUp extends SnapshotRestoreSetupTask { @Override public void doSetup(final ManagementClient managementClient, final String containerId) throws Exception { final Operations.CompositeOperationBuilder operationBuilder = Operations.CompositeOperationBuilder.create(); // First we need to add the Agroal extension final ModelNode extensionAddress = Operations.createAddress("extension", "org.wildfly.extension.datasources-agroal"); ModelNode op = Operations.createAddOperation(extensionAddress); op.get("module").set("org.wildfly.extension.datasources-agroal"); execute(managementClient.getControllerClient(), Operation.Factory.create(op)); // Next add the subsystem operationBuilder.addStep(Operations.createAddOperation(Operations.createAddress("subsystem", "datasources-agroal"))); // Add the JDBC driver op = Operations.createAddOperation(Operations.createAddress("subsystem", "datasources-agroal", "driver", "agroal-h2")); op.get("module").set("com.h2database.h2"); operationBuilder.addStep(op); // Add the datasource op = Operations.createAddOperation(Operations.createAddress("subsystem", "datasources-agroal", "datasource", "batch-db")); op.get("jndi-name").set("java:jboss/datasources/batch"); final ModelNode connectionFactory = op.get("connection-factory"); connectionFactory.get("driver").set("agroal-h2"); connectionFactory.get("url").set("jdbc:h2:mem:batch-agroal-test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); final ModelNode connectionPool = op.get("connection-pool"); connectionPool.get("max-size").set(10); operationBuilder.addStep(op); // Add a new JDBC job repository with the new data-source op = Operations.createAddOperation(Operations.createAddress("subsystem", "batch-jberet", "jdbc-job-repository", REPOSITORY_NAME)); op.get("data-source").set("batch-db"); operationBuilder.addStep(op); operationBuilder.addStep(Operations.createWriteAttributeOperation( Operations.createAddress("subsystem", "batch-jberet"), "default-job-repository", REPOSITORY_NAME)); execute(managementClient.getControllerClient(), operationBuilder.build()); ServerReload.reloadIfRequired(managementClient); } private static void execute(final ModelControllerClient client, final Operation op) throws IOException { final ModelNode result = client.execute(op); if (!Operations.isSuccessfulOutcome(result)) { Assert.fail(Operations.getFailureDescription(result).toString()); } Operations.readResult(result); } } }
8,089
46.309942
154
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/repository/InMemoryRepositoryExecutionsLimitTestCase.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.batch.repository; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.batch.common.AbstractBatchTestCase; import org.jboss.as.test.integration.batch.common.CountingItemReader; import org.jboss.as.test.integration.batch.common.CountingItemWriter; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.ServiceContainer; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.descriptor.api.Descriptors; import org.jboss.shrinkwrap.descriptor.api.spec.se.manifest.ManifestDescriptor; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @ServerSetup(InMemoryRepositoryExecutionsLimitTestCase.InMemoryRepositorySetup.class) public class InMemoryRepositoryExecutionsLimitTestCase extends AbstractBatchTestCase { private static final String DEPLOYMENT_NAME = "jdbc-batch.war"; @ArquillianResource private ServiceContainer serviceContainer; @Deployment(name = DEPLOYMENT_NAME) public static WebArchive createNamedJdbcDeployment() { return createDefaultWar(DEPLOYMENT_NAME, InMemoryRepositoryExecutionsLimitTestCase.class.getPackage(), "test-chunk.xml") .addClasses(CountingItemReader.class, CountingItemWriter.class, JobRepositoryTestUtils.class, InMemoryRepositorySetup.class) .setManifest(new StringAsset( Descriptors.create(ManifestDescriptor.class) .attribute("Dependencies", "org.jboss.msc,org.wildfly.security.manager,org.wildfly.extension.batch.jberet") .exportAsString())); } @Test public void testGetJobExecutionsWithLimit() { JobRepositoryTestUtils.testGetJobExecutionsWithLimit(serviceContainer, "in-memory"); } static class InMemoryRepositorySetup extends SnapshotRestoreSetupTask { @Override protected void doSetup(ManagementClient client, String containerId) throws Exception { super.doSetup(client, containerId); ModelNode op = Operations.createWriteAttributeOperation( Operations.createAddress("subsystem", "batch-jberet", "in-memory-job-repository", "in-memory"), "execution-records-limit", 2); final ModelNode result = client.getControllerClient().execute(op); if (!Operations.isSuccessfulOutcome(result)) { Assert.fail(Operations.getFailureDescription(result).toString()); } Operations.readResult(result); ServerReload.reloadIfRequired(client); } } }
3,728
42.360465
139
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/batchlet/SimpleCounterBatchletTestCase.java
/* * Copyright 2017 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.batch.batchlet; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.Set; import jakarta.batch.operations.JobOperator; import jakarta.batch.runtime.BatchRuntime; import jakarta.batch.runtime.BatchStatus; import jakarta.batch.runtime.JobExecution; import jakarta.batch.runtime.JobInstance; import jakarta.batch.runtime.StepExecution; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.integration.batch.common.AbstractBatchTestCase; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests that a {@code @RequestScoped} bean will work correctly in a batch job. * <p> * The order of the two tests should not matter. The reason it's tested twice however is a {@code @RequestScoped} bean * should create a new instance for each job executed. Executing twice ensures the scoping for batch is correct. * </p> * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunWith(Arquillian.class) public class SimpleCounterBatchletTestCase extends AbstractBatchTestCase { @Deployment public static WebArchive createDeployment() { return createDefaultWar("simple-counter-batchlet.war", SimpleCounterBatchletTestCase.class.getPackage(), "simple-counter-batchlet.xml", "inactive-job.xml") .addPackage(SimpleCounterBatchletTestCase.class.getPackage()); } /** * Tests that a request scope bean will be injected and the counter should start with 1 and end at 10. * * @throws Exception if an error occurs */ @Test public void testRequestScope10() throws Exception { final Properties jobProperties = new Properties(); jobProperties.setProperty("count", "10"); final JobOperator jobOperator = BatchRuntime.getJobOperator(); // check available job names // jobOperator.getJobNames() should return all available jobs in the // current deployment, whether a job has been started or not. final String inactiveJobName = "inactive-job"; final List<String> expectedJobNames = Arrays.asList("simple-counter-batchlet", inactiveJobName); final Set<String> jobNames = jobOperator.getJobNames(); Assert.assertTrue(String.format("Expecting job names: %s, but got %s", expectedJobNames, jobNames), jobNames.containsAll(expectedJobNames)); Assert.assertEquals(2, jobNames.size()); //getJobInstanceCount, getJobInstances & getRunningExecutions on an inactive job name should not cause exception final int jobInstanceCount = jobOperator.getJobInstanceCount(inactiveJobName); Assert.assertEquals("getJobInstanceCount() should return 0 for job name: " + inactiveJobName, 0, jobInstanceCount); final List<JobInstance> jobInstances = jobOperator.getJobInstances(inactiveJobName, 0, Integer.MAX_VALUE); Assert.assertEquals("getJobInstances() should return empty list for job name: " + inactiveJobName, 0, jobInstances.size()); final List<Long> runningExecutions = jobOperator.getRunningExecutions(inactiveJobName); Assert.assertEquals("getRunningExecutions() should return empty list for job name: " + inactiveJobName, 0, runningExecutions.size()); // Start the first job long executionId = jobOperator.start("simple-counter-batchlet", jobProperties); JobExecution jobExecution = jobOperator.getJobExecution(executionId); // Wait until the job is complete for a maximum of 5 seconds waitForTermination(jobExecution, 5); Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getBatchStatus()); // Get the first step, should only be one, and get the exit status Assert.assertEquals("1,2,3,4,5,6,7,8,9,10", getFirst(jobOperator, executionId).getExitStatus()); } /** * Tests that a request scope bean will be injected and the counter should start with 1 and end at 8. * * @throws Exception if an error occurs */ @Test public void testRequestScope8() throws Exception { final Properties jobProperties = new Properties(); jobProperties.setProperty("count", "8"); final JobOperator jobOperator = BatchRuntime.getJobOperator(); // Start the first job long executionId = jobOperator.start("simple-counter-batchlet", jobProperties); JobExecution jobExecution = jobOperator.getJobExecution(executionId); // Wait until the job is complete for a maximum of 5 seconds waitForTermination(jobExecution, 5); Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getBatchStatus()); // Get the first step, should only be one, and get the exit status Assert.assertEquals("1,2,3,4,5,6,7,8", getFirst(jobOperator, executionId).getExitStatus()); } private StepExecution getFirst(final JobOperator jobOperator, final long executionId) { final List<StepExecution> steps = jobOperator.getStepExecutions(executionId); Assert.assertFalse(steps.isEmpty()); return steps.get(0); } }
5,921
43.863636
141
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/batchlet/RequestScopeCounter.java
/* * Copyright 2017 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.batch.batchlet; import java.util.concurrent.atomic.AtomicInteger; import jakarta.enterprise.context.RequestScoped; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RequestScoped public class RequestScopeCounter { private final AtomicInteger counter = new AtomicInteger(); public int get() { return counter.get(); } public int incrementAndGet() { return counter.incrementAndGet(); } }
1,087
28.405405
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/batchlet/SimpleCounterBatchlet.java
/* * Copyright 2017 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.batch.batchlet; import jakarta.batch.api.AbstractBatchlet; import jakarta.batch.api.BatchProperty; import jakarta.inject.Inject; import jakarta.inject.Named; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @Named public class SimpleCounterBatchlet extends AbstractBatchlet { @Inject private RequestScopeCounter counter; @Inject @BatchProperty private int count; @Override public String process() throws Exception { final StringBuilder exitStatus = new StringBuilder(); int current = 0; while (current < count) { current = counter.incrementAndGet(); exitStatus.append(current); if (current < count) { exitStatus.append(','); } } return exitStatus.toString(); } }
1,465
28.32
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/flow/Batchlet1.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.batch.flow; import jakarta.batch.api.BatchProperty; import jakarta.inject.Inject; import jakarta.inject.Named; import org.jboss.as.test.integration.batch.common.Batchlet0; import org.junit.Assert; @Named public class Batchlet1 extends Batchlet0 { @Inject @BatchProperty(name = "reference-step-prop") private String referencingStepProp; @Override public String process() throws Exception { final String result = super.process(); final String stepToVerify = "step1"; if (stepContext.getStepName().equals(stepToVerify)) { Assert.assertEquals("step-prop", referencingStepProp); } return result; } }
1,739
33.8
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/flow/FlowTestCase.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.batch.flow; import java.net.URL; import jakarta.batch.runtime.BatchStatus; import jakarta.batch.runtime.JobExecution; 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.batch.common.AbstractBatchTestCase; import org.jboss.as.test.integration.batch.common.JobExecutionMarshaller; import org.jboss.as.test.integration.batch.common.StartBatchServlet; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunWith(Arquillian.class) @RunAsClient public class FlowTestCase extends AbstractBatchTestCase { @ArquillianResource private URL url; @Deployment public static WebArchive createDeployment() { return createDefaultWar("batch-flow.war", FlowTestCase.class.getPackage(), "flow.xml") .addPackage(FlowTestCase.class.getPackage()); } @Test public void flow() throws Exception { final UrlBuilder builder = UrlBuilder.of(url, "start"); builder.addParameter(StartBatchServlet.JOB_XML_PARAMETER, "flow"); builder.addParameter("job-param", "job-param"); final String result = performCall(builder.build()); final JobExecution jobExecution = JobExecutionMarshaller.unmarshall(result); Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getBatchStatus()); } }
2,686
39.104478
94
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/suspend/LongRunningBatchlet.java
/* * Copyright 2021 JBoss by Red Hat. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.batch.suspend; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import jakarta.batch.api.BatchProperty; import jakarta.batch.api.Batchlet; import jakarta.inject.Inject; import jakarta.inject.Named; /** * <p>Batchlet that runs until the static method <em>success</em> is called. * It is used to perform the suspend and resume while this job is running. * Only one job of this class can be executed simultaneously.</p> * * @author rmartinc */ @Named public class LongRunningBatchlet implements Batchlet { @Inject @BatchProperty(name = "max.seconds") private Integer maxSeconds; private static final AtomicBoolean success = new AtomicBoolean(false); private static CountDownLatch latch = new CountDownLatch(0); public static synchronized boolean isStarted() { return latch.getCount() > 0; } public static synchronized void success() throws Exception { if (!success.compareAndSet(false, true)) { throw new Exception("Called twice!"); } latch.countDown(); } public static synchronized void reset() throws Exception { if (latch.getCount() > 0) { throw new Exception("The job is not finished!"); } success.set(false); latch = new CountDownLatch(1); } @Override public String process() throws Exception { reset(); latch.await(maxSeconds, TimeUnit.SECONDS); String exitStatus = success.get()? "OK" : "KO"; return exitStatus; } @Override public void stop() throws Exception { latch.countDown(); } }
2,324
29.592105
76
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/suspend/SuspendBatchletTestCase.java
/* * Copyright 2021 JBoss by Red Hat. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.batch.suspend; import java.io.FilePermission; import java.io.IOException; import java.util.List; import java.util.Properties; import java.util.PropertyPermission; import java.util.concurrent.TimeUnit; import jakarta.batch.operations.JobOperator; import jakarta.batch.runtime.BatchRuntime; import jakarta.batch.runtime.BatchStatus; import jakarta.batch.runtime.JobExecution; import jakarta.batch.runtime.JobInstance; import jakarta.batch.runtime.StepExecution; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.batch.common.AbstractBatchTestCase; import org.jboss.as.test.shared.PermissionUtils; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.remoting3.security.RemotingPermission; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * <p>Test that starts a long running batchlet and performs a suspend/resume. * The batch should be restarted after the resume.</p> * * @author rmartinc */ @RunWith(Arquillian.class) public class SuspendBatchletTestCase extends AbstractBatchTestCase { @ArquillianResource private ManagementClient managementClient; @Deployment public static WebArchive createDeployment() { return createDefaultWar("suspend-batchlet.war", SuspendBatchletTestCase.class.getPackage(), "suspend-batchlet.xml") .addClass(LongRunningBatchlet.class) .addAsResource(new StringAsset("Dependencies: org.jboss.dmr, org.jboss.as.controller, org.jboss.remoting\n"), "META-INF/MANIFEST.MF") .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( new RemotingPermission("createEndpoint"), new RemotingPermission("connect"), new PropertyPermission("ts.timeout.factor", "read"), new FilePermission(System.getProperty("jboss.inst") + "/standalone/tmp/auth/*", "read") ), "permissions.xml"); } private void suspendServer() throws IOException { ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.OP).set("suspend"); ModelNode result = managementClient.getControllerClient().execute(op); Assert.assertTrue("Failed to suspend: " + result, Operations.isSuccessfulOutcome(result)); } private void resumeServer() throws IOException { ModelNode op = new ModelNode(); op.get(ModelDescriptionConstants.OP).set("resume"); ModelNode result = managementClient.getControllerClient().execute(op); Assert.assertTrue("Failed to resume: " + result, Operations.isSuccessfulOutcome(result)); } private void checkJobExecution(JobOperator jobOperator, JobExecution jobExecution, BatchStatus expectedBatchStatus, String expectedExitStatus) { waitForTermination(jobExecution, 10); Assert.assertEquals("The batchlet is not in the expected batch status", expectedBatchStatus, jobExecution.getBatchStatus()); List<StepExecution> steps = jobOperator.getStepExecutions(jobExecution.getExecutionId()); Assert.assertFalse("The job execution has no steps", steps.isEmpty()); Assert.assertEquals("The batchlet did not return the expected exit status", expectedExitStatus, steps.get(0).getExitStatus()); } private static JobExecution waitForJobRestarted(final JobOperator jobOperator, final JobInstance jobInstance, final int timeout) { long waitTimeout = TimeoutUtil.adjust(timeout * 1000); long sleep = 100L; JobExecution jobExecution = null; while (jobExecution == null) { for (JobExecution je : jobOperator.getJobExecutions(jobInstance)) { if (je.getBatchStatus() == BatchStatus.STARTED && LongRunningBatchlet.isStarted()) { jobExecution = je; break; } } if (jobExecution == null) { try { TimeUnit.MILLISECONDS.sleep(sleep); } catch (InterruptedException e) { throw new RuntimeException(e); } waitTimeout -= sleep; if (waitTimeout <= 0) { throw new IllegalStateException("Batch job was not restarted within the allotted time."); } } } return jobExecution; } /** * Tests that a batchlet is restarted after a server suspend/resume. * @throws Exception if an error occurs */ @Test public void testSuspendResume() throws Exception { final Properties jobProperties = new Properties(); jobProperties.setProperty("max.seconds", "10"); final JobOperator jobOperator = BatchRuntime.getJobOperator(); long executionId = jobOperator.start("suspend-batchlet", jobProperties); JobExecution jobExecution = jobOperator.getJobExecution(executionId); suspendServer(); // check job is stopped checkJobExecution(jobOperator, jobExecution, BatchStatus.STOPPED, "KO"); resumeServer(); // the job should be restarted with a new ID, wait for it a max of 10s JobInstance jobInstance = jobOperator.getJobInstance(executionId); jobExecution = waitForJobRestarted(jobOperator, jobInstance, 10); // hack to force the batchlet to finish now it's finally started LongRunningBatchlet.success(); // check job finishes OK checkJobExecution(jobOperator, jobExecution, BatchStatus.COMPLETED, "OK"); } }
6,646
42.730263
149
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/transaction/TransactedService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.batch.transaction; import jakarta.ejb.Stateless; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; @Stateless @TransactionAttribute(TransactionAttributeType.REQUIRED) public class TransactedService { @PersistenceContext(unitName = "ExampleDS") private EntityManager em; public void query(int timeout) { if (timeout > 0) { try { Thread.sleep(timeout); } catch (InterruptedException e) { e.printStackTrace(); } } em.createQuery("Select t from TestEntity t").getResultList(); } }
1,778
33.882353
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/transaction/TestEntity.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.batch.transaction; import jakarta.persistence.Entity; import jakarta.persistence.Id; @Entity public class TestEntity { @Id public long id; }
1,214
34.735294
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/transaction/TransactedWriter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.batch.transaction; import jakarta.batch.api.chunk.AbstractItemWriter; import jakarta.inject.Named; import java.util.List; @Named public class TransactedWriter extends AbstractItemWriter { @Override public void writeItems(List<Object> list) throws Exception { // do nothing } }
1,361
36.833333
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/transaction/TransactedReader.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.batch.transaction; import jakarta.batch.api.BatchProperty; import jakarta.batch.api.chunk.AbstractItemReader; import jakarta.inject.Inject; import jakarta.inject.Named; import org.jboss.logging.Logger; @Named public class TransactedReader extends AbstractItemReader { private static final Logger logger = Logger.getLogger(TransactedReader.class); @Inject @BatchProperty(name = "job.timeout") private int timeout; @Inject private TransactedService transactedService; @Override public Object readItem() throws Exception { // one can check the log to verify which batch thread is been used to // run this step or partition logger.info("About to read item, job.timeout: " + timeout); transactedService.query(timeout); return null; } }
1,876
34.415094
82
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/transaction/BatchTransactionTimeoutTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.batch.transaction; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.URL; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import jakarta.batch.runtime.JobExecution; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.batch.common.AbstractBatchTestCase; import org.jboss.as.test.integration.batch.common.JobExecutionMarshaller; import org.jboss.as.test.integration.batch.common.StartBatchServlet; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Test for JBERET-231/JBEAP-4811. * When a batch job fails due to transaction timeout, another job should be able to run on the same thread. * <p> * {@link ThreadBatchSetup} configures jberet to have {@code max-threads} 3. * The test job, {@code timeout-job.xml}, contains a step with 2 partitions. * The test starts the job twice: first with a {@code job.timeout} value to trigger transaction timeout * and job execution failure; second time without causing transaction timeout. * <p> * The first job execution is expected to fail due to transaction timeout. * The second job execution should complete successfully. */ @RunWith(Arquillian.class) @ServerSetup(ThreadBatchSetup.class) public class BatchTransactionTimeoutTestCase extends AbstractBatchTestCase { @Deployment public static WebArchive createDeployment() { return createDefaultWar("batch-transaction-timeout.war", BatchTransactionTimeoutTestCase.class.getPackage(), "timeout-job.xml") .addPackage(BatchTransactionTimeoutTestCase.class.getPackage()) .addAsResource("org/jboss/as/test/integration/batch/transaction/persistence.xml", "META-INF/persistence.xml"); } @RunAsClient @Test public void testThreadIsAvailableForNextJob(@ArquillianResource final URL url) throws Exception { assertEquals("FAILED", executeJobWithTimeout(url)); assertEquals("COMPLETED", executeJobWithoutTimout(url)); } private String executeJobWithTimeout(@ArquillianResource URL url) throws ExecutionException, IOException, TimeoutException { return executeJob(url, 10000); } private String executeJobWithoutTimout(@ArquillianResource URL url) throws ExecutionException, IOException, TimeoutException { return executeJob(url, -1); } private String executeJob(@ArquillianResource URL url, int timeout) throws ExecutionException, IOException, TimeoutException { final UrlBuilder builder = UrlBuilder.of(url, "start"); builder.addParameter(StartBatchServlet.JOB_XML_PARAMETER, "timeout-job"); builder.addParameter("job.timeout", timeout); final String result = performCall(builder.build(), 20); final JobExecution jobExecution = JobExecutionMarshaller.unmarshall(result); return jobExecution.getExitStatus(); } }
4,246
43.705263
135
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/batch/transaction/ThreadBatchSetup.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.batch.transaction; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import java.io.IOException; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.ManagementOperations; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; class ThreadBatchSetup extends SnapshotRestoreSetupTask { @Override public void doSetup(ManagementClient managementClient, String containerId) throws Exception { setThreadSize(managementClient, 3); } private void setThreadSize(ManagementClient managementClient, int threadCount) throws IOException, MgmtOperationException { ModelNode op = new ModelNode(); op.get(OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(OP_ADDR).add(SUBSYSTEM, "batch-jberet"); op.get(OP_ADDR).add("thread-pool", "batch"); op.get(NAME).set("max-threads"); op.get(VALUE).set(threadCount); ManagementOperations.executeOperation(managementClient.getControllerClient(), op); ServerReload.executeReloadAndWaitForCompletion(managementClient); } }
2,787
44.704918
127
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/security/DeserializationBlockListTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.messaging.security; import static org.jboss.as.test.integration.messaging.security.DeserializationMessagingBean.BLACK_LIST_CF_LOOKUP; import static org.jboss.as.test.integration.messaging.security.DeserializationMessagingBean.BLACK_LIST_REGULAR_CF_LOOKUP; import static org.jboss.as.test.integration.messaging.security.DeserializationMessagingBean.WHITE_LIST_CF_LOOKUP; import static org.jboss.shrinkwrap.api.ArchivePaths.create; import java.util.Date; import java.util.UUID; import jakarta.ejb.EJB; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ @RunWith(Arquillian.class) @ServerSetup(DeserializationBlockListTestCase.SetupTask.class) public class DeserializationBlockListTestCase { static class SetupTask implements ServerSetupTask { private static final String CF_NAME = "myBlockListCF"; @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { managementClient.getControllerClient().execute(Operations.createWriteAttributeOperation(new ModelNode().add("subsystem", "ee"), "annotation-property-replacement", true)); JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); ModelNode attributes = new ModelNode(); if (ops.isRemoteBroker()) { attributes.get("connectors").add("artemis"); } else { attributes.get("connectors").add("in-vm"); } attributes.get("deserialization-block-list").add(new ModelNode("*")); ops.addJmsConnectionFactory(CF_NAME, BLACK_LIST_REGULAR_CF_LOOKUP, attributes); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); ops.removeJmsConnectionFactory(CF_NAME); managementClient.getControllerClient().execute(Operations.createWriteAttributeOperation(new ModelNode().add("subsystem", "ee"), "annotation-property-replacement", ops.isRemoteBroker())); } } @Deployment public static JavaArchive createArchive() { JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "DeserializationBlockListTestCase.jar") .addClass(DeserializationMessagingBean.class) .addAsManifestResource( EmptyAsset.INSTANCE, create("beans.xml")); return archive; } @EJB private DeserializationMessagingBean bean; @Test public void testDeserializationBlockList() throws NamingException { // UUID is block listed, any other Serializable must be deserialized. UUID uuid = UUID.randomUUID(); Date date = new Date(); bean.send(uuid); bean.receive(uuid, BLACK_LIST_CF_LOOKUP,true); bean.send(date); bean.receive(date, BLACK_LIST_CF_LOOKUP,false); } @Test public void testDeserializationBlockListFromRegularConnectionFactory() throws NamingException { // all classes are block listed UUID uuid = UUID.randomUUID(); Date date = new Date(); bean.send(uuid); bean.receive(uuid, BLACK_LIST_REGULAR_CF_LOOKUP,true); bean.send(date); bean.receive(date, BLACK_LIST_REGULAR_CF_LOOKUP,true); } @Test public void testDeserializationAllowList() throws NamingException { // UUID is allow listed, any other Serializable must not be deserialized. UUID uuid = UUID.randomUUID(); Date date = new Date(); bean.send(uuid); bean.receive(uuid, WHITE_LIST_CF_LOOKUP,false); bean.send(date); bean.receive(date, WHITE_LIST_CF_LOOKUP,true); } }
5,640
40.785185
198
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/security/DeserializationMessagingBean.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.messaging.security; import org.jboss.logging.Logger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.Serializable; import jakarta.annotation.Resource; import jakarta.ejb.Stateless; import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSConnectionFactoryDefinition; import jakarta.jms.JMSConnectionFactoryDefinitions; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSDestinationDefinition; import jakarta.jms.JMSException; import jakarta.jms.Message; import jakarta.jms.ObjectMessage; import jakarta.jms.Queue; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2013 Red Hat inc. */ @JMSDestinationDefinition( name="java:comp/env/myQueue", interfaceName="jakarta.jms.Queue" ) @JMSConnectionFactoryDefinitions( value = { @JMSConnectionFactoryDefinition( name = "java:comp/env/myBlockListCF", interfaceName = "jakarta.jms.QueueConnectionFactory", properties = { "connectors=${org.jboss.messaging.default-connector:in-vm}", "deserialization-black-list=java.util.UUID" }), @JMSConnectionFactoryDefinition( name = "java:comp/env/myAllowListCF", interfaceName = "jakarta.jms.QueueConnectionFactory", properties = { "connectors=${org.jboss.messaging.default-connector:in-vm}", "deserialization-white-list=java.util.UUID" } ) }) @Stateless public class DeserializationMessagingBean { public static final String BLACK_LIST_CF_LOOKUP = "java:comp/env/myBlockListCF"; public static final String WHITE_LIST_CF_LOOKUP = "java:comp/env/myAllowListCF"; public static final String BLACK_LIST_REGULAR_CF_LOOKUP = "java:/jms/myBlockListCF"; static final Logger log = Logger.getLogger(DeserializationMessagingBean.class); @Resource(lookup = "java:comp/env/myQueue") private Queue queue; public void send(Serializable serializable) throws NamingException { assertNotNull(queue); Context namingContext = new InitialContext(); ConnectionFactory cf = (ConnectionFactory) namingContext.lookup(BLACK_LIST_CF_LOOKUP); assertNotNull(cf); try (JMSContext context = cf.createContext(JMSContext.AUTO_ACKNOWLEDGE)) { context.createProducer().send(queue, serializable); } } public void receive(Serializable serializable, String cfLookup, boolean consumeMustFail) throws NamingException { assertNotNull(queue); Context namingContext = new InitialContext(); ConnectionFactory cf = (ConnectionFactory) namingContext.lookup(cfLookup); try ( JMSContext context = cf.createContext(JMSContext.AUTO_ACKNOWLEDGE)) { JMSConsumer consumer = context.createConsumer(queue); try { Message response = consumer.receive(1000); assertNotNull(response); assertTrue(response instanceof ObjectMessage); Serializable o = ((ObjectMessage)response).getObject(); if (consumeMustFail) { fail(o + " must not be deserialized when message is consumed"); } else { assertEquals(serializable, o); } } catch (JMSException e) { if (consumeMustFail) { log.trace("Expected JMSException", e); } else { log.error("Unexpected exception", e); fail(serializable + " is allowed to be deserialized when message is consumed"); } } } } }
5,196
39.286822
117
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/security/SecurityTestCase.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.messaging.security; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.HashMap; import java.util.Map; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.ActiveMQExceptionType; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; 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.junit.Test; import org.junit.runner.RunWith; /** * Tests the security integration for HornetQ * * @author Justin Bertram (c) 2011 Red Hat Inc. */ @RunAsClient @RunWith(Arquillian.class) public class SecurityTestCase { @ContainerResource private ManagementClient managementClient; @Test public void testFailedAuthenticationBadUserPass() throws Exception { final ClientSessionFactory sf = createClientSessionFactory(managementClient.getMgmtAddress(), managementClient.getWebUri().getPort()); try { sf.createSession("fail", "epicfail", false, true, true, false, 1); fail("must not allow to create a session with bad authentication"); } catch (ActiveMQException e) { assertEquals(ActiveMQExceptionType.SECURITY_EXCEPTION, e.getType()); assertTrue(e.getMessage(), e.getMessage().startsWith("AMQ229031")); } finally { if (sf != null) { sf.close(); } } } @Test public void testFailedAuthenticationBlankUserPass() throws Exception { final ClientSessionFactory sf = createClientSessionFactory(managementClient.getMgmtAddress(), managementClient.getWebUri().getPort()); try { sf.createSession(); fail("must not allow to create a session without any authentication"); } catch (ActiveMQException e) { assertEquals(ActiveMQExceptionType.SECURITY_EXCEPTION, e.getType()); assertTrue(e.getMessage(), e.getMessage().startsWith("AMQ229031")); } finally { if (sf != null) { sf.close(); } } } @Test public void testDefaultClusterUser() throws Exception { final ClientSessionFactory sf = createClientSessionFactory(managementClient.getMgmtAddress(), managementClient.getWebUri().getPort()); try { sf.createSession(ActiveMQDefaultConfiguration.getDefaultClusterUser(), ActiveMQDefaultConfiguration.getDefaultClusterPassword(), false, true, true, false, 1); fail("must not allow to create a session with the default cluster user credentials"); } catch (ActiveMQException e) { assertEquals(ActiveMQExceptionType.CLUSTER_SECURITY_EXCEPTION, e.getType()); assertTrue(e.getMessage(), e.getMessage().startsWith("AMQ229099")); } finally { if (sf != null) { sf.close(); } } } @Test public void testSuccessfulAuthentication() throws Exception { final ClientSessionFactory sf = createClientSessionFactory(managementClient.getMgmtAddress(), managementClient.getWebUri().getPort()); ClientSession session = null; try { session = sf.createSession("guest", "guest", false, true, true, false, 1); assertNotNull(session); } finally { if (session != null) { session.close(); } } } @Test public void testSuccessfulAuthorization() throws Exception { final String queueName = "queue.testSuccessfulAuthorization"; final ClientSessionFactory sf = createClientSessionFactory(managementClient.getMgmtAddress(), managementClient.getWebUri().getPort()); ClientSession session = null; try { session = sf.createSession("guest", "guest", false, true, true, false, 1); session.createQueue(queueName, queueName, false); ClientConsumer messageConsumer = session.createConsumer(queueName); session.start(); session.stop(); messageConsumer.close(); session.deleteQueue(queueName); } finally { if (session != null) { session.close(); } } } @Test public void testUnsuccessfulAuthorization() throws Exception { final String queueName = "queue.testUnsuccessfulAuthorization"; final ClientSessionFactory sf = createClientSessionFactory(managementClient.getMgmtAddress(), managementClient.getWebUri().getPort()); ClientSession session = null; try { session = sf.createSession("guest", "guest", false, true, true, false, 1); session.createQueue(queueName, queueName, true); fail("Must not create a durable queue without the CREATE_DURABLE_QUEUE permission"); } catch (ActiveMQException e) { assertEquals(ActiveMQExceptionType.SECURITY_EXCEPTION, e.getType()); // Code of exception has changed in Artemis 2.x assertTrue(e.getMessage().startsWith("AMQ229213")); assertTrue(e.getMessage().contains("CREATE_DURABLE_QUEUE")); } finally { if (session != null) { session.close(); } } } static ClientSessionFactory createClientSessionFactory(String host, int port) throws Exception { final Map<String, Object> properties = new HashMap<String, Object>(); properties.put("host", host); properties.put("port", port); properties.put(TransportConstants.HTTP_UPGRADE_ENABLED_PROP_NAME, true); properties.put(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, "http-acceptor"); final TransportConfiguration configuration = new TransportConfiguration(NettyConnectorFactory.class.getName(), properties); return ActiveMQClient.createServerLocatorWithoutHA(configuration).createSessionFactory(); } }
7,764
42.623596
170
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/PrintDataTestCase.java
/* * Copyright 2020 JBoss by Red Hat. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.messaging.mgmt; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.jboss.as.test.shared.ServerReload.executeReloadAndWaitForCompletion; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.regex.Matcher; import java.util.regex.Pattern; import jakarta.jms.ConnectionFactory; import jakarta.jms.DeliveryMode; import jakarta.jms.Destination; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSException; import jakarta.jms.TextMessage; import javax.naming.Context; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.OperationMessageHandler; import org.jboss.as.controller.client.OperationResponse; import org.jboss.as.repository.PathUtil; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Emmanuel Hugonnet (c) 2020 Red Hat, Inc. */ @RunWith(Arquillian.class) @RunAsClient public class PrintDataTestCase { protected final String jmsQueueName = "PrintDataTestCase-Queue"; protected final String jmsQueueLookup = "jms/" + jmsQueueName; private static final Pattern ADDRESS_ID = Pattern.compile(";userRecordType=44;isUpdate=false;compactCount=0;" + "PersistentAddressBindingEncoding \\[id=([0-9]+), name=jms.queue.PrintDataTestCase-Queue, " + "routingTypes=\\{ANYCAST\\}, autoCreated=false\\]"); private static final Pattern QUEUE_ID = Pattern.compile("userRecordType=21;isUpdate=false;compactCount=0;PersistentQueueBindingEncoding " + "\\[id=([0-9]+), name=jms.queue.PrintDataTestCase-Queue, address=jms.queue.PrintDataTestCase-Queue, filterString=null, " + "user=null, autoCreated=false, maxConsumers=-1, purgeOnNoConsumers=false, enabled=true, exclusive=false, lastValue=false," + " lastValueKey=null, nonDestructive=false, consumersBeforeDispatch=0, delayBeforeDispatch=-1, routingType=1, " + "configurationManaged=false, groupRebalance=false, groupRebalancePauseDispatch=false, groupBuckets=-1, groupFirstKey=null, " + "autoDelete=false, autoDeleteDelay=0, autoDeleteMessageCount=0\\]"); private static final Pattern SAFE_QUEUE_COUNT = Pattern.compile("queue id [0-9]+,count=1"); @ContainerResource private Context remoteContext; @ContainerResource private ManagementClient managementClient; private Path dataPath; protected static void sendMessage(Context ctx, String destinationLookup, String text) throws NamingException, JMSException { ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory"); assertNotNull(cf); Destination destination = (Destination) ctx.lookup(destinationLookup); assertNotNull(destination); try (JMSContext context = cf.createContext("guest", "guest", JMSContext.AUTO_ACKNOWLEDGE)) { TextMessage message = context.createTextMessage(text); message.setJMSDeliveryMode(DeliveryMode.PERSISTENT); context.createProducer().send(destination, message); } } protected static void receiveMessage(Context ctx, String destinationLookup, boolean expectReceivedMessage, String expectedText) throws NamingException { ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory"); assertNotNull(cf); Destination destination = (Destination) ctx.lookup(destinationLookup); assertNotNull(destination); try (JMSContext context = cf.createContext("guest", "guest")) { JMSConsumer consumer = context.createConsumer(destination); String text = consumer.receiveBody(String.class, TimeoutUtil.adjust(5000)); if (expectReceivedMessage) { assertNotNull(text); assertEquals(expectedText, text); } else { assertNull("should not have received any message", text); } } } protected static ModelNode execute(ModelControllerClient client, ModelNode operation) throws Exception { ModelNode response = client.execute(operation); boolean success = SUCCESS.equals(response.get(OUTCOME).asString()); if (success) { return response.get(RESULT); } throw new Exception("Operation failed"); } @Before public void setUp() { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); jmsOperations.createJmsQueue(jmsQueueName, "java:jboss/exported/" + jmsQueueLookup); jmsOperations.close(); } @After public void tearDown() throws IOException { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); jmsOperations.removeJmsQueue(jmsQueueName); jmsOperations.close(); executeReloadAndWaitForCompletion(managementClient, false); Files.deleteIfExists(dataPath); } /** * Test that: * - send a message to a queue. * - put the server in admin mode. * - print the journal. * - checks that data are correctly printed. * - checks that sensitive data are printed. * @throws Exception */ @Test public void testPrintFullData() throws Exception { prepareQueue(); // reload in admin-only mode executeReloadAndWaitForCompletion(managementClient, true); // export the journal (must be performed in admin-only mode) dataPath = new File("print-data.txt").toPath(); Files.deleteIfExists(dataPath); printData(dataPath, false, false); String addressId = null; String queueId = null; boolean inMessages = false; boolean hasQueueCount = false; for (String line : Files.readAllLines(dataPath)) { if (addressId == null) { Matcher addressMatcher = ADDRESS_ID.matcher(line); if (addressMatcher.find()) { addressId = addressMatcher.group(1); } } else { if (queueId == null) { Matcher queueMatcher = QUEUE_ID.matcher(line); if (queueMatcher.find()) { queueId = queueMatcher.group(1); } } else { if (!inMessages) { inMessages = "M E S S A G E S J O U R N A L".equals(line); } else { if (!hasQueueCount) { hasQueueCount = ("queue id " + queueId + ",count=1").equals(line); } } } } } Assert.assertNotNull("Address Id not found", addressId); Assert.assertNotNull("Queue Id not found", queueId); Assert.assertTrue("Should have a message count of 1 for " + jmsQueueName, hasQueueCount); } /** * Test that: * - send a message to a queue. * - put the server in admin mode. * - print the journal in safe mode. * - checks that data are correctly printed. * - checks that sensitive data are not printed. * @throws Exception */ @Test public void testPrintSafeData() throws Exception { prepareQueue(); // reload in admin-only mode executeReloadAndWaitForCompletion(managementClient, true); // export the journal (must be performed in admin-only mode) dataPath = new File("print-safe-data.txt").toPath(); Files.deleteIfExists(dataPath); printData(dataPath, true, false); checkSafeJournal(); } /** * Test that: * - send a message to a queue. * - put the server in admin mode. * - print the journal in safe mode and as an archive. * - unzip the result of the operation. * - checks that data are correctly printed. * - checks that sensitive data are not printed. * @throws Exception */ @Test public void testPrintSafeArchiveData() throws Exception { prepareQueue(); // reload in admin-only mode executeReloadAndWaitForCompletion(managementClient, true); // export the journal (must be performed in admin-only mode) Path zipaPath = new File("print-safe-data.zip").toPath().toAbsolutePath(); Files.deleteIfExists(zipaPath); printData(zipaPath, true, true); PathUtil.unzip(zipaPath, zipaPath.getParent()); dataPath = zipaPath.getParent().resolve("data-print-report.txt"); Files.deleteIfExists(zipaPath); checkSafeJournal(); } private void checkSafeJournal() throws IOException { boolean inMessages = false; boolean hasQueueCount = false; String addressId = null; String queueId = null; for (String line : Files.readAllLines(dataPath)) { if (addressId == null) { Matcher addressMatcher = ADDRESS_ID.matcher(line); if (addressMatcher.find()) { addressId = addressMatcher.group(1); } } if (queueId == null) { Matcher queueMatcher = QUEUE_ID.matcher(line); if (queueMatcher.find()) { queueId = queueMatcher.group(1); } } if (!inMessages) { inMessages = "M E S S A G E S J O U R N A L".equals(line); } else { if (!hasQueueCount) { hasQueueCount = SAFE_QUEUE_COUNT.matcher(line).find(); } } } Assert.assertNull("Address Id found", addressId); Assert.assertNull("Queue Id found", queueId); Assert.assertTrue("Should have a message count of 1 for " + jmsQueueName, hasQueueCount); } private void prepareQueue() throws Exception { // send a persistent message removeAllMessagesFromQueue(jmsQueueName); String text = "print-safe-data"; sendMessage(remoteContext, jmsQueueLookup, text); Assert.assertEquals(1, countMessagesInQueue(jmsQueueName)); } private void removeAllMessagesFromQueue(String jmsQueueName) throws Exception { ModelNode removeAllMessagesOp = new ModelNode(); removeAllMessagesOp.get(OP_ADDR).add("subsystem", "messaging-activemq"); removeAllMessagesOp.get(OP_ADDR).add("server", "default"); removeAllMessagesOp.get(OP_ADDR).add("jms-queue", jmsQueueName); removeAllMessagesOp.get(OP).set("remove-messages"); execute(managementClient.getControllerClient(), removeAllMessagesOp); } private int countMessagesInQueue(String jmsQueueName) throws Exception { ModelNode removeAllMessagesOp = new ModelNode(); removeAllMessagesOp.get(OP_ADDR).add("subsystem", "messaging-activemq"); removeAllMessagesOp.get(OP_ADDR).add("server", "default"); removeAllMessagesOp.get(OP_ADDR).add("jms-queue", jmsQueueName); removeAllMessagesOp.get(OP).set("count-messages"); return execute(managementClient.getControllerClient(), removeAllMessagesOp).asInt(); } private void printData(Path file, boolean secret, boolean archive) throws Exception { ModelNode printDataOp = new ModelNode(); printDataOp.get(OP_ADDR).add("subsystem", "messaging-activemq"); printDataOp.get(OP_ADDR).add("server", "default"); printDataOp.get(OP).set("print-data"); printDataOp.get("secret").set(secret); printDataOp.get("archive").set(archive); OperationResponse response = managementClient.getControllerClient().executeOperation(Operation.Factory.create(printDataOp), OperationMessageHandler.logging); ModelNode result = response.getResponseNode(); System.out.println("result = " + result); boolean success = SUCCESS.equals(result.get(OUTCOME).asString()); if (success) { String uuid = result.get(RESULT).get("uuid").asString(); try (InputStream in = response.getInputStream(uuid).getStream()) { Files.copy(in, file); } } else { throw new Exception("Operation failed " + result.get(FAILURE_DESCRIPTION)); } } }
14,234
42.53211
165
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/NetworkHealthTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.messaging.mgmt; import java.io.IOException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.cli.Util; import org.jboss.as.controller.client.helpers.Operations; import static org.jboss.as.controller.client.helpers.Operations.isSuccessfulOutcome; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Emmanuel Hugonnet (c) 2020 Red Hat, Inc. */ @RunWith(Arquillian.class) @RunAsClient public class NetworkHealthTestCase extends ContainerResourceMgmtTestBase { @ContainerResource private ManagementClient managementClient; @Test public void testNetworkHealthWrite() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); // <jms server address>/address-setting=jms.queue.foo:write-attribute(name=redelivery-delay,value=50) ModelNode op = Operations.createReadResourceOperation(jmsOperations.getServerAddress()); op.get("include-defaults").set(true); op.get("attributes-only").set(true); ModelNode server = executeOperation(op, true); Assert.assertFalse(server.hasDefined("network-check-list")); Assert.assertFalse(server.hasDefined("network-check-nic")); Assert.assertFalse(server.hasDefined("network-check-url-list")); Assert.assertEquals(5000L, server.get("network-check-period").asLong()); Assert.assertEquals(1000L, server.get("network-check-timeout").asLong()); Assert.assertEquals("ping -c 1 -t %d %s", server.get("network-check-ping-command").asString()); Assert.assertEquals("ping6 -c 1 %2$s", server.get("network-check-ping6-command").asString()); op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-list", TestSuiteEnvironment.getServerAddress()); executeOperationForSuccess(op); op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-nic", "lo"); executeOperationForSuccess(op); op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-url-list", TestSuiteEnvironment.getHttpAddress()); executeOperationForSuccess(op); op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-period", 10000L); executeOperationForSuccess(op); op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-timeout", 5000L); executeOperationForSuccess(op); op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-ping-command", "ping"); executeOperationForSuccess(op); op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "network-check-ping6-command", "ping6"); executeOperationForSuccess(op); ServerReload.executeReloadAndWaitForCompletion(managementClient); jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); op = Operations.createReadResourceOperation(jmsOperations.getServerAddress()); op.get("include-defaults").set(true); op.get("attributes-only").set(true); server = executeOperation(op, true); Assert.assertEquals(server.toJSONString(false), TestSuiteEnvironment.getHttpAddress(), server.get("network-check-list").asString()); Assert.assertEquals(server.toJSONString(false), "lo", server.get("network-check-nic").asString()); Assert.assertEquals(server.toJSONString(false), TestSuiteEnvironment.getHttpAddress(), server.get("network-check-url-list").asString()); Assert.assertEquals(server.toJSONString(false), 10000L, server.get("network-check-period").asLong()); Assert.assertEquals(server.toJSONString(false), 5000L, server.get("network-check-timeout").asLong()); Assert.assertEquals(server.toJSONString(false), "ping", server.get("network-check-ping-command").asString()); Assert.assertEquals(server.toJSONString(false), "ping6", server.get("network-check-ping6-command").asString()); op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-list"); executeOperationForSuccess(op); op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-nic"); executeOperationForSuccess(op); op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-url-list"); executeOperationForSuccess(op); op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-period"); executeOperationForSuccess(op); op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-timeout"); executeOperationForSuccess(op); op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-ping-command"); executeOperationForSuccess(op); op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "network-check-ping6-command"); executeOperationForSuccess(op); ServerReload.executeReloadAndWaitForCompletion(managementClient); } private void executeOperationForSuccess(ModelNode operation) throws IOException, MgmtOperationException { ModelNode result = executeOperation(operation, false); Assert.assertTrue(Util.getFailureDescription(result), isSuccessfulOutcome(result)); } }
7,278
59.658333
153
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/CriticalAnalyzerTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.messaging.mgmt; import java.io.IOException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.cli.Util; import org.jboss.as.controller.client.helpers.Operations; import static org.jboss.as.controller.client.helpers.Operations.isSuccessfulOutcome; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Emmanuel Hugonnet (c) 2020 Red Hat, Inc. */ @RunWith(Arquillian.class) @RunAsClient public class CriticalAnalyzerTestCase extends ContainerResourceMgmtTestBase { @ContainerResource private ManagementClient managementClient; @Test public void testCriticalAnalyzerWrite() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); ModelNode op = Operations.createReadResourceOperation(jmsOperations.getServerAddress()); op.get("include-defaults").set(true); op.get("attributes-only").set(true); ModelNode server = executeOperation(op, true); Assert.assertTrue(server.hasDefined("critical-analyzer-enabled")); Assert.assertTrue(server.get("critical-analyzer-enabled").asBoolean()); Assert.assertTrue(server.hasDefined("critical-analyzer-policy")); Assert.assertEquals("LOG", server.get("critical-analyzer-policy").asString()); Assert.assertTrue(server.hasDefined("critical-analyzer-timeout")); Assert.assertEquals(120000L, server.get("critical-analyzer-timeout").asLong()); Assert.assertTrue(server.hasDefined("critical-analyzer-check-period")); Assert.assertEquals(0L, server.get("critical-analyzer-check-period").asLong()); op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-enabled", ModelNode.FALSE); executeOperationForSuccess(op); op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-policy", new ModelNode("HALT")); executeOperationForSuccess(op); op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-timeout", new ModelNode(240000L)); executeOperationForSuccess(op); op = Operations.createWriteAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-check-period", new ModelNode(120000L)); executeOperationForSuccess(op); ServerReload.executeReloadAndWaitForCompletion(managementClient); jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); op = Operations.createReadResourceOperation(jmsOperations.getServerAddress()); op.get("include-defaults").set(true); op.get("attributes-only").set(true); server = executeOperation(op, true); Assert.assertTrue(server.hasDefined("critical-analyzer-enabled")); Assert.assertFalse(server.get("critical-analyzer-enabled").asBoolean()); Assert.assertTrue(server.hasDefined("critical-analyzer-policy")); Assert.assertEquals("HALT", server.get("critical-analyzer-policy").asString()); Assert.assertTrue(server.hasDefined("critical-analyzer-timeout")); Assert.assertEquals(240000L, server.get("critical-analyzer-timeout").asLong()); Assert.assertTrue(server.hasDefined("critical-analyzer-check-period")); Assert.assertEquals(120000L, server.get("critical-analyzer-check-period").asLong()); op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-enabled"); executeOperationForSuccess(op); op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-policy"); executeOperationForSuccess(op); op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-timeout"); executeOperationForSuccess(op); op = Operations.createUndefineAttributeOperation(jmsOperations.getServerAddress(), "critical-analyzer-check-period"); executeOperationForSuccess(op); ServerReload.executeReloadAndWaitForCompletion(managementClient); } private void executeOperationForSuccess(ModelNode operation) throws IOException, MgmtOperationException { ModelNode result = executeOperation(operation, false); Assert.assertTrue(Util.getFailureDescription(result), isSuccessfulOutcome(result)); } }
6,060
55.12037
146
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/PooledConnectionFactoryStatisticsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.messaging.mgmt; 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.READ_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STATISTICS_ENABLED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import static org.jboss.shrinkwrap.api.ArchivePaths.create; import static org.junit.Assert.assertEquals; import java.io.IOException; import javax.naming.Context; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.ServerSnapshot; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests the statistics for pooled-connection-factory. */ @RunAsClient @RunWith(Arquillian.class) public class PooledConnectionFactoryStatisticsTestCase { @ContainerResource private ManagementClient managementClient; @ContainerResource private Context context; @Deployment public static JavaArchive deploy() { return ShrinkWrap.create(JavaArchive.class, "PooledConnectionFactoryStatisticsTestCase.jar") .addClass(ConnectionHoldingBean.class) .addClass(RemoteConnectionHolding.class) .addAsManifestResource(EmptyAsset.INSTANCE, create("beans.xml")); } @Test public void testStatistics() throws Exception { try (AutoCloseable snapshot = ServerSnapshot.takeSnapshot(managementClient)){ checkStatisticsAreDisabled(); enableStatistics(); assertEquals(0, readStatistic("InUseCount")); RemoteConnectionHolding bean = (RemoteConnectionHolding) context.lookup("PooledConnectionFactoryStatisticsTestCase/ConnectionHoldingBean!org.jboss.as.test.integration.messaging.mgmt.RemoteConnectionHolding"); bean.createConnection(); assertEquals(1, readStatistic("InUseCount")); bean.closeConnection(); assertEquals(0, readStatistic("InUseCount")); } } ModelNode getPooledConnectionFactoryAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("server", "default"); address.add("pooled-connection-factory", "activemq-ra"); return address; } ModelNode getStatisticsAddress() { return getPooledConnectionFactoryAddress().add("statistics", "pool"); } private void checkStatisticsAreDisabled() throws IOException { ModelNode op = new ModelNode(); op.get(OP_ADDR).set(getStatisticsAddress()); op.get(OP).set(READ_RESOURCE_OPERATION); execute(op, false); } private void enableStatistics() throws IOException { ModelNode op = new ModelNode(); op.get(OP_ADDR).set(getPooledConnectionFactoryAddress()); op.get(OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(NAME).set(STATISTICS_ENABLED); op.get(VALUE).set(true); execute(op, true); ServerReload.executeReloadAndWaitForCompletion(managementClient); } private int readStatistic(String name) throws IOException { ModelNode op = new ModelNode(); op.get(OP_ADDR).set(getStatisticsAddress()); op.get(OP).set(READ_ATTRIBUTE_OPERATION); op.get(NAME).set(name); ModelNode result = execute(op, true); return result.asInt(); } private ModelNode execute(final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { assertEquals("success", outcome); return response.get("result"); } else { assertEquals("failed", outcome); return response.get("failure-description"); } } }
5,832
39.227586
220
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/JMSQueueManagementTestCase.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.messaging.mgmt; import static jakarta.jms.Session.AUTO_ACKNOWLEDGE; import static org.jboss.as.controller.operations.common.Util.getEmptyOperation; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.io.IOException; import java.io.StringReader; import jakarta.jms.Connection; import jakarta.jms.ConnectionFactory; import jakarta.jms.Message; import jakarta.jms.MessageConsumer; import jakarta.jms.MessageProducer; import jakarta.jms.Queue; import jakarta.jms.Session; import jakarta.json.Json; import jakarta.json.JsonObject; import jakarta.json.JsonReader; 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.operations.common.Util; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.logging.Logger; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests the management API for Jakarta Messaging queues. * * @author Brian Stansberry (c) 2011 Red Hat Inc. */ @RunAsClient() @RunWith(Arquillian.class) public class JMSQueueManagementTestCase { private static final Logger LOGGER = Logger.getLogger(JMSQueueManagementTestCase.class); private static final String EXPORTED_PREFIX = "java:jboss/exported/"; private static final long SAMPLE_PERIOD = 1001; private static long count = System.currentTimeMillis(); private static final long TIMEOUT = TimeoutUtil.adjust(5000); @ContainerResource private Context remoteContext; @ContainerResource private ManagementClient managementClient; private JMSOperations adminSupport; private Connection conn; private Queue queue; private Queue otherQueue; private Session session; private Connection consumerConn; private Session consumerSession; @Before public void addQueues() throws Exception { adminSupport = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); count++; adminSupport.createJmsQueue(getQueueName(), EXPORTED_PREFIX + getQueueJndiName()); adminSupport.createJmsQueue(getOtherQueueName(), EXPORTED_PREFIX + getOtherQueueJndiName()); ConnectionFactory cf = (ConnectionFactory) remoteContext.lookup("jms/RemoteConnectionFactory"); assertNotNull(cf); conn = cf.createConnection("guest", "guest"); conn.start(); queue = (Queue) remoteContext.lookup(getQueueJndiName()); otherQueue = (Queue) remoteContext.lookup(getOtherQueueJndiName()); session = conn.createSession(false, AUTO_ACKNOWLEDGE); } @After public void removeQueues() throws Exception { if (conn != null) { conn.stop(); } if (session != null) { session.close(); } if (conn != null) { conn.close(); } if (consumerConn != null) { consumerConn.stop(); } if (consumerSession != null) { consumerSession.close(); } if (consumerConn != null) { consumerConn.close(); } if (adminSupport != null) { adminSupport.removeJmsQueue(getQueueName()); adminSupport.removeJmsQueue(getOtherQueueName()); adminSupport.close(); } } private void enableStatistics(boolean enabled) throws IOException { if (enabled) { ModelNode enableStatistics = Util.getWriteAttributeOperation(adminSupport.getServerAddress(), "statistics-enabled", new ModelNode(enabled)); ModelNode accelerateSamplingPeriod = Util.getWriteAttributeOperation(adminSupport.getServerAddress(), "message-counter-sample-period", new ModelNode(SAMPLE_PERIOD)); execute(enableStatistics, true); execute(accelerateSamplingPeriod, true); } else { ModelNode undefineStatisticsEnabled = Util.getUndefineAttributeOperation(PathAddress.pathAddress(adminSupport.getServerAddress()), "statistics-enabled"); ModelNode undefineMessageCounterSamplePeriod = Util.getUndefineAttributeOperation(PathAddress.pathAddress(adminSupport.getServerAddress()), "message-counter-sample-period"); execute(undefineStatisticsEnabled, true); execute(undefineMessageCounterSamplePeriod, true); } } private static JsonObject fromString(String string) { try (JsonReader reader = Json.createReader(new StringReader(string))) { return reader.readObject(); } } @Test public void testListAndCountMessages() throws Exception { MessageProducer producer = session.createProducer(queue); Message message1 = session.createTextMessage("A"); producer.send(message1); Message message2 = session.createTextMessage("B"); producer.send(message2); listMessages(2); ModelNode result = execute(getQueueOperation("count-messages"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals("count-messages result " + result, 2, result.asInt()); } @Test public void testMessageCounters() throws Exception { try { enableStatistics(true); MessageProducer producer = session.createProducer(queue); producer.send(session.createTextMessage("A")); producer.send(session.createTextMessage("B")); // wait for 2 sample periods to let the counters be updated. checkMessageCounters(2, 2); ModelNode result = execute(getQueueOperation("list-message-counter-as-html"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); result = execute(getQueueOperation("list-message-counter-history-as-json"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); result = execute(getQueueOperation("list-message-counter-history-as-html"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); result = execute(getQueueOperation("reset-message-counter"), true); Assert.assertFalse(result.isDefined()); // check that the messageCountDelta has been reset to 0 after invoking "reset-message-counter" checkMessageCounters(2, 0); result = execute(getQueueOperation("list-message-counter-history-as-json"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); } finally { enableStatistics(false); } } /** * Given that message counters are sampled, we fetched them several time (with a period shorter than the sample period) * to make the test pass faster. */ private void checkMessageCounters(int expectedMessageCount, int expectedMessageCountDelta) throws Exception { long start = System.currentTimeMillis(); long now; JsonObject messageCounters; do { Thread.sleep((long) (SAMPLE_PERIOD / 2.0)); ModelNode result = execute(getQueueOperation("list-message-counter-as-json"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); messageCounters = fromString(result.asString()); int actualMessageCount = messageCounters.getInt("messageCount"); int actualMessageCountDelta = messageCounters.getInt("messageCountDelta"); if (actualMessageCount == expectedMessageCount && actualMessageCountDelta == expectedMessageCountDelta) { // got correct counters return; } now = System.currentTimeMillis(); } while (now - start < (2.0 * SAMPLE_PERIOD)); // after twice the sample period, the assertions must always be true Assert.assertEquals(messageCounters.toString(), expectedMessageCount, messageCounters.getInt("messageCount")); Assert.assertEquals(messageCounters.toString(), expectedMessageCountDelta, messageCounters.getInt("messageCountDelta")); } @Test public void testPauseAndResume() throws Exception { final ModelNode readAttr = getQueueOperation("read-attribute"); readAttr.get("name").set("paused"); ModelNode result = execute(readAttr, true); Assert.assertTrue(result.isDefined()); Assert.assertFalse(result.asBoolean()); result = execute(getQueueOperation("pause"), true); Assert.assertFalse(result.isDefined()); result = execute(readAttr, true); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.asBoolean()); result = execute(getQueueOperation("resume"), true); Assert.assertFalse(result.isDefined()); result = execute(readAttr, true); Assert.assertTrue(result.isDefined()); Assert.assertFalse(result.asBoolean()); } // @org.junit.Ignore("AS7-2480") @Test public void testMessageRemoval() throws Exception { MessageProducer producer = session.createProducer(queue); Message msgA = session.createTextMessage("A"); producer.send(msgA); producer.send(session.createTextMessage("B")); producer.send(session.createTextMessage("C")); final ModelNode op = getQueueOperation("remove-message"); op.get("message-id").set(msgA.getJMSMessageID()); ModelNode result = execute(op, true); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.asBoolean()); result = execute(getQueueOperation("count-messages"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(2, result.asInt()); result = execute(getQueueOperation("remove-messages"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(2, result.asInt()); result = execute(getQueueOperation("count-messages"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(0, result.asInt()); } // @org.junit.Ignore("AS7-2480") @Test public void testMessageMovement() throws Exception { MessageProducer producer = session.createProducer(queue); Message msgA = session.createTextMessage("A"); producer.send(msgA); producer.send(session.createTextMessage("B")); producer.send(session.createTextMessage("C")); ModelNode op = getQueueOperation("move-message"); op.get("message-id").set(msgA.getJMSMessageID()); op.get("other-queue-name").set(getOtherQueueName()); ModelNode result = execute(op, true); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.asBoolean()); result = execute(getQueueOperation("count-messages"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(2, result.asInt()); op = getQueueOperation("move-messages"); op.get("other-queue-name").set(getOtherQueueName()); result = execute(op, true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(2, result.asInt()); result = execute(getQueueOperation("count-messages"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(0, result.asInt()); } @Test public void testChangeMessagePriority() throws Exception { final int priority = 3; MessageProducer producer = session.createProducer(queue); producer.setPriority(priority); Message msgA = session.createTextMessage("A"); producer.send(msgA); String messageId = msgA.getJMSMessageID(); Message msgB = session.createTextMessage("B"); producer.send(msgB); Message msgC = session.createTextMessage("C"); producer.send(msgC); ModelNode result = listMessages(3); Assert.assertEquals(3, result.asInt()); for (ModelNode node : result.asList()) { Assert.assertEquals("Priority should be " + priority, priority, node.get("JMSPriority").asInt()); } int newPriority = 5; ModelNode op = getQueueOperation("change-message-priority"); op.get("message-id").set(messageId); op.get("new-priority").set(newPriority); result = execute(op, true); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.asBoolean()); result = listMessages(3); Assert.assertEquals("The expected messages are " + msgA + " "+ msgB + " "+ msgC + " and we got " + result, 3, result.asList().size()); boolean found = false; for (ModelNode node : result.asList()) { if (messageId.equals(node.get("JMSMessageID").asString())) { Assert.assertEquals("Message should have the new priority", newPriority, node.get("JMSPriority").asInt()); found = true; } else { Assert.assertEquals("Message should have the set priority", priority, node.get("JMSPriority").asInt()); } } Assert.assertTrue(found); op = getQueueOperation("change-messages-priority"); op.get("new-priority").set(newPriority); result = execute(op, true); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.asInt() > 1 && result.asInt() < 4); result = listMessages(3); Assert.assertEquals(3, result.asInt()); for (ModelNode node : result.asList()) { Assert.assertEquals("Message should have the new priority", newPriority, node.get("JMSPriority").asInt()); } } private ModelNode listMessages(int expectedSize) throws IOException, InterruptedException { final ModelNode listMessagesOperation = getQueueOperation("list-messages"); long end = System.currentTimeMillis() + TIMEOUT; boolean passed = false; ModelNode result = null; while (end > System.currentTimeMillis()) { result = execute(listMessagesOperation, true); Assert.assertTrue(result.isDefined()); passed = result.asList().size() == expectedSize; if (passed) { break; } Thread.sleep(100); } Assert.assertTrue("Here is what we got instead of the " + expectedSize + " messages " + result, passed); return result; } @Test public void testListConsumers() throws Exception { ConnectionFactory cf = (ConnectionFactory) remoteContext.lookup("jms/RemoteConnectionFactory"); consumerConn = cf.createConnection("guest", "guest"); consumerConn.start(); consumerSession = consumerConn.createSession(false, AUTO_ACKNOWLEDGE); ModelNode result = execute(getQueueOperation("list-consumers-as-json"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); } @Test public void testAddJndi() throws Exception { ModelNode op = getQueueOperation("add-jndi"); op.get("jndi-binding").set("queue/added" + count); ModelNode result = execute(op, true); Assert.assertFalse(result.isDefined()); op = getQueueOperation("read-attribute"); op.get("name").set("entries"); result = execute(op, true); Assert.assertTrue(result.isDefined()); for (ModelNode binding : result.asList()) { if (binding.asString().equals("queue/added" + count)) return; } fail("queue/added" + count + " was not found"); } @Test public void testRemoveJndi() throws Exception { String jndiName = "queue/added" + count; ModelNode op = getQueueOperation("add-jndi"); op.get("jndi-binding").set(jndiName); ModelNode result = execute(op, true); Assert.assertFalse(result.isDefined()); op = getQueueOperation("remove-jndi"); op.get("jndi-binding").set(jndiName); result = execute(op, true); Assert.assertFalse(result.isDefined()); op = getQueueOperation("read-attribute"); op.get("name").set("entries"); result = execute(op, true); Assert.assertTrue(result.isDefined()); for (ModelNode binding : result.asList()) { if (binding.asString().equals(jndiName)) { Assert.fail("found " + jndiName + " while it must be removed"); } } } @Test public void testRemoveLastJndi() throws Exception { ModelNode op = getQueueOperation("remove-jndi"); op.get("jndi-binding").set(EXPORTED_PREFIX + getQueueJndiName()); // removing the last jndi name must generate a failure execute(op, false); op = getQueueOperation("read-attribute"); op.get("name").set("entries"); ModelNode result = execute(op, true); Assert.assertTrue(result.isDefined()); for (ModelNode binding : result.asList()) { if (binding.asString().equals(EXPORTED_PREFIX + getQueueJndiName())) return; } Assert.fail(getQueueJndiName() + " was not found"); } private ModelNode getQueueOperation(String operationName) { final ModelNode address = adminSupport.getServerAddress().add("jms-queue", getQueueName()); return getEmptyOperation(operationName, address); } private ModelNode execute(final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { if (!"success".equals(outcome)) { LOGGER.trace(response); } Assert.assertEquals("success", outcome); return response.get("result"); } else { if ("success".equals(outcome)) { LOGGER.trace(response); } Assert.assertEquals("failed", outcome); return response.get("failure-description"); } } @Test public void removeJMSQueueRemovesAllMessages() throws Exception { MessageProducer producer = session.createProducer(queue); producer.send(session.createTextMessage("A")); MessageConsumer consumer = session.createConsumer(queue); ModelNode result = execute(getQueueOperation("count-messages"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(1, result.asInt()); // remove the queue adminSupport.removeJmsQueue(getQueueName()); // add the queue back adminSupport.createJmsQueue(getQueueName(), EXPORTED_PREFIX + getQueueJndiName()); result = execute(getQueueOperation("count-messages"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(0, result.asInt()); } private String getQueueName() { return getClass().getSimpleName() + count; } private String getQueueJndiName() { return "queue/" + getQueueName(); } private String getOtherQueueName() { return getClass().getSimpleName() + "other" + count; } private String getOtherQueueJndiName() { return "queue/" + getOtherQueueName(); } }
21,049
37.553114
185
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/AddressSettingsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.messaging.mgmt; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_DEFAULTS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_DESCRIPTION_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.Set; 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.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.dmr.ModelNode; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * @author Emanuel Muckenhuber */ @RunWith(Arquillian.class) @RunAsClient public class AddressSettingsTestCase extends ContainerResourceMgmtTestBase { private static final String ACTIVEMQ_ADDRESS = "activemq-address"; private static final String MESSAGE_COUNTER_HISTORY_DAY_LIMIT = "message-counter-history-day-limit"; private static final String RESOLVE_ADDRESS_SETTING = "resolve-address-setting"; private ModelNode defaultAddress; private ModelNode address; @ContainerResource private ManagementClient managementClient; private JMSOperations jmsOperations; @Before public void before() { jmsOperations = JMSOperationsProvider.getInstance(managementClient); defaultAddress = jmsOperations.getServerAddress().add("address-setting", "#"); address = jmsOperations.getServerAddress().add("address-setting", "jms.queue.foo"); } @Test public void testAddressSettingWrite() throws Exception { // <jms server address>/address-setting=jms.queue.foo:write-attribute(name=redelivery-delay,value=50) final ModelNode add = new ModelNode(); add.get(ModelDescriptionConstants.OP).set(ADD); add.get(ModelDescriptionConstants.OP_ADDR).set(address); executeOperation(add); final ModelNode update = new ModelNode(); update.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION); update.get(ModelDescriptionConstants.OP_ADDR).set(address); update.get(ModelDescriptionConstants.NAME).set("redistribution-delay"); update.get(ModelDescriptionConstants.VALUE).set(-1L); executeOperation(update); remove(address); } @Test public void testResolveAddressSettings() throws Exception { final ModelNode readResourceDescription = new ModelNode(); readResourceDescription.get(ModelDescriptionConstants.OP_ADDR).set(defaultAddress); readResourceDescription.get(ModelDescriptionConstants.OP).set(READ_RESOURCE_DESCRIPTION_OPERATION); final ModelNode description = executeOperation(readResourceDescription, true); Set<String> attributeNames = description.get(ATTRIBUTES).keys(); final ModelNode readResource = new ModelNode(); readResource.get(ModelDescriptionConstants.OP_ADDR).set(defaultAddress); readResource.get(ModelDescriptionConstants.OP).set(READ_RESOURCE_OPERATION); final ModelNode defaultAddressSetting = executeOperation(readResource); // there is no address-setting for the given address but // we can resolve its settings based on HornetQ hierarchical // repository of address setting. final ModelNode resolve = new ModelNode(); resolve.get(ModelDescriptionConstants.OP_ADDR).set(jmsOperations.getServerAddress()); resolve.get(ModelDescriptionConstants.OP).set(RESOLVE_ADDRESS_SETTING); resolve.get(ACTIVEMQ_ADDRESS).set("jms.queue.foo"); ModelNode result = executeOperation(resolve); for (String attributeName : attributeNames) { assertEquals("unexpected value for " + attributeName, defaultAddressSetting.get(attributeName), result.get(attributeName)); } } @Test public void testSpecificAddressSetting() throws Exception { // <jms server address>/address-setting=jms.queue.foo:add() final ModelNode add = new ModelNode(); add.get(ModelDescriptionConstants.OP).set(ADD); add.get(ModelDescriptionConstants.OP_ADDR).set(address); executeOperation(add); final ModelNode readResourceWithoutDefault = new ModelNode(); readResourceWithoutDefault.get(ModelDescriptionConstants.OP).set(READ_RESOURCE_OPERATION); readResourceWithoutDefault.get(ModelDescriptionConstants.OP_ADDR).set(address); readResourceWithoutDefault.get(INCLUDE_DEFAULTS).set(false); ModelNode result = executeOperation(readResourceWithoutDefault); // the resource has not defined the message-counter-history-day-limit attribute assertFalse(result.hasDefined(MESSAGE_COUNTER_HISTORY_DAY_LIMIT)); final ModelNode resolve = new ModelNode(); resolve.get(ModelDescriptionConstants.OP_ADDR).set(jmsOperations.getServerAddress()); resolve.get(ModelDescriptionConstants.OP).set(RESOLVE_ADDRESS_SETTING); resolve.get(ACTIVEMQ_ADDRESS).set("jms.queue.foo"); result = executeOperation(resolve); // inherit the message-counter-history-day-limit for the '#' address-setting assertEquals(10, result.get(MESSAGE_COUNTER_HISTORY_DAY_LIMIT).asInt()); remove(address); } }
6,979
46.162162
135
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/ExportImportJournalTestCase.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.mgmt; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.jboss.as.test.shared.ServerReload.executeReloadAndWaitForCompletion; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.io.File; import jakarta.jms.ConnectionFactory; import jakarta.jms.DeliveryMode; import jakarta.jms.Destination; import jakarta.jms.JMSConsumer; import jakarta.jms.JMSContext; import jakarta.jms.JMSException; import jakarta.jms.TextMessage; import javax.naming.Context; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc. */ @RunWith(Arquillian.class) @RunAsClient public class ExportImportJournalTestCase { protected final String jmsQueueName = "ExportImportJournalTestCase-Queue"; protected final String jmsQueueLookup = "jms/" + jmsQueueName; @ContainerResource private Context remoteContext; @ContainerResource private ManagementClient managementClient; protected static void sendMessage(Context ctx, String destinationLookup, String text) throws NamingException, JMSException { ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory"); assertNotNull(cf); Destination destination = (Destination) ctx.lookup(destinationLookup); assertNotNull(destination); try (JMSContext context = cf.createContext("guest", "guest")) { TextMessage message = context.createTextMessage(text); message.setJMSDeliveryMode(DeliveryMode.PERSISTENT); context.createProducer().send(destination, message); } } protected static void receiveMessage(Context ctx, String destinationLookup, boolean expectReceivedMessage, String expectedText) throws NamingException { ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory"); assertNotNull(cf); Destination destination = (Destination) ctx.lookup(destinationLookup); assertNotNull(destination); try (JMSContext context = cf.createContext("guest", "guest")) { JMSConsumer consumer = context.createConsumer(destination); String text = consumer.receiveBody(String.class, TimeoutUtil.adjust(5000)); if (expectReceivedMessage) { assertNotNull(text); assertEquals(expectedText, text); } else { assertNull("should not have received any message", text); } } } protected static ModelNode execute(ModelControllerClient client, ModelNode operation) throws Exception { //System.out.println("operation = " + operation); ModelNode response = client.execute(operation); //System.out.println("response = " + response); boolean success = SUCCESS.equals(response.get(OUTCOME).asString()); if (success) { return response.get(RESULT); } throw new Exception("Operation failed"); } @Before public void setUp() { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); jmsOperations.createJmsQueue(jmsQueueName, "java:jboss/exported/" + jmsQueueLookup); jmsOperations.close(); } @After public void tearDown() { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); jmsOperations.removeJmsQueue(jmsQueueName); jmsOperations.close(); } @Test public void testExportImportJournal() throws Exception { // send a persistent message String text = java.util.UUID.randomUUID().toString(); sendMessage(remoteContext, jmsQueueLookup, text); // reload in admin-only mode executeReloadAndWaitForCompletion(managementClient, true); // export the journal (must be performed in admin-only mode) String dumpFilePath = exportJournal(); // reload in normal mode executeReloadAndWaitForCompletion(managementClient, false); // remove all messages removeAllMessagesFromQueue(jmsQueueName); // no message to receive receiveMessage(remoteContext, jmsQueueLookup, false, null); // import the journal (must be performed in normal mode) importJournal(dumpFilePath); // check the message is received receiveMessage(remoteContext, jmsQueueLookup, true, text); // remove the dump file File f = new File(dumpFilePath); f.delete(); } private void removeAllMessagesFromQueue(String jmsQueueName) throws Exception { ModelNode removeAllMessagesOp = new ModelNode(); removeAllMessagesOp.get(OP_ADDR).add("subsystem", "messaging-activemq"); removeAllMessagesOp.get(OP_ADDR).add("server", "default"); removeAllMessagesOp.get(OP_ADDR).add("jms-queue", jmsQueueName); removeAllMessagesOp.get(OP).set("remove-messages"); execute(managementClient.getControllerClient(), removeAllMessagesOp); } private String exportJournal() throws Exception { ModelNode exportJournalOp = new ModelNode(); exportJournalOp.get(OP_ADDR).add("subsystem", "messaging-activemq"); exportJournalOp.get(OP_ADDR).add("server", "default"); exportJournalOp.get(OP).set("export-journal"); ModelNode result = execute(managementClient.getControllerClient(), exportJournalOp); //System.out.println("result = " + result); String dumpFilePath = result.asString(); return dumpFilePath; } private void importJournal(String dumpFilePath) throws Exception { ModelNode importJournalOp = new ModelNode(); importJournalOp.get(OP_ADDR).add("subsystem", "messaging-activemq"); importJournalOp.get(OP_ADDR).add("server", "default"); importJournalOp.get(OP).set("import-journal"); importJournalOp.get("file").set(dumpFilePath); execute(managementClient.getControllerClient(), importJournalOp); } }
8,184
39.925
157
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/CoreQueueManagementTestCase.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.messaging.mgmt; import static java.util.UUID.randomUUID; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE_RUNTIME; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.HashMap; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests the management API for Artemis core queues. * * @author Brian Stansberry (c) 2011 Red Hat Inc. */ @RunAsClient() @RunWith(Arquillian.class) public class CoreQueueManagementTestCase { private static long count = System.currentTimeMillis(); private static final long TIMEOUT = TimeoutUtil.adjust(5000); @ContainerResource private ManagementClient managementClient; private ClientSessionFactory sessionFactory; private ClientSession session; private ClientSession consumerSession; @Before public void setup() throws Exception { count++; HashMap<String, Object> map = new HashMap<String, Object>(); map.put("host", TestSuiteEnvironment.getServerAddress()); map.put("port", 8080); map.put(TransportConstants.HTTP_UPGRADE_ENABLED_PROP_NAME, true); map.put(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, "http-acceptor"); TransportConfiguration transportConfiguration = new TransportConfiguration(NettyConnectorFactory.class.getName(), map); ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(transportConfiguration); locator.setBlockOnDurableSend(true); locator.setBlockOnNonDurableSend(true); sessionFactory = locator.createSessionFactory(); session = sessionFactory.createSession("guest", "guest", false, true, true, false, 1); session.createQueue(getQueueName(), getQueueName(), false); session.createQueue(getOtherQueueName(), getOtherQueueName(), false); consumerSession = sessionFactory.createSession("guest", "guest", false, false, false, false, 1); } @After public void cleanup() throws Exception { if (consumerSession != null) { consumerSession.close(); } if (session != null) { session.deleteQueue(getQueueName()); session.deleteQueue(getOtherQueueName()); session.close(); } if (sessionFactory != null) { sessionFactory.cleanup(); sessionFactory.close(); } } @Test public void testReadResource() throws Exception { String address = randomUUID().toString(); String queueName = randomUUID().toString(); final ModelNode readQueueResourceOp = getQueueOperation("read-resource", queueName); final ModelNode readRuntimeQueueResourceOp = getRuntimeQueueOperation("read-resource", queueName); readRuntimeQueueResourceOp.get(INCLUDE_RUNTIME).set(true); // resource does not exist ModelNode result = execute(readQueueResourceOp, false); assertTrue(result.toJSONString(false), result.asString().contains("WFLYCTL0216")); result = execute(readRuntimeQueueResourceOp, false); assertTrue(result.toJSONString(false), result.asString().contains("WFLYCTL0216")); session.createQueue(address, queueName, false); // resource does not exist for core queue... result = execute(readQueueResourceOp, false); assertTrue(result.toJSONString(false), result.asString().contains("WFLYCTL0216")); // ... but it does for runtime-queue result = execute(readRuntimeQueueResourceOp, true); assertTrue(result.isDefined()); assertEquals(address, result.get("queue-address").asString()); session.deleteQueue(queueName); // resource no longer exists result = execute(readQueueResourceOp, false); assertTrue(result.toJSONString(false), result.asString().contains("WFLYCTL0216")); result = execute(readRuntimeQueueResourceOp, false); assertTrue(result.toJSONString(false), result.asString().contains("WFLYCTL0216")); } @Test public void testListAndCountMessages() throws Exception { ClientProducer producer = session.createProducer(getQueueName()); ClientMessage message1 = session.createMessage(ClientMessage.TEXT_TYPE, false); message1.putStringProperty("hope", "message1"); producer.send(message1); ClientMessage message2 = session.createMessage(ClientMessage.TEXT_TYPE, false); message2.putStringProperty("hope", "message2"); producer.send(message2); listMessages(2); ModelNode result = execute(getQueueOperation("count-messages"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(2, result.asInt()); } private ModelNode listMessages(int expectedSize) throws IOException, InterruptedException { final ModelNode listMessagesOperation = getQueueOperation("list-messages"); long end = System.currentTimeMillis() + TIMEOUT; boolean passed = false; ModelNode result = null; while (end > System.currentTimeMillis()) { result = execute(listMessagesOperation, true); Assert.assertTrue(result.isDefined()); passed = result.asList().size() == expectedSize; if (passed) { break; } Thread.sleep(100); } Assert.assertTrue("Here is what we got instead of the " + expectedSize + " messages " + result, passed); return result; } @Test public void testMessageCounters() throws Exception { ClientProducer producer = session.createProducer(getQueueName()); producer.send(session.createMessage(ClientMessage.TEXT_TYPE, false)); producer.send(session.createMessage(ClientMessage.TEXT_TYPE, false)); ModelNode result = execute(getQueueOperation("list-message-counter-as-json"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); result = execute(getQueueOperation("list-message-counter-as-html"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); result = execute(getQueueOperation("list-message-counter-history-as-json"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); result = execute(getQueueOperation("list-message-counter-history-as-html"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); result = execute(getQueueOperation("reset-message-counter"), true); Assert.assertFalse(result.isDefined()); result = execute(getQueueOperation("list-message-counter-history-as-json"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); } @Test public void testPauseAndResume() throws Exception { final ModelNode readAttr = getQueueOperation("read-attribute"); readAttr.get("name").set("paused"); ModelNode result = execute(readAttr, true); Assert.assertTrue(result.isDefined()); Assert.assertFalse(result.asBoolean()); result = execute(getQueueOperation("pause"), true); Assert.assertFalse(result.isDefined()); result = execute(readAttr, true); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.asBoolean()); result = execute(getQueueOperation("resume"), true); Assert.assertFalse(result.isDefined()); result = execute(readAttr, true); Assert.assertTrue(result.isDefined()); Assert.assertFalse(result.asBoolean()); } // @org.junit.Ignore("AS7-2480") @Test public void testMessageRemoval() throws Exception { ClientProducer producer = session.createProducer(getQueueName()); ClientMessage msgA = session.createMessage(ClientMessage.TEXT_TYPE, false); producer.send(msgA); producer.send(session.createMessage(ClientMessage.TEXT_TYPE, false)); producer.send(session.createMessage(ClientMessage.TEXT_TYPE, false)); final ModelNode op = getQueueOperation("remove-message"); op.get("message-id").set(findMessageID()); ModelNode result = execute(op, true); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.asBoolean()); result = execute(getQueueOperation("count-messages"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(2, result.asInt()); result = execute(getQueueOperation("remove-messages"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(2, result.asInt()); result = execute(getQueueOperation("count-messages"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(0, result.asInt()); } private long findMessageID() throws Exception { final ModelNode result = execute(getQueueOperation("list-messages"), true); return result.get(0).get("messageID").asLong(); } // @org.junit.Ignore("AS7-2480") @Test public void testMessageMovement() throws Exception { ClientProducer producer = session.createProducer(getQueueName()); ClientMessage msgA = session.createMessage(ClientMessage.TEXT_TYPE, false); producer.send(msgA); producer.send(session.createMessage(ClientMessage.TEXT_TYPE, false)); producer.send(session.createMessage(ClientMessage.TEXT_TYPE, false)); ModelNode op = getQueueOperation("move-message"); op.get("message-id").set(findMessageID()); op.get("other-queue-name").set(getOtherQueueName()); ModelNode result = execute(op, true); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.asBoolean()); result = execute(getQueueOperation("count-messages"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(2, result.asInt()); op = getQueueOperation("move-messages"); op.get("other-queue-name").set(getOtherQueueName()); result = execute(op, true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(2, result.asInt()); result = execute(getQueueOperation("count-messages"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(0, result.asInt()); } // @org.junit.Ignore("AS7-2480") @Test public void testChangeMessagePriority() throws Exception { final int priority = 3; ClientProducer producer = session.createProducer(getQueueName()); producer.send(session.createMessage(ClientMessage.TEXT_TYPE, false).setPriority((byte)priority)); long id = findMessageID(); producer.send(session.createMessage(ClientMessage.TEXT_TYPE, false).setPriority((byte)priority)); producer.send(session.createMessage(ClientMessage.TEXT_TYPE, false).setPriority((byte)priority)); ModelNode result = listMessages(3); for (ModelNode node : result.asList()) { Assert.assertEquals("Priority should be " + priority, priority, node.get("priority").asInt()); } int newPriority = 5; ModelNode op = getQueueOperation("change-message-priority"); op.get("message-id").set(id); op.get("new-priority").set(newPriority); result = execute(op, true); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.asBoolean()); result = listMessages(3); boolean found = false; for (ModelNode node : result.asList()) { if (id == node.get("messageID").asLong()) { Assert.assertEquals("Message should have the new priority", newPriority, node.get("priority").asInt()); found = true; } else { Assert.assertEquals("Message should have the set priority", priority, node.get("priority").asInt()); } } Assert.assertTrue("We should have found the updated message", found); op = getQueueOperation("change-messages-priority"); op.get("new-priority").set(newPriority); result = execute(op, true); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.asInt() > 1 && result.asInt() < 4); result = listMessages(3); for (ModelNode node : result.asList()) { Assert.assertEquals("Message should have the new priority", newPriority, node.get("priority").asInt()); } } @Test public void testListConsumers() throws Exception { consumerSession.createConsumer(getQueueName()); ModelNode result = execute(getQueueOperation("list-consumers-as-json"), true); Assert.assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); } private ModelNode getQueueOperation(String operationName, String queueName) { final ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("server", "default"); address.add("queue", queueName); return org.jboss.as.controller.operations.common.Util.getEmptyOperation(operationName, address); } private ModelNode getRuntimeQueueOperation(String operationName, String queueName) { final ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("server", "default"); address.add("runtime-queue", queueName); return org.jboss.as.controller.operations.common.Util.getEmptyOperation(operationName, address); } private ModelNode getQueueOperation(String operationName) { return getQueueOperation(operationName, getQueueName()); } private ModelNode execute(final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { Assert.assertEquals("success", outcome); return response.get("result"); } else { Assert.assertEquals("failed", outcome); return response.get("failure-description"); } } private String getQueueName() { return getClass().getSimpleName() + count; } private String getOtherQueueName() { return getClass().getSimpleName() + "other" + count; } }
16,872
39.756039
119
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/ExternalPooledConnectionFactoryStatisticsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.messaging.mgmt; 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_RESOURCE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STATISTICS_ENABLED; import static org.jboss.shrinkwrap.api.ArchivePaths.create; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.SocketPermission; import javax.naming.Context; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.PermissionUtils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests the statistics for pooled-connection-factory. */ @RunAsClient @RunWith(Arquillian.class) @ServerSetup({ExternalPooledConnectionFactoryStatisticsTestCase.SetupTask.class}) public class ExternalPooledConnectionFactoryStatisticsTestCase { static class SetupTask extends SnapshotRestoreSetupTask { private static final Logger logger = Logger.getLogger(ExternalPooledConnectionFactoryStatisticsTestCase.SetupTask.class); @Override public void doSetup(org.jboss.as.arquillian.container.ManagementClient managementClient, String s) throws Exception { ServerReload.executeReloadAndWaitForCompletion(managementClient, true); JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); ops.addExternalHttpConnector("http-test-connector", "http", "http-acceptor"); ModelNode attr = new ModelNode(); attr.get("connectors").add("http-test-connector"); ModelNode op = Operations.createRemoveOperation(getInitialPooledConnectionFactoryAddress()); execute(managementClient, op, true); op = Operations.createAddOperation(getPooledConnectionFactoryAddress()); op.get("transaction").set("xa"); op.get("entries").add("java:/JmsXA java:jboss/DefaultJMSConnectionFactory"); op.get("connectors").add("http-test-connector"); execute(managementClient, op, true); ServerReload.executeReloadAndWaitForCompletion(managementClient); } private ModelNode execute(final org.jboss.as.arquillian.container.ManagementClient managementClient, final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { assertEquals(response.toString(), "success", outcome); return response.get("result"); } else { assertEquals("failed", outcome); return response.get("failure-description"); } } ModelNode getPooledConnectionFactoryAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("pooled-connection-factory", "activemq-ra"); return address; } ModelNode getInitialPooledConnectionFactoryAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("server", "default"); address.add("pooled-connection-factory", "activemq-ra"); return address; } } @ContainerResource private ManagementClient managementClient; @ContainerResource private Context context; @Deployment public static JavaArchive deploy() { return ShrinkWrap.create(JavaArchive.class, "PooledConnectionFactoryStatisticsTestCase.jar") .addClass(ConnectionHoldingBean.class) .addClass(RemoteConnectionHolding.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( new SocketPermission("localhost", "resolve")), "permissions.xml") .addAsManifestResource(EmptyAsset.INSTANCE, create("beans.xml")); } @Test public void testStatistics() throws Exception { checkStatisticsAreDisabled(); enableStatistics(); assertEquals(0, readStatistic("InUseCount")); RemoteConnectionHolding bean = (RemoteConnectionHolding) context.lookup("PooledConnectionFactoryStatisticsTestCase/ConnectionHoldingBean!org.jboss.as.test.integration.messaging.mgmt.RemoteConnectionHolding"); bean.createConnection(); assertEquals(1, readStatistic("InUseCount")); bean.closeConnection(); assertEquals(0, readStatistic("InUseCount")); } ModelNode getPooledConnectionFactoryAddress() { ModelNode address = new ModelNode(); address.add("subsystem", "messaging-activemq"); address.add("pooled-connection-factory", "activemq-ra"); return address; } ModelNode getStatisticsAddress() { return getPooledConnectionFactoryAddress().add("statistics", "pool"); } private void checkStatisticsAreDisabled() throws IOException { ModelNode op = new ModelNode(); op.get(OP_ADDR).set(getStatisticsAddress()); op.get(OP).set(READ_RESOURCE_OPERATION); execute(op, false); } private void enableStatistics() throws IOException { ModelNode op = Operations.createWriteAttributeOperation(getPooledConnectionFactoryAddress(), STATISTICS_ENABLED, true); execute(op, true); ServerReload.executeReloadAndWaitForCompletion(managementClient); } private int readStatistic(String name) throws IOException { ModelNode op = Operations.createReadAttributeOperation(getStatisticsAddress(), name); ModelNode result = execute(op, true); return result.asInt(); } private ModelNode execute(final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { assertEquals("success", outcome); return response.get("result"); } else { assertEquals("failed", outcome); return response.get("failure-description"); } } }
8,301
43.395722
220
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/ConnectionFactoryManagementTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.messaging.mgmt; import static java.util.UUID.randomUUID; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLED_BACK; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c)2012 Red Hat, inc * * https://issues.jboss.org/browse/AS7-5107 */ @RunWith(Arquillian.class) @RunAsClient public class ConnectionFactoryManagementTestCase extends ContainerResourceMgmtTestBase { private static final String CF_NAME = randomUUID().toString(); @ContainerResource private ManagementClient managementClient; @Test public void testWriteDiscoveryGroupAttributeWhenConnectorIsAlreadyDefined() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); ModelNode attributes = new ModelNode(); attributes.get("connectors").add("in-vm"); jmsOperations.addJmsConnectionFactory(CF_NAME, "java:/jms/" + CF_NAME, attributes); final ModelNode writeAttribute = new ModelNode(); writeAttribute.get(OP).set(WRITE_ATTRIBUTE_OPERATION); writeAttribute.get(OP_ADDR).set(jmsOperations.getServerAddress().add("connection-factory", CF_NAME)); writeAttribute.get(NAME).set("discovery-group"); writeAttribute.get(VALUE).set(randomUUID().toString()); try { executeOperation(writeAttribute); fail("it is not possible to define a discovery group when the connector attribute is already defined"); } catch (MgmtOperationException e) { assertEquals(FAILED, e.getResult().get(OUTCOME).asString()); assertEquals(true, e.getResult().get(ROLLED_BACK).asBoolean()); assertTrue(e.getResult().get(FAILURE_DESCRIPTION).asString().contains("WFLYCTL0105")); } jmsOperations.removeJmsConnectionFactory(CF_NAME); ServerReload.executeReloadAndWaitForCompletion(managementClient); } @Test public void testRemoveReferencedConnector() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); ModelNode address = jmsOperations.getServerAddress().add("in-vm-connector", "in-vm-test"); ModelNode addOp = Operations.createAddOperation(address); addOp.get("server-id").set(0); ModelNode params = addOp.get("params").setEmptyList(); params.add("buffer-pooling", ModelNode.FALSE); managementClient.getControllerClient().execute(addOp); ModelNode attributes = new ModelNode(); attributes.get("connectors").add("in-vm-test"); jmsOperations.addJmsConnectionFactory(CF_NAME, "java:/jms/" + CF_NAME, attributes); try { execute(managementClient.getControllerClient(), Operations.createRemoveOperation(address)); fail("it is not possible to remove a connector when it is referenced from a connection factory"); } catch (Exception e) { assertTrue(e.getMessage(), e.getMessage().contains("WFLYCTL0367")); } finally { jmsOperations.removeJmsConnectionFactory(CF_NAME); managementClient.getControllerClient().execute( Operations.createRemoveOperation(address)); } ServerReload.executeReloadAndWaitForCompletion(managementClient); } private static ModelNode execute(ModelControllerClient client, ModelNode operation) throws Exception { //System.out.println("operation = " + operation); ModelNode response = client.execute(operation); //System.out.println("response = " + response); boolean success = SUCCESS.equals(response.get(OUTCOME).asString()); if (success) { return response.get(RESULT); } throw new Exception(response.get(FAILURE_DESCRIPTION).asString()); } }
6,671
49.545455
115
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/ExternalConnectionFactoryClientMappingTestCase.java
/* * Copyright 2017 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.messaging.mgmt; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.annotation.Resource; import jakarta.jms.ConnectionFactory; import java.io.IOException; import java.util.Map; import static org.jboss.as.controller.client.helpers.ClientConstants.*; 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.WRITE_ATTRIBUTE_OPERATION; import static org.junit.Assert.assertEquals; /** * Created by spyrkob on 18/05/2017. */ @RunWith(Arquillian.class) @ServerSetup({ExternalConnectionFactoryClientMappingTestCase.SetupTask.class}) public class ExternalConnectionFactoryClientMappingTestCase { private static final String CONNECTION_FACTORY_JNDI_NAME = "java:jboss/exported/jms/TestConnectionFactory"; static class SetupTask extends SnapshotRestoreSetupTask { private static final Logger logger = Logger.getLogger(ExternalConnectionFactoryClientMappingTestCase.SetupTask.class); @Override public void doSetup(org.jboss.as.arquillian.container.ManagementClient managementClient, String s) throws Exception { JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); addSocketBinding(managementClient, "test-binding", clientMapping("test", "8000")); ops.addExternalHttpConnector("http-test-connector", "test-binding", "http-acceptor"); ModelNode attr = new ModelNode(); attr.get("connectors").add("http-test-connector"); ops.addJmsExternalConnectionFactory("TestConnectionFactory", CONNECTION_FACTORY_JNDI_NAME, attr); ServerReload.executeReloadAndWaitForCompletion(managementClient); } private ModelNode clientMapping(String destAddr, String destPort) { ModelNode clientMapping = new ModelNode(); clientMapping.get("destination-address").set(destAddr); clientMapping.get("destination-port").set(destPort); return clientMapping; } private void addSocketBinding(ManagementClient managementClient, String bindingName, ModelNode clientMapping) throws Exception { ModelNode address = new ModelNode(); address.add("socket-binding-group", "standard-sockets"); address.add("socket-binding", bindingName); ModelNode socketBindingOp = new ModelNode(); socketBindingOp.get(OP).set(ADD); socketBindingOp.get(OP_ADDR).set(address); execute(managementClient, socketBindingOp); ModelNode clientMappingOp = new ModelNode(); clientMappingOp.get(OP).set(WRITE_ATTRIBUTE_OPERATION); clientMappingOp.get(OP_ADDR).set(address); clientMappingOp.get(NAME).set("client-mappings"); clientMappingOp.get(VALUE).add(clientMapping); execute(managementClient, clientMappingOp); } static void execute(ManagementClient managementClient, final ModelNode operation) throws IOException { ModelNode result = managementClient.getControllerClient().execute(operation); if (result.hasDefined(ClientConstants.OUTCOME) && ClientConstants.SUCCESS.equals(result.get(ClientConstants.OUTCOME).asString())) { logger.trace("Operation successful for update = " + operation.toString()); } else if (result.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) { final String failureDesc = result.get(ClientConstants.FAILURE_DESCRIPTION).toString(); throw new RuntimeException(failureDesc); } else { throw new RuntimeException("Operation not successful; outcome = " + result.get(ClientConstants.OUTCOME)); } } } @Deployment(testable = true) public static JavaArchive createDeployment() { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "test.jar"); jar.addClass(ExternalConnectionFactoryClientMappingTestCase.class); jar.add(EmptyAsset.INSTANCE, "META-INF/beans.xml"); jar.add(new StringAsset( "<jboss-deployment-structure>\n" + " <deployment>\n" + " <dependencies>\n" + " <module name=\"org.apache.activemq.artemis\"/>\n" + " </dependencies>\n" + " </deployment>\n" + "</jboss-deployment-structure>"), "META-INF/jboss-deployment-structure.xml"); return jar; } @Resource(lookup = "java:jboss/exported/jms/TestConnectionFactory") private ConnectionFactory connectionFactory; @Test public void testClientMappingInConnectionFactory() throws Exception { Map<String, Object> params = ((ActiveMQJMSConnectionFactory) connectionFactory).getStaticConnectors()[0].getParams(); params.forEach((s, o) -> System.out.println(s + ": " + o)); assertEquals("test", params.get(TransportConstants.HOST_PROP_NAME)); assertEquals(8000, params.get(TransportConstants.PORT_PROP_NAME)); } }
6,829
46.430556
143
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/JMSTopicManagementTestCase.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.messaging.mgmt; import static jakarta.jms.Session.AUTO_ACKNOWLEDGE; import static org.jboss.as.controller.client.helpers.ClientConstants.NAME; import static org.jboss.as.controller.client.helpers.ClientConstants.VALUE; import static org.jboss.as.controller.client.helpers.ClientConstants.WRITE_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.operations.common.Util.getEmptyOperation; import static org.junit.Assert.assertTrue; import java.io.IOException; import jakarta.jms.Connection; import jakarta.jms.ConnectionFactory; import jakarta.jms.MessageProducer; import jakarta.jms.Session; import jakarta.jms.TextMessage; import jakarta.jms.Topic; import jakarta.jms.TopicSubscriber; import javax.naming.Context; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests the management API for Jakarta Messaging topics. * * @author Brian Stansberry (c) 2011 Red Hat Inc. */ @RunAsClient() @RunWith(Arquillian.class) public class JMSTopicManagementTestCase { private static final String EXPORTED_PREFIX = "java:jboss/exported/"; private static long count = System.currentTimeMillis(); private ConnectionFactory cf; @ContainerResource private ManagementClient managementClient; @ContainerResource private Context remoteContext; private JMSOperations adminSupport; private Connection conn; private Topic topic; private Session session; private Connection consumerConn; private Session consumerSession; @Before public void before() throws Exception { cf = (ConnectionFactory) remoteContext.lookup("jms/RemoteConnectionFactory"); adminSupport = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); count++; adminSupport.createJmsTopic(getTopicName(), EXPORTED_PREFIX + getTopicJndiName()); topic = (Topic) remoteContext.lookup(getTopicJndiName()); conn = cf.createConnection("guest", "guest"); conn.setClientID("sender"); conn.start(); session = conn.createSession(false, AUTO_ACKNOWLEDGE); consumerConn = cf.createConnection("guest", "guest"); consumerConn.setClientID("consumer"); consumerConn.start(); consumerSession = consumerConn.createSession(false, AUTO_ACKNOWLEDGE); addSecuritySettings(); } private void addSecuritySettings() throws Exception { // <jms server address>/security-setting=#/role=guest:write-attribute(name=create-durable-queue, value=TRUE) ModelNode address = adminSupport.getServerAddress() .add("security-setting", "#") .add("role", "guest"); ModelNode op = new ModelNode(); op.get(ClientConstants.OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(ClientConstants.OP_ADDR).set(address); op.get(NAME).set("create-durable-queue"); op.get(VALUE).set(true); applyUpdate(op, managementClient.getControllerClient()); op = new ModelNode(); op.get(ClientConstants.OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(ClientConstants.OP_ADDR).set(address); op.get(NAME).set("delete-durable-queue"); op.get(VALUE).set(true); applyUpdate(op, managementClient.getControllerClient()); } @After public void after() throws Exception { removeSecuritySetting(); if (conn != null) { conn.stop(); } if (session != null) { session.close(); } if (conn != null) { conn.close(); } if (consumerConn != null) { consumerConn.stop(); } if (consumerSession != null) { consumerSession.close(); } if (consumerConn != null) { consumerConn.close(); } if (adminSupport != null) { adminSupport.removeJmsTopic(getTopicName()); adminSupport.close(); } } private void removeSecuritySetting() throws Exception { // <jms server address>/security-setting=#/role=guest:write-attribute(name=create-durable-queue, value=FALSE) ModelNode address = adminSupport.getServerAddress() .add("security-setting", "#") .add("role", "guest"); ModelNode op = new ModelNode(); op.get(ClientConstants.OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(ClientConstants.OP_ADDR).set(address); op.get(NAME).set("create-durable-queue"); op.get(VALUE).set(false); applyUpdate(op, managementClient.getControllerClient()); op = new ModelNode(); op.get(ClientConstants.OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(ClientConstants.OP_ADDR).set(address); op.get(NAME).set("delete-durable-queue"); op.get(VALUE).set(false); applyUpdate(op, managementClient.getControllerClient()); } @Test public void testListMessagesForSubscription() throws Exception { consumerSession.createDurableSubscriber(topic, "testListMessagesForSubscription", null, false); consumerSession.close(); consumerSession = null; MessageProducer producer = session.createProducer(topic); producer.send(session.createTextMessage("A")); producer.send(session.createTextMessage("B")); // session.commit(); ModelNode result = execute(getTopicOperation("list-all-subscriptions"), true); final ModelNode subscriber = result.asList().get(0); //System.out.println(result); ModelNode operation = getTopicOperation("list-messages-for-subscription"); operation.get("queue-name").set(subscriber.get("queueName")); result = execute(operation, true); assertTrue(result.isDefined()); Assert.assertEquals(2, result.asList().size()); } @Test public void testCountMessagesForSubscription() throws Exception { consumerSession.createDurableSubscriber(topic, "testCountMessagesForSubscription", null, false); consumerSession.close(); consumerSession = null; MessageProducer producer = session.createProducer(topic); producer.send(session.createTextMessage("A")); producer.send(session.createTextMessage("B")); // session.commit(); ModelNode result = execute(getTopicOperation("list-all-subscriptions"), true); final ModelNode subscriber = result.asList().get(0); ModelNode operation = getTopicOperation("count-messages-for-subscription"); operation.get("client-id").set(subscriber.get("clientID")); operation.get("subscription-name").set("testCountMessagesForSubscription"); result = execute(operation, true); assertTrue(result.isDefined()); Assert.assertEquals(2, result.asInt()); } @Test public void testListAllSubscriptions() throws Exception { session.createDurableSubscriber(topic, "testListAllSubscriptions", "foo=bar", false); session.createConsumer(topic); final ModelNode result = execute(getTopicOperation("list-all-subscriptions"), true); assertTrue(result.isDefined()); Assert.assertEquals(2, result.asList().size()); } @Test public void testListAllSubscriptionsAsJSON() throws Exception { session.createDurableSubscriber(topic, "testListAllSubscriptionsAsJSON", "foo=bar", false); session.createConsumer(topic); final ModelNode result = execute(getTopicOperation("list-all-subscriptions-as-json"), true); assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); } @Test public void testListDurableSubscriptions() throws Exception { session.createDurableSubscriber(topic, "testListDurableSubscriptions", "foo=bar", false); session.createConsumer(topic); final ModelNode result = execute(getTopicOperation("list-durable-subscriptions"), true); assertTrue(result.isDefined()); Assert.assertEquals(1, result.asList().size()); } @Test public void testListDurableSubscriptionsAsJSON() throws Exception { session.createDurableSubscriber(topic, "testListDurableSubscriptionsAsJSON", "foo=bar", false); session.createConsumer(topic); final ModelNode result = execute(getTopicOperation("list-durable-subscriptions-as-json"), true); assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); } @Test public void testListNonDurableSubscriptions() throws Exception { session.createDurableSubscriber(topic, "testListNonDurableSubscriptions", "foo=bar", false); session.createConsumer(topic, "foo=bar", false); final ModelNode result = execute(getTopicOperation("list-non-durable-subscriptions"), true); assertTrue(result.isDefined()); Assert.assertEquals(1, result.asList().size()); } @Test public void testListNonDurableSubscriptionsAsJSON() throws Exception { session.createDurableSubscriber(topic, "testListNonDurableSubscriptionsAsJSON", "foo=bar", false); session.createConsumer(topic, "foo=bar", false); final ModelNode result = execute(getTopicOperation("list-non-durable-subscriptions-as-json"), true); assertTrue(result.isDefined()); Assert.assertEquals(ModelType.STRING, result.getType()); } @Test public void testDropDurableSubscription() throws Exception { consumerSession.createDurableSubscriber(topic, "testDropDurableSubscription", "foo=bar", false); consumerSession.close(); consumerSession = null; ModelNode result = execute(getTopicOperation("list-durable-subscriptions"), true); assertTrue(result.isDefined()); Assert.assertEquals(1, result.asList().size()); ModelNode op = getTopicOperation("drop-durable-subscription"); op.get("client-id").set("consumer"); op.get("subscription-name").set("testDropDurableSubscription"); result = execute(op, true); Assert.assertFalse(result.isDefined()); result = execute(getTopicOperation("list-durable-subscriptions"), true); assertTrue(result.isDefined()); Assert.assertEquals(0, result.asList().size()); } @Test public void testDropAllSubscription() throws Exception { consumerSession.createDurableSubscriber(topic, "testDropAllSubscription", "foo=bar", false); consumerSession.createDurableSubscriber(topic, "testDropAllSubscription2", null, false); consumerSession.close(); consumerSession = null; ModelNode result = execute(getTopicOperation("list-all-subscriptions"), true); assertTrue(result.isDefined()); Assert.assertEquals(2, result.asList().size()); result = execute(getTopicOperation("drop-all-subscriptions"), true); Assert.assertFalse(result.isDefined()); result = execute(getTopicOperation("list-all-subscriptions"), true); assertTrue(result.isDefined()); Assert.assertEquals(0, result.asList().size()); } @Test public void testAddJndi() throws Exception { String jndiName = "topic/added" + count; ModelNode op = getTopicOperation("add-jndi"); op.get("jndi-binding").set(jndiName); ModelNode result = execute(op, true); Assert.assertFalse(result.isDefined()); op = getTopicOperation("read-attribute"); op.get("name").set("entries"); result = execute(op, true); assertTrue(result.isDefined()); for (ModelNode binding : result.asList()) { if (binding.asString().equals(jndiName)) { return; } } Assert.fail(jndiName + " was not found"); } @Test public void testRemoveJndi() throws Exception { String jndiName = "topic/added" + count; ModelNode op = getTopicOperation("add-jndi"); op.get("jndi-binding").set(jndiName); ModelNode result = execute(op, true); Assert.assertFalse(result.isDefined()); op = getTopicOperation("remove-jndi"); op.get("jndi-binding").set(jndiName); result = execute(op, true); Assert.assertFalse(result.isDefined()); op = getTopicOperation("read-attribute"); op.get("name").set("entries"); result = execute(op, true); Assert.assertTrue(result.isDefined()); for (ModelNode binding : result.asList()) { if (binding.asString().equals(jndiName)) { Assert.fail("found " + jndiName + " while it must be removed"); } } } @Test public void testRemoveLastJndi() throws Exception { ModelNode op = getTopicOperation("remove-jndi"); op.get("jndi-binding").set(EXPORTED_PREFIX + getTopicJndiName()); // removing the last jndi name must generate a failure execute(op, false); op = getTopicOperation("read-attribute"); op.get("name").set("entries"); ModelNode result = execute(op, true); Assert.assertTrue(result.isDefined()); for (ModelNode binding : result.asList()) { if (binding.asString().equals(EXPORTED_PREFIX + getTopicJndiName())) { return; } } Assert.fail(getTopicJndiName() + " was not found"); } @Test public void removeJMSTopicRemovesAllMessages() throws Exception { // create a durable subscriber final String subscriptionName = "removeJMSTopicRemovesAllMessages"; // stop the consumer connection to prevent eager consumption of messages consumerConn.stop(); TopicSubscriber consumer = consumerSession.createDurableSubscriber(topic, subscriptionName); MessageProducer producer = session.createProducer(topic); producer.send(session.createTextMessage("A")); TextMessage message = (TextMessage)consumer.receive(TimeoutUtil.adjust(500)); Assert.assertNull("The message was received by the consumer, this is wrong as the connection is stopped", message); ModelNode operation = getTopicOperation("count-messages-for-subscription"); operation.get("client-id").set(consumerConn.getClientID()); operation.get("subscription-name").set(subscriptionName); ModelNode result = execute(operation, true); assertTrue(result.isDefined()); Assert.assertEquals(1, result.asInt()); // remove the topic adminSupport.removeJmsTopic(getTopicName()); // add the topic adminSupport.createJmsTopic(getTopicName(), getTopicJndiName()); // and recreate the durable subscriber to check all the messages have // been removed from the topic consumerSession.createDurableSubscriber(topic, subscriptionName); result = execute(operation, true); assertTrue(result.isDefined()); Assert.assertEquals(0, result.asInt()); } @Test public void testPauseAndResume() throws Exception { final ModelNode readAttr = getTopicOperation("read-attribute"); readAttr.get("name").set("paused"); ModelNode result = execute(readAttr, true); Assert.assertTrue(result.isDefined()); Assert.assertFalse(result.asBoolean()); result = execute(getTopicOperation("pause"), true); Assert.assertFalse(result.isDefined()); result = execute(readAttr, true); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.asBoolean()); final String subscriptionName = "pauseJMSTopic"; TopicSubscriber consumer = consumerSession.createDurableSubscriber(topic, subscriptionName); MessageProducer producer = session.createProducer(topic); producer.send(session.createTextMessage("A")); TextMessage message = (TextMessage)consumer.receive(TimeoutUtil.adjust(500)); Assert.assertNull("The message was received by the consumer, this is wrong as the connection is paused", message); ModelNode operation = getTopicOperation("count-messages-for-subscription"); operation.get("client-id").set(consumerConn.getClientID()); operation.get("subscription-name").set(subscriptionName); result = execute(operation, true); assertTrue(result.isDefined()); Assert.assertEquals(1, result.asInt()); result = execute(getTopicOperation("resume"), true); Assert.assertFalse(result.isDefined()); result = execute(readAttr, true); Assert.assertTrue(result.isDefined()); Assert.assertFalse(result.asBoolean()); message = (TextMessage)consumer.receive(TimeoutUtil.adjust(500)); Assert.assertNotNull("The message was not received by the consumer, this is wrong as the connection is resumed", message); Assert.assertEquals("A", message.getText()); Thread.sleep(TimeoutUtil.adjust(500)); operation = getTopicOperation("count-messages-for-subscription"); operation.get("client-id").set(consumerConn.getClientID()); operation.get("subscription-name").set(subscriptionName); result = execute(operation, true); assertTrue(result.isDefined()); Assert.assertEquals(0, result.asInt()); } private ModelNode getTopicOperation(String operationName) { final ModelNode address = adminSupport.getServerAddress() .add("jms-topic", getTopicName()); return getEmptyOperation(operationName, address); } private ModelNode execute(final ModelNode op, final boolean expectSuccess) throws IOException { ModelNode response = managementClient.getControllerClient().execute(op); final String outcome = response.get("outcome").asString(); if (expectSuccess) { Assert.assertEquals("success", outcome); return response.get("result"); } else { Assert.assertEquals("failed", outcome); return response.get("failure-description"); } } private String getTopicName() { return getClass().getSimpleName() + count; } private String getTopicJndiName() { return "topic/" + getTopicName(); } static void applyUpdate(ModelNode update, final ModelControllerClient client) throws IOException { ModelNode result = client.execute(new OperationBuilder(update).build()); if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) { /*if (result.hasDefined("result")) { System.out.println(result.get("result")); }*/ } else if (result.hasDefined("failure-description")) { throw new RuntimeException(result.get("failure-description").toString()); } else { throw new RuntimeException("Operation not successful; outcome = " + result.get("outcome")); } } }
20,697
38.880539
130
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/ConnectionFactoryClientMappingTestCase.java
/* * Copyright 2017 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.messaging.mgmt; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.SnapshotRestoreSetupTask; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.annotation.Resource; import jakarta.jms.ConnectionFactory; import java.io.IOException; import java.util.Map; import static org.jboss.as.controller.client.helpers.ClientConstants.*; 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.WRITE_ATTRIBUTE_OPERATION; import static org.junit.Assert.assertEquals; import java.util.HashMap; /** * Created by spyrkob on 18/05/2017. */ @RunWith(Arquillian.class) @ServerSetup({ConnectionFactoryClientMappingTestCase.SetupTask.class}) public class ConnectionFactoryClientMappingTestCase { private static final String CONNECTION_FACTORY_JNDI_NAME = "java:jboss/exported/jms/TestConnectionFactory"; static class SetupTask extends SnapshotRestoreSetupTask { private static final Logger logger = Logger.getLogger(ConnectionFactoryClientMappingTestCase.SetupTask.class); @Override public void doSetup(org.jboss.as.arquillian.container.ManagementClient managementClient, String s) throws Exception { JMSOperations ops = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); addSocketBinding(managementClient, "test-binding", clientMapping("test", "8000")); Map<String, String> parameters = new HashMap<>(); parameters.put("multicast-prefix", "jms.topic"); parameters.put("anycast-prefix", "jms.queue"); ops.addHttpConnector("http-test-connector", "test-binding", "http-acceptor", parameters); ModelNode attr = new ModelNode(); attr.get("connectors").add("http-test-connector"); ops.addJmsConnectionFactory("TestConnectionFactory", CONNECTION_FACTORY_JNDI_NAME, attr); ServerReload.executeReloadAndWaitForCompletion(managementClient); } private ModelNode clientMapping(String destAddr, String destPort) { ModelNode clientMapping = new ModelNode(); clientMapping.get("destination-address").set(destAddr); clientMapping.get("destination-port").set(destPort); return clientMapping; } private void addSocketBinding(ManagementClient managementClient, String bindingName, ModelNode clientMapping) throws Exception { ModelNode address = new ModelNode(); address.add("socket-binding-group", "standard-sockets"); address.add("socket-binding", bindingName); ModelNode socketBindingOp = new ModelNode(); socketBindingOp.get(OP).set(ADD); socketBindingOp.get(OP_ADDR).set(address); execute(managementClient, socketBindingOp); ModelNode clientMappingOp = new ModelNode(); clientMappingOp.get(OP).set(WRITE_ATTRIBUTE_OPERATION); clientMappingOp.get(OP_ADDR).set(address); clientMappingOp.get(NAME).set("client-mappings"); clientMappingOp.get(VALUE).add(clientMapping); execute(managementClient, clientMappingOp); } static void execute(ManagementClient managementClient, final ModelNode operation) throws IOException { ModelNode result = managementClient.getControllerClient().execute(operation); if (result.hasDefined(ClientConstants.OUTCOME) && ClientConstants.SUCCESS.equals(result.get(ClientConstants.OUTCOME).asString())) { logger.trace("Operation successful for update = " + operation.toString()); } else if (result.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) { final String failureDesc = result.get(ClientConstants.FAILURE_DESCRIPTION).toString(); throw new RuntimeException(failureDesc); } else { throw new RuntimeException("Operation not successful; outcome = " + result.get(ClientConstants.OUTCOME)); } } } @Deployment(testable = true) public static JavaArchive createDeployment() { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "test.jar"); jar.addClass(ConnectionFactoryClientMappingTestCase.class); jar.add(EmptyAsset.INSTANCE, "META-INF/beans.xml"); jar.add(new StringAsset( "<jboss-deployment-structure>\n" + " <deployment>\n" + " <dependencies>\n" + " <module name=\"org.apache.activemq.artemis\"/>\n" + " </dependencies>\n" + " </deployment>\n" + "</jboss-deployment-structure>"), "META-INF/jboss-deployment-structure.xml"); return jar; } @Resource(lookup = "java:jboss/exported/jms/TestConnectionFactory") private ConnectionFactory connectionFactory; @Test public void testClientMappingInConnectionFactory() throws Exception { Map<String, Object> params = ((ActiveMQJMSConnectionFactory) connectionFactory).getStaticConnectors()[0].getParams(); assertEquals("test", params.get(TransportConstants.HOST_PROP_NAME)); assertEquals(8000, params.get(TransportConstants.PORT_PROP_NAME)); } }
6,935
45.550336
143
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/RemoteConnectionHolding.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.messaging.mgmt; import jakarta.jms.JMSException; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2016 Red Hat inc. */ public interface RemoteConnectionHolding { void createConnection() throws JMSException; void closeConnection() throws JMSException; }
1,344
36.361111
78
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/ConnectionHoldingBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.messaging.mgmt; import jakarta.annotation.Resource; import jakarta.ejb.Remote; import jakarta.ejb.Stateful; import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSContext; import jakarta.jms.JMSException; import jakarta.jms.TemporaryQueue; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2016 Red Hat inc. */ @Stateful @Remote(RemoteConnectionHolding.class) public class ConnectionHoldingBean implements RemoteConnectionHolding { @Resource(lookup = "java:/JmsXA") ConnectionFactory factory; private JMSContext context; @Override public void createConnection() throws JMSException { // create a consumer on a temp queue to ensure the Jakarta Messaging // connection is actually created and started context = factory.createContext("guest", "guest"); TemporaryQueue tempQueue = context.createTemporaryQueue(); context.createConsumer(tempQueue); } @Override public void closeConnection() throws JMSException { context.close(); } }
2,102
34.644068
78
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/ExternalConnectionFactoryManagementTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.messaging.mgmt; import static java.util.UUID.randomUUID; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLED_BACK; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedAction; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; import org.jgroups.util.StackType; import org.jgroups.util.Util; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c)2012 Red Hat, inc * * https://issues.jboss.org/browse/AS7-5107 */ @RunWith(Arquillian.class) @RunAsClient public class ExternalConnectionFactoryManagementTestCase extends ContainerResourceMgmtTestBase { private static final String CF_NAME = randomUUID().toString(); private static final String CONNECTOR_NAME = "client-http-connector"; @ContainerResource private ManagementClient managementClient; @BeforeClass public static void beforeClass() { AccessController.doPrivileged((PrivilegedAction<Void>) () -> { Assume.assumeFalse("[WFCI-32] Disable on Windows+IPv6 until CI environment is fixed", Util.checkForWindows() && (Util.getIpStackType() == StackType.IPv6)); return null; }); } @Test public void testWriteDiscoveryGroupAttributeWhenConnectorIsAlreadyDefined() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient()); try { jmsOperations.addExternalHttpConnector(CONNECTOR_NAME, "http", "http-acceptor"); ModelNode attributes = new ModelNode(); attributes.get("connectors").add(CONNECTOR_NAME); jmsOperations.addJmsExternalConnectionFactory(CF_NAME, "java:/jms/" + CF_NAME, attributes); final ModelNode writeAttribute = new ModelNode(); writeAttribute.get(OP).set(WRITE_ATTRIBUTE_OPERATION); writeAttribute.get(OP_ADDR).set(jmsOperations.getSubsystemAddress().add("connection-factory", CF_NAME)); writeAttribute.get(NAME).set("discovery-group"); writeAttribute.get(VALUE).set(randomUUID().toString()); try { executeOperation(writeAttribute); fail("it is not possible to define a discovery group when the connector attribute is already defined"); } catch (MgmtOperationException e) { assertEquals(FAILED, e.getResult().get(OUTCOME).asString()); assertEquals(true, e.getResult().get(ROLLED_BACK).asBoolean()); assertTrue(e.getResult().get(FAILURE_DESCRIPTION).asString().contains("WFLYCTL0105")); } } finally { jmsOperations.removeJmsExternalConnectionFactory(CF_NAME); jmsOperations.removeExternalHttpConnector(CONNECTOR_NAME); } ServerReload.executeReloadAndWaitForCompletion(managementClient); } @Test public void testRemovePooledConnectionFactory() throws Exception { // /subsystem=messaging-activemq/in-vm-connector=invm1:add(server-id=123) ModelNode invmConnectorAddress = new ModelNode(); invmConnectorAddress.add("subsystem", "messaging-activemq"); invmConnectorAddress.add("in-vm-connector", "invm1"); ModelNode op = Operations.createAddOperation(invmConnectorAddress); op.get("server-id").set("123"); execute(managementClient.getControllerClient(), op); // /subsystem=messaging-activemq/pooled-connection-factory=pool3:add(connectors=[invm1],entries=[foo]) ModelNode pcfAddress = new ModelNode(); pcfAddress.add("subsystem", "messaging-activemq"); pcfAddress.add("pooled-connection-factory", "pool3"); op = Operations.createAddOperation(pcfAddress); op.get("connectors").setEmptyList().add("invm1"); op.get("entries").setEmptyList().add("foo"); execute(managementClient.getControllerClient(), op); // /subsystem=messaging-activemq/pooled-connection-factory=pool3:remove() op = Operations.createRemoveOperation(pcfAddress); execute(managementClient.getControllerClient(), op); op = Operations.createRemoveOperation(invmConnectorAddress); execute(managementClient.getControllerClient(), op); ServerReload.executeReloadAndWaitForCompletion(managementClient); } private static ModelNode execute(final ModelControllerClient client, final ModelNode op) throws IOException { final ModelNode result = client.execute(op); if (!Operations.isSuccessfulOutcome(result)) { throw new RuntimeException(Operations.getFailureDescription(result).asString()); } return result; } }
7,350
47.361842
167
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/NoAuditLogTestCase.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.messaging.mgmt; import static org.jboss.shrinkwrap.api.ArchivePaths.create; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * This is a simple test that deploys an application then checks the logs for ActiveMQ audit logs. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @RunAsClient @RunWith(Arquillian.class) public class NoAuditLogTestCase { @ArquillianResource private ManagementClient managementClient; @Deployment public static JavaArchive deploy() { return ShrinkWrap.create(JavaArchive.class, NoAuditLogTestCase.class.getName() + ".jar") .addClass(ConnectionHoldingBean.class) .addClass(RemoteConnectionHolding.class) .addAsManifestResource(EmptyAsset.INSTANCE, create("beans.xml")); } @Test public void testNoAuditMessagesLogged() throws Exception { try (BufferedReader reader = Files.newBufferedReader(getLogFile(), StandardCharsets.UTF_8)) { String line; while ((line = reader.readLine()) != null) { Assert.assertFalse(String.format("Log contains ActiveMQ audit log messages: %n%s", line), line.contains("org.apache.activemq.audit")); } } } private Path getLogFile() throws IOException { final ModelNode address = Operations.createAddress("subsystem", "logging", "periodic-rotating-file-handler", "FILE"); final ModelNode op = Operations.createOperation("resolve-path", address); final ModelNode result = managementClient.getControllerClient().execute(op); if (!Operations.isSuccessfulOutcome(result)) { Assert.fail("Failed to locate the log file: " + Operations.getFailureDescription(result).asString()); } return Paths.get(Operations.readResult(result).asString()); } }
3,213
38.195122
150
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/messaging/mgmt/DiscovertBroadcastGroupManagementTestCase.java
/* * Copyright 2019 JBoss by Red Hat. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.messaging.mgmt; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import java.io.IOException; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.common.jms.JMSOperations; import org.jboss.as.test.integration.common.jms.JMSOperationsProvider; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Emmanuel Hugonnet (c) 2019 Red Hat, Inc. */ @RunWith(Arquillian.class) @RunAsClient public class DiscovertBroadcastGroupManagementTestCase extends ContainerResourceMgmtTestBase { private static final String MULTICAST_SOCKET_BINDING = "messaging-group"; private static final String JGROUPS_CLUSTER = "activemq-cluster"; @Test public void testServerBroadcastGroup() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(getModelControllerClient()); executeOperation(createBroadcastGroupWithSocketBinding(jmsOperations.getServerAddress(), "bg-group1", MULTICAST_SOCKET_BINDING, "http-connector"), true); final ModelNode legacyBgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/broadcast-group=bg-group1").toModelNode(); final ModelNode socketBgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/socket-broadcast-group=bg-group1").toModelNode(); ModelNode broadcastLegacy = executeOperation(Operations.createReadResourceOperation(legacyBgAddress)); broadcastLegacy.remove("jgroups-channel"); broadcastLegacy.remove("jgroups-cluster"); broadcastLegacy.remove("jgroups-stack"); ModelNode broadcast = executeOperation(Operations.createReadResourceOperation(socketBgAddress)); Assert.assertEquals(broadcast.toString(), broadcastLegacy.toString()); checkNoResource("/subsystem=messaging-activemq/server=default/jgroups-broadcast-group=bg-group1"); executeOperation(Operations.createWriteAttributeOperation(socketBgAddress, "broadcast-period", 5000)); Assert.assertEquals(5000L, executeOperation(Operations.createReadAttributeOperation(legacyBgAddress, "broadcast-period")).asLong()); Assert.assertEquals(5000L, executeOperation(Operations.createReadAttributeOperation(socketBgAddress, "broadcast-period")).asLong()); executeOperation(Operations.createUndefineAttributeOperation(socketBgAddress, "broadcast-period")); Assert.assertEquals(2000L, executeOperation(Operations.createReadAttributeOperation(legacyBgAddress, "broadcast-period")).asLong()); Assert.assertEquals(2000L, executeOperation(Operations.createReadAttributeOperation(socketBgAddress, "broadcast-period")).asLong()); executeOperation(Operations.createRemoveOperation(socketBgAddress)); checkNoResource(socketBgAddress); checkNoResource(legacyBgAddress); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); } @Test public void testServerBroadcastGroupCluster() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(getModelControllerClient()); executeOperation(createBroadcastGroupWithJGroupsCluster(jmsOperations.getServerAddress(), "bg-group1", JGROUPS_CLUSTER, "http-connector"), true); final ModelNode legacyBgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/broadcast-group=bg-group1").toModelNode(); final ModelNode jgroupBgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/jgroups-broadcast-group=bg-group1").toModelNode(); ModelNode broadcastLegacy = executeOperation(Operations.createReadResourceOperation(legacyBgAddress)); broadcastLegacy.remove("socket-binding"); ModelNode broadcast = executeOperation(Operations.createReadResourceOperation(jgroupBgAddress)); Assert.assertEquals(broadcast.toString(), broadcastLegacy.toString()); checkNoResource("/subsystem=messaging-activemq/server=default/socket-broadcast-group=bg-group1"); executeOperation(Operations.createWriteAttributeOperation(jgroupBgAddress, "broadcast-period", 5000)); Assert.assertEquals(5000L, executeOperation(Operations.createReadAttributeOperation(legacyBgAddress, "broadcast-period")).asLong()); Assert.assertEquals(5000L, executeOperation(Operations.createReadAttributeOperation(jgroupBgAddress, "broadcast-period")).asLong()); executeOperation(Operations.createUndefineAttributeOperation(jgroupBgAddress, "broadcast-period")); Assert.assertEquals(2000L, executeOperation(Operations.createReadAttributeOperation(legacyBgAddress, "broadcast-period")).asLong()); Assert.assertEquals(2000L, executeOperation(Operations.createReadAttributeOperation(jgroupBgAddress, "broadcast-period")).asLong()); executeOperation(Operations.createRemoveOperation(jgroupBgAddress)); checkNoResource(jgroupBgAddress); checkNoResource(legacyBgAddress); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); } @Test public void testServerDiscoveryGroup() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(getModelControllerClient()); executeOperation(createDiscoveryGroupWithSocketBinding(jmsOperations.getServerAddress(), "dg-group1", MULTICAST_SOCKET_BINDING), true); final ModelNode legacyDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/discovery-group=dg-group1").toModelNode(); final ModelNode socketDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/socket-discovery-group=dg-group1").toModelNode(); ModelNode discoveryLegacy = executeOperation(Operations.createReadResourceOperation(legacyDgAddress)); discoveryLegacy.remove("jgroups-channel"); discoveryLegacy.remove("jgroups-cluster"); discoveryLegacy.remove("jgroups-stack"); ModelNode discovery = executeOperation(Operations.createReadResourceOperation(socketDgAddress)); Assert.assertEquals(discovery.toString(), discoveryLegacy.toString()); checkNoResource("/subsystem=messaging-activemq/server=default/jgroups-discovery-group=dg-group1"); executeOperation(Operations.createWriteAttributeOperation(socketDgAddress, "initial-wait-timeout", 50000)); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "initial-wait-timeout")).asLong()); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(socketDgAddress, "initial-wait-timeout")).asLong()); executeOperation(Operations.createUndefineAttributeOperation(socketDgAddress, "initial-wait-timeout")); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "initial-wait-timeout")).asLong()); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(socketDgAddress, "initial-wait-timeout")).asLong()); executeOperation(Operations.createRemoveOperation(socketDgAddress)); checkNoResource(socketDgAddress); checkNoResource(legacyDgAddress); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); } @Test public void testServerDiscoveryGroupCluster() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(getModelControllerClient()); executeOperation(createDiscoveryGroupWithJGroupsCluster(jmsOperations.getServerAddress(), "dg-group1", JGROUPS_CLUSTER), true); final ModelNode legacyDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/discovery-group=dg-group1").toModelNode(); final ModelNode socketDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/jgroups-discovery-group=dg-group1").toModelNode(); ModelNode discoveryLegacy = executeOperation(Operations.createReadResourceOperation(legacyDgAddress)); discoveryLegacy.remove("socket-binding"); ModelNode discovery = executeOperation(Operations.createReadResourceOperation(socketDgAddress)); Assert.assertEquals(discovery.toString(), discoveryLegacy.toString()); checkNoResource("/subsystem=messaging-activemq/server=default/socket-discovery-group=dg-group1"); executeOperation(Operations.createWriteAttributeOperation(socketDgAddress, "initial-wait-timeout", 50000)); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "initial-wait-timeout")).asLong()); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(socketDgAddress, "initial-wait-timeout")).asLong()); executeOperation(Operations.createUndefineAttributeOperation(socketDgAddress, "initial-wait-timeout")); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "initial-wait-timeout")).asLong()); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(socketDgAddress, "initial-wait-timeout")).asLong()); executeOperation(Operations.createRemoveOperation(socketDgAddress)); checkNoResource(socketDgAddress); checkNoResource(legacyDgAddress); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); } @Test public void testExternalDiscoveryGroup() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(getModelControllerClient()); jmsOperations.createSocketBinding(MULTICAST_SOCKET_BINDING, "public", 5444); executeOperation(createDiscoveryGroupWithSocketBinding(jmsOperations.getSubsystemAddress(), "dg-group1", MULTICAST_SOCKET_BINDING), true); final ModelNode legacyDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/discovery-group=dg-group1").toModelNode(); final ModelNode socketDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/socket-discovery-group=dg-group1").toModelNode(); ModelNode discoveryLegacy = executeOperation(Operations.createReadResourceOperation(legacyDgAddress)); discoveryLegacy.remove("jgroups-channel"); discoveryLegacy.remove("jgroups-cluster"); discoveryLegacy.remove("jgroups-stack"); ModelNode discovery = executeOperation(Operations.createReadResourceOperation(socketDgAddress)); Assert.assertEquals(discovery.toString(), discoveryLegacy.toString()); checkNoResource("/subsystem=messaging-activemq/jgroups-discovery-group=dg-group1"); executeOperation(Operations.createWriteAttributeOperation(socketDgAddress, "refresh-timeout", 50000)); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "refresh-timeout")).asLong()); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(socketDgAddress, "refresh-timeout")).asLong()); executeOperation(Operations.createUndefineAttributeOperation(socketDgAddress, "refresh-timeout")); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "refresh-timeout")).asLong()); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(socketDgAddress, "refresh-timeout")).asLong()); executeOperation(Operations.createRemoveOperation(socketDgAddress)); checkNoResource(socketDgAddress); checkNoResource(legacyDgAddress); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); executeOperation(Operations.createRemoveOperation(PathAddress.parseCLIStyleAddress("/socket-binding-group=standard-sockets/socket-binding=" + MULTICAST_SOCKET_BINDING).toModelNode())); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); } @Test public void testExternalDiscoveryGroupCluster() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(getModelControllerClient()); executeOperation(createDiscoveryGroupWithJGroupsCluster(jmsOperations.getSubsystemAddress(), "dg-group1", JGROUPS_CLUSTER), true); final ModelNode legacyDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/discovery-group=dg-group1").toModelNode(); final ModelNode jgroupDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/jgroups-discovery-group=dg-group1").toModelNode(); ModelNode discoveryLegacy = executeOperation(Operations.createReadResourceOperation(legacyDgAddress)); discoveryLegacy.remove("socket-binding"); ModelNode discovery = executeOperation(Operations.createReadResourceOperation(jgroupDgAddress)); Assert.assertEquals(discovery.toString(), discoveryLegacy.toString()); checkNoResource("/subsystem=messaging-activemq/socket-discovery-group=dg-group1"); executeOperation(Operations.createWriteAttributeOperation(jgroupDgAddress, "refresh-timeout", 50000)); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "refresh-timeout")).asLong()); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(jgroupDgAddress, "refresh-timeout")).asLong()); executeOperation(Operations.createUndefineAttributeOperation(jgroupDgAddress, "refresh-timeout")); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "refresh-timeout")).asLong()); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(jgroupDgAddress, "refresh-timeout")).asLong()); executeOperation(Operations.createRemoveOperation(jgroupDgAddress)); checkNoResource(jgroupDgAddress); checkNoResource(legacyDgAddress); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); } @Test public void testServerShallowBroadcastGroup() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(getModelControllerClient()); executeOperation(createShallowBroadcastGroupWithSocketBinding(jmsOperations.getServerAddress(), "bg-group1", MULTICAST_SOCKET_BINDING, "http-connector"), true); final ModelNode legacyBgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/broadcast-group=bg-group1").toModelNode(); final ModelNode socketBgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/socket-broadcast-group=bg-group1").toModelNode(); ModelNode broadcastLegacy = executeOperation(Operations.createReadResourceOperation(legacyBgAddress)); broadcastLegacy.remove("jgroups-channel"); broadcastLegacy.remove("jgroups-cluster"); broadcastLegacy.remove("jgroups-stack"); ModelNode broadcast = executeOperation(Operations.createReadResourceOperation(socketBgAddress)); Assert.assertEquals(broadcast.toString(), broadcastLegacy.toString()); checkNoResource("/subsystem=messaging-activemq/server=default/jgroups-broadcast-group=bg-group1"); executeOperation(Operations.createWriteAttributeOperation(legacyBgAddress, "broadcast-period", 5000)); Assert.assertEquals(5000L, executeOperation(Operations.createReadAttributeOperation(legacyBgAddress, "broadcast-period")).asLong()); Assert.assertEquals(5000L, executeOperation(Operations.createReadAttributeOperation(socketBgAddress, "broadcast-period")).asLong()); executeOperation(Operations.createUndefineAttributeOperation(socketBgAddress, "broadcast-period")); Assert.assertEquals(2000L, executeOperation(Operations.createReadAttributeOperation(legacyBgAddress, "broadcast-period")).asLong()); Assert.assertEquals(2000L, executeOperation(Operations.createReadAttributeOperation(socketBgAddress, "broadcast-period")).asLong()); executeOperation(Operations.createRemoveOperation(legacyBgAddress)); checkNoResource(legacyBgAddress); checkNoResource(socketBgAddress); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); } @Test public void testServerShallowBroadcastGroupCluster() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(getModelControllerClient()); executeOperation(createShallowBroadcastGroupWithhJGroupCluster(jmsOperations.getServerAddress(), "bg-group1", JGROUPS_CLUSTER, "http-connector"), true); final ModelNode legacyBgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/broadcast-group=bg-group1").toModelNode(); final ModelNode jgroupBgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/jgroups-broadcast-group=bg-group1").toModelNode(); ModelNode broadcastLegacy = executeOperation(Operations.createReadResourceOperation(legacyBgAddress)); broadcastLegacy.remove("socket-binding"); ModelNode broadcast = executeOperation(Operations.createReadResourceOperation(jgroupBgAddress)); Assert.assertEquals(broadcast.toString(), broadcastLegacy.toString()); checkNoResource("/subsystem=messaging-activemq/server=default/socket-broadcast-group=bg-group1"); executeOperation(Operations.createWriteAttributeOperation(legacyBgAddress, "broadcast-period", 5000)); Assert.assertEquals(5000L, executeOperation(Operations.createReadAttributeOperation(legacyBgAddress, "broadcast-period")).asLong()); Assert.assertEquals(5000L, executeOperation(Operations.createReadAttributeOperation(jgroupBgAddress, "broadcast-period")).asLong()); executeOperation(Operations.createUndefineAttributeOperation(jgroupBgAddress, "broadcast-period")); Assert.assertEquals(2000L, executeOperation(Operations.createReadAttributeOperation(legacyBgAddress, "broadcast-period")).asLong()); Assert.assertEquals(2000L, executeOperation(Operations.createReadAttributeOperation(jgroupBgAddress, "broadcast-period")).asLong()); executeOperation(Operations.createRemoveOperation(legacyBgAddress)); checkNoResource(legacyBgAddress); checkNoResource(jgroupBgAddress); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); } @Test public void testServerShallowDiscoveryGroup() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(getModelControllerClient()); executeOperation(createShallowDiscoveryGroupWithSocketBinding(jmsOperations.getServerAddress(), "dg-group1", MULTICAST_SOCKET_BINDING), true); final ModelNode legacyDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/discovery-group=dg-group1").toModelNode(); final ModelNode socketDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/socket-discovery-group=dg-group1").toModelNode(); ModelNode discoveryLegacy = executeOperation(Operations.createReadResourceOperation(legacyDgAddress)); discoveryLegacy.remove("jgroups-channel"); discoveryLegacy.remove("jgroups-cluster"); discoveryLegacy.remove("jgroups-stack"); ModelNode discovery = executeOperation(Operations.createReadResourceOperation(socketDgAddress)); Assert.assertEquals(discovery.toString(), discoveryLegacy.toString()); checkNoResource("/subsystem=messaging-activemq/server=default/jgroups-discovery-group=dg-group1"); executeOperation(Operations.createWriteAttributeOperation(legacyDgAddress, "refresh-timeout", 50000)); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "refresh-timeout")).asLong()); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(socketDgAddress, "refresh-timeout")).asLong()); executeOperation(Operations.createUndefineAttributeOperation(socketDgAddress, "refresh-timeout")); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "refresh-timeout")).asLong()); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(socketDgAddress, "refresh-timeout")).asLong()); executeOperation(Operations.createRemoveOperation(legacyDgAddress)); checkNoResource(legacyDgAddress); checkNoResource(socketDgAddress); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); } @Test public void testServerShallowDiscoveryGroupCluster() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(getModelControllerClient()); executeOperation(createShallowDiscoveryGroupWithJGroupCluster(jmsOperations.getServerAddress(), "dg-group1", JGROUPS_CLUSTER), true); final ModelNode legacyDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/discovery-group=dg-group1").toModelNode(); final ModelNode jgroupDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/server=default/jgroups-discovery-group=dg-group1").toModelNode(); ModelNode discoveryLegacy = executeOperation(Operations.createReadResourceOperation(legacyDgAddress)); discoveryLegacy.remove("socket-binding"); ModelNode discovery = executeOperation(Operations.createReadResourceOperation(jgroupDgAddress)); Assert.assertEquals(discovery.toString(), discoveryLegacy.toString()); checkNoResource("/subsystem=messaging-activemq/server=default/socket-discovery-group=dg-group1"); executeOperation(Operations.createWriteAttributeOperation(legacyDgAddress, "refresh-timeout", 50000)); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "refresh-timeout")).asLong()); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(jgroupDgAddress, "refresh-timeout")).asLong()); executeOperation(Operations.createUndefineAttributeOperation(jgroupDgAddress, "refresh-timeout")); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "refresh-timeout")).asLong()); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(jgroupDgAddress, "refresh-timeout")).asLong()); executeOperation(Operations.createRemoveOperation(legacyDgAddress)); checkNoResource(legacyDgAddress); checkNoResource(jgroupDgAddress); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); } @Test public void testExternalShallowDiscoveryGroup() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(getModelControllerClient()); jmsOperations.createSocketBinding(MULTICAST_SOCKET_BINDING, "public", 5444); executeOperation(createShallowDiscoveryGroupWithSocketBinding(jmsOperations.getSubsystemAddress(), "dg-group1", MULTICAST_SOCKET_BINDING), true); final ModelNode legacyDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/discovery-group=dg-group1").toModelNode(); final ModelNode socketDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/socket-discovery-group=dg-group1").toModelNode(); ModelNode discoveryLegacy = executeOperation(Operations.createReadResourceOperation(legacyDgAddress)); discoveryLegacy.remove("jgroups-channel"); discoveryLegacy.remove("jgroups-cluster"); discoveryLegacy.remove("jgroups-stack"); ModelNode discovery = executeOperation(Operations.createReadResourceOperation(socketDgAddress)); Assert.assertEquals(discovery.toString(), discoveryLegacy.toString()); checkNoResource("/subsystem=messaging-activemq/jgroups-discovery-group=dg-group1"); executeOperation(Operations.createWriteAttributeOperation(legacyDgAddress, "initial-wait-timeout", 50000)); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "initial-wait-timeout")).asLong()); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(socketDgAddress, "initial-wait-timeout")).asLong()); executeOperation(Operations.createUndefineAttributeOperation(socketDgAddress, "initial-wait-timeout")); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "initial-wait-timeout")).asLong()); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(socketDgAddress, "initial-wait-timeout")).asLong()); executeOperation(Operations.createRemoveOperation(legacyDgAddress)); checkNoResource(legacyDgAddress); checkNoResource(socketDgAddress); executeOperation(Operations.createRemoveOperation(PathAddress.parseCLIStyleAddress("/socket-binding-group=standard-sockets/socket-binding=" + MULTICAST_SOCKET_BINDING).toModelNode())); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); } @Test public void testExternalShallowDiscoveryGroupCluster() throws Exception { JMSOperations jmsOperations = JMSOperationsProvider.getInstance(getModelControllerClient()); executeOperation(createShallowDiscoveryGroupWithJGroupCluster(jmsOperations.getSubsystemAddress(), "dg-group1", JGROUPS_CLUSTER), true); final ModelNode legacyDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/discovery-group=dg-group1").toModelNode(); final ModelNode jgroupDgAddress = PathAddress.parseCLIStyleAddress("/subsystem=messaging-activemq/jgroups-discovery-group=dg-group1").toModelNode(); ModelNode discoveryLegacy = executeOperation(Operations.createReadResourceOperation(legacyDgAddress)); discoveryLegacy.remove("socket-binding"); ModelNode discovery = executeOperation(Operations.createReadResourceOperation(jgroupDgAddress)); Assert.assertEquals(discovery.toString(), discoveryLegacy.toString()); checkNoResource("/subsystem=messaging-activemq/socket-discovery-group=dg-group1"); executeOperation(Operations.createWriteAttributeOperation(legacyDgAddress, "initial-wait-timeout", 50000)); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "initial-wait-timeout")).asLong()); Assert.assertEquals(50000L, executeOperation(Operations.createReadAttributeOperation(jgroupDgAddress, "initial-wait-timeout")).asLong()); executeOperation(Operations.createUndefineAttributeOperation(jgroupDgAddress, "initial-wait-timeout")); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(legacyDgAddress, "initial-wait-timeout")).asLong()); Assert.assertEquals(10000L, executeOperation(Operations.createReadAttributeOperation(jgroupDgAddress, "initial-wait-timeout")).asLong()); executeOperation(Operations.createRemoveOperation(legacyDgAddress)); checkNoResource(legacyDgAddress); checkNoResource(jgroupDgAddress); ServerReload.executeReloadAndWaitForCompletion(getManagementClient()); } ModelNode createShallowDiscoveryGroupWithSocketBinding(ModelNode serverAddress, String discoveryGroupName, String socketBinding) throws Exception { ModelNode address = serverAddress.clone(); address.add("discovery-group", discoveryGroupName); ModelNode op = Operations.createAddOperation(address); op.get("socket-binding").set(socketBinding); return op; } ModelNode createShallowBroadcastGroupWithSocketBinding(ModelNode serverAddress, String broadcastGroupName, String socketBinding, String connector) throws Exception { ModelNode address = serverAddress.clone(); address.add("broadcast-group", broadcastGroupName); ModelNode op = Operations.createAddOperation(address); op.get("socket-binding").set(socketBinding); op.get("connectors").add(connector); return op; } ModelNode createShallowDiscoveryGroupWithJGroupCluster(ModelNode serverAddress, String discoveryGroupName, String jgroupCluster) throws Exception { ModelNode address = serverAddress.clone(); address.add("discovery-group", discoveryGroupName); ModelNode op = Operations.createAddOperation(address); op.get("jgroups-cluster").set(jgroupCluster); return op; } ModelNode createShallowBroadcastGroupWithhJGroupCluster(ModelNode serverAddress, String broadcastGroupName, String jgroupCluster, String connector) throws Exception { ModelNode address = serverAddress.clone(); address.add("broadcast-group", broadcastGroupName); ModelNode op = Operations.createAddOperation(address); op.get("jgroups-cluster").set(jgroupCluster); op.get("connectors").add(connector); return op; } ModelNode createDiscoveryGroupWithSocketBinding(ModelNode serverAddress, String discoveryGroupName, String socketBinding) throws Exception { ModelNode address = serverAddress.clone(); address.add("socket-discovery-group", discoveryGroupName); ModelNode op = Operations.createAddOperation(address); op.get("socket-binding").set(socketBinding); return op; } ModelNode createBroadcastGroupWithSocketBinding(ModelNode serverAddress, String broadcastGroupName, String socketBinding, String connector) throws Exception { ModelNode address = serverAddress.clone(); address.add("socket-broadcast-group", broadcastGroupName); ModelNode op = Operations.createAddOperation(address); op.get("socket-binding").set(socketBinding); op.get("connectors").add(connector); return op; } ModelNode createDiscoveryGroupWithJGroupsCluster(ModelNode serverAddress, String discoveryGroupName, String jgroupCluster) throws Exception { ModelNode address = serverAddress.clone(); address.add("jgroups-discovery-group", discoveryGroupName); ModelNode op = Operations.createAddOperation(address); op.get("jgroups-cluster").set(jgroupCluster); return op; } ModelNode createBroadcastGroupWithJGroupsCluster(ModelNode serverAddress, String broadcastGroupName, String jgroupCluster, String connector) throws Exception { ModelNode address = serverAddress.clone(); address.add("jgroups-broadcast-group", broadcastGroupName); ModelNode op = Operations.createAddOperation(address); op.get("jgroups-cluster").set(jgroupCluster); op.get("connectors").add(connector); return op; } void checkNoResource(String address) throws IOException, MgmtOperationException { checkNoResource(PathAddress.parseCLIStyleAddress(address).toModelNode()); } void checkNoResource(ModelNode address) throws IOException, MgmtOperationException { ModelNode result = executeOperation(Operations.createReadResourceOperation(address), false); Assert.assertEquals(ModelDescriptionConstants.FAILED, result.require(OUTCOME).asString()); Assert.assertTrue(result.require(FAILURE_DESCRIPTION).asString().contains("WFLYCTL0216")); } }
33,005
71.540659
192
java