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/clustering/src/test/java/org/jboss/as/test/clustering/cluster/dispatcher/bean/TestCommand.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.clustering.cluster.dispatcher.bean;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.wildfly.clustering.dispatcher.Command;
import org.wildfly.clustering.group.Node;
public class TestCommand implements Command<String, Node> {
private static final long serialVersionUID = -3405593925871250676L;
@Override
public String execute(Node node) {
try {
// Ensure the thread context classloader of the command execution is correct
Thread.currentThread().getContextClassLoader().loadClass(this.getClass().getName());
// Ensure the correct naming context is set
Context context = new InitialContext();
try {
context.lookup("java:comp/env/clustering/dispatcher");
} finally {
context.close();
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
} catch (NamingException e) {
throw new IllegalStateException(e);
}
return node.getName();
}
}
| 2,164
| 39.092593
| 96
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/cdi/CDIFailoverTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.cdi;
import org.infinispan.transaction.TransactionMode;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.clustering.ClusterTestUtil;
import org.jboss.as.test.clustering.cluster.cdi.webapp.IncrementorBean;
import org.jboss.as.test.clustering.cluster.ejb.stateful.bean.Incrementor;
import org.jboss.as.test.clustering.cluster.web.AbstractWebFailoverTestCase;
import org.jboss.as.test.clustering.single.web.Mutable;
import org.jboss.as.test.clustering.single.web.SimpleServlet;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
/**
* Test failover with CDI session scoped bean.
*
* @author Tomas Remes
* @author Radoslav Husar
*/
@RunWith(Arquillian.class)
public class CDIFailoverTestCase extends AbstractWebFailoverTestCase {
private static final String MODULE_NAME = CDIFailoverTestCase.class.getSimpleName();
private static final String DEPLOYMENT_NAME = MODULE_NAME + ".war";
public CDIFailoverTestCase() {
super(DEPLOYMENT_NAME, TransactionMode.TRANSACTIONAL);
}
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_3, managed = false, testable = false)
@TargetsContainer(NODE_3)
public static Archive<?> deployment3() {
return createDeployment();
}
private static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_NAME);
war.addPackage(IncrementorBean.class.getPackage());
war.addClasses(Incrementor.class, SimpleServlet.class, Mutable.class);
ClusterTestUtil.addTopologyListenerDependencies(war);
war.setWebXML(CDIFailoverTestCase.class.getPackage(), "web.xml");
return war;
}
}
| 3,331
| 39.634146
| 88
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/cdi/ProtoStreamCDIFailoverTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.cdi;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.transaction.TransactionMode;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.clustering.ClusterTestUtil;
import org.jboss.as.test.clustering.cluster.cdi.webapp.IncrementorBean;
import org.jboss.as.test.clustering.cluster.cdi.webapp.CDISerializationContextInitializer;
import org.jboss.as.test.clustering.cluster.ejb.stateful.bean.Incrementor;
import org.jboss.as.test.clustering.cluster.web.AbstractWebFailoverTestCase;
import org.jboss.as.test.clustering.single.web.Mutable;
import org.jboss.as.test.clustering.single.web.SimpleServlet;
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.WebArchive;
import org.junit.runner.RunWith;
/**
* Test failover with CDI session scoped bean using ProtoStream.
*
* @author Paul Ferraro
*/
@RunWith(Arquillian.class)
public class ProtoStreamCDIFailoverTestCase extends AbstractWebFailoverTestCase {
private static final String MODULE_NAME = CDIFailoverTestCase.class.getSimpleName();
private static final String DEPLOYMENT_NAME = MODULE_NAME + ".ear";
private static final String WEB_DEPLOYMENT_NAME = MODULE_NAME + ".war";
public ProtoStreamCDIFailoverTestCase() {
super(DEPLOYMENT_NAME + '.' + WEB_DEPLOYMENT_NAME, TransactionMode.TRANSACTIONAL);
}
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_3, managed = false, testable = false)
@TargetsContainer(NODE_3)
public static Archive<?> deployment3() {
return createDeployment();
}
private static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, WEB_DEPLOYMENT_NAME);
war.addPackage(IncrementorBean.class.getPackage());
war.addClasses(Incrementor.class, SimpleServlet.class, Mutable.class);
ClusterTestUtil.addTopologyListenerDependencies(war);
war.setWebXML(CDIFailoverTestCase.class.getPackage(), "web.xml");
war.addAsWebInfResource(CDIFailoverTestCase.class.getPackage(), "distributable-web.xml", "distributable-web.xml");
war.addAsServiceProvider(SerializationContextInitializer.class.getName(), CDISerializationContextInitializer.class.getName() + "Impl");
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, DEPLOYMENT_NAME);
ear.addAsModule(war);
return ear;
}
}
| 4,058
| 44.606742
| 143
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/cdi/webapp/CDIServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.cdi.webapp;
import java.io.IOException;
import jakarta.inject.Inject;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.jboss.as.test.clustering.cluster.ejb.stateful.bean.Incrementor;
import org.jboss.as.test.clustering.single.web.SimpleServlet;
/**
* Note that the servlet is mapped to /simple using web.xml servlet-mapping overriding @WebServlet of the SimpleServlet.
*
* @author Tomas Remes
* @author Radoslav Husar
*/
public class CDIServlet extends SimpleServlet {
private static final long serialVersionUID = 5167789049451718160L;
@Inject
private Incrementor incrementor;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
this.increment(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
this.increment(request, response);
}
private void increment(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession(true);
response.addHeader(SESSION_ID_HEADER, session.getId());
int value = this.incrementor.increment();
response.setIntHeader(VALUE_HEADER, value);
this.getServletContext().log(request.getRequestURI() + ", value = " + value);
response.getWriter().write("Success");
}
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
response.addHeader(SESSION_ID_HEADER, session.getId());
this.incrementor.reset();
}
}
| 2,918
| 35.949367
| 121
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/cdi/webapp/IncrementorDecorator.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.clustering.cluster.cdi.webapp;
import java.io.Serializable;
import jakarta.annotation.Priority;
import jakarta.decorator.Decorator;
import jakarta.decorator.Delegate;
import jakarta.inject.Inject;
import jakarta.interceptor.Interceptor;
import org.jboss.as.test.clustering.cluster.ejb.stateful.bean.Incrementor;
/**
* Test that Weld's {@link Decorator} impl serializes and deserializes on a remote note.
*
* @author Radoslav Husar
*/
@Decorator
@Priority(Interceptor.Priority.APPLICATION)
public class IncrementorDecorator implements Incrementor, Serializable {
private static final long serialVersionUID = 7389752076482339566L;
@Inject
@Delegate
private Incrementor delegate;
@Override
public int increment() {
return delegate.increment();
}
}
| 1,839
| 34.384615
| 88
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/cdi/webapp/IncrementorBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.cdi.webapp;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;
import jakarta.enterprise.context.SessionScoped;
import jakarta.inject.Named;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.jboss.as.test.clustering.cluster.ejb.stateful.bean.Incrementor;
/**
* @author Tomas Remes
*/
@Named
@SessionScoped
public class IncrementorBean implements Incrementor, Serializable {
private static final long serialVersionUID = -8232968628862534975L;
private final AtomicInteger count;
IncrementorBean() {
this.count = new AtomicInteger(0);
}
@ProtoFactory
IncrementorBean(int value) {
this.count = new AtomicInteger(value);
}
@Override
public int increment() {
return this.count.incrementAndGet();
}
@Override
public void reset() {
this.count.set(0);
}
@ProtoField(number = 1, defaultValue = "0")
int value() {
return this.count.get();
}
}
| 2,123
| 30.235294
| 74
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/cdi/webapp/CDISerializationContextInitializer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.cdi.webapp;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
/**
* @author Paul Ferraro
*/
@AutoProtoSchemaBuilder(includeClasses = { IncrementorBean.class }, service = false)
public interface CDISerializationContextInitializer extends SerializationContextInitializer {
}
| 1,434
| 40
| 93
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/registry/RegistryTestCase.java
|
package org.jboss.as.test.clustering.cluster.registry;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.*;
import java.util.Collection;
import java.util.PropertyPermission;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.clustering.cluster.registry.bean.RegistryRetriever;
import org.jboss.as.test.clustering.cluster.registry.bean.RegistryRetrieverBean;
import org.jboss.as.test.clustering.ejb.EJBDirectory;
import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory;
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;
@RunWith(Arquillian.class)
public class RegistryTestCase extends AbstractClusteringTestCase {
private static final String MODULE_NAME = RegistryTestCase.class.getSimpleName();
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> createDeploymentForContainer1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> createDeploymentForContainer2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
return ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war")
.addPackage(RegistryRetriever.class.getPackage())
.setWebXML(RegistryTestCase.class.getPackage(), "web.xml")
.addAsManifestResource(createPermissionsXmlAsset(new PropertyPermission(NODE_NAME_PROPERTY, "read"), new RuntimePermission("getClassLoader")), "permissions.xml")
;
}
@Test
public void test() throws Exception {
try (EJBDirectory context = new RemoteEJBDirectory(MODULE_NAME)) {
RegistryRetriever bean = context.lookupStateless(RegistryRetrieverBean.class, RegistryRetriever.class);
Collection<String> names = bean.getNodes();
assertEquals(2, names.size());
assertTrue(names.toString(), names.contains(NODE_1));
assertTrue(names.toString(), names.contains(NODE_2));
undeploy(DEPLOYMENT_1);
names = bean.getNodes();
assertEquals(1, names.size());
assertTrue(names.contains(NODE_2));
deploy(DEPLOYMENT_1);
names = bean.getNodes();
assertEquals(2, names.size());
assertTrue(names.contains(NODE_1));
assertTrue(names.contains(NODE_2));
stop(NODE_2);
names = bean.getNodes();
assertEquals(1, names.size());
assertTrue(names.contains(NODE_1));
start(NODE_2);
names = bean.getNodes();
assertEquals(2, names.size());
assertTrue(names.contains(NODE_1));
assertTrue(names.contains(NODE_2));
}
}
}
| 3,265
| 37.423529
| 177
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/registry/bean/RegistryRetrieverBean.java
|
package org.jboss.as.test.clustering.cluster.registry.bean;
import java.util.Collection;
import java.util.TreeSet;
import jakarta.ejb.EJB;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateless;
import org.wildfly.clustering.registry.Registry;
@Stateless
@Remote(RegistryRetriever.class)
public class RegistryRetrieverBean implements RegistryRetriever {
@EJB
private Registry<String, String> registry;
@Override
public Collection<String> getNodes() {
return new TreeSet<>(this.registry.getEntries().keySet());
}
}
| 548
| 22.869565
| 66
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/registry/bean/RegistryBean.java
|
package org.jboss.as.test.clustering.cluster.registry.bean;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.AbstractMap;
import java.util.Map;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import jakarta.ejb.Local;
import jakarta.ejb.Singleton;
import jakarta.ejb.Startup;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.wildfly.clustering.Registration;
import org.wildfly.clustering.group.Group;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.registry.Registry;
import org.wildfly.clustering.registry.RegistryFactory;
import org.wildfly.clustering.registry.RegistryListener;
@Singleton
@Startup
@Local(Registry.class)
public class RegistryBean implements Registry<String, String>, RegistryListener<String, String> {
@Resource(name = "clustering/registry")
private RegistryFactory<String, String> factory;
private Registry<String, String> registry;
private Registration registration;
private static String getLocalHost() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return null;
}
}
@PostConstruct
public void init() {
this.registry = this.factory.createRegistry(new AbstractMap.SimpleImmutableEntry<>(System.getProperty("jboss.node.name"), getLocalHost()));
this.registration = this.registry.register(this);
}
@PreDestroy
public void destroy() {
this.registration.close();
this.registry.close();
}
@Override
public void close() {
// We'll close on destroy
}
@Override
public void addedEntries(Map<String, String> added) {
try {
// Ensure the thread context classloader of the notification is correct
Thread.currentThread().getContextClassLoader().loadClass(this.getClass().getName());
// Ensure the correct naming context is set
Context context = new InitialContext();
try {
context.lookup("java:comp/env/clustering/registry");
} finally {
context.close();
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
} catch (NamingException e) {
throw new IllegalStateException(e);
}
System.out.println("New registry entry:" + added);
}
@Override
public void updatedEntries(Map<String, String> updated) {
try {
// Ensure the thread context classloader of the notification is correct
Thread.currentThread().getContextClassLoader().loadClass(this.getClass().getName());
// Ensure the correct naming context is set
Context context = new InitialContext();
try {
context.lookup("java:comp/env/clustering/registry");
} finally {
context.close();
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
} catch (NamingException e) {
throw new IllegalStateException(e);
}
System.out.println("Updated registry entry:" + updated);
}
@Override
public void removedEntries(Map<String, String> removed) {
try {
// Ensure the thread context classloader of the notification is correct
Thread.currentThread().getContextClassLoader().loadClass(this.getClass().getName());
// Ensure the correct naming context is set
Context context = new InitialContext();
try {
context.lookup("java:comp/env/clustering/registry");
} finally {
context.close();
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
} catch (NamingException e) {
throw new IllegalStateException(e);
}
System.out.println("Removed registry entry:" + removed);
}
@Override
public Group getGroup() {
return this.registry.getGroup();
}
@Override
public Registration register(RegistryListener<String, String> listener) {
return this.registry.register(listener);
}
@Override
public Map<String, String> getEntries() {
return this.registry.getEntries();
}
@Override
public Map.Entry<String, String> getEntry(Node node) {
return this.registry.getEntry(node);
}
}
| 4,619
| 32
| 147
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/registry/bean/RegistryRetriever.java
|
package org.jboss.as.test.clustering.cluster.registry.bean;
import java.util.Collection;
public interface RegistryRetriever {
Collection<String> getNodes();
}
| 165
| 19.75
| 59
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jpa/DummyEntity.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.jpa;
import java.io.Serializable;
import jakarta.persistence.Cacheable;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class DummyEntity implements Serializable {
@Id
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String toString() {
return "DummyEntity{" +
"id=" + id +
'}';
}
}
| 1,714
| 29.625
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jpa/ClusteredJPA2LCTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.jpa;
import java.net.URISyntaxException;
import java.net.URL;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.clustering.ClusterDatabaseTestUtil;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.shared.ManagementServerSetupTask;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Smoke test of clustered Jakarta Persistence 2nd level cache implemented by Infinispan.
* @author Jan Martiska
*/
@RunWith(Arquillian.class)
@ServerSetup(ClusteredJPA2LCTestCase.ServerSetupTask.class)
public class ClusteredJPA2LCTestCase extends AbstractClusteringTestCase {
private static final String MODULE_NAME = ClusteredJPA2LCTestCase.class.getSimpleName();
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> createDeploymentForContainer1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> createDeploymentForContainer2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war");
war.addPackage(ClusteredJPA2LCTestCase.class.getPackage());
war.addAsWebInfResource(ClusteredJPA2LCTestCase.class.getPackage(), "persistence.xml",
"classes/META-INF/persistence.xml");
return war;
}
@BeforeClass
public static void beforeClass() throws Exception {
ClusterDatabaseTestUtil.startH2();
}
@AfterClass
public static void afterClass() throws Exception {
ClusterDatabaseTestUtil.stopH2();
}
// REST client to control entity creation, caching, eviction,... on the servers
private Client restClient;
@Before
public void init() {
this.restClient = ClientBuilder.newClient();
}
@After
public void destroy() {
this.restClient.close();
}
@Test
public void testEntityCacheInvalidation(@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) URL url0,
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) URL url1)
throws Exception {
final WebTarget node0 = getWebTarget(url0);
final WebTarget node1 = getWebTarget(url1);
final String entityId = "1";
createEntity(node0, entityId);
Assert.assertTrue(isInCache(node0, entityId));
Thread.sleep(GRACE_TIME_TO_REPLICATE);
addToCache(node1, entityId);
Assert.assertTrue(isInCache(node1, entityId));
evictFromCache(node1, entityId);
Assert.assertFalse(isInCache(node0, entityId));
Assert.assertFalse(isInCache(node1, entityId));
}
private boolean isInCache(WebTarget node, String entityId) {
return Boolean.valueOf(
node.path("isInCache").path(entityId).request().get().readEntity(String.class));
}
private void addToCache(WebTarget node, String entityId) {
int status = node.path("cache").path(entityId).request().get().getStatus();
Assert.assertEquals(204, status);
}
private void evictFromCache(WebTarget node, String entityId) {
int status = node.path("evict").path(entityId).request().get().getStatus();
Assert.assertEquals(204, status);
}
private void createEntity(WebTarget node, String entityId) {
int status = node.path("create").path(entityId).request().get().getStatus();
Assert.assertEquals(204, status);
}
protected WebTarget getWebTarget(URL url) throws URISyntaxException {
return restClient.target(url.toURI());
}
public static class ServerSetupTask extends ManagementServerSetupTask {
public ServerSetupTask() {
super(NODE_1_2, createContainerConfigurationBuilder()
.setupScript(createScriptBuilder()
.add("/subsystem=datasources/data-source=h2:add(jndi-name=java:jboss/datasources/H2, enabled=true, use-java-context=true, connection-url=\"jdbc:h2:tcp://localhost:%s/MainPU;VARIABLE_BINARY=TRUE\", driver-name=h2)", DB_PORT)
.add("/subsystem=infinispan/cache-container=hibernate:write-attribute(name=marshaller, value=PROTOSTREAM)")
.build())
.tearDownScript(createScriptBuilder()
.add("/subsystem=infinispan/cache-container=hibernate:write-attribute(name=marshaller, value=JBOSS)")
.add("/subsystem=datasources/data-source=h2:remove")
.build())
.build()
);
}
}
}
| 6,574
| 39.337423
| 251
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jpa/DummyEntityRESTResource.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.jpa;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import jakarta.persistence.CacheRetrieveMode;
import jakarta.persistence.CacheStoreMode;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.UserTransaction;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
/**
* @author Jan Martiska
*/
@RequestScoped
@Path("/")
public class DummyEntityRESTResource {
@PersistenceContext(unitName = "MainPU")
private EntityManager em;
@Inject
private UserTransaction tx;
@GET
@Path("/create/{id}")
public void createNew(@PathParam(value = "id") Long id) throws Exception {
final DummyEntity entity = new DummyEntity();
entity.setId(id);
tx.begin();
em.persist(entity);
tx.commit();
}
@GET
@Path("/cache/{id}")
public void addToCacheByQuerying(@PathParam(value = "id") Long id) {
em.createQuery("select b from DummyEntity b where b.id=:id", DummyEntity.class)
.setParameter("id", id)
.setHint("jakarta.persistence.cache.storeMode", CacheStoreMode.USE)
.setHint("jakarta.persistence.cache.retrieveMode", CacheRetrieveMode.BYPASS)
.getSingleResult();
}
@GET
@Path("/evict/{id}")
public void evict(@PathParam(value = "id") Long id) {
em.getEntityManagerFactory().getCache().evict(DummyEntity.class, id);
}
@GET
@Path("/isInCache/{id}")
@Produces("text/plain")
public boolean isEntityInCache(@PathParam(value = "id") Long id) {
return em.getEntityManagerFactory().getCache().contains(DummyEntity.class, id);
}
}
| 2,848
| 32.916667
| 92
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jpa/DummyEntityControllingApplication.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.jpa;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
/**
* @author Jan Martiska
*/
@ApplicationPath("/")
public class DummyEntityControllingApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<Class<?>>();
s.add(DummyEntityRESTResource.class);
return s;
}
}
| 1,504
| 32.444444
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jpa/custom/ClusteredJPA2LCCustomRegionTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.jpa.custom;
import java.net.URISyntaxException;
import java.net.URL;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Response;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.shared.CLIServerSetupTask;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.spec.se.manifest.ManifestDescriptor;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test of clustered Jakarta Persistence 2nd level cache implemented by Infinispan using entity custom region.
* <p>
* In persistence.xml we add the following:
* <code>
* <property name="hibernate.cache.infinispan.entity.cfg" value="entity-replicated"/>
* </code>
* This has the effect of using the Infinispan cache "entity-replicated" as the template for entities's caches;
* </p>
* <p>
* In the standalone-ha.xml, we have an invalidation-cache named "entity" in the cache container "hibernate" of
* the Infinispan subsystem;
* By default, this cache would be used as the template for entities's caches;
* Here we are overriding this default creating a replicated-cache in the cache container "hibernate", and using it
* as template;
* </p>
* <p>
* We are using the entity {@link DummyEntityCustomRegion}, which also defines a custom region name to be used for
* its second level cache name:
* <code>
*
* @author Jan Martiska and Tommaso Borgato
* @Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL, region = DummyEntityCustomRegion.DUMMY_ENTITY_REGION_NAME)
* </code>
* </p>
* <p>
* The result is that, for the entity {@link DummyEntityCustomRegion}, a replicated-cache named
* "ClusteredJPA2LCCustomRegionTestCase.war#MainPU.DUMMY_ENTITY_REGION_NAME" is created;
* </p>
* <p>
* The goals of this test are:
* <ul>
* <li>verify that the cache created for the entity {@link DummyEntityCustomRegion} is actually a replicated-cache</li>
* <li>verify that the cache created for the entity {@link DummyEntityCustomRegion} is actually named accordingly with the annotation on the entity</li>
* </ul>
* </p>
*/
@RunWith(Arquillian.class)
@ServerSetup(ClusteredJPA2LCCustomRegionTestCase.ServerSetupTask.class)
public class ClusteredJPA2LCCustomRegionTestCase extends AbstractClusteringTestCase {
private static final String MODULE_NAME = ClusteredJPA2LCCustomRegionTestCase.class.getSimpleName();
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> createDeploymentForContainer1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> createDeploymentForContainer2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war");
war.addPackage(ClusteredJPA2LCCustomRegionTestCase.class.getPackage());
war.addAsWebInfResource(ClusteredJPA2LCCustomRegionTestCase.class.getPackage(), "persistence.xml",
"classes/META-INF/persistence.xml");
war.addAsWebInfResource(getWebXml(), "web.xml");
war.setManifest(new StringAsset(
Descriptors.create(ManifestDescriptor.class)
.attribute("Dependencies", "org.infinispan, org.infinispan.commons")
.exportAsString()));
return war;
}
/**
* We need a reference to the <code>hibernate</code> cache-container to access its properties programmatically
*/
private static StringAsset getWebXml() {
return new StringAsset("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<web-app version=\"3.0\" metadata-complete=\"false\" xmlns=\"http://java.sun.com/xml/ns/javaee\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\">\n"
+ " <resource-ref>\n"
+ " <res-ref-name>infinispan/hibernate</res-ref-name>\n"
+ " <res-type>org.infinispan.manager.CacheContainer</res-type>"
+ " <lookup-name>java:jboss/infinispan/container/hibernate</lookup-name>\n"
+ " </resource-ref>\n"
+ "</web-app>");
}
// REST client to control entity creation, caching, eviction,... on the servers
private Client restClient;
@Before
public void init() {
this.restClient = ClientBuilder.newClient();
}
@After
public void destroy() {
this.restClient.close();
}
/**
* We have a replicated entity cache between two nodes.
* We verify that the cache is actually a replicated cache and that it was named accordingly to the
* {@link DummyEntityCustomRegion} entity annotation
* <code>@Cache(region = DummyEntityCustomRegion.DUMMY_ENTITY_REGION_NAME)</code>;
* <p>
* The two nodes don't actually have a shared database instance, but that doesn't matter for this test.
*/
@Test
public void testEntityInCustomCache(@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) URL url0,
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) URL url1)
throws Exception {
final WebTarget node0 = getWebTarget(url0);
final WebTarget node1 = getWebTarget(url1);
final String entityId = "2";
// create entity
createEntity(node0, entityId);
// put entity in second level cache
addEntityToCache(node0, entityId);
// get the name of the cache containing the entity
String regionName = getRegionNameForEntity(node1, entityId);
Assert.assertNotNull(
String.format("Region name for entity '%s' should NOT be null!", DummyEntityCustomRegion.class.getCanonicalName()),
regionName);
Assert.assertTrue(
String.format("Region name for entity '%s' should be something like %s.war#MainPUCustomRegion.%s",
DummyEntityCustomRegion.class.getCanonicalName(),
ClusteredJPA2LCCustomRegionTestCase.class.getName(),
DummyEntityCustomRegion.DUMMY_ENTITY_REGION_NAME),
regionName.contains(DummyEntityCustomRegion.DUMMY_ENTITY_REGION_NAME));
// verify that cache is actually a replicated one
Boolean isReplicated = getCustomRegionCacheIsReplicated(node1, regionName);
Assert.assertTrue(String.format("Cache '%s' should be a replicated-cache!", regionName), isReplicated);
Boolean isInvalidation = getCustomRegionCacheIsInvalidation(node0, regionName);
Assert.assertFalse(String.format("Cache '%s' should NOT be an invalidation-cache!", regionName), isInvalidation);
}
/**
* We have a replicated entity cache between two nodes.
* We verify that the cache is actually a replicated cache and that it was configured accordingly to the
* settings in persistence.xml;
* <p>
* The two nodes don't actually have a shared database instance, but that doesn't matter for this test.
*/
@Test
public void testPropsInCustomCache(@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) URL url0,
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) URL url1)
throws Exception {
final WebTarget node0 = getWebTarget(url0);
final WebTarget node1 = getWebTarget(url1);
final String entityId = "3";
// create entity
createEntity(node0, entityId);
// put entity in second level cache
addEntityToCache(node0, entityId);
// get the name of the cache containing the entity
String regionName = getRegionNameForEntity(node1, entityId);
Assert.assertNotNull(
String.format("Region name for entity '%s' should NOT be null!", DummyEntityCustomRegion.class.getCanonicalName()),
regionName);
// max_entries
Long evictionMaxEntries = getEvictionMaxEntries(node0, regionName);
Assert.assertEquals(String.format("Cache '%s' should have attribute memory.size=99991", regionName), evictionMaxEntries.longValue(), 99991);
// lifespan
Long expirationLifespan = getExpirationLifespan(node0, regionName);
Assert.assertEquals(String.format("Cache '%s' should have attribute expiration.lifespan=99992", regionName), expirationLifespan.longValue(), 99992);
// max_idle
Long expirationMaxIdle = getExpirationMaxIdle(node0, regionName);
Assert.assertEquals(String.format("Cache '%s' should have attribute expiration.maxIdle=99993", regionName), expirationMaxIdle.longValue(), 99993);
// wake_up_interval
Long expirationWakeUpInterval = getExpirationWakeUpInterval(node0, regionName);
Assert.assertEquals(String.format("Cache '%s' should have attribute expiration.wakeUpInterval=9994", regionName), expirationWakeUpInterval.longValue(), 9994);
}
private static void createEntity(WebTarget node, String entityId) {
int status = node.path("custom-region").path("create").path(entityId).request().get().getStatus();
Assert.assertEquals(204, status);
}
private static void addEntityToCache(WebTarget node, String entityId) {
int status = node.path("custom-region").path("cache").path(entityId).request().get().getStatus();
Assert.assertEquals(204, status);
}
private static String getRegionNameForEntity(WebTarget node, String entityId) {
Response response = node.path("custom-region").path("region-name")
.queryParam("name", DummyEntityCustomRegion.DUMMY_ENTITY_REGION_NAME)
.queryParam("id", entityId)
.request().get();
int status = response.getStatus();
Assert.assertEquals(200, status);
return response.readEntity(String.class);
}
private static Boolean getCustomRegionCacheIsReplicated(WebTarget node, String regionName) {
Response response = node.path("custom-region").path("is-replicated").path(regionName).request().get();
int status = response.getStatus();
Assert.assertEquals(200, status);
return (response.readEntity(Boolean.class));
}
private static Boolean getCustomRegionCacheIsInvalidation(WebTarget node, String regionName) {
Response response = node.path("custom-region").path("is-invalidation").path(regionName).request().get();
int status = response.getStatus();
Assert.assertEquals(200, status);
return (response.readEntity(Boolean.class));
}
private static Long getEvictionMaxEntries(WebTarget node, String cacheName) {
Response response = node.path("custom-region").path("eviction-max-entries").path(cacheName).request().get();
int status = response.getStatus();
Assert.assertEquals(200, status);
return (response.readEntity(Long.class));
}
private static Long getExpirationLifespan(WebTarget node, String cacheName) {
Response response = node.path("custom-region").path("expiration-lifespan").path(cacheName).request().get();
int status = response.getStatus();
Assert.assertEquals(200, status);
return (response.readEntity(Long.class));
}
private static Long getExpirationMaxIdle(WebTarget node, String cacheName) {
Response response = node.path("custom-region").path("expiration-max-idle").path(cacheName).request().get();
int status = response.getStatus();
Assert.assertEquals(200, status);
return (response.readEntity(Long.class));
}
private static Long getExpirationWakeUpInterval(WebTarget node, String cacheName) {
Response response = node.path("custom-region").path("expiration-wake-up-interval").path(cacheName).request().get();
int status = response.getStatus();
Assert.assertEquals(200, status);
return (response.readEntity(Long.class));
}
protected WebTarget getWebTarget(URL url) throws URISyntaxException {
return restClient.target(url.toURI());
}
public static class ServerSetupTask extends CLIServerSetupTask {
public ServerSetupTask() {
this.builder.node(TWO_NODES)
.setup("/subsystem=infinispan/cache-container=hibernate/replicated-cache=entity-replicated-template:add()")
.teardown("/subsystem=infinispan/cache-container=hibernate/replicated-cache=entity-replicated-template:remove()")
;
}
}
}
| 14,617
| 45.852564
| 166
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jpa/custom/DummyEntityCustomRegion.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.jpa.custom;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import jakarta.persistence.Cacheable;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import java.io.Serializable;
@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL, region = DummyEntityCustomRegion.DUMMY_ENTITY_REGION_NAME)
public class DummyEntityCustomRegion implements Serializable {
public static final String DUMMY_ENTITY_REGION_NAME = "DUMMY_ENTITY_REGION_NAME";
@Id
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String toString() {
return "DummyEntityCustomRegion{" +
"id=" + id +
'}';
}
}
| 1,891
| 31.62069
| 113
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jpa/custom/DummyEntityCustomRegionRESTResource.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.jpa.custom;
import org.hibernate.Session;
import org.hibernate.stat.Statistics;
import org.infinispan.Cache;
import org.infinispan.manager.CacheContainer;
import jakarta.annotation.Resource;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import jakarta.persistence.CacheRetrieveMode;
import jakarta.persistence.CacheStoreMode;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.UserTransaction;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Response;
/**
* @author Tommaso Borgato
*/
@RequestScoped
@Path("/custom-region")
public class DummyEntityCustomRegionRESTResource {
@PersistenceContext(unitName = "MainPUCustomRegion")
private EntityManager em;
@Resource(name = "infinispan/hibernate")
private CacheContainer container;
@Inject
private UserTransaction tx;
@GET
@Path("/create/{id}")
public void createNew(@PathParam(value = "id") Long id) throws Exception {
final DummyEntityCustomRegion entity = new DummyEntityCustomRegion();
entity.setId(id);
tx.begin();
em.persist(entity);
tx.commit();
}
@GET
@Path("/cache/{id}")
public void addToCacheByQuerying(@PathParam(value = "id") Long id) {
em.createQuery("select b from DummyEntityCustomRegion b where b.id=:id", DummyEntityCustomRegion.class)
.setParameter("id", id)
.setHint("jakarta.persistence.cache.storeMode", CacheStoreMode.USE)
.setHint("jakarta.persistence.cache.retrieveMode", CacheRetrieveMode.BYPASS)
.getSingleResult();
}
@GET
@Path("/evict/{id}")
public void evict(@PathParam(value = "id") Long id) {
em.getEntityManagerFactory().getCache().evict(DummyEntityCustomRegion.class, id);
}
@GET
@Path("/isInCache/{id}")
@Produces("text/plain")
public boolean isEntityInCache(@PathParam(value = "id") Long id) {
return em.getEntityManagerFactory().getCache().contains(DummyEntityCustomRegion.class, id);
}
@GET
@Path("/clear-statistics")
@Produces("text/plain")
public Response clearStatistics() {
Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics();
stats.clear();
return Response.ok().build();
}
@GET
@Path("/region-name")
@Produces("text/plain")
public Response getRegionNameForEntity(@QueryParam("name") String dummyEntityRegionName, @QueryParam("id") Long id) {
for (String name : container.getCacheNames()) {
if (name.contains(dummyEntityRegionName)) {
Cache cache = container.getCache(name);
for (Object cs: cache.keySet()) {
if (cs.toString().equalsIgnoreCase(String.format("%s#%d", DummyEntityCustomRegion.class.getCanonicalName(), id))) {
return Response.ok(name).build();
}
}
}
}
return Response.status(Response.Status.NO_CONTENT).build();
}
@GET
@Path("/is-replicated/{cache-name}")
@Produces("text/plain")
public Response getIsReplicated(@PathParam(value = "cache-name") String cacheName) {
boolean res = container.getCache(cacheName).getCacheConfiguration().clustering().cacheMode().isReplicated();
return Response.ok().entity(Boolean.toString(res)).build();
}
@GET
@Path("/is-invalidation/{cache-name}")
@Produces("text/plain")
public Response getIsInvalidation(@PathParam(value = "cache-name") String cacheName) {
boolean res = container.getCache(cacheName).getCacheConfiguration().clustering().cacheMode().isInvalidation();
return Response.ok().entity(Boolean.toString(res)).build();
}
@GET
@Path("/eviction-max-entries/{cache-name}")
@Produces("text/plain")
public Response getEvictionMaxEntries(@PathParam(value = "cache-name") String cacheName) {
Object res = container.getCache(cacheName).getCacheConfiguration().memory().size();
return Response.ok().entity(res).build();
}
@GET
@Path("/expiration-lifespan/{cache-name}")
@Produces("text/plain")
public Response getExpirationLifespan(@PathParam(value = "cache-name") String cacheName) {
Object res = container.getCache(cacheName).getCacheConfiguration().expiration().lifespan();
return Response.ok().entity(res).build();
}
@GET
@Path("/expiration-max-idle/{cache-name}")
@Produces("text/plain")
public Response getExpirationMaxIdle(@PathParam(value = "cache-name") String cacheName) {
Object res = container.getCache(cacheName).getCacheConfiguration().expiration().maxIdle();
return Response.ok().entity(res).build();
}
@GET
@Path("/expiration-wake-up-interval/{cache-name}")
@Produces("text/plain")
public Response getExpirationWakeUpInterval(@PathParam(value = "cache-name") String cacheName) {
Object res = container.getCache(cacheName).getCacheConfiguration().expiration().wakeUpInterval();
return Response.ok().entity(res).build();
}
}
| 6,379
| 36.97619
| 135
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jpa/custom/DummyEntityControllingApplication.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.jpa.custom;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
/**
* @author Tommaso Borgato
*/
@ApplicationPath("/")
public class DummyEntityControllingApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<Class<?>>();
s.add(DummyEntityCustomRegionRESTResource.class);
return s;
}
}
| 1,526
| 32.933333
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jsf/JSFFailoverTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.jsf;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.clustering.cluster.jsf.webapp.Game;
import org.jboss.as.test.clustering.cluster.web.DistributableTestCase;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
/**
* @author Paul Ferraro
*/
@RunWith(Arquillian.class)
public class JSFFailoverTestCase extends AbstractJSFFailoverTestCase {
private static final String MODULE_NAME = JSFFailoverTestCase.class.getSimpleName();
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war");
war.addPackage(Game.class.getPackage());
war.setWebXML(DistributableTestCase.class.getPackage(), "web.xml");
war.addAsWebResource(AbstractJSFFailoverTestCase.class.getPackage(), "home.xhtml", "home.xhtml");
war.addAsWebInfResource(AbstractJSFFailoverTestCase.class.getPackage(), "faces-config.xml", "faces-config.xml");
war.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
return war;
}
}
| 2,776
| 41.075758
| 120
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jsf/ProtoStreamJSFFailoverTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.jsf;
import org.infinispan.protostream.SerializationContextInitializer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.clustering.cluster.jsf.webapp.Game;
import org.jboss.as.test.clustering.cluster.jsf.webapp.JSFSerializationContextInitializer;
import org.jboss.as.test.clustering.cluster.web.DistributableTestCase;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
/**
* @author Paul Ferraro
*/
@RunWith(Arquillian.class)
public class ProtoStreamJSFFailoverTestCase extends AbstractJSFFailoverTestCase {
private static final String MODULE_NAME = ProtoStreamJSFFailoverTestCase.class.getSimpleName();
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war");
war.addPackage(Game.class.getPackage());
war.setWebXML(DistributableTestCase.class.getPackage(), "web.xml");
war.addAsWebResource(AbstractJSFFailoverTestCase.class.getPackage(), "home.xhtml", "home.xhtml");
war.addAsWebInfResource(AbstractJSFFailoverTestCase.class.getPackage(), "faces-config.xml", "faces-config.xml");
war.addAsWebInfResource(AbstractJSFFailoverTestCase.class.getPackage(), "distributable-web.xml", "distributable-web.xml");
war.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
war.addAsServiceProvider(SerializationContextInitializer.class.getName(), JSFSerializationContextInitializer.class.getName() + "Impl");
return war;
}
}
| 3,231
| 45.171429
| 143
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jsf/AbstractJSFFailoverTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.jsf;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.junit.Assert;
import org.junit.Test;
/**
* Weld numberguess example converted to a test
*
* @author Stuart Douglas
*/
public abstract class AbstractJSFFailoverTestCase extends AbstractClusteringTestCase {
/**
* Parses the response page and headers for a cookie, Jakarta Server Faces view state and the numberguess game status.
*/
private static NumberGuessState parseState(HttpResponse response, String sessionId) throws IllegalStateException, IOException {
Pattern smallestPattern = Pattern.compile("<span id=\"numberGuess:smallest\">([^<]+)</span>");
Pattern biggestPattern = Pattern.compile("<span id=\"numberGuess:biggest\">([^<]+)</span>");
Pattern remainingPattern = Pattern.compile("You have (\\d+) guesses remaining.");
Pattern viewStatePattern = Pattern.compile("id=\".*jakarta.faces.ViewState.*\" value=\"([^\"]*)\"");
Matcher matcher;
NumberGuessState state = new NumberGuessState();
String responseString = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
Map.Entry<String, String> sessionRouteEntry = parseSessionRoute(response);
state.sessionId = (sessionRouteEntry != null) ? sessionRouteEntry.getKey() : sessionId;
matcher = smallestPattern.matcher(responseString);
if (matcher.find()) {
state.smallest = matcher.group(1);
}
matcher = biggestPattern.matcher(responseString);
if (matcher.find()) {
state.biggest = matcher.group(1);
}
matcher = remainingPattern.matcher(responseString);
if (matcher.find()) {
state.remainingGuesses = matcher.group(1);
}
matcher = viewStatePattern.matcher(responseString);
if (matcher.find()) {
state.jsfViewState = matcher.group(1);
}
return state;
}
/**
* Creates an HTTP POST request with a number guess.
*/
private static HttpUriRequest buildPostRequest(String url, String sessionId, String viewState, String guess) {
HttpPost post = new HttpPost(url);
List<NameValuePair> list = new LinkedList<>();
list.add(new BasicNameValuePair("jakarta.faces.ViewState", viewState));
list.add(new BasicNameValuePair("numberGuess", "numberGuess"));
list.add(new BasicNameValuePair("numberGuess:guessButton", "Guess"));
list.add(new BasicNameValuePair("numberGuess:inputGuess", guess));
post.setEntity(new StringEntity(URLEncodedUtils.format(list, StandardCharsets.UTF_8), ContentType.APPLICATION_FORM_URLENCODED));
if (sessionId != null) {
post.setHeader("Cookie", "JSESSIONID=" + sessionId);
}
return post;
}
/**
* Creates an HTTP GET request, with a potential JSESSIONID cookie.
*/
private static HttpUriRequest buildGetRequest(String url, String sessionId) {
HttpGet request = new HttpGet(url);
if (sessionId != null) {
request.addHeader("Cookie", "JSESSIONID=" + sessionId);
}
return request;
}
/**
* Test simple graceful shutdown failover:
* <p/>
* 1/ Start 2 containers and deploy <distributable/> webapp.
* 2/ Query first container creating a web session.
* 3/ Shutdown first container.
* 4/ Query second container verifying sessions got replicated.
* 5/ Bring up the first container.
* 6/ Query first container verifying that updated sessions replicated back.
*/
@Test
public void testGracefulSimpleFailover(
@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
throws IOException {
String url1 = baseURL1.toString() + "home.jsf";
String url2 = baseURL2.toString() + "home.jsf";
log.trace("URLs are: " + url1 + ", " + url2);
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
HttpResponse response;
NumberGuessState state;
// First non-Jakarta Server Faces request to the home page
response = client.execute(buildGetRequest(url1, null));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
state = parseState(response, null);
} finally {
HttpClientUtils.closeQuietly(response);
}
// We get a cookie!
String sessionId = state.sessionId;
Assert.assertNotNull(sessionId);
Assert.assertEquals("0", state.smallest);
Assert.assertEquals("100", state.biggest);
Assert.assertEquals("10", state.remainingGuesses);
// We do a Jakarta Server Faces POST request, guessing "1"
response = client.execute(buildPostRequest(url1, state.sessionId, state.jsfViewState, "1"));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
state = parseState(response, sessionId);
} finally {
HttpClientUtils.closeQuietly(response);
}
Assert.assertEquals("2", state.smallest);
Assert.assertEquals("100", state.biggest);
Assert.assertEquals("9", state.remainingGuesses);
// Gracefully shutdown the 1st container.
stop(NODE_1);
// Now we do a Jakarta Server Faces POST request with a cookie on to the second node, guessing 100, expecting to find a replicated state.
response = client.execute(buildPostRequest(url2, state.sessionId, state.jsfViewState, "100"));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
state = parseState(response, sessionId);
} finally {
HttpClientUtils.closeQuietly(response);
}
// If the state would not be replicated, we would have 9 remaining guesses.
Assert.assertEquals("Session failed to replicate after container 1 was shutdown.", "8", state.remainingGuesses);
// The server should accept our cookie and not try to set a different one
Assert.assertEquals(sessionId, state.sessionId);
Assert.assertEquals("2", state.smallest);
Assert.assertEquals("99", state.biggest);
// Now we do a Jakarta Server Faces POST request on the second node again, guessing "99"
response = client.execute(buildPostRequest(url2, sessionId, state.jsfViewState, "99"));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
state = parseState(response, sessionId);
} finally {
HttpClientUtils.closeQuietly(response);
}
Assert.assertEquals("7", state.remainingGuesses);
Assert.assertEquals("2", state.smallest);
Assert.assertEquals("98", state.biggest);
start(NODE_1);
// And now we go back to the first node, guessing 2
response = client.execute(buildPostRequest(url1, state.sessionId, state.jsfViewState, "2"));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
state = parseState(response, sessionId);
} finally {
HttpClientUtils.closeQuietly(response);
}
Assert.assertEquals("Session failed to replicate after container 1 was brought up.", "6", state.remainingGuesses);
Assert.assertEquals(sessionId, state.sessionId);
Assert.assertEquals("3", state.smallest);
Assert.assertEquals("98", state.biggest);
// One final guess on the first node, guess 50
response = client.execute(buildPostRequest(url1, state.sessionId, state.jsfViewState, "50"));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
state = parseState(response, sessionId);
} finally {
HttpClientUtils.closeQuietly(response);
}
Assert.assertEquals(sessionId, state.sessionId);
Assert.assertEquals("5", state.remainingGuesses);
Assert.assertEquals("3", state.smallest);
Assert.assertEquals("49", state.biggest);
}
// Assert.fail("Show me the logs please!");
}
/**
* Test simple undeploy failover:
* <p/>
* 1/ Start 2 containers and deploy <distributable/> webapp.
* 2/ Query first container creating a web session.
* 3/ Undeploy application from the first container.
* 4/ Query second container verifying sessions got replicated.
* 5/ Redeploy application to the first container.
* 6/ Query first container verifying that updated sessions replicated back.
*/
@Test
public void testGracefulUndeployFailover(
@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
throws IOException {
String url1 = baseURL1.toString() + "home.jsf";
String url2 = baseURL2.toString() + "home.jsf";
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
HttpResponse response;
NumberGuessState state;
// First non-Jakarta Server Faces request to the home page
response = client.execute(buildGetRequest(url1, null));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
state = parseState(response, null);
} finally {
HttpClientUtils.closeQuietly(response);
}
// We get a cookie!
String sessionId = state.sessionId;
Assert.assertNotNull(sessionId);
Assert.assertEquals("0", state.smallest);
Assert.assertEquals("100", state.biggest);
Assert.assertEquals("10", state.remainingGuesses);
// We do a Jakarta Server Faces POST request, guessing "1"
response = client.execute(buildPostRequest(url1, state.sessionId, state.jsfViewState, "1"));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
state = parseState(response, sessionId);
} finally {
HttpClientUtils.closeQuietly(response);
}
Assert.assertEquals("2", state.smallest);
Assert.assertEquals("100", state.biggest);
Assert.assertEquals("9", state.remainingGuesses);
// Gracefully undeploy from the 1st container.
undeploy(DEPLOYMENT_1);
// Now we do a Jakarta Server Faces POST request with a cookie on to the second node, guessing 100, expecting to find a replicated state.
response = client.execute(buildPostRequest(url2, state.sessionId, state.jsfViewState, "100"));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
state = parseState(response, sessionId);
} finally {
HttpClientUtils.closeQuietly(response);
}
// If the state would not be replicated, we would have 9 remaining guesses.
Assert.assertEquals("Session failed to replicate after container 1 was shutdown.", "8", state.remainingGuesses);
// The server should accept our cookie and not try to set a different one
Assert.assertEquals(sessionId, state.sessionId);
Assert.assertEquals("2", state.smallest);
Assert.assertEquals("99", state.biggest);
// Now we do a Jakarta Server Faces POST request on the second node again, guessing "99"
response = client.execute(buildPostRequest(url2, sessionId, state.jsfViewState, "99"));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
state = parseState(response, sessionId);
} finally {
HttpClientUtils.closeQuietly(response);
}
Assert.assertEquals("7", state.remainingGuesses);
Assert.assertEquals("2", state.smallest);
Assert.assertEquals("98", state.biggest);
// Redeploy
deploy(DEPLOYMENT_1);
// And now we go back to the first node, guessing 2
response = client.execute(buildPostRequest(url1, state.sessionId, state.jsfViewState, "2"));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
state = parseState(response, sessionId);
} finally {
HttpClientUtils.closeQuietly(response);
}
Assert.assertEquals("Session failed to replicate after container 1 was brought up.", "6", state.remainingGuesses);
Assert.assertEquals(sessionId, state.sessionId);
Assert.assertEquals("3", state.smallest);
Assert.assertEquals("98", state.biggest);
// One final guess on the first node, guess 50
response = client.execute(buildPostRequest(url1, state.sessionId, state.jsfViewState, "50"));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
state = parseState(response, sessionId);
} finally {
HttpClientUtils.closeQuietly(response);
}
Assert.assertEquals(sessionId, state.sessionId);
Assert.assertEquals("5", state.remainingGuesses);
Assert.assertEquals("3", state.smallest);
Assert.assertEquals("49", state.biggest);
}
}
/**
* A simple class representing the client state.
*/
static class NumberGuessState {
String smallest;
String biggest;
String sessionId;
String remainingGuesses;
String jsfViewState;
}
}
| 16,684
| 42.225389
| 149
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jsf/webapp/Random.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.clustering.cluster.jsf.webapp;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import jakarta.inject.Qualifier;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({TYPE, METHOD, PARAMETER, FIELD})
@Retention(RUNTIME)
@Documented
@Qualifier
public @interface Random {
}
| 1,627
| 36.860465
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jsf/webapp/MaxNumber.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.clustering.cluster.jsf.webapp;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import jakarta.inject.Qualifier;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({TYPE, METHOD, PARAMETER, FIELD})
@Retention(RUNTIME)
@Documented
@Qualifier
public @interface MaxNumber {
}
| 1,630
| 36.930233
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jsf/webapp/Generator.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.clustering.cluster.jsf.webapp;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Produces;
@ApplicationScoped
public class Generator {
private int maxNumber = 100;
@Produces
@Random
int next() {
//random number, chosen by a completely fair dice roll
return 3;
}
@Produces
@MaxNumber
int getMaxNumber() {
return maxNumber;
}
}
| 1,476
| 31.822222
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jsf/webapp/Game.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.clustering.cluster.jsf.webapp;
import java.io.Serializable;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.SessionScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.enterprise.inject.spi.CDI;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.component.UIComponent;
import jakarta.faces.component.UIInput;
import jakarta.faces.context.FacesContext;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
@Named
@SessionScoped
public class Game implements Serializable {
/**
*
*/
private static final long serialVersionUID = 991300443278089016L;
private int number;
private int guess;
private int smallest;
@Inject
@MaxNumber
int maxNumber;
private int biggest;
private int remainingGuesses;
@Inject
@Random
Instance<Integer> randomNumber;
@SuppressWarnings("unchecked")
@ProtoFactory
static Game create(int number, int guess, int smallest, int biggest, int remainingGuesses) {
Game game = new Game();
game.number = number;
game.guess = guess;
game.smallest = smallest;
game.biggest = biggest;
game.remainingGuesses = remainingGuesses;
try {
game.maxNumber = (Integer) CDI.current().select(game.getClass().getDeclaredField("maxNumber").getAnnotation(MaxNumber.class)).get();
game.randomNumber = (Instance<Integer>) (Instance<?>) CDI.current().select(game.getClass().getDeclaredField("randomNumber").getAnnotation(Random.class));
return game;
} catch (NoSuchFieldException e) {
throw new IllegalStateException(e);
}
}
@ProtoField(number = 1, defaultValue = "0")
public int getNumber() {
return number;
}
@ProtoField(number = 2, defaultValue = "0")
public int getGuess() {
return guess;
}
public void setGuess(int guess) {
this.guess = guess;
}
@ProtoField(number = 3, defaultValue = "0")
public int getSmallest() {
return smallest;
}
@ProtoField(number = 4, defaultValue = "0")
public int getBiggest() {
return biggest;
}
@ProtoField(number = 5, defaultValue = "0")
public int getRemainingGuesses() {
return remainingGuesses;
}
public void check() {
if (guess > number) {
biggest = guess - 1;
} else if (guess < number) {
smallest = guess + 1;
} else if (guess == number) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Correct!"));
}
remainingGuesses--;
}
@PostConstruct
public void reset() {
this.smallest = 0;
this.guess = 0;
this.remainingGuesses = 10;
this.biggest = maxNumber;
this.number = randomNumber.get();
}
public void validateNumberRange(FacesContext context, UIComponent toValidate, Object value) {
if (remainingGuesses <= 0) {
FacesMessage message = new FacesMessage("No guesses left!");
context.addMessage(toValidate.getClientId(context), message);
((UIInput) toValidate).setValid(false);
return;
}
int input = (Integer) value;
if (input < smallest || input > biggest) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage("Invalid guess");
context.addMessage(toValidate.getClientId(context), message);
}
}
}
| 4,708
| 30.817568
| 165
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jsf/webapp/JSFSerializationContextInitializer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.jsf.webapp;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
/**
* @author Paul Ferraro
*/
@AutoProtoSchemaBuilder(includeClasses = { Game.class }, service = false)
public interface JSFSerializationContextInitializer extends SerializationContextInitializer {
}
| 1,423
| 39.685714
| 93
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/jms/ClusteredMessagingTestCase.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.clustering.cluster.jms;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Properties;
import java.util.UUID;
import jakarta.jms.ConnectionFactory;
import jakarta.jms.Destination;
import jakarta.jms.JMSConsumer;
import jakarta.jms.JMSContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.integration.common.jms.JMSOperations;
import org.jboss.as.test.integration.common.jms.JMSOperationsProvider;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.as.test.shared.TimeoutUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.naming.client.WildFlyInitialContextFactory;
import org.wildfly.test.api.Authentication;
/**
* @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc.
* @author Radoslav Husar
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ClusteredMessagingTestCase extends AbstractClusteringTestCase {
public static final String JMS_USERNAME = "guest";
public static final String JMS_PASSWORD = "guest";
private static final String jmsQueueName = ClusteredMessagingTestCase.class.getSimpleName() + "-Queue";
private static final String jmsQueueLookup = "jms/" + jmsQueueName;
private static final String jmsTopicName = ClusteredMessagingTestCase.class.getSimpleName() + "-Topic";
private static final String jmsTopicLookup = "jms/" + jmsTopicName;
public ClusteredMessagingTestCase() {
super(TWO_NODES, new String[] {});
}
protected static ModelControllerClient createClient1() {
return TestSuiteEnvironment.getModelControllerClient();
}
protected static ModelControllerClient createClient2() throws UnknownHostException {
return ModelControllerClient.Factory.create(InetAddress.getByName(TestSuiteEnvironment.getServerAddress()), TestSuiteEnvironment.getServerPort() + getPortOffsetForNode(NODE_2), Authentication.getCallbackHandler());
}
@Override
public void beforeTestMethod() throws Exception {
super.beforeTestMethod();
// Create JMS Queue and Topic (the ServerSetupTask won't do the trick since there is no deployment in this test case...)
Arrays.stream(new ModelControllerClient[] { createClient1(), createClient2() }).forEach(client -> {
JMSOperations jmsOperations = JMSOperationsProvider.getInstance(client);
jmsOperations.createJmsQueue(jmsQueueName, "java:jboss/exported/" + jmsQueueLookup);
jmsOperations.createJmsTopic(jmsTopicName, "java:jboss/exported/" + jmsTopicLookup);
});
}
@Override
public void afterTestMethod() throws Exception {
super.afterTestMethod();
// Remove JMS Queue and Topic
Arrays.stream(new ModelControllerClient[] { createClient1(), createClient2() }).forEach(client -> {
JMSOperations jmsOperations = JMSOperationsProvider.getInstance(client);
jmsOperations.removeJmsQueue(jmsQueueName);
jmsOperations.removeJmsTopic(jmsTopicName);
});
}
@Test
public void testClusteredQueue() throws Exception {
InitialContext contextFromServer1 = createJNDIContext(NODE_1);
InitialContext contextFromServer2 = createJNDIContext(NODE_2);
try {
String text = UUID.randomUUID().toString();
Destination destination1 = (Destination) contextFromServer1.lookup(jmsQueueLookup);
Destination destination2 = (Destination) contextFromServer2.lookup(jmsQueueLookup);
// send to the queue on server 1
sendMessage(contextFromServer1, destination1, text);
// receive it from the queue on server 2
receiveMessage(contextFromServer2, destination2, text);
String anotherText = UUID.randomUUID().toString();
// send to the queue on server 2
sendMessage(contextFromServer2, destination2, anotherText);
// receive it from the queue on server 1
receiveMessage(contextFromServer1, destination1, anotherText);
} finally {
contextFromServer1.close();
contextFromServer2.close();
}
}
@Test
public void testClusteredTopic() throws Exception {
InitialContext contextFromServer1 = createJNDIContext(NODE_1);
InitialContext contextFromServer2 = createJNDIContext(NODE_2);
try (
JMSContext jmsContext1 = createJMSContext(createJNDIContext(NODE_1));
JMSConsumer consumer1 = jmsContext1.createConsumer((Destination) contextFromServer1.lookup(jmsTopicLookup));
JMSContext jmsContext2 = createJMSContext(createJNDIContext(NODE_2));
JMSConsumer consumer2 = jmsContext2.createConsumer((Destination) contextFromServer2.lookup(jmsTopicLookup))
) {
String text = UUID.randomUUID().toString();
Destination destination1 = (Destination) contextFromServer1.lookup(jmsTopicLookup);
Destination destination2 = (Destination) contextFromServer2.lookup(jmsTopicLookup);
// send a message to the topic on server 1
sendMessage(contextFromServer1, destination1, text);
// consumers receive it on both servers
receiveMessage(consumer1, text);
receiveMessage(consumer2, text);
String anotherText = UUID.randomUUID().toString();
// send another message to topic on server 2
sendMessage(contextFromServer2, destination2, anotherText);
// consumers receive it on both servers
receiveMessage(consumer1, anotherText);
receiveMessage(consumer2, anotherText);
} finally {
contextFromServer1.close();
contextFromServer2.close();
}
}
protected static InitialContext createJNDIContext(String node) throws NamingException {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, WildFlyInitialContextFactory.class.getName());
int port = 8080 + getPortOffsetForNode(node);
env.put(Context.PROVIDER_URL, "remote+http://" + TestSuiteEnvironment.getServerAddress() + ":" + port);
env.put(Context.SECURITY_PRINCIPAL, JMS_USERNAME);
env.put(Context.SECURITY_CREDENTIALS, JMS_PASSWORD);
return new InitialContext(env);
}
protected static void sendMessage(Context ctx, Destination destination, String text) throws NamingException {
ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory");
assertNotNull(cf);
assertNotNull(destination);
try (JMSContext context = cf.createContext(JMS_USERNAME, JMS_PASSWORD)) {
context.createProducer().send(destination, text);
}
}
protected static JMSContext createJMSContext(Context ctx) throws NamingException {
ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory");
assertNotNull(cf);
return cf.createContext(JMS_USERNAME, JMS_PASSWORD);
}
protected static void receiveMessage(JMSConsumer consumer, String expectedText) {
String text = consumer.receiveBody(String.class, TimeoutUtil.adjust(5000));
assertNotNull(text);
assertEquals(expectedText, text);
}
protected static void receiveMessage(Context ctx, Destination destination, String expectedText) throws NamingException {
ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory");
assertNotNull(cf);
assertNotNull(destination);
try (JMSContext context = cf.createContext(JMS_USERNAME, JMS_PASSWORD)) {
JMSConsumer consumer = context.createConsumer(destination);
receiveMessage(consumer, expectedText);
}
}
}
| 9,329
| 43.218009
| 222
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/modcluster/StartWorkersInSuspendedModeTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.modcluster;
import static org.jboss.as.controller.client.helpers.ClientConstants.ADDRESS;
import static org.jboss.as.controller.client.helpers.ClientConstants.INCLUDE_RUNTIME;
import static org.jboss.as.controller.client.helpers.ClientConstants.OUTCOME;
import static org.jboss.as.controller.client.helpers.ClientConstants.READ_RESOURCE_OPERATION;
import static org.jboss.as.controller.client.helpers.ClientConstants.RECURSIVE;
import static org.jboss.as.controller.client.helpers.ClientConstants.STATUS;
import static org.jboss.as.controller.client.helpers.ClientConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
import java.util.Set;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.shared.ManagementServerSetupTask;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Verifies behavior of mod_cluster interaction when a worker node is started in suspended mode.
*
* @author Bartosz Spyrko-Smietanko
* @author Radoslav Husar
*/
@RunAsClient
@RunWith(Arquillian.class)
@ServerSetup(StartWorkersInSuspendedModeTestCase.ServerSetupTask.class)
public class StartWorkersInSuspendedModeTestCase extends AbstractClusteringTestCase {
private static final String MODULE_NAME = StartWorkersInSuspendedModeTestCase.class.getSimpleName();
private static final String DEPLOYMENT_NAME = MODULE_NAME + ".war";
public static final long STATUS_REFRESH_TIMEOUT = 30_000;
public static final int LB_OFFSET = 500;
@Deployment(name = DEPLOYMENT_1, testable = false, managed = false)
@TargetsContainer(NODE_1)
public static WebArchive deployment() {
WebArchive pojoWar = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_NAME);
pojoWar.add(new StringAsset("Hello World"), "index.html");
return pojoWar;
}
public StartWorkersInSuspendedModeTestCase() {
super(Set.of(LOAD_BALANCER_1, NODE_1), Set.of(DEPLOYMENT_1));
}
@Test
public void testWorkerNodeIsRegisteredStopped() throws Exception {
ServerReload.executeReloadAndWaitForCompletion(TestSuiteEnvironment.getModelControllerClient(), ServerReload.TIMEOUT,
false, true,
null,
-1, null);
assertWorkerNodeContextIsStopped();
}
private void assertWorkerNodeContextIsStopped() throws Exception {
ModelNode op = createOpNode("subsystem=undertow/configuration=filter/mod-cluster=load-balancer/balancer=mycluster/node=" + NODE_1, READ_RESOURCE_OPERATION);
op.get(ADDRESS).add("context", "/" + MODULE_NAME);
op.get(RECURSIVE).set(true);
op.get(INCLUDE_RUNTIME).set(true);
final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient(
null,
TestSuiteEnvironment.getServerAddress(),
TestSuiteEnvironment.getServerPort() + LB_OFFSET);
// might need to wait for mod_cluster nodes to be registered
long start = System.currentTimeMillis();
ModelNode modelNode = null;
while (System.currentTimeMillis() - start < STATUS_REFRESH_TIMEOUT) {
modelNode = client.execute(op);
if (modelNode.has(RESULT) && modelNode.get(RESULT).has(STATUS)) {
break;
}
Thread.sleep(100);
}
Assert.assertEquals(SUCCESS, modelNode.get(OUTCOME).asString());
Assert.assertEquals("stopped", modelNode.get(RESULT).get(STATUS).asString());
}
static class ServerSetupTask extends ManagementServerSetupTask {
public ServerSetupTask() {
super(NODE_1, createContainerConfigurationBuilder()
.setupScript(createScriptBuilder()
.startBatch()
.add("/subsystem=modcluster/proxy=default:write-attribute(name=advertise, value=false)")
.add("/socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=proxy1:add(host=localhost, port=8590)")
.add("/subsystem=modcluster/proxy=default:list-add(name=proxies, value=proxy1)")
.endBatch()
.build()
)
.tearDownScript(createScriptBuilder()
.startBatch()
.add("/subsystem=modcluster/proxy=default:list-remove(name=proxies, value=proxy1)")
.add("/socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=proxy1:remove")
.add("/subsystem=modcluster/proxy=default:write-attribute(name=advertise, value=true)")
.endBatch()
.build())
.build()
);
}
}
}
| 6,783
| 46.440559
| 164
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/xsite/CacheAccessServlet.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.clustering.cluster.xsite;
import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.infinispan.Cache;
/**
* Servlet providing get/put access to Infinispan cache instance.
*
* http://127.0.0.1:8080/cache?operation=get&key=a
* http://127.0.0.1:8080/cache?operation=put&key=a;value=b
*
* where keys are Strings and Values are String representations of int.
*
* NOTE: Caches defined in the infinispan subsystem need to be started on demand.
* On demand in this case means either:
* (i) through deployment of a distributable web app which uses the cache as a session cache
* (ii) by way of @Resource(lookup=) which will cause the corresponding JNDI binding instance to be started
* and so the cache.
*
* Cache instances are started in this test case by way of a res-ref in the web.xml file in order to
* permit parametrization of the JNDI name.
*
* @author Richard Achmatowicz
*/
@WebServlet(urlPatterns = { CacheAccessServlet.SERVLET_PATH }, loadOnStartup = 0)
public class CacheAccessServlet extends HttpServlet {
private static final long serialVersionUID = 9130271954748513391L;
private static final String SERVLET_NAME = "cache";
static final String SERVLET_PATH = "/" + SERVLET_NAME;
private static final String OPERATION = "operation";
private static final String GET = "get";
private static final String PUT = "put";
private static final String KEY = "key";
private static final String VALUE = "value";
public static URI createGetURI(URL baseURL, String key) throws URISyntaxException {
return createURI(baseURL, GET, key, null);
}
public static URI createPutURI(URL baseURL, String key, String value) throws URISyntaxException {
return createURI(baseURL, PUT, key, value);
}
public static URI createURI(URL baseURL, String operation, String key, String value) throws URISyntaxException {
StringBuilder builder = new StringBuilder(SERVLET_NAME);
builder.append('?').append(OPERATION).append('=').append(operation);
builder.append('&').append(KEY).append('=').append(key);
if (value != null) {
builder.append('&').append(VALUE).append('=').append(value);
}
return baseURL.toURI().resolve(builder.toString());
}
@Resource(name="infinispan/cache")
private Cache<String, Custom> cache;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String operation = req.getParameter(OPERATION);
if (operation == null) {
throw new ServletException(String.format("No '%s' parameter specified)", OPERATION));
}
//
switch (operation) {
case GET: {
String key = req.getParameter(KEY);
validateKeyParam(operation, key);
Custom value = cache.get(key);
if (value == null) {
throw new ServletException(String.format("No value is defined for key '%s'", key));
}
resp.setIntHeader("value", value.getValue());
resp.getWriter().write("Success");
break;
}
case PUT: {
String key = req.getParameter(KEY);
validateKeyParam(operation, key);
String value = req.getParameter(VALUE);
validateValueParam(operation, value);
int intValue = Integer.parseInt(value);
// put the new instance of Custom here to the cache
// todo: difference between putting new value and modifying existing old value
cache.put(key, new Custom(intValue));
resp.getWriter().write("Success");
break;
}
default: {
throw new ServletException(String.format("Unknown operation '%s': valid operations are get/put)", operation));
}
}
}
private void validateKeyParam(String operation, String key) throws ServletException {
if (key == null || key.length() == 0) {
throw new ServletException(String.format("key parameter for operation %s is null or has zero length", operation));
}
}
private void validateValueParam(String operation, String value) throws ServletException {
if (value == null || value.length() == 0) {
throw new ServletException(String.format("key parameter for operation %s is null or has zero length", operation));
}
try {
Integer.parseInt(value) ;
}
catch(NumberFormatException nfe) {
throw new ServletException(String.format("value parameter for operation %s must be int", operation));
}
}
/**
* Serializable object holding an int value
*/
public static class Custom implements Serializable {
private static final long serialVersionUID = -5129400250276547619L;
private transient boolean serialized = false;
private int value;
public Custom(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public void setValue(int value) {
this.value = value;
}
public boolean wasSerialized() {
return this.serialized;
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
this.serialized = true;
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
this.serialized = true;
}
}
}
| 7,150
| 38.291209
| 126
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/xsite/XSiteSimpleTestCase.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.clustering.cluster.xsite;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.as.test.shared.ManagementServerSetupTask;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test xsite functionality on a 4-node, 3-site test deployment:
*
* sites:
* LON: {LON-0, LON-1} // maps to NODE_1/NODE_2
* NYC: {NYC-0} // maps to NODE_3
* SFO: {SFO-0} // maps to NODE_4
*
* routes:
* LON -> NYC,SFO
* NYC -> LON
* SFO -> LON
*
* backups: (<site>:<container>:<cache>)
* LON:web:dist backed up by NYC:web:dist, SFO:web:dist
* NYC not backed up
* SFO not backed up
*
* @author Richard Achmatowicz
*/
@RunWith(Arquillian.class)
@ServerSetup({ XSiteSimpleTestCase.CacheSetupTask.class, XSiteSimpleTestCase.ServerSetupTask.class })
public class XSiteSimpleTestCase extends AbstractClusteringTestCase {
private static final String MODULE_NAME = XSiteSimpleTestCase.class.getSimpleName();
public XSiteSimpleTestCase() {
super(NODE_1_2_3_4);
}
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return getDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return getDeployment();
}
@Deployment(name = DEPLOYMENT_3, managed = false, testable = false)
@TargetsContainer(NODE_3)
public static Archive<?> deployment3() {
return getDeployment();
}
@Deployment(name = DEPLOYMENT_4, managed = false, testable = false)
@TargetsContainer(NODE_4)
public static Archive<?> deployment4() {
return getDeployment();
}
private static Archive<?> getDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war");
war.addClass(CacheAccessServlet.class);
war.setWebXML(XSiteSimpleTestCase.class.getPackage(), "web.xml");
war.setManifest(new StringAsset("Manifest-Version: 1.0\nDependencies: org.infinispan\n"));
return war;
}
@Override
public void beforeTestMethod() throws Exception {
// Orchestrate startup of clusters to purge previously discovered views.
stop();
start(NODE_1);
deploy(DEPLOYMENT_1);
start(NODE_3);
deploy(DEPLOYMENT_3);
start(NODE_4);
deploy(DEPLOYMENT_4);
start(NODE_2);
deploy(DEPLOYMENT_2);
}
@Test
public void test(@ArquillianResource(CacheAccessServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
@ArquillianResource(CacheAccessServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2,
@ArquillianResource(CacheAccessServlet.class) @OperateOnDeployment(DEPLOYMENT_3) URL baseURL3,
@ArquillianResource(CacheAccessServlet.class) @OperateOnDeployment(DEPLOYMENT_4) URL baseURL4
) throws IllegalStateException, IOException, URISyntaxException, InterruptedException {
/*
* Tests that puts get relayed to their backup sites
*
* Put the key-value (a,100) on LON-0 on site LON and check that the key-value pair:
* arrives at LON-1 on site LON
* arrives at NYC-0 on site NYC
* arrives at SFO-0 on site SFO
*/
String value = "100";
URI url1 = CacheAccessServlet.createPutURI(baseURL1, "a", value);
URI url2 = CacheAccessServlet.createGetURI(baseURL2, "a");
URI url3 = CacheAccessServlet.createGetURI(baseURL3, "a");
URI url4 = CacheAccessServlet.createGetURI(baseURL4, "a");
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
// put a value to LON-0
HttpResponse response = client.execute(new HttpGet(url1));
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
response.getEntity().getContent().close();
// Lets wait for the session to replicate
Thread.sleep(GRACE_TIME_TO_REPLICATE);
// do a get on LON-1
response = client.execute(new HttpGet(url2));
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(value, response.getFirstHeader("value").getValue());
response.getEntity().getContent().close();
// do a get on NYC-0
response = client.execute(new HttpGet(url3));
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(value, response.getFirstHeader("value").getValue());
response.getEntity().getContent().close();
// do a get on SFO-0
response = client.execute(new HttpGet(url4));
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(value, response.getFirstHeader("value").getValue());
response.getEntity().getContent().close();
}
/*
* Tests that puts at the backup caches do not get relayed back to the origin cache.
*
* Put the key-value (b,200) on NYC-0 on site NYC and check that the key-value pair:
* does not arrive at LON-0 on site LON
*/
url1 = CacheAccessServlet.createGetURI(baseURL1, "b");
url3 = CacheAccessServlet.createPutURI(baseURL3, "b", "200");
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
// put a value to NYC-0
HttpResponse response = client.execute(new HttpGet(url3));
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
response.getEntity().getContent().close();
// Lets wait for the session to replicate
Thread.sleep(GRACE_TIME_TO_REPLICATE);
// do a get on LON-1 - this should fail
response = client.execute(new HttpGet(url1));
Assert.assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatusLine().getStatusCode());
response.getEntity().getContent().close();
}
}
public static class CacheSetupTask extends ManagementServerSetupTask {
public CacheSetupTask() {
super(NODE_1_2_3_4, createContainerConfigurationBuilder()
.setupScript(createScriptBuilder()
.startBatch()
.add("/subsystem=infinispan/cache-container=foo:add(marshaller=JBOSS)")
.add("/subsystem=infinispan/cache-container=foo/transport=jgroups:add")
.add("/subsystem=infinispan/cache-container=foo/distributed-cache=bar:add")
.endBatch()
.build())
.tearDownScript(createScriptBuilder()
.add("/subsystem=infinispan/cache-container=foo:remove")
.build())
.build());
}
}
public static class ServerSetupTask extends ManagementServerSetupTask {
public ServerSetupTask() {
super(createContainerSetConfigurationBuilder()
// LON
.addContainers(NODE_1_2, createContainerConfigurationBuilder()
.setupScript(createScriptBuilder()
.startBatch()
.add("/subsystem=infinispan/cache-container=foo/distributed-cache=bar/component=backups/backup=NYC:add(failure-policy=WARN, strategy=SYNC, timeout=10000, enabled=true)")
.add("/subsystem=infinispan/cache-container=foo/distributed-cache=bar/component=backups/backup=SFO:add(failure-policy=WARN, strategy=SYNC, timeout=10000, enabled=true)")
.add("/subsystem=jgroups/channel=bridge:add(stack=tcp-bridge)")
.add("/subsystem=jgroups/stack=tcp/relay=relay.RELAY2:add(site=LON)")
.add("/subsystem=jgroups/stack=tcp/relay=relay.RELAY2/remote-site=NYC:add(channel=bridge)")
.add("/subsystem=jgroups/stack=tcp/relay=relay.RELAY2/remote-site=SFO:add(channel=bridge)")
.add("/subsystem=jgroups/stack=tcp/protocol=TCPPING:write-attribute(name=socket-bindings, value=[node-1, node-2])")
.endBatch()
.build())
.tearDownScript(createScriptBuilder()
.startBatch()
.add("/subsystem=jgroups/stack=tcp/protocol=TCPPING:write-attribute(name=socket-bindings, value=[node-1, node-2, node-3, node-4])")
.add("/subsystem=jgroups/stack=tcp/relay=relay.RELAY2:remove")
.add("/subsystem=jgroups/channel=bridge:remove")
.add("/subsystem=infinispan/cache-container=foo/distributed-cache=bar/component=backups/backup=SFO:remove")
.add("/subsystem=infinispan/cache-container=foo/distributed-cache=bar/component=backups/backup=NYC:remove")
.endBatch()
.build())
.build())
// NYC
.addContainer(NODE_3, createContainerConfigurationBuilder()
.setupScript(createScriptBuilder()
.startBatch()
.add("/subsystem=jgroups/channel=bridge:add(stack=tcp-bridge)")
.add("/subsystem=jgroups/stack=tcp/relay=relay.RELAY2:add(site=NYC)")
.add("/subsystem=jgroups/stack=tcp/relay=relay.RELAY2/remote-site=LON:add(channel=bridge)")
.add("/subsystem=jgroups/stack=tcp/relay=relay.RELAY2/remote-site=SFO:add(channel=bridge)")
.add("/subsystem=jgroups/stack=tcp/protocol=TCPPING:write-attribute(name=socket-bindings, value=[node-3])")
.endBatch()
.build())
.tearDownScript(createScriptBuilder()
.startBatch()
.add("/subsystem=jgroups/stack=tcp/protocol=TCPPING:write-attribute(name=socket-bindings, value=[node-1, node-2, node-3, node-4])")
.add("/subsystem=jgroups/stack=tcp/relay=relay.RELAY2:remove")
.add("/subsystem=jgroups/channel=bridge:remove")
.endBatch()
.build())
.build())
// SFO
.addContainer(NODE_4, createContainerConfigurationBuilder()
.setupScript(createScriptBuilder()
.startBatch()
.add("/subsystem=jgroups/channel=bridge:add(stack=tcp-bridge)")
.add("/subsystem=jgroups/stack=tcp/relay=relay.RELAY2:add(site=SFO)")
.add("/subsystem=jgroups/stack=tcp/relay=relay.RELAY2/remote-site=LON:add(channel=bridge)")
.add("/subsystem=jgroups/stack=tcp/relay=relay.RELAY2/remote-site=NYC:add(channel=bridge)")
.add("/subsystem=jgroups/stack=tcp/protocol=TCPPING:write-attribute(name=socket-bindings, value=[node-4])")
.endBatch()
.build())
.tearDownScript(createScriptBuilder()
.startBatch()
.add("/subsystem=jgroups/stack=tcp/protocol=TCPPING:write-attribute(name=socket-bindings, value=[node-1, node-2, node-3, node-4])")
.add("/subsystem=jgroups/stack=tcp/relay=relay.RELAY2:remove")
.add("/subsystem=jgroups/channel=bridge:remove")
.endBatch()
.build())
.build())
.build());
}
}
}
| 14,445
| 49.687719
| 201
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/affinity/RankedAffinityTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.affinity;
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.SUCCESS;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import java.util.Set;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.clustering.ClusterHttpClientUtil;
import org.jboss.as.test.clustering.ClusterTestUtil;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.clustering.single.web.Mutable;
import org.jboss.as.test.clustering.single.web.SimpleServlet;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.as.test.shared.ManagementServerSetupTask;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test for ranked affinity support in the server and in the Undertow-based mod_cluster load balancer.
*
* @author Radoslav Husar
*/
@RunWith(Arquillian.class)
@ServerSetup(RankedAffinityTestCase.ServerSetupTask.class)
public class RankedAffinityTestCase extends AbstractClusteringTestCase {
private static final String MODULE_NAME = RankedAffinityTestCase.class.getSimpleName();
private static final String DEPLOYMENT_NAME = MODULE_NAME + ".war";
private static final String BALANCER_NAME = "mycluster";
public RankedAffinityTestCase() {
super(Set.of(NODE_1, NODE_2, NODE_3, LOAD_BALANCER_1), DEPLOYMENT_1_2_3);
}
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return deployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return deployment();
}
@Deployment(name = DEPLOYMENT_3, managed = false, testable = false)
@TargetsContainer(NODE_3)
public static Archive<?> deployment3() {
return deployment();
}
private static Archive<?> deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_NAME)
.addClasses(SimpleServlet.class, Mutable.class)
.setWebXML(SimpleServlet.class.getPackage(), "web.xml");
ClusterTestUtil.addTopologyListenerDependencies(war);
return war;
}
/**
* Test ranked routing by (1) creating a session on a node, (2) disabling the node that served the request using the load
* balancer API and (3) verifying correct affinity on subsequent request.
*/
@Test
public void test(@ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL) throws Exception {
URL lbURL = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort() + 500, baseURL.getFile());
URI lbURI = SimpleServlet.createURI(lbURL);
establishTopology(baseURL, THREE_NODES);
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
String[] previousAffinities;
int value = 1;
// 1
HttpResponse response = client.execute(new HttpGet(lbURI));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(value++, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue()));
Map.Entry<String, String> entry = parseSessionRoute(response);
previousAffinities = entry.getValue().split("\\.");
log.debugf("Response #1: %s", response);
Assert.assertNotNull(entry);
Assert.assertEquals(entry.getKey(), response.getFirstHeader(SimpleServlet.SESSION_ID_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
// TODO remove workaround for "UNDERTOW-1585 mod_cluster nodes are added in ERROR state" for which we need to wait until first status for ranked affinity to work
Thread.sleep(3_000);
// 2
ModelControllerClient lbModelControllerClient = TestSuiteEnvironment.getModelControllerClient(null, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort() + 500);
try (ManagementClient lbManagementClient = new ManagementClient(lbModelControllerClient, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort() + 500, "remote+http")) {
String node = previousAffinities[0];
ModelNode operation = new ModelNode();
operation.get(OP).set(ModelDescriptionConstants.STOP);
PathAddress address = PathAddress.parseCLIStyleAddress(String.format("/subsystem=undertow/configuration=filter/mod-cluster=load-balancer/balancer=%s/node=%s", BALANCER_NAME, node));
operation.get(OP_ADDR).set(address.toModelNode());
ModelNode result = lbManagementClient.getControllerClient().execute(operation);
log.debugf("Running operation: %s", operation.toJSONString(false));
Assert.assertEquals(result.toString(), SUCCESS, result.get(OUTCOME).asString());
log.debugf("Operation result: %s", result.toJSONString(false));
operation = new ModelNode();
operation.get(OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION);
address = PathAddress.parseCLIStyleAddress("/subsystem=undertow/configuration=filter/mod-cluster=load-balancer");
operation.get(OP_ADDR).set(address.toModelNode());
operation.get(ModelDescriptionConstants.RECURSIVE).set(ModelNode.TRUE);
operation.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(ModelNode.TRUE);
result = lbManagementClient.getControllerClient().execute(operation);
log.debugf("Running operation: %s", operation.toJSONString(false));
Assert.assertEquals(result.toString(), SUCCESS, result.get(OUTCOME).asString());
log.debugf("Operation result: %s", result.toJSONString(false));
Thread.sleep(GRACE_TIME_TOPOLOGY_CHANGE);
// 3
response = client.execute(new HttpGet(lbURI));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(value++, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue()));
Assert.assertEquals("The subsequent request should have been served by the 2nd node in the affinity list", previousAffinities[1], response.getFirstHeader(SimpleServlet.HEADER_NODE_NAME).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
}
}
}
private static void establishTopology(URL baseURL, String... nodes) throws URISyntaxException, IOException {
ClusterHttpClientUtil.establishTopology(baseURL, "web", DEPLOYMENT_NAME, nodes);
}
public static class ServerSetupTask extends ManagementServerSetupTask {
public ServerSetupTask() {
super(NODE_1_2_3, createContainerConfigurationBuilder()
.setupScript(createScriptBuilder()
.startBatch()
.add("/socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=load-balancer-1:add(host=localhost, port=8590)")
.add("/subsystem=modcluster/proxy=default:write-attribute(name=proxies, value=[load-balancer-1])")
.add("/subsystem=modcluster/proxy=default:write-attribute(name=status-interval, value=1)")
.add("/subsystem=distributable-web/infinispan-session-management=default/affinity=ranked:add()")
.endBatch()
.build())
.tearDownScript(createScriptBuilder()
.startBatch()
.add("/subsystem=distributable-web/infinispan-session-management=default/affinity=primary-owner:add()")
.add("/subsystem=modcluster/proxy=default:undefine-attribute(name=status-interval)")
.add("/subsystem=modcluster/proxy=default:undefine-attribute(name=proxies)")
.add("/socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=load-balancer-1:remove()")
.endBatch()
.build())
.build());
}
}
}
| 11,086
| 51.051643
| 218
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/affinity/CookieAffinityTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.affinity;
import java.net.URI;
import java.net.URL;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.clustering.ClusterTestUtil;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.clustering.single.web.Mutable;
import org.jboss.as.test.clustering.single.web.SimpleServlet;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.as.test.shared.ManagementServerSetupTask;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test to verify that a custom affinity cookie can be configured and be used to drive session affinity.
* Works synthetically without a load-balancer.
*
* @author Radoslav Husar
* @see <a href="https://issues.redhat.com/browse/WFLY-16043">WFLY-16043</a>
*/
@RunWith(Arquillian.class)
@ServerSetup(CookieAffinityTestCase.ServerSetupTask.class)
public class CookieAffinityTestCase extends AbstractClusteringTestCase {
private static final String MODULE_NAME = CookieAffinityTestCase.class.getSimpleName();
private static final String DEPLOYMENT_NAME = MODULE_NAME + ".war";
private static final String AFFINITY_COOKIE_NAME = "custom-cookie-name";
public CookieAffinityTestCase() {
super(NODE_1_2);
}
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return deployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return deployment();
}
private static Archive<?> deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_NAME)
.addClasses(SimpleServlet.class, Mutable.class)
.setWebXML(SimpleServlet.class.getPackage(), "web.xml");
ClusterTestUtil.addTopologyListenerDependencies(war);
return war;
}
protected static String parseCookieAffinity(HttpResponse response) {
for (Header header : response.getAllHeaders()) {
if (!header.getName().equals("Set-Cookie")) continue;
String setCookieValue = header.getValue();
String cookieName = setCookieValue.substring(0, setCookieValue.indexOf('='));
if (cookieName.equals(AFFINITY_COOKIE_NAME)) {
return setCookieValue.substring(setCookieValue.indexOf('=') + 1, setCookieValue.indexOf(';'));
}
}
return null;
}
/**
* Test routing by
* (1) creating a session on a node 1 - verify route is set
* (2) verify subsequent request
* (3) verify requesting same session on a different node that correct affinity is overridden.
*/
@Test
public void test(@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws Exception {
URI uri1 = SimpleServlet.createURI(baseURL1);
URI uri2 = SimpleServlet.createURI(baseURL2);
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
int value = 1;
String sessionAffinity;
// 1 -> node 1
HttpResponse response = client.execute(new HttpGet(uri1));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(value++, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue()));
String affinity = parseCookieAffinity(response);
log.infof("Response #1: %s; affinity=%s", response, affinity);
Assert.assertNotNull(affinity);
sessionAffinity = affinity;
} finally {
HttpClientUtils.closeQuietly(response);
}
// 2
response = client.execute(new HttpGet(uri1));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(value++, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue()));
String affinity = parseCookieAffinity(response);
log.infof("Response #2: %s; affinity=%s", response, affinity);
Assert.assertNotNull(affinity);
Assert.assertEquals(sessionAffinity, affinity);
} finally {
HttpClientUtils.closeQuietly(response);
}
// 3 -> node 2
response = client.execute(new HttpGet(uri2));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(value++, Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue()));
String affinity = parseCookieAffinity(response);
log.infof("Response #3: %s; affinity=%s", response, affinity);
Assert.assertNotNull(affinity);
Assert.assertEquals(sessionAffinity, affinity);
} finally {
HttpClientUtils.closeQuietly(response);
}
}
}
static class ServerSetupTask extends ManagementServerSetupTask {
ServerSetupTask() {
super(NODE_1_2, createContainerConfigurationBuilder()
.setupScript(createScriptBuilder()
.startBatch()
.add("/subsystem=undertow/servlet-container=default/setting=affinity-cookie:add(name=%s)", AFFINITY_COOKIE_NAME)
.endBatch()
.build())
.tearDownScript(createScriptBuilder()
.startBatch()
.add("/subsystem=undertow/servlet-container=default/setting=affinity-cookie:remove()")
.endBatch()
.build())
.build());
}
}
}
| 7,948
| 40.401042
| 140
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/failover/RemoteEJBClientStatefulBeanFailoverTestCase.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.clustering.cluster.ejb2.stateful.failover;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.util.PropertyPermission;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.clustering.NodeNameGetter;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.failover.bean.shared.CounterRemote;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests that invocations on a clustered stateful session Enterprise Beans 2 bean from a remote Jakarta Enterprise Beans client, failover to
* other node(s) in cases like a node going down.
* This test is taken from test of ejb3 beans.
*
* @author Jaikiran Pai
* @author Radoslav Husar
* @author Ondrej Chaloupka
*/
@RunWith(Arquillian.class)
public class RemoteEJBClientStatefulBeanFailoverTestCase extends RemoteEJBClientStatefulFailoverTestBase {
@Deployment(name = DEPLOYMENT_HELPER_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> createDeploymentForContainer1Singleton() {
return createDeploymentSingleton();
}
@Deployment(name = DEPLOYMENT_HELPER_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> createDeploymentForContainer2Singleton() {
return createDeploymentSingleton();
}
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> createDeploymentForContainer1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> createDeploymentForContainer2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, MODULE_NAME + ".jar");
jar.addPackage(CounterRemote.class.getPackage());
jar.addClass(CounterBean.class);
jar.addClass(NodeNameGetter.class);
jar.addAsManifestResource(new StringAsset("Manifest-Version: 1.0\nDependencies: deployment." + MODULE_NAME_SINGLE + ".jar\n"), "MANIFEST.MF");
jar.addAsResource(createPermissionsXmlAsset(
new PropertyPermission("jboss.node.name", "read")),
"META-INF/jboss-permissions.xml");
return jar;
}
@Override
@Test
public void testFailoverFromRemoteClientWhenOneNodeGoesDown() throws Exception {
failoverFromRemoteClient(false);
}
@Override
@Test
public void testFailoverFromRemoteClientWhenOneNodeUndeploys() throws Exception {
failoverFromRemoteClient(true);
}
}
| 4,090
| 39.50495
| 150
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/failover/RemoteEJBClientStatefulFailoverTestBase.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.clustering.cluster.ejb2.stateful.failover;
import javax.naming.NamingException;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.failover.bean.shared.CounterRemote;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.failover.bean.shared.CounterRemoteHome;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.failover.bean.shared.CounterResult;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.failover.bean.singleton.CounterSingleton;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.failover.bean.singleton.CounterSingletonRemote;
import org.jboss.as.test.clustering.ejb.EJBDirectory;
import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
/**
* @author Ondrej Chaloupka
*/
public abstract class RemoteEJBClientStatefulFailoverTestBase extends AbstractClusteringTestCase {
private static final Logger log = Logger.getLogger(RemoteEJBClientStatefulFailoverTestBase.class);
protected static final String MODULE_NAME = RemoteEJBClientStatefulFailoverTestBase.class.getSimpleName();
protected static final String MODULE_NAME_SINGLE = MODULE_NAME + "-single";
protected EJBDirectory singletonDirectory;
protected EJBDirectory directory;
protected static Archive<?> createDeploymentSingleton() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, MODULE_NAME_SINGLE + ".jar");
jar.addPackage(CounterSingletonRemote.class.getPackage());
return jar;
}
public RemoteEJBClientStatefulFailoverTestBase() {
super(NODE_1_2, DEPLOYMENT_1_2);
}
@Override
protected void deploy() {
this.deploy(DEPLOYMENT_HELPER_1_2);
super.deploy();
}
@Override
protected void undeploy() {
super.undeploy();
this.deploy(DEPLOYMENT_HELPER_1_2);
}
@Override
public void afterTestMethod() {
start();
undeploy(DEPLOYMENT_1_2);
undeploy(DEPLOYMENT_HELPER_1_2);
}
@Before
public void beforeTest() throws NamingException {
directory = new RemoteEJBDirectory(MODULE_NAME);
singletonDirectory = new RemoteEJBDirectory(MODULE_NAME_SINGLE);
}
@After
public void afterTest() throws Exception {
directory.close();
singletonDirectory.close();
}
/**
* Starts 2 nodes with the clustered beans deployed on each node. Invokes a clustered SFSB a few times.
* Then stops a node from among the cluster (the one which received the last invocation) and continues invoking
* on the same SFSB. These subsequent invocations are expected to failover to the other node and also have the
* correct state of the SFSB.
*/
public abstract void testFailoverFromRemoteClientWhenOneNodeGoesDown() throws Exception;
/**
* Same as above, but application gets undeployed while the server keeps running.
*/
public abstract void testFailoverFromRemoteClientWhenOneNodeUndeploys() throws Exception;
/**
* Implementation of defined abstract tests above.
*/
protected void failoverFromRemoteClient(boolean undeployOnly) throws Exception {
CounterRemoteHome home = directory.lookupHome(CounterBean.class, CounterRemoteHome.class);
CounterRemote remoteCounter = home.create();
Assert.assertNotNull(remoteCounter);
final CounterSingletonRemote destructionCounter = singletonDirectory.lookupSingleton(CounterSingleton.class, CounterSingletonRemote.class);
destructionCounter.resetDestroyCount();
// invoke on the bean a few times
final int NUM_TIMES = 25;
for (int i = 0; i < NUM_TIMES; i++) {
final CounterResult result = remoteCounter.increment();
log.trace("Counter incremented to " + result.getCount() + " on node " + result.getNodeName());
}
final CounterResult result = remoteCounter.getCount();
Assert.assertNotNull("Result from remote stateful counter was null", result);
Assert.assertEquals("Unexpected count from remote counter", NUM_TIMES, result.getCount());
Assert.assertEquals("Nothing should have been destroyed yet", 0, destructionCounter.getDestroyCount());
// shutdown the node on which the previous invocation happened
final int totalCountBeforeShuttingDownANode = result.getCount();
final String previousInvocationNodeName = result.getNodeName();
// the value is configured in arquillian.xml of the project
if (previousInvocationNodeName.equals(NODE_1)) {
if (undeployOnly) {
deployer.undeploy(DEPLOYMENT_1);
deployer.undeploy(DEPLOYMENT_HELPER_1);
} else {
stop(GRACEFUL_SHUTDOWN_TIMEOUT, NODE_1);
}
} else {
if (undeployOnly) {
deployer.undeploy(DEPLOYMENT_2);
deployer.undeploy(DEPLOYMENT_HELPER_2);
} else {
stop(GRACEFUL_SHUTDOWN_TIMEOUT, NODE_2);
}
}
// invoke again
CounterResult resultAfterShuttingDownANode = remoteCounter.increment();
Assert.assertNotNull("Result from remote stateful counter, after shutting down a node was null", resultAfterShuttingDownANode);
Assert.assertEquals("Unexpected count from remote counter, after shutting down a node", totalCountBeforeShuttingDownANode + 1, resultAfterShuttingDownANode.getCount());
Assert.assertFalse("Result was received from an unexpected node, after shutting down a node", previousInvocationNodeName.equals(resultAfterShuttingDownANode.getNodeName()));
// repeat invocations
final int countBeforeDecrementing = resultAfterShuttingDownANode.getCount();
final String aliveNode = resultAfterShuttingDownANode.getNodeName();
for (int i = NUM_TIMES; i > 0; i--) {
resultAfterShuttingDownANode = remoteCounter.decrement();
Assert.assertNotNull("Result from remote stateful counter, after shutting down a node was null", resultAfterShuttingDownANode);
Assert.assertEquals("Result was received from an unexpected node, after shutting down a node", aliveNode, resultAfterShuttingDownANode.getNodeName());
log.trace("Counter decremented to " + resultAfterShuttingDownANode.getCount() + " on node " + resultAfterShuttingDownANode.getNodeName());
}
final CounterResult finalResult = remoteCounter.getCount();
Assert.assertNotNull("Result from remote stateful counter, after shutting down a node was null", finalResult);
final int finalCount = finalResult.getCount();
final String finalNodeName = finalResult.getNodeName();
Assert.assertEquals("Result was received from an unexpected node, after shutting down a node", aliveNode, finalNodeName);
Assert.assertEquals("Unexpected count from remote counter, after shutting down a node", countBeforeDecrementing - NUM_TIMES, finalCount);
Assert.assertEquals("Nothing should have been destroyed yet", 0, destructionCounter.getDestroyCount());
remoteCounter.remove();
Assert.assertEquals("SFSB was not destroyed", 1, destructionCounter.getDestroyCount());
}
}
| 8,579
| 47.202247
| 181
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/failover/CounterBean.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.clustering.cluster.ejb2.stateful.failover;
import jakarta.ejb.EJBException;
import jakarta.ejb.RemoteHome;
import jakarta.ejb.SessionBean;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Stateful;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.failover.bean.shared.CounterBaseBean;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.failover.bean.shared.CounterRemoteHome;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.failover.bean.singleton.CounterSingleton;
import org.jboss.logging.Logger;
/**
* @author Ondrej Chaloupka
*/
@Stateful
@RemoteHome(CounterRemoteHome.class)
public class CounterBean extends CounterBaseBean implements SessionBean {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(CounterBean.class);
@Override
public void ejbRemove() throws EJBException {
log.trace("ejbRemove called...");
CounterSingleton.destroyCounter.incrementAndGet();
}
@Override
public void ejbActivate() throws EJBException {
}
@Override
public void ejbPassivate() throws EJBException {
}
@Override
public void setSessionContext(SessionContext arg0) throws EJBException {
}
}
| 2,290
| 33.712121
| 99
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/failover/dd/RemoteEJB2ClientStatefulBeanFailoverDDTestCase.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.clustering.cluster.ejb2.stateful.failover.dd;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.util.PropertyPermission;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.clustering.NodeNameGetter;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.failover.RemoteEJBClientStatefulFailoverTestBase;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.failover.bean.shared.CounterRemote;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Ondrej Chaloupka
*/
@RunWith(Arquillian.class)
public class RemoteEJB2ClientStatefulBeanFailoverDDTestCase extends RemoteEJBClientStatefulFailoverTestBase {
@Deployment(name = DEPLOYMENT_HELPER_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> createDeploymentForContainer1Singleton() {
return createDeploymentSingleton();
}
@Deployment(name = DEPLOYMENT_HELPER_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> createDeploymentForContainer2Singleton() {
return createDeploymentSingleton();
}
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> createDeploymentForContainer1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> createDeploymentForContainer2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, MODULE_NAME + ".jar");
jar.addPackage(CounterRemote.class.getPackage());
jar.addClass(CounterBeanDD.class);
jar.addClass(NodeNameGetter.class);
jar.addAsManifestResource(RemoteEJB2ClientStatefulBeanFailoverDDTestCase.class.getPackage(), "ejb-jar.xml", "ejb-jar.xml");
jar.addAsManifestResource(new StringAsset("Dependencies: deployment." + MODULE_NAME_SINGLE + ".jar\n"), "MANIFEST.MF");
jar.addAsResource(createPermissionsXmlAsset(
new PropertyPermission("jboss.node.name", "read")),
"META-INF/jboss-permissions.xml");
return jar;
}
@Override
@Test
public void testFailoverFromRemoteClientWhenOneNodeGoesDown() throws Exception {
failoverFromRemoteClient(false);
}
@Override
@Test
public void testFailoverFromRemoteClientWhenOneNodeUndeploys() throws Exception {
failoverFromRemoteClient(true);
}
}
| 4,024
| 40.494845
| 131
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/failover/dd/CounterBeanDD.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.ejb2.stateful.failover.dd;
import java.rmi.RemoteException;
import jakarta.ejb.EJBException;
import jakarta.ejb.SessionBean;
import jakarta.ejb.SessionContext;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.failover.bean.shared.CounterBaseBean;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.failover.bean.singleton.CounterSingleton;
import org.jboss.logging.Logger;
/**
* @author Ondrej Chaloupka
*/
public class CounterBeanDD extends CounterBaseBean implements SessionBean {
private static final Logger log = Logger.getLogger(CounterBeanDD.class);
private static final long serialVersionUID = 1L;
@Override
public void ejbRemove() throws EJBException, RemoteException {
log.trace("ejbRemove() was called..");
CounterSingleton.destroyCounter.incrementAndGet();
}
@Override
public void ejbActivate() throws EJBException, RemoteException {
}
@Override
public void ejbPassivate() throws EJBException, RemoteException {
}
@Override
public void setSessionContext(SessionContext arg0) throws EJBException, RemoteException {
}
}
| 2,208
| 34.063492
| 99
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/failover/bean/shared/CounterResult.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.clustering.cluster.ejb2.stateful.failover.bean.shared;
import java.io.Serializable;
/**
* @author Jaikiran Pai
*/
public class CounterResult implements Serializable {
private static final long serialVersionUID = 1L;
private int count;
private String nodeName;
public CounterResult(final int count, final String nodeName) {
this.count = count;
this.nodeName = nodeName;
}
public int getCount() {
return this.count;
}
public String getNodeName() {
return this.nodeName;
}
}
| 1,598
| 31.632653
| 80
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/failover/bean/shared/CounterRemote.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.clustering.cluster.ejb2.stateful.failover.bean.shared;
import jakarta.ejb.EJBObject;
/**
* @author Ondrej Chaloupka
*/
public interface CounterRemote extends EJBObject {
CounterResult increment();
CounterResult decrement();
CounterResult getCount();
}
| 1,320
| 34.702703
| 80
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/failover/bean/shared/CounterBaseBean.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.clustering.cluster.ejb2.stateful.failover.bean.shared;
import java.rmi.RemoteException;
import jakarta.ejb.CreateException;
import org.jboss.as.test.clustering.NodeNameGetter;
/**
* @author Ondrej Chaloupka
*/
public abstract class CounterBaseBean {
private int count;
public void ejbCreate() throws RemoteException, CreateException {
// Creating method for home interface...
}
public CounterResult increment() {
this.count++;
return new CounterResult(this.count, getNodeName());
}
public CounterResult decrement() {
this.count--;
return new CounterResult(this.count, getNodeName());
}
public CounterResult getCount() {
return new CounterResult(this.count, getNodeName());
}
private String getNodeName() {
return NodeNameGetter.getNodeName();
}
}
| 1,907
| 31.896552
| 80
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/failover/bean/shared/CounterRemoteHome.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.clustering.cluster.ejb2.stateful.failover.bean.shared;
import jakarta.ejb.EJBHome;
/**
* @author Ondrej Chaloupka
*/
public interface CounterRemoteHome extends EJBHome {
CounterRemote create() throws java.rmi.RemoteException, jakarta.ejb.CreateException;
}
| 1,316
| 37.735294
| 88
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/failover/bean/singleton/CounterSingletonRemote.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.clustering.cluster.ejb2.stateful.failover.bean.singleton;
import jakarta.ejb.Remote;
/**
* @author Ondrej Chaloupka
*/
@Remote
public interface CounterSingletonRemote {
int getDestroyCount();
void resetDestroyCount();
}
| 1,283
| 34.666667
| 83
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/failover/bean/singleton/CounterSingleton.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.clustering.cluster.ejb2.stateful.failover.bean.singleton;
import java.util.concurrent.atomic.AtomicInteger;
import jakarta.ejb.Singleton;
import jakarta.ejb.Startup;
import org.jboss.logging.Logger;
@Singleton
@Startup
public class CounterSingleton implements CounterSingletonRemote {
public static AtomicInteger destroyCounter = new AtomicInteger(0);
private static final Logger log = Logger.getLogger(CounterSingleton.class);
public int getDestroyCount() {
log.trace("destroyCounter: " + destroyCounter.get());
return destroyCounter.get();
}
public void resetDestroyCount() {
destroyCounter.set(0);
}
}
| 1,709
| 35.382979
| 83
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/passivation/StatefulBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.ejb2.stateful.passivation;
import jakarta.ejb.RemoteHome;
import jakarta.ejb.SessionBean;
import jakarta.ejb.Stateful;
/**
* @author Ondrej Chaloupka
*/
@Stateful
@RemoteHome(StatefulRemoteHome.class)
public class StatefulBean extends StatefulBeanBase implements SessionBean {
private static final long serialVersionUID = 1L;
}
| 1,406
| 36.026316
| 75
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/passivation/ClusterPassivationTestCase.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.clustering.cluster.ejb2.stateful.passivation;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.*;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.clustering.NodeInfoServlet;
import org.jboss.as.test.clustering.NodeNameGetter;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Clustering ejb passivation of EJB2 beans defined by annotation.
*
* @author Ondrej Chaloupka
*/
@Ignore("Uses legacy client hack")
@RunWith(Arquillian.class)
public class ClusterPassivationTestCase extends ClusterPassivationTestBase {
private static Logger log = Logger.getLogger(ClusterPassivationTestCase.class);
@ArquillianResource
private ContainerController controller;
@ArquillianResource
private Deployer deployer;
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment0() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment1() {
return createDeployment();
}
private static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war");
war.addClasses(StatefulBeanBase.class, StatefulBean.class, StatefulRemote.class, StatefulRemoteHome.class);
war.addClasses(NodeNameGetter.class, NodeInfoServlet.class);
return war;
}
@Override
protected void startServers(ManagementClient client1, ManagementClient client2) {
if (client1 == null || !client1.isServerInRunningState()) {
log.trace("Starting server: " + NODE_1);
controller.start(NODE_1);
deployer.deploy(DEPLOYMENT_1);
}
if (client2 == null || !client2.isServerInRunningState()) {
log.trace("Starting server: " + NODE_2);
controller.start(NODE_2);
deployer.deploy(DEPLOYMENT_2);
}
}
@Test
@InSequence(-2)
public void arquillianStartServers() {
// Container is unmanaged, need to start manually - see https://community.jboss.org/thread/176096
startServers(null, null);
}
/**
* Association of node names to deployment,container names and client context
*/
@Test
@InSequence(-1)
public void defineMaps(@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2,
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) ManagementClient client1,
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) ManagementClient client2) throws Exception {
String nodeName1 = HttpRequest.get(baseURL1.toString() + NodeInfoServlet.SERVLET_NAME, HTTP_REQUEST_WAIT_TIME_S, TimeUnit.SECONDS);
node2deployment.put(nodeName1, DEPLOYMENT_1);
node2container.put(nodeName1, NODE_1);
log.trace("URL1 nodename: " + nodeName1);
String nodeName2 = HttpRequest.get(baseURL2.toString() + NodeInfoServlet.SERVLET_NAME, HTTP_REQUEST_WAIT_TIME_S, TimeUnit.SECONDS);
node2deployment.put(nodeName2, DEPLOYMENT_2);
node2container.put(nodeName2, NODE_2);
log.trace("URL2 nodename: " + nodeName2);
}
@Test
@InSequence(1)
public void testPassivationBeanAnnotated(
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) ManagementClient client1,
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) ManagementClient client2) throws Exception {
setPassivationAttributes(client1.getControllerClient());
setPassivationAttributes(client2.getControllerClient());
// Setting context from .properties file to get ejb:/ remote context
setupEJBClientContextSelector();
StatefulRemoteHome home = directory.lookupHome(StatefulBean.class, StatefulRemoteHome.class);
StatefulRemote statefulBean = home.create();
runPassivation(statefulBean, controller, deployer);
startServers(client1, client2);
}
@Test
@InSequence(100)
public void stopAndClean(
@OperateOnDeployment(DEPLOYMENT_1) @ArquillianResource ManagementClient client1,
@OperateOnDeployment(DEPLOYMENT_2) @ArquillianResource ManagementClient client2) throws Exception {
log.trace("Stop&Clean...");
// unset & undeploy & stop
if (client1.isServerInRunningState()) {
unsetPassivationAttributes(client1.getControllerClient());
deployer.undeploy(DEPLOYMENT_1);
controller.stop(NODE_1);
}
if (client2.isServerInRunningState()) {
unsetPassivationAttributes(client2.getControllerClient());
deployer.undeploy(DEPLOYMENT_2);
controller.stop(NODE_2);
}
}
}
| 6,814
| 40.054217
| 139
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/passivation/StatefulRemoteHome.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.ejb2.stateful.passivation;
import java.rmi.RemoteException;
import jakarta.ejb.CreateException;
import jakarta.ejb.EJBHome;
/**
* @author Ondrej Chaloupka
*/
public interface StatefulRemoteHome extends EJBHome {
StatefulRemote create() throws RemoteException, CreateException;
}
| 1,366
| 36.972222
| 71
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/passivation/StatefulRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.ejb2.stateful.passivation;
import jakarta.ejb.EJBObject;
/**
* @author Ondrej Chaloupka
*/
public interface StatefulRemote extends EJBObject {
int getNumber();
String setNumber(int number);
String incrementNumber();
void setPassivationNode(String node);
String getPassivatedBy();
}
| 1,379
| 32.658537
| 71
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/passivation/ClusterPassivationTestBase.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.clustering.cluster.ejb2.stateful.passivation;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.WAIT_FOR_PASSIVATION_MS;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.naming.NamingException;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.test.clustering.DMRUtil;
import org.jboss.as.test.clustering.ejb.EJBDirectory;
import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory;
import org.jboss.ejb.client.EJBClientContext;
import org.jboss.logging.Logger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
/**
* Base class for passivation tests on Enterprise Beans 2 beans.
*
* @author Ondrej Chaloupka
*/
public abstract class ClusterPassivationTestBase {
private static Logger log = Logger.getLogger(ClusterPassivationTestBase.class);
public static final String MODULE_NAME = ClusterPassivationTestBase.class.getSimpleName();
protected EJBDirectory directory;
@Before
public void beforeTest() throws NamingException {
directory = new RemoteEJBDirectory(MODULE_NAME);
}
@After
public void afterTest() throws Exception {
directory.close();
}
// Properties pass amongst tests
protected static Map<String, String> node2deployment = new HashMap<String, String>();
protected static Map<String, String> node2container = new HashMap<String, String>();
/**
* Setting all passivation attributes.
*/
protected void setPassivationAttributes(ModelControllerClient client) throws Exception {
DMRUtil.setMaxSize(client, 1);
}
/**
* Unsetting all cache attributes - defining their default values.
*/
protected void unsetPassivationAttributes(ModelControllerClient client) throws Exception {
DMRUtil.unsetMaxSizeAttribute(client);
}
/**
* Sets up the Jakarta Enterprise Beans client context to use a selector which processes and sets up Jakarta Enterprise Beans receivers based on this testcase
* specific jboss-ejb-client.properties file
*/
protected void setupEJBClientContextSelector() throws IOException {
// TODO Elytron: Once support for legacy Jakarta Enterprise Beans properties has been added back, actually set the Jakarta Enterprise Beans properties
// that should be used for this test using sfsb-failover-jboss-ejb-client.properties and ensure the Jakarta Enterprise Beans client
// context is reset to its original state at the end of the test
//EJBClientContextSelector.setup("cluster/ejb3/stateful/failover/sfsb-failover-jboss-ejb-client.properties");
}
/**
* Start servers whether their are not started.
*
* @param client1 client for server1
* @param client2 client for server2
*/
protected abstract void startServers(ManagementClient client1, ManagementClient client2);
/**
* Waiting for getting cluster context - it could take some time for client to get info from cluster nodes
*/
protected void waitForClusterContext() throws InterruptedException {
int counter = 0;
EJBClientContext ejbClientContext = EJBClientContext.getCurrent();
// TODO Elytron: Determine how this should be adapted once the clustering and Jakarta Enterprise Beans client changes are in
// ClusterContext clusterContext;
//do {
// clusterContext = ejbClientContext.getClusterContext(CLUSTER_NAME);
// counter--;
// Thread.sleep(CLUSTER_ESTABLISHMENT_WAIT_MS);
//} while (clusterContext == null && counter < CLUSTER_ESTABLISHMENT_LOOP_COUNT);
//Assert.assertNotNull("Cluster context for " + CLUSTER_NAME + " was not taken in "
// + (CLUSTER_ESTABLISHMENT_LOOP_COUNT * CLUSTER_ESTABLISHMENT_WAIT_MS) + " ms", clusterContext);
}
/**
* Testing passivation over nodes - switching a node on and off. Testing ejbPassivate bean function.
*/
protected void runPassivation(StatefulRemote statefulBean, ContainerController controller, Deployer deployer) throws Exception {
Assert.assertNotNull(statefulBean);
// Calling on server one
int clientNumber = 40;
String calledNodeFirst = statefulBean.setNumber(clientNumber);
statefulBean.setPassivationNode(calledNodeFirst);
statefulBean.incrementNumber(); // 41
Assert.assertEquals(++clientNumber, statefulBean.getNumber()); // 41
// nodeName of nested bean should be the same as the node of parent
log.trace("Called node name first: " + calledNodeFirst);
Thread.sleep(WAIT_FOR_PASSIVATION_MS); // waiting for passivation
// A small hack - deleting node (by name) from cluster which this client knows
// It means that the next request (ejb call) will be passed to the server #2
// TODO Elytron: Determine how this should be adapted once the clustering and Jakarta Enterprise Beans client changes are in
//EJBClientContext.requireCurrent().getClusterContext(CLUSTER_NAME).removeClusterNode(calledNodeFirst);
Assert.assertEquals("Supposing to get passivation node which was set", calledNodeFirst, statefulBean.getPassivatedBy());
String calledNodeSecond = statefulBean.incrementNumber(); // 42
statefulBean.setPassivationNode(calledNodeSecond);
log.trace("Called node name second: " + calledNodeSecond);
Thread.sleep(WAIT_FOR_PASSIVATION_MS); // waiting for passivation
// Resetting cluster context to know both cluster nodes
setupEJBClientContextSelector();
// Waiting for getting cluster context - it could take some time for client to get info from cluster nodes
waitForClusterContext();
// Stopping node #2
deployer.undeploy(node2deployment.get(calledNodeSecond));
controller.stop(node2container.get(calledNodeSecond));
// We killed second node and we check the value on first node
Assert.assertEquals(++clientNumber, statefulBean.getNumber()); // 42
// Calling on first server
String calledNode = statefulBean.incrementNumber(); // 43
// Checking called node and set number
Assert.assertEquals("It can't be node " + calledNodeSecond + " because is switched off", calledNodeFirst, calledNode);
Assert.assertEquals("Supposing to get passivation node which was set", calledNodeSecond, statefulBean.getPassivatedBy());
Thread.sleep(WAIT_FOR_PASSIVATION_MS); // waiting for passivation
Assert.assertEquals(++clientNumber, statefulBean.getNumber()); // 43
}
}
| 7,905
| 44.965116
| 162
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/passivation/StatefulBeanBase.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.clustering.cluster.ejb2.stateful.passivation;
import java.rmi.RemoteException;
import jakarta.ejb.EJBException;
import jakarta.ejb.SessionContext;
import org.jboss.as.test.clustering.NodeNameGetter;
import org.jboss.logging.Logger;
/**
* @author Ondrej Chaloupka
*/
public abstract class StatefulBeanBase {
private static Logger log = Logger.getLogger(StatefulBeanBase.class);
protected int number;
protected String passivatedBy = "unknown";
protected String actIfIsNode;
protected int postActivateCalled = 0;
protected int prePassivateCalled = 0;
/**
* Getting number.
*/
public int getNumber() {
return number;
}
public String incrementNumber() {
number++;
log.trace("Incrementing number: " + Integer.toString(number));
return NodeNameGetter.getNodeName();
}
/**
* Setting number and returns node name where the method was called.
*/
public String setNumber(int number) {
log.trace("Setting number: " + Integer.toString(number));
this.number = number;
return NodeNameGetter.getNodeName();
}
public String getPassivatedBy() {
return this.passivatedBy;
}
public void setPassivationNode(String nodeName) {
this.actIfIsNode = nodeName;
}
/**
* Creating method for home interface...
*/
public void ejbCreate() throws java.rmi.RemoteException, jakarta.ejb.CreateException {
}
/**
* @Override on SessionBean
*/
public void ejbActivate() throws EJBException, RemoteException {
postActivateCalled++;
log.trace("Activating with number: " + number + " and was passivated by " + getPassivatedBy() + ", postActivate method called " + postActivateCalled + " times");
}
/**
* @Override on SessionBean
*/
public void ejbPassivate() throws EJBException, RemoteException {
prePassivateCalled++;
log.trace("Passivating with number: " + number + " and was passivated by " + getPassivatedBy() + ", prePassivate method called " + prePassivateCalled + " times");
// when we should act on passivation - we change value of isPassivated variable
if (NodeNameGetter.getNodeName().equals(actIfIsNode)) {
passivatedBy = NodeNameGetter.getNodeName();
log.trace("I'm node " + actIfIsNode + " => changing passivatedBy to " + passivatedBy);
}
}
/**
* @Override on SessionBean
*/
public void ejbRemove() throws EJBException, RemoteException {
}
/**
* @Override on SessionBean
*/
public void setSessionContext(SessionContext arg0) throws EJBException, RemoteException {
}
}
| 3,765
| 31.188034
| 170
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/passivation/dd/StatefulBeanDD.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.clustering.cluster.ejb2.stateful.passivation.dd;
import jakarta.ejb.SessionBean;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.passivation.StatefulBeanBase;
/**
* @author Ondrej Chaloupka
*/
public class StatefulBeanDD extends StatefulBeanBase implements SessionBean {
private static final long serialVersionUID = 1L;
}
| 1,391
| 38.771429
| 87
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateful/passivation/dd/ClusterPassivationDDTestCase.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.clustering.cluster.ejb2.stateful.passivation.dd;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.*;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.clustering.NodeInfoServlet;
import org.jboss.as.test.clustering.NodeNameGetter;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.passivation.ClusterPassivationTestBase;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.passivation.StatefulBeanBase;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.passivation.StatefulRemote;
import org.jboss.as.test.clustering.cluster.ejb2.stateful.passivation.StatefulRemoteHome;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Clustering ejb passivation of EJB2 bean defined by descriptor.
*
* @author Ondrej Chaloupka
*/
@Ignore("Uses legacy client hack")
@RunWith(Arquillian.class)
public class ClusterPassivationDDTestCase extends ClusterPassivationTestBase {
private static Logger log = Logger.getLogger(ClusterPassivationDDTestCase.class);
@ArquillianResource
private ContainerController controller;
@ArquillianResource
private Deployer deployer;
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war");
war.addClasses(StatefulBeanBase.class, StatefulBeanDD.class, StatefulRemote.class, StatefulRemoteHome.class);
war.addAsWebInfResource(ClusterPassivationDDTestCase.class.getPackage(), "ejb-jar.xml", "ejb-jar.xml");
war.addClasses(NodeNameGetter.class, NodeInfoServlet.class);
return war;
}
@Override
protected void startServers(ManagementClient client1, ManagementClient client2) {
if (client1 == null || !client1.isServerInRunningState()) {
log.trace("Starting server: " + NODE_1);
controller.start(NODE_1);
deployer.deploy(DEPLOYMENT_1);
}
if (client2 == null || !client2.isServerInRunningState()) {
log.trace("Starting server: " + NODE_2);
controller.start(NODE_2);
deployer.deploy(DEPLOYMENT_2);
}
}
@Test
@InSequence(-2)
public void startServersForTests() {
startServers(null, null);
}
/**
* Association of node names to deployment,container names and client context
*/
@Test
@InSequence(-1)
public void defineMaps(@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2,
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) ManagementClient client1,
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) ManagementClient client2) throws Exception {
String nodeName1 = HttpRequest.get(baseURL1.toString() + NodeInfoServlet.SERVLET_NAME, HTTP_REQUEST_WAIT_TIME_S, TimeUnit.SECONDS);
node2deployment.put(nodeName1, DEPLOYMENT_1);
node2container.put(nodeName1, NODE_1);
log.trace("URL1 nodename: " + nodeName1);
String nodeName2 = HttpRequest.get(baseURL2.toString() + NodeInfoServlet.SERVLET_NAME, HTTP_REQUEST_WAIT_TIME_S, TimeUnit.SECONDS);
node2deployment.put(nodeName2, DEPLOYMENT_2);
node2container.put(nodeName2, NODE_2);
log.trace("URL2 nodename: " + nodeName2);
}
@Test
@InSequence(1)
public void testPassivationBeanDefinedByDescriptor(
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) ManagementClient client1,
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) ManagementClient client2) throws Exception {
setPassivationAttributes(client1.getControllerClient());
setPassivationAttributes(client2.getControllerClient());
// Setting context from .properties file to get ejb:/ remote context
setupEJBClientContextSelector();
StatefulRemoteHome home = directory.lookupHome(StatefulBeanDD.class, StatefulRemoteHome.class);
StatefulRemote statefulBean = home.create();
runPassivation(statefulBean, controller, deployer);
startServers(client1, client2);
}
@Test
@InSequence(100)
public void stopAndClean(
@OperateOnDeployment(DEPLOYMENT_1) @ArquillianResource ManagementClient client1,
@OperateOnDeployment(DEPLOYMENT_2) @ArquillianResource ManagementClient client2) throws Exception {
log.trace("Stop&Clean...");
// unset & undeploy & stop
if (client1.isServerInRunningState()) {
unsetPassivationAttributes(client1.getControllerClient());
deployer.undeploy(DEPLOYMENT_1);
controller.stop(NODE_1);
}
if (client2.isServerInRunningState()) {
unsetPassivationAttributes(client2.getControllerClient());
deployer.undeploy(DEPLOYMENT_2);
controller.stop(NODE_2);
}
}
}
| 7,197
| 42.101796
| 139
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/remote/SuspendResumeRemoteEJB2TestCase.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.clustering.cluster.ejb2.remote;
import org.apache.commons.lang3.RandomUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.clustering.cluster.ejb2.remote.bean.HeartbeatBeanBase;
import org.jboss.as.test.clustering.cluster.ejb2.remote.bean.HeartbeatRemote;
import org.jboss.as.test.clustering.cluster.ejb2.remote.bean.HeartbeatRemoteHome;
import org.jboss.as.test.clustering.cluster.ejb2.remote.bean.Result;
import org.jboss.as.test.clustering.cluster.ejb2.remote.bean.SlowHeartbeatBean;
import org.jboss.as.test.clustering.ejb.EJBDirectory;
import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory;
import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.PropertyPermission;
import java.util.Set;
import static org.jboss.as.controller.client.helpers.ClientConstants.CONTROLLER_PROCESS_STATE_STARTING;
import static org.jboss.as.controller.client.helpers.ClientConstants.CONTROLLER_PROCESS_STATE_STOPPING;
import static org.jboss.as.controller.client.helpers.ClientConstants.RUNNING_STATE_SUSPENDED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
/**
* Test for WFLY-13871.
*
* This test will set up an EJB client interacting with a cluster of two nodes and verify that when
* one of the nodes is suspended, invovations no longer are sent to the suspended node; and that when the node is resumed,
* invocations return to the resumed node.
*
* @author Richard Achmatowicz
*/
@RunWith(Arquillian.class)
public class SuspendResumeRemoteEJB2TestCase extends AbstractClusteringTestCase {
static final Logger LOGGER = Logger.getLogger(SuspendResumeRemoteEJB2TestCase.class);
private static final String MODULE_NAME = SuspendResumeRemoteEJB2TestCase.class.getSimpleName();
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> createDeploymentForContainer1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> createDeploymentForContainer2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
return ShrinkWrap.create(JavaArchive.class, MODULE_NAME + ".jar")
.addPackage(EJBDirectory.class.getPackage())
.addClasses(Result.class, HeartbeatRemote.class, HeartbeatRemoteHome.class, SlowHeartbeatBean.class, HeartbeatBeanBase.class, RandomUtils.class)
.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new PropertyPermission(NODE_NAME_PROPERTY, "read")), "permissions.xml")
;
}
@ArquillianResource
@TargetsContainer(NODE_1)
private ManagementClient client1;
@ArquillianResource
@TargetsContainer(NODE_2)
private ManagementClient client2;
final int INVOCATION_LOOP_TIMES = 5 ;
final int SUSPEND_RESUME_LOOP_TIMES = 5 ;
// time between invocations
final long INV_WAIT_DURATION_MSECS = 10 ;
// time that the server remains suspended (or resumed) during continuous invocations
final long SUSPEND_RESUME_DURATION_MSECS = 1 * 1000 ;
// the set of nodes available, according to suspend/resume
Set<String> nodesAvailable = new HashSet<String>();
@Before
public void initialiseNodesAvailable() {
nodesAvailable.addAll(Arrays.asList(NODE_1,NODE_2));
}
/**
* This test checks that suspending and then resuming the server during invocation results in correct behaviour
* in the case that the proxy is created before the server is suspended.
*
* The test assertion is checked after each invocation result, and verifies that no invocation is sent to a suspended node.
*
* @throws Exception
*/
@Test
@InSequence(1)
public void testSuspendResumeAfterProxyInit() throws Exception {
LOGGER.info("testSuspendResumeAfterProxyInit() - start");
try (EJBDirectory directory = new RemoteEJBDirectory(MODULE_NAME)) {
HeartbeatRemoteHome home = directory.lookupHome(SlowHeartbeatBean.class, HeartbeatRemoteHome.class);
HeartbeatRemote bean = home.create();
for (int i = 1; i < INVOCATION_LOOP_TIMES; i++) {
performInvocation(bean);
}
suspendTheServer(NODE_1);
for (int i = 1; i < INVOCATION_LOOP_TIMES; i++) {
performInvocation(bean);
}
resumeTheServer(NODE_1);
for (int i = 1; i < INVOCATION_LOOP_TIMES; i++) {
performInvocation(bean);
}
} catch(Exception e) {
LOGGER.info("Caught exception! e = " + e.getMessage());
Assert.fail("Test failed with exception: e = " + e.getMessage());
} finally {
LOGGER.info("testSuspendResumeAfterProxyInit() - end");
}
}
/**
* This test checks that suspending and then resuming the server during invocation results in correct behaviour
* in the case that the proxy is created after the server is suspended.
*
* The test assertion is checked after each invocation result, and verifies that no invocation is sent to a suspended node.
*
* @throws Exception
*/
@Test
@InSequence(2)
public void testSuspendResumeBeforeProxyInit() throws Exception {
LOGGER.info("testSuspendResumeBeforeProxyInit() - start");
try (EJBDirectory directory = new RemoteEJBDirectory(MODULE_NAME)) {
suspendTheServer(NODE_1);
HeartbeatRemoteHome home = directory.lookupHome(SlowHeartbeatBean.class, HeartbeatRemoteHome.class);
HeartbeatRemote bean = home.create();
for (int i = 1; i < INVOCATION_LOOP_TIMES; i++) {
performInvocation(bean);
}
resumeTheServer(NODE_1);
for (int i = 1; i < INVOCATION_LOOP_TIMES; i++) {
performInvocation(bean);
}
} catch(Exception e) {
LOGGER.info("Caught exception! e = " + e.getMessage());
Assert.fail("Test failed with exception: e = " + e.getMessage());
} finally {
LOGGER.info("testSuspendResumeBeforeProxyInit() - end");
}
}
/**
* This test checks that suspending and then resuming the server during invocation results in correct behaviour
* in the case that the proxy is created after the server is suspended.
*
* The test assertion is checked after each invocation result, and verifies that no invocation is sent to a suspended node.
*
* @throws Exception
*/
@Test
@InSequence(3)
public void testSuspendResumeContinuous() throws Exception {
LOGGER.info("testSuspendResumeContinuous() - start");
try (EJBDirectory directory = new RemoteEJBDirectory(MODULE_NAME)) {
HeartbeatRemoteHome home = directory.lookupHome(SlowHeartbeatBean.class, HeartbeatRemoteHome.class);
HeartbeatRemote bean = home.create();
ContinuousInvoker continuousInvoker = new ContinuousInvoker(bean);
Thread thread = new Thread(continuousInvoker);
LOGGER.info("Starting the invoker ...");
thread.start();
for (int i = 0; i < SUSPEND_RESUME_LOOP_TIMES; i++) {
// suspend and then resume each server in turn while invocations happen
sleep(SUSPEND_RESUME_DURATION_MSECS);
suspendTheServer(NODE_1);
sleep(SUSPEND_RESUME_DURATION_MSECS);
resumeTheServer(NODE_1);
// suspend and then resume each server in turn while invocations happen
sleep(SUSPEND_RESUME_DURATION_MSECS);
suspendTheServer(NODE_2);
sleep(SUSPEND_RESUME_DURATION_MSECS);
resumeTheServer(NODE_2);
}
continuousInvoker.stopInvoking();
}
catch(Exception e) {
LOGGER.info("Caught exception! e = " + e.getMessage());
Assert.fail("Test failed with exception: e = " + e.getMessage());
}
LOGGER.info("testSuspendResumeContinuous() - end");
}
/**
* Helper class that performs invocations on a bean once per second until stopInvoking() is called.
*/
private class ContinuousInvoker implements Runnable {
private boolean invoking = true ;
HeartbeatRemote bean = null;
public ContinuousInvoker(HeartbeatRemote bean) {
this.bean = bean;
}
public synchronized void stopInvoking() {
LOGGER.info("Stopping the invoker ...");
this.invoking = false;
}
private synchronized boolean keepInvoking() {
return this.invoking == true;
}
@Override
public void run() {
try {
while (keepInvoking()) {
performInvocation(bean);
}
} catch (Exception e) {
LOGGER.info("ContinousInvoker: caught exception while performing invocation: e = " + e.getMessage());
throw e;
}
}
}
private void performInvocation(HeartbeatRemote bean) {
Result<Date> result = null;
try {
result = bean.pulse();
LOGGER.info("invoked pulse(), result: node = " + result.getNode() + ", value = " + result.getValue()) ;
Assert.assertTrue(nodesAvailable.contains(result.getNode()));
sleep(INV_WAIT_DURATION_MSECS);
} catch (Exception e) {
LOGGER.info("Exception caught while invoking pulse(): " + e.getMessage());
throw e;
}
}
// helper methods to determine server state
private void suspendTheServer(String node) {
LOGGER.info("=================== SUSPEND " + node + " ===========================");
if (suspendServer(node)) {
nodesAvailable.remove(node);
}
LOGGER.info(isServerSuspended(node) ? node + " is suspended" : node + " is NOT suspended") ;
}
private void resumeTheServer(String node) {
LOGGER.info("=================== RESUME " + node + " ===========================");
if (resumeServer(node)) {
nodesAvailable.add(node);
}
LOGGER.info(isServerSuspended(node) ? node + " is suspended" : node + " is NOT suspended") ;
}
private boolean isServerRunning(String node) {
try {
ModelNode op = Util.createOperation("read-attribute", PathAddress.EMPTY_ADDRESS);
op.get(NAME).set("server-state");
ModelNode result = null;
if (NODE_1.equals(node)) {
result = client1.getControllerClient().execute(op);
} else {
result = client2.getControllerClient().execute(op);
}
return SUCCESS.equals(result.get(OUTCOME).asString())
&& !CONTROLLER_PROCESS_STATE_STARTING.equals(result.get(RESULT).asString())
&& !CONTROLLER_PROCESS_STATE_STOPPING.equals(result.get(RESULT).asString());
} catch(IOException e) {
return false;
}
}
/**
* Suspend a server by calling the management operation ":suspend"
*
* @param node the node to be suspended
* @return true if the operation succeeded
*/
private boolean suspendServer(String node) {
try {
ModelNode op = Util.createOperation("suspend", PathAddress.EMPTY_ADDRESS);
ModelNode result = null;
if (NODE_1.equals(node)) {
result = client1.getControllerClient().execute(op);
} else {
result = client2.getControllerClient().execute(op);
}
return SUCCESS.equals(result.get(OUTCOME).asString());
} catch(IOException e) {
return false;
}
}
/**
* Resume a server by calling the management operation ":suspend"
*
* @param node the node to be suspended
* @return true if the operation succeeded
*/
private boolean resumeServer(String node) {
try {
ModelNode op = Util.createOperation("resume", PathAddress.EMPTY_ADDRESS);
ModelNode result = null;
if (NODE_1.equals(node)) {
result = client1.getControllerClient().execute(op);
} else {
result = client2.getControllerClient().execute(op);
}
return SUCCESS.equals(result.get(OUTCOME).asString());
} catch(IOException e) {
return false;
}
}
/**
* Check if a server is suspended by reading the server attribute "suspend-state"
*
* @param node the node to be checked
* @return true if the server is suspended
*/
private boolean isServerSuspended(String node) {
try {
ModelNode op = Util.createOperation("read-attribute", PathAddress.EMPTY_ADDRESS);
op.get(NAME).set("suspend-state");
ModelNode result = null;
if (NODE_1.equals(node)) {
result = client1.getControllerClient().execute(op);
} else {
result = client2.getControllerClient().execute(op);
}
return SUCCESS.equals(result.get(OUTCOME).asString())
&& RUNNING_STATE_SUSPENDED.equalsIgnoreCase(result.get(RESULT).asString());
} catch(IOException e) {
return false;
}
}
private void sleep(long ms) {
try {
LOGGER.info("Sleeping for " + ms + " ms ...");
Thread.sleep( ms);
} catch(InterruptedException ie) {
// noop
}
}
}
| 16,055
| 37.782609
| 160
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/remote/bean/Result.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.clustering.cluster.ejb2.remote.bean;
import java.io.Serializable;
/**
* A wrapper for a return value that includes the node on which the result was generated.
* @author Paul Ferraro
*/
public class Result<T> implements Serializable {
private static final long serialVersionUID = -1079933234795356933L;
private final T value;
private final String node;
public Result(T value) {
this.value = value;
this.node = System.getProperty("jboss.node.name");
}
public T getValue() {
return this.value;
}
public String getNode() {
return this.node;
}
}
| 1,667
| 33.040816
| 89
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/remote/bean/HeartbeatRemote.java
|
package org.jboss.as.test.clustering.cluster.ejb2.remote.bean;
import jakarta.ejb.EJBObject;
import java.util.Date;
/**
* The remote / business interface for the Heartbeat Enterprise Beans 2.x bean
*
* @author Richard Achmatowicz
*/
public interface HeartbeatRemote extends EJBObject {
Result<Date> pulse();
}
| 320
| 21.928571
| 78
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/remote/bean/SlowHeartbeatBean.java
|
package org.jboss.as.test.clustering.cluster.ejb2.remote.bean;
import jakarta.ejb.Remote;
import jakarta.ejb.RemoteHome;
import jakarta.ejb.SessionBean;
import jakarta.ejb.Stateless;
import java.util.Date;
import java.util.concurrent.TimeUnit;
@Stateless
@Remote(HeartbeatRemote.class)
@RemoteHome(HeartbeatRemoteHome.class)
public class SlowHeartbeatBean extends HeartbeatBeanBase implements SessionBean {
public Result<Date> pulse() {
delay();
Date now = new Date();
return new Result<>(now);
}
private static void delay() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
| 729
| 24.172414
| 81
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/remote/bean/HeartbeatRemoteHome.java
|
package org.jboss.as.test.clustering.cluster.ejb2.remote.bean;
import jakarta.ejb.EJBHome;
/**
* The remote home interface for the Heartbeat Enterprise Beans 2.x bean
*
* @author Richard Achmatowicz
*/
public interface HeartbeatRemoteHome extends EJBHome {
HeartbeatRemote create() throws java.rmi.RemoteException, jakarta.ejb.CreateException;
}
| 356
| 26.461538
| 90
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/remote/bean/HeartbeatBean.java
|
package org.jboss.as.test.clustering.cluster.ejb2.remote.bean;
import jakarta.ejb.Remote;
import jakarta.ejb.RemoteHome;
import jakarta.ejb.SessionBean;
import jakarta.ejb.Stateless;
@Stateless
@Remote(HeartbeatRemote.class)
@RemoteHome(HeartbeatRemoteHome.class)
public class HeartbeatBean extends HeartbeatBeanBase implements SessionBean {
}
| 347
| 23.857143
| 77
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/remote/bean/HeartbeatBeanBase.java
|
package org.jboss.as.test.clustering.cluster.ejb2.remote.bean;
import jakarta.ejb.EJBException;
import jakarta.ejb.SessionContext;
import java.rmi.RemoteException;
import java.util.Date;
public abstract class HeartbeatBeanBase {
public Result<Date> pulse() {
Date now = new Date();
return new Result<>(now);
}
public void ejbCreate() throws EJBException, RemoteException {
// creating ejb2 bean
}
public void setSessionContext(SessionContext sessionContext) throws EJBException, RemoteException {
}
public void ejbRemove() throws EJBException, RemoteException {
}
public void ejbActivate() throws EJBException, RemoteException {
}
public void ejbPassivate() throws EJBException, RemoteException {
}
}
| 785
| 21.457143
| 103
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateless/RemoteStatelessFailoverTestCase.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.clustering.cluster.ejb2.stateless;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.*;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PropertyPermission;
import javax.naming.NamingException;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.clustering.NodeNameGetter;
import org.jboss.as.test.clustering.cluster.ejb2.stateless.bean.StatelessRemote;
import org.jboss.as.test.clustering.cluster.ejb2.stateless.bean.StatelessRemoteHome;
import org.jboss.as.test.clustering.ejb.EJBDirectory;
import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Enterprise Beans 2 stateless bean - basic cluster tests - failover and load balancing.
*
* @author Paul Ferraro
* @author Ondrej Chaloupka
*/
@RunWith(Arquillian.class)
public class RemoteStatelessFailoverTestCase {
private static final Logger log = Logger.getLogger(RemoteStatelessFailoverTestCase.class);
private static final String MODULE_NAME = RemoteStatelessFailoverTestCase.class.getSimpleName();
private static final String MODULE_NAME_DD = MODULE_NAME + "dd";
private static final Map<String, Boolean> deployed = new HashMap<String, Boolean>();
private static final Map<String, Boolean> started = new HashMap<String, Boolean>();
private static final Map<String, List<String>> container2deployment = new HashMap<String, List<String>>();
private EJBDirectory directoryAnnotation;
private EJBDirectory directoryDD;
@BeforeClass
public static void init() throws NamingException {
deployed.put(DEPLOYMENT_1, false);
deployed.put(DEPLOYMENT_2, false);
deployed.put(DEPLOYMENT_HELPER_1, false);
deployed.put(DEPLOYMENT_HELPER_2, false);
started.put(NODE_1, false);
started.put(NODE_2, false);
List<String> deployments1 = new ArrayList<>();
deployments1.add(DEPLOYMENT_1);
deployments1.add(DEPLOYMENT_HELPER_1);
container2deployment.put(NODE_1, deployments1);
List<String> deployments2 = new ArrayList<>();
deployments2.add(DEPLOYMENT_2);
deployments2.add(DEPLOYMENT_HELPER_2);
container2deployment.put(NODE_2, deployments2);
}
@Before
public void beforeTest() throws Exception {
directoryAnnotation = new RemoteEJBDirectory(MODULE_NAME);
directoryDD = new RemoteEJBDirectory(MODULE_NAME_DD);
}
@After
public void afterTest() throws Exception {
directoryAnnotation.close();
directoryDD.close();
}
@ArquillianResource
private ContainerController container;
@ArquillianResource
private Deployer deployer;
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> createDeploymentForContainer1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> createDeploymentForContainer2() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_HELPER_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> createDeploymentOnDescriptorForContainer1() {
return createDeploymentOnDescriptor();
}
@Deployment(name = DEPLOYMENT_HELPER_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> createDeploymentOnDescriptorForContainer2() {
return createDeploymentOnDescriptor();
}
private static Archive<?> createDeployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, MODULE_NAME + ".jar");
jar.addPackage(StatelessRemote.class.getPackage());
jar.addClass(StatelessBean.class);
jar.addClass(NodeNameGetter.class);
jar.addAsResource(createPermissionsXmlAsset(
new PropertyPermission("jboss.node.name", "read")),
"META-INF/jboss-permissions.xml");
return jar;
}
private static Archive<?> createDeploymentOnDescriptor() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, MODULE_NAME_DD + ".jar");
jar.addPackage(StatelessRemote.class.getPackage());
jar.addClass(StatelessBeanDD.class);
jar.addClass(NodeNameGetter.class);
jar.addAsManifestResource(RemoteStatelessFailoverTestCase.class.getPackage(), "ejb-jar.xml", "ejb-jar.xml");
jar.addAsResource(createPermissionsXmlAsset(
new PropertyPermission("jboss.node.name", "read")),
"META-INF/jboss-permissions.xml");
return jar;
}
@Test
public void testFailoverOnStopAnnotatedBean() throws Exception {
doFailover(true, directoryAnnotation, DEPLOYMENT_1, DEPLOYMENT_2);
}
@Test
public void testFailoverOnStopBeanSpecifiedByDescriptor() throws Exception {
doFailover(true, directoryDD, DEPLOYMENT_HELPER_1, DEPLOYMENT_HELPER_2);
}
@Test
public void testFailoverOnUndeployAnnotatedBean() throws Exception {
doFailover(false, directoryAnnotation, DEPLOYMENT_1, DEPLOYMENT_2);
}
@Test
public void testFailoverOnUndeploySpecifiedByDescriptor() throws Exception {
doFailover(false, directoryDD, DEPLOYMENT_HELPER_1, DEPLOYMENT_HELPER_2);
}
private void doFailover(boolean isStop, EJBDirectory directory, String deployment1, String deployment2) throws Exception {
this.start(NODE_1);
this.deploy(NODE_1, deployment1);
// TODO Elytron: Once support for legacy Jakarta Enterprise Beans properties has been added back, actually set the Jakarta Enterprise Beans properties
// that should be used for this test using CLIENT_PROPERTIES and ensure the Jakarta Enterprise Beans client context is reset
// to its original state at the end of the test
// EJBClientContextSelector.setup(CLIENT_PROPERTIES);
try {
StatelessRemoteHome home = directory.lookupHome(StatelessBean.class, StatelessRemoteHome.class);
StatelessRemote bean = home.create();
assertEquals("The only " + TWO_NODES[0] + " is active. Bean had to be invoked on it but it wasn't.", TWO_NODES[0], bean.getNodeName());
this.start(NODE_2);
this.deploy(NODE_2, deployment2);
if (isStop) {
this.stop(NODE_1);
} else {
this.undeploy(NODE_1, deployment1);
}
assertEquals("Only " + TWO_NODES[1] + " is active. The bean had to be invoked on it but it wasn't.", TWO_NODES[1], bean.getNodeName());
} finally {
// need to have the container started to undeploy deployment afterwards
this.start(NODE_1);
// shutdown the containers
undeployAll();
shutdownAll();
}
}
@Test
public void testLoadbalanceAnnotatedBean() throws Exception {
loadbalance(directoryAnnotation, DEPLOYMENT_1, DEPLOYMENT_2);
}
@Test
public void testLoadbalanceSpecifiedByDescriptor() throws Exception {
loadbalance(directoryDD, DEPLOYMENT_HELPER_1, DEPLOYMENT_HELPER_2);
}
/**
* Basic load balance testing. A random distribution is used amongst nodes for client now.
*/
private void loadbalance(EJBDirectory directory, String deployment1, String deployment2) throws Exception {
this.start(NODE_1);
this.deploy(NODE_1, deployment1);
this.start(NODE_2);
this.deploy(NODE_2, deployment2);
// TODO Elytron: Once support for legacy Jakarta Enterprise Beans properties has been added back, actually set the Jakarta Enterprise Beans properties
// that should be used for this test using CLIENT_PROPERTIES and ensure the Jakarta Enterprise Beans client context is reset
// to its original state at the end of the test
// EJBClientContextSelector.setup(CLIENT_PROPERTIES);
int numberOfServers = 2;
int numberOfCalls = 40;
// there will be at least 20% of calls processed by all servers
double serversProcessedAtLeast = 0.2;
try {
StatelessRemoteHome home = directory.lookupHome(StatelessBean.class, StatelessRemoteHome.class);
StatelessRemote bean = home.create();
String node = bean.getNodeName();
log.trace("Node called : " + node);
validateBalancing(bean, numberOfCalls, numberOfServers, serversProcessedAtLeast);
// Properties contextChangeProperties = new Properties();
// contextChangeProperties.put(REMOTE_PORT_PROPERTY_NAME, PORT_2.toString());
// contextChangeProperties.put(REMOTE_HOST_PROPERTY_NAME, HOST_2.toString());
// EJBClientContextSelector.setup(CLIENT_PROPERTIES, contextChangeProperties);
bean = home.create();
node = bean.getNodeName();
log.trace("Node called : " + node);
validateBalancing(bean, numberOfCalls, numberOfServers, serversProcessedAtLeast);
} finally {
// undeploy&shutdown the containers
undeployAll();
shutdownAll();
}
}
/**
* Method calls the bean function getNodeName() {numCalls} times and checks whether all servers processed at least part of calls.
* The necessary number of processed calls by each server is {minPercentage} of the number of all calls.
*/
private static void validateBalancing(StatelessRemote bean, int numCalls, int expectedServers, double minPercentage) {
Map<String, Integer> callCount = new HashMap<String, Integer>();
int maxNumOfProcessedCalls = -1;
int minNumOfProcessedCalls = Integer.MAX_VALUE;
for (int i = 0; i < numCalls; i++) {
String nodeName = bean.getNodeName();
Integer count = callCount.get(nodeName);
count = count == null ? 1 : ++count;
callCount.put(nodeName, count);
}
Assert.assertEquals("It was running " + expectedServers + " servers but not all of them were used for loadbalancing.",
expectedServers, callCount.size());
for (Integer count : callCount.values()) {
maxNumOfProcessedCalls = count > maxNumOfProcessedCalls ? count : maxNumOfProcessedCalls;
minNumOfProcessedCalls = count < minNumOfProcessedCalls ? count : minNumOfProcessedCalls;
}
Assert.assertTrue("Minimal number of calls done to all servers have to be " + minPercentage * numCalls + " but was " + minNumOfProcessedCalls,
minPercentage * numCalls <= minNumOfProcessedCalls);
log.trace("All " + expectedServers + " servers processed at least " + minNumOfProcessedCalls + " of calls");
}
private void undeployAll() {
for (Map.Entry<String, List<String>> entry : container2deployment.entrySet()) {
for (String deployment : entry.getValue()) {
undeploy(entry.getKey(), deployment);
}
}
}
private void shutdownAll() {
for (String container : container2deployment.keySet()) {
stop(container);
}
}
private void deploy(String container, String deployment) {
if (started.get(container) && !deployed.get(deployment)) {
this.deployer.deploy(deployment);
deployed.put(deployment, true);
}
}
private void undeploy(String container, String deployment) {
if (started.get(container) && deployed.get(deployment)) {
this.deployer.undeploy(deployment);
deployed.put(deployment, false);
}
}
private void start(String container) {
if (!started.get(container)) {
this.container.start(container);
started.put(container, true);
}
}
private void stop(String container) {
if (started.get(container)) {
this.container.stop(container);
started.put(container, false);
}
}
}
| 13,989
| 39.906433
| 158
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateless/StatelessBeanDD.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.clustering.cluster.ejb2.stateless;
import jakarta.ejb.SessionBean;
import org.jboss.as.test.clustering.cluster.ejb2.stateless.bean.StatelessBeanBase;
/**
* @author Ondrej Chaloupka
*/
public class StatelessBeanDD extends StatelessBeanBase implements SessionBean {
private static final long serialVersionUID = 1L;
}
| 1,374
| 38.285714
| 82
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateless/StatelessBean.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.clustering.cluster.ejb2.stateless;
import jakarta.ejb.Remote;
import jakarta.ejb.RemoteHome;
import jakarta.ejb.SessionBean;
import jakarta.ejb.Stateless;
import org.jboss.as.test.clustering.cluster.ejb2.stateless.bean.StatelessBeanBase;
import org.jboss.as.test.clustering.cluster.ejb2.stateless.bean.StatelessRemote;
import org.jboss.as.test.clustering.cluster.ejb2.stateless.bean.StatelessRemoteHome;
/**
* @author Ondrej Chaloupka
*/
@Stateless
@RemoteHome(StatelessRemoteHome.class)
@Remote(StatelessRemote.class)
public class StatelessBean extends StatelessBeanBase implements SessionBean {
private static final long serialVersionUID = 1L;
}
| 1,707
| 38.72093
| 84
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateless/bean/StatelessRemoteHome.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.ejb2.stateless.bean;
import java.rmi.RemoteException;
import jakarta.ejb.CreateException;
import jakarta.ejb.EJBHome;
/**
* @author Ondrej Chaloupka
*/
public interface StatelessRemoteHome extends EJBHome {
StatelessRemote create() throws RemoteException, CreateException;
}
| 1,361
| 37.914286
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateless/bean/StatelessRemote.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.ejb2.stateless.bean;
import jakarta.ejb.EJBObject;
/**
* @author Ondrej Chaloupka
*/
public interface StatelessRemote extends EJBObject {
String getNodeName();
}
| 1,248
| 36.848485
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb2/stateless/bean/StatelessBeanBase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.ejb2.stateless.bean;
import java.rmi.RemoteException;
import jakarta.ejb.EJBException;
import jakarta.ejb.SessionContext;
import jakarta.ejb.TransactionAttribute;
import jakarta.ejb.TransactionAttributeType;
import org.jboss.as.test.clustering.NodeNameGetter;
import org.jboss.logging.Logger;
/**
* @author Ondrej Chaloupka
*/
public abstract class StatelessBeanBase {
private static final Logger log = Logger.getLogger(StatelessBeanBase.class);
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public String getNodeName() {
String nodeName = NodeNameGetter.getNodeName();
log.trace("StatelessBean.getNodeName() was called on node: " + nodeName);
return nodeName;
}
public void ejbCreate() throws EJBException, RemoteException {
// creating ejb2 bean
}
/**
* Overrides SessionBean method
*/
public void ejbActivate() throws EJBException, RemoteException {
}
/**
* Overrides SessionBean method
*/
public void ejbPassivate() throws EJBException, RemoteException {
}
/**
* Overrides SessionBean method
*/
public void ejbRemove() throws EJBException, RemoteException {
}
/**
* Overrides SessionBean method
*/
public void setSessionContext(SessionContext arg0) throws EJBException, RemoteException {
}
}
| 2,445
| 29.575
| 93
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/provider/ServiceProviderRegistrationTestCase.java
|
package org.jboss.as.test.clustering.cluster.provider;
import static org.junit.Assert.*;
import java.util.Collection;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.clustering.cluster.provider.bean.ServiceProviderRetriever;
import org.jboss.as.test.clustering.cluster.provider.bean.ServiceProviderRetrieverBean;
import org.jboss.as.test.clustering.ejb.EJBDirectory;
import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory;
import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils;
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;
@RunWith(Arquillian.class)
public class ServiceProviderRegistrationTestCase extends AbstractClusteringTestCase {
private static final String MODULE_NAME = ServiceProviderRegistrationTestCase.class.getSimpleName();
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> createDeploymentForContainer1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> createDeploymentForContainer2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war");
war.addPackage(ServiceProviderRetriever.class.getPackage());
war.setWebXML(ServiceProviderRegistrationTestCase.class.getPackage(), "web.xml");
war.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new RuntimePermission("getClassLoader")), "permissions.xml");
return war;
}
@Test
public void test() throws Exception {
try (EJBDirectory directory = new RemoteEJBDirectory(MODULE_NAME)) {
ServiceProviderRetriever bean = directory.lookupStateless(ServiceProviderRetrieverBean.class, ServiceProviderRetriever.class);
Collection<String> names = bean.getProviders();
assertEquals(2, names.size());
assertTrue(names.toString(), names.contains(NODE_1));
assertTrue(names.toString(), names.contains(NODE_2));
undeploy(DEPLOYMENT_1);
names = bean.getProviders();
assertEquals(1, names.size());
assertTrue(names.contains(NODE_2));
deploy(DEPLOYMENT_1);
names = bean.getProviders();
assertEquals(2, names.size());
assertTrue(names.contains(NODE_1));
assertTrue(names.contains(NODE_2));
stop(NODE_2);
names = bean.getProviders();
assertEquals(1, names.size());
assertTrue(names.contains(NODE_1));
start(NODE_2);
names = bean.getProviders();
assertEquals(2, names.size());
assertTrue(names.contains(NODE_1));
assertTrue(names.contains(NODE_2));
}
}
}
| 3,283
| 38.095238
| 138
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/provider/bean/ServiceProviderRetriever.java
|
package org.jboss.as.test.clustering.cluster.provider.bean;
import java.util.Collection;
public interface ServiceProviderRetriever {
Collection<String> getProviders();
}
| 177
| 18.777778
| 59
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/provider/bean/ServiceProviderRegistrationBean.java
|
package org.jboss.as.test.clustering.cluster.provider.bean;
import java.util.Set;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import jakarta.ejb.Local;
import jakarta.ejb.Singleton;
import jakarta.ejb.Startup;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.logging.Logger;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.provider.ServiceProviderRegistration;
import org.wildfly.clustering.provider.ServiceProviderRegistry;
@Singleton
@Startup
@Local(ServiceProviderRegistration.class)
public class ServiceProviderRegistrationBean implements ServiceProviderRegistration<String>, ServiceProviderRegistration.Listener {
static final Logger log = Logger.getLogger(ServiceProviderRegistrationBean.class);
@Resource(name = "clustering/providers")
private ServiceProviderRegistry<String> factory;
private ServiceProviderRegistration<String> registration;
@PostConstruct
public void init() {
this.registration = this.factory.register("ServiceProviderRegistrationTestCase", this);
}
@PreDestroy
public void destroy() {
this.close();
}
@Override
public String getService() {
return this.registration.getService();
}
@Override
public Set<Node> getProviders() {
return this.registration.getProviders();
}
@Override
public void close() {
this.registration.close();
}
@Override
public void providersChanged(Set<Node> nodes) {
try {
// Ensure the thread context classloader of the notification is correct
Thread.currentThread().getContextClassLoader().loadClass(this.getClass().getName());
// Ensure the correct naming context is set
Context context = new InitialContext();
try {
context.lookup("java:comp/env/clustering/providers");
} finally {
context.close();
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
} catch (NamingException e) {
throw new IllegalStateException(e);
}
log.info(String.format("ProviderRegistration.Listener.providersChanged(%s)", nodes));
}
}
| 2,367
| 30.573333
| 131
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/provider/bean/ServiceProviderRetrieverBean.java
|
package org.jboss.as.test.clustering.cluster.provider.bean;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import jakarta.ejb.EJB;
import jakarta.ejb.Remote;
import jakarta.ejb.Stateless;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.provider.ServiceProviderRegistration;
@Stateless
@Remote(ServiceProviderRetriever.class)
public class ServiceProviderRetrieverBean implements ServiceProviderRetriever {
@EJB
private ServiceProviderRegistration<String> registration;
@Override
public Collection<String> getProviders() {
Set<Node> nodes = this.registration.getProviders();
List<String> result = new ArrayList<>(nodes.size());
for (Node node: nodes) {
result.add(node.getName());
}
return result;
}
}
| 857
| 25.8125
| 79
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/AbstractCacheTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import java.io.IOException;
import java.lang.reflect.ReflectPermission;
import java.net.URISyntaxException;
import java.net.URL;
import javax.management.MBeanPermission;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.infinispan.protostream.SerializationContextInitializer;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.clustering.cluster.infinispan.bean.Cache;
import org.jboss.as.test.clustering.cluster.infinispan.bean.InfinispanCacheSerializationContextInitializer;
import org.jboss.as.test.clustering.cluster.infinispan.servlet.InfinispanCacheServlet;
import org.jboss.as.test.clustering.single.web.SimpleWebTestCase;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Validates marshallability of application specific cache entries.
* @author Paul Ferraro
*/
@RunWith(Arquillian.class)
public abstract class AbstractCacheTestCase extends AbstractClusteringTestCase {
protected static Archive<?> createDeployment(Class<? extends Cache> beanClass, String module) {
WebArchive war = ShrinkWrap.create(WebArchive.class, beanClass.getSimpleName() + ".war");
war.addPackage(InfinispanCacheServlet.class.getPackage());
war.addPackage(Cache.class.getPackage());
war.addClass(beanClass);
war.setWebXML(SimpleWebTestCase.class.getPackage(), "web.xml");
war.addAsResource(new StringAsset(String.format("Manifest-Version: 1.0\nDependencies: %s, org.infinispan.commons, org.infinispan.protostream\n", module)), "META-INF/MANIFEST.MF");
war.addAsServiceProvider(SerializationContextInitializer.class.getName(), InfinispanCacheSerializationContextInitializer.class.getName() + "Impl");
war.addAsManifestResource(createPermissionsXmlAsset(
new MBeanPermission("-#-[-]", "queryNames"),
new MBeanPermission("org.infinispan.*[org.wildfly.clustering.infinispan:*,type=*]", "registerMBean"),
new ReflectPermission("suppressAccessChecks"),
new RuntimePermission("accessDeclaredMembers"),
new RuntimePermission("getClassLoader")
), "permissions.xml");
return war;
}
@Test
public void test(@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws URISyntaxException, IOException {
System.out.println(InfinispanCacheServlet.createURI(baseURL1, "foo", "bar"));
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
try (CloseableHttpResponse response = client.execute(new HttpPut(InfinispanCacheServlet.createURI(baseURL1, "foo", "bar")))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertFalse(response.containsHeader(InfinispanCacheServlet.RESULT));
}
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanCacheServlet.createURI(baseURL2, "foo")))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(InfinispanCacheServlet.RESULT));
Assert.assertEquals("bar", response.getFirstHeader(InfinispanCacheServlet.RESULT).getValue());
}
try (CloseableHttpResponse response = client.execute(new HttpDelete(InfinispanCacheServlet.createURI(baseURL1, "foo")))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(InfinispanCacheServlet.RESULT));
Assert.assertEquals("bar", response.getFirstHeader(InfinispanCacheServlet.RESULT).getValue());
}
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanCacheServlet.createURI(baseURL2, "foo")))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertFalse(response.containsHeader(InfinispanCacheServlet.RESULT));
}
}
}
}
| 6,105
| 54.009009
| 199
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/remote/RemoteInfinispanCacheTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.remote;
import static org.jboss.as.test.clustering.InfinispanServerUtil.infinispanServerTestRule;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.clustering.cluster.infinispan.AbstractCacheTestCase;
import org.jboss.as.test.clustering.cluster.infinispan.bean.remote.RemoteCacheBean;
import org.jboss.as.test.shared.ManagementServerSetupTask;
import org.jboss.shrinkwrap.api.Archive;
import org.junit.ClassRule;
import org.junit.rules.TestRule;
/**
* @author Paul Ferraro
*/
@ServerSetup(RemoteInfinispanCacheTestCase.InfinispanServerSetupTask.class)
public class RemoteInfinispanCacheTestCase extends AbstractCacheTestCase {
@ClassRule
public static final TestRule INFINISPAN_SERVER_RULE = infinispanServerTestRule();
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
return createDeployment(RemoteCacheBean.class, "org.infinispan.client.hotrod");
}
public static class InfinispanServerSetupTask extends ManagementServerSetupTask {
public InfinispanServerSetupTask() {
super(NODE_1_2, createContainerConfigurationBuilder()
.setupScript(createScriptBuilder()
.startBatch()
.add("/socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=infinispan-server:add(port=%d,host=%s)", INFINISPAN_SERVER_PORT, INFINISPAN_SERVER_ADDRESS)
.add("/subsystem=infinispan/remote-cache-container=remote:add(default-remote-cluster=infinispan-server-cluster, marshaller=PROTOSTREAM, properties={infinispan.client.hotrod.auth_username=%s, infinispan.client.hotrod.auth_password=%s})", INFINISPAN_APPLICATION_USER, INFINISPAN_APPLICATION_PASSWORD)
.add("/subsystem=infinispan/remote-cache-container=remote/remote-cluster=infinispan-server-cluster:add(socket-bindings=[infinispan-server])")
.endBatch()
.build())
.tearDownScript(createScriptBuilder()
.startBatch()
.add("/subsystem=infinispan/remote-cache-container=remote:remove")
.add("/socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=infinispan-server:remove")
.endBatch()
.build())
.build());
}
}
}
| 4,004
| 47.841463
| 326
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/embedded/ManagedInfinispanCacheTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.embedded;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.as.test.clustering.cluster.infinispan.AbstractCacheTestCase;
import org.jboss.as.test.clustering.cluster.infinispan.bean.embedded.ManagedCacheBean;
import org.jboss.shrinkwrap.api.Archive;
/**
* Validates marshallability of application specific cache entries.
* @author Paul Ferraro
*/
public class ManagedInfinispanCacheTestCase extends AbstractCacheTestCase {
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
return createDeployment(ManagedCacheBean.class, "org.infinispan");
}
}
| 2,111
| 38.849057
| 86
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/embedded/CreatedInfinispanCacheTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.embedded;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.as.test.clustering.cluster.infinispan.AbstractCacheTestCase;
import org.jboss.as.test.clustering.cluster.infinispan.bean.embedded.CreatedCacheBean;
import org.jboss.shrinkwrap.api.Archive;
/**
* @author Paul Ferraro
*/
public class CreatedInfinispanCacheTestCase extends AbstractCacheTestCase {
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
return createDeployment(CreatedCacheBean.class, "org.infinispan");
}
}
| 2,043
| 38.307692
| 86
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/lock/InfinispanLockTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.lock;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.UUID;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.clustering.cluster.infinispan.lock.deployment.InfinispanLockServlet;
import org.jboss.as.test.clustering.cluster.infinispan.lock.deployment.InfinispanLockServlet.LockOperation;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.as.test.shared.ManagementServerSetupTask;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test case to verify Infinispan lock module usage.
* The server setup configures a new cache container with org.infinispan.lock module and a default replicated cache.
* Test creates a lock on one node, then tests lock availability on the other node.
*
* @author Radoslav Husar
*/
@RunWith(Arquillian.class)
@ServerSetup(InfinispanLockTestCase.ServerSetupTask.class)
public class InfinispanLockTestCase extends AbstractClusteringTestCase {
private static final String MODULE_NAME = InfinispanLockTestCase.class.getSimpleName();
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
return ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war")
.addPackage(InfinispanLockServlet.class.getPackage())
.setManifest(new StringAsset("Manifest-Version: 1.0\nDependencies: org.infinispan, org.infinispan.commons, org.infinispan.lock\n"))
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
;
}
@Test
public void test(@ArquillianResource(InfinispanLockServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
@ArquillianResource(InfinispanLockServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
throws IOException, URISyntaxException {
String lockName = UUID.randomUUID().toString();
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanLockServlet.createURI(baseURL1, lockName, LockOperation.DEFINE)))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(Boolean.parseBoolean(EntityUtils.toString(response.getEntity())));
}
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanLockServlet.createURI(baseURL1, lockName, LockOperation.IS_LOCKED)))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertFalse(Boolean.parseBoolean(EntityUtils.toString(response.getEntity())));
}
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanLockServlet.createURI(baseURL1, lockName, LockOperation.LOCK)))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(Boolean.parseBoolean(EntityUtils.toString(response.getEntity())));
}
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanLockServlet.createURI(baseURL1, lockName, LockOperation.IS_LOCKED)))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(Boolean.parseBoolean(EntityUtils.toString(response.getEntity())));
}
// -> node2
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanLockServlet.createURI(baseURL2, lockName, LockOperation.IS_LOCKED)))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(Boolean.parseBoolean(EntityUtils.toString(response.getEntity())));
}
// -> node 1
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanLockServlet.createURI(baseURL1, lockName, LockOperation.UNLOCK)));) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
// unlock has no output – only check SC
}
// -> node 2
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanLockServlet.createURI(baseURL2, lockName, LockOperation.IS_LOCKED)));) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertFalse(Boolean.parseBoolean(EntityUtils.toString(response.getEntity())));
}
// -> node1
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanLockServlet.createURI(baseURL1, lockName, LockOperation.IS_LOCKED)));) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertFalse(Boolean.parseBoolean(EntityUtils.toString(response.getEntity())));
}
}
}
public static class ServerSetupTask extends ManagementServerSetupTask {
public ServerSetupTask() {
super(NODE_1_2, createContainerConfigurationBuilder()
.setupScript(createScriptBuilder()
.startBatch()
.add("/subsystem=infinispan/cache-container=lock:add(default-cache=repl, modules=[org.infinispan.lock])")
.add("/subsystem=infinispan/cache-container=lock/transport=jgroups:add")
.add("/subsystem=infinispan/cache-container=lock/replicated-cache=repl:add")
.endBatch()
.build())
.tearDownScript(createScriptBuilder()
.startBatch()
.add("/subsystem=infinispan/cache-container=lock:remove")
.endBatch()
.build())
.build());
}
}
}
| 8,437
| 49.22619
| 159
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/lock/deployment/InfinispanLockServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.lock.deployment;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.infinispan.lock.EmbeddedClusteredLockManagerFactory;
import org.infinispan.lock.api.ClusteredLock;
import org.infinispan.lock.api.ClusteredLockManager;
import org.infinispan.manager.EmbeddedCacheManager;
/**
* Clustered lock servlet exposing define/is locked/lock/unlock operations for a given named lock.
* Operates on cache manager called 'lock'.
*
* @author Radoslav Husar
*/
@WebServlet(urlPatterns = { InfinispanLockServlet.SERVLET_PATH })
public class InfinispanLockServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String SERVLET_NAME = "lock";
static final String SERVLET_PATH = "/" + SERVLET_NAME;
public static final long LOCK_TIMEOUT_MS = 5_000;
public static final String LOCK_NAME_PARAMETER = "lock-name";
public static final String OPERATION_PARAMETER = "operation";
public enum LockOperation {
DEFINE, IS_LOCKED, LOCK, UNLOCK
}
@Resource(lookup = "java:jboss/infinispan/container/lock")
private EmbeddedCacheManager cm;
private ClusteredLockManager clm;
public static URI createURI(URL baseURL, String lockName, LockOperation operation) throws URISyntaxException {
return baseURL.toURI().resolve(buildQuery(lockName).append('&').append(OPERATION_PARAMETER).append('=').append(operation.name()).toString());
}
private static StringBuilder buildQuery(String lockName) {
return new StringBuilder(SERVLET_NAME).append('?').append(LOCK_NAME_PARAMETER).append('=').append(lockName);
}
@Override
public void init() throws ServletException {
clm = EmbeddedClusteredLockManagerFactory.from(cm);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String lockName = getRequiredParameter(request, LOCK_NAME_PARAMETER);
String operationName = getRequiredParameter(request, OPERATION_PARAMETER);
LockOperation operation = LockOperation.valueOf(operationName);
try {
switch (operation) {
case DEFINE: {
boolean defined = clm.defineLock(lockName);
response.getWriter().print(defined);
break;
}
case IS_LOCKED: {
ClusteredLock lock = clm.get(lockName);
CompletableFuture<Boolean> cf = lock.isLocked();
Boolean locked = cf.get();
response.getWriter().print(locked);
break;
}
case LOCK: {
ClusteredLock lock = clm.get(lockName);
CompletableFuture<Boolean> cf = lock.tryLock(LOCK_TIMEOUT_MS, TimeUnit.MILLISECONDS);
Boolean acquired = cf.get();
response.getWriter().print(acquired);
break;
}
case UNLOCK: {
ClusteredLock lock = clm.get(lockName);
CompletableFuture<Void> cf = lock.unlock();
cf.get();
break;
}
}
} catch (InterruptedException | ExecutionException ex) {
throw new ServletException(ex);
}
}
private static String getRequiredParameter(HttpServletRequest request, String name) throws ServletException {
String value = request.getParameter(name);
if (value == null) {
throw new ServletException(String.format("No %s specified", name));
}
return value;
}
}
| 5,239
| 39
| 149
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/servlet/InfinispanCacheServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.servlet;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import jakarta.ejb.EJB;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jboss.as.test.clustering.cluster.infinispan.bean.Cache;
/**
* @author Paul Ferraro
*/
@WebServlet(urlPatterns = { InfinispanCacheServlet.SERVLET_PATH })
public class InfinispanCacheServlet extends HttpServlet {
private static final long serialVersionUID = 8191787312871139014L;
private static final String SERVLET_NAME = "cache";
static final String SERVLET_PATH = "/" + SERVLET_NAME;
private static final String KEY = "key";
private static final String VALUE = "value";
public static final String RESULT = "result";
public static URI createURI(URL baseURL, String key) throws URISyntaxException {
return baseURL.toURI().resolve(SERVLET_NAME + '?' + KEY + '=' + key);
}
public static URI createURI(URL baseURL, String key, String value) throws URISyntaxException {
return baseURL.toURI().resolve(SERVLET_NAME + '?' + KEY + '=' + key + '&' + VALUE + '=' + value);
}
@EJB
private Cache bean;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String key = requireParameter(request, KEY);
String result = this.bean.get(key);
if (result != null) {
response.setHeader(RESULT, result);
}
}
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String key = requireParameter(request, KEY);
String value = requireParameter(request, VALUE);
String result = this.bean.put(key, value);
if (result != null) {
response.setHeader(RESULT, result);
}
}
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String key = requireParameter(request, KEY);
String result = this.bean.remove(key);
if (result != null) {
response.setHeader(RESULT, result);
}
}
private static String requireParameter(HttpServletRequest request, String name) throws ServletException {
String result = request.getParameter(name);
if (result == null) {
throw new ServletException("Missing parameter " + name);
}
return result;
}
}
| 3,776
| 37.151515
| 124
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/bean/Value.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.bean;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
/**
* @author Paul Ferraro
*/
public class Value {
private final String value;
@ProtoFactory
public Value(String value) {
this.value = value;
}
@ProtoField(number = 1)
public String getValue() {
return this.value;
}
@Override
public String toString() {
return this.value;
}
}
| 1,552
| 30.06
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/bean/InfinispanCacheSerializationContextInitializer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.bean;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
/**
* @author Paul Ferraro
*/
@AutoProtoSchemaBuilder(includeClasses = { Key.class, Value.class }, service = false)
public interface InfinispanCacheSerializationContextInitializer extends SerializationContextInitializer {
}
| 1,452
| 40.514286
| 105
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/bean/Cache.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.bean;
/**
* @author Paul Ferraro
*/
public interface Cache {
String get(String key);
String put(String key, String value);
String remove(String key);
}
| 1,247
| 36.818182
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/bean/Key.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.bean;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
/**
* @author Paul Ferraro
*/
public class Key {
private final String key;
@ProtoFactory
public Key(String key) {
this.key = key;
}
@ProtoField(number = 1)
public String getKey() {
return this.key;
}
@Override
public int hashCode() {
return this.key.hashCode();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Key)) return false;
return this.key.equals(object.toString());
}
@Override
public String toString() {
return this.key;
}
}
| 1,786
| 28.295082
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/bean/CacheBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.bean;
import java.util.function.Supplier;
import org.infinispan.commons.api.BasicCache;
/**
* @author Paul Ferraro
*/
public abstract class CacheBean implements Cache, Supplier<BasicCache<Key, Value>> {
@Override
public String get(String key) {
Value value = this.get().get(new Key(key));
return (value != null) ? value.getValue() : null;
}
@Override
public String put(String key, String value) {
Value old = this.get().put(new Key(key), new Value(value));
return (old != null) ? old.getValue() : null;
}
@Override
public String remove(String key) {
Value old = this.get().remove(new Key(key));
return (old != null) ? old.getValue() : null;
}
}
| 1,817
| 33.961538
| 84
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/bean/remote/RemoteCacheBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.bean.remote;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import jakarta.ejb.Local;
import jakarta.ejb.Singleton;
import jakarta.ejb.Startup;
import org.infinispan.client.hotrod.DefaultTemplate;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheContainer;
import org.infinispan.commons.api.BasicCache;
import org.jboss.as.test.clustering.cluster.infinispan.bean.Cache;
import org.jboss.as.test.clustering.cluster.infinispan.bean.CacheBean;
import org.jboss.as.test.clustering.cluster.infinispan.bean.Key;
import org.jboss.as.test.clustering.cluster.infinispan.bean.Value;
/**
* @author Paul Ferraro
*/
@Local(Cache.class)
@Singleton
@Startup
public class RemoteCacheBean extends CacheBean {
private static final String CACHE_NAME = RemoteCacheBean.class.getName();
@Resource(lookup = "java:jboss/infinispan/remote-container/remote")
private RemoteCacheContainer container;
private RemoteCache<Key, Value> cache;
@PostConstruct
public void init() {
this.container.getConfiguration().addRemoteCache(CACHE_NAME, builder -> builder.templateName(DefaultTemplate.LOCAL).forceReturnValues(true));
this.cache = this.container.getCache(CACHE_NAME);
this.cache.start();
}
@PreDestroy
public void destroy() {
this.cache.stop();
this.container.getConfiguration().removeRemoteCache(CACHE_NAME);
}
@Override
public BasicCache<Key, Value> get() {
return this.cache;
}
}
| 2,661
| 35.465753
| 149
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/bean/embedded/CreatedCacheBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.bean.embedded;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import jakarta.ejb.Local;
import jakarta.ejb.Singleton;
import jakarta.ejb.Startup;
import org.infinispan.commons.api.BasicCache;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.manager.EmbeddedCacheManager;
import org.jboss.as.test.clustering.cluster.infinispan.bean.Cache;
import org.jboss.as.test.clustering.cluster.infinispan.bean.CacheBean;
import org.jboss.as.test.clustering.cluster.infinispan.bean.Key;
import org.jboss.as.test.clustering.cluster.infinispan.bean.Value;
/**
* @author Paul Ferraro
*/
@Local(Cache.class)
@Singleton
@Startup
public class CreatedCacheBean extends CacheBean {
@Resource(lookup = "java:jboss/infinispan/container/server")
private EmbeddedCacheManager container;
@Resource(lookup = "java:jboss/infinispan/configuration/server/default")
private Configuration config;
private org.infinispan.Cache<Key, Value> cache;
@PostConstruct
public void init() {
this.cache = this.container.administration().createCache(this.getClass().getSimpleName(), this.config);
this.cache.start();
}
@PreDestroy
public void destroy() {
this.cache.stop();
this.container.administration().removeCache(this.getClass().getSimpleName());
}
@Override
public BasicCache<Key, Value> get() {
return this.cache;
}
}
| 2,565
| 34.638889
| 111
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/bean/embedded/ManagedCacheBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.bean.embedded;
import jakarta.annotation.Resource;
import jakarta.ejb.Local;
import jakarta.ejb.Singleton;
import jakarta.ejb.Startup;
import org.infinispan.commons.api.BasicCache;
import org.jboss.as.test.clustering.cluster.infinispan.bean.Cache;
import org.jboss.as.test.clustering.cluster.infinispan.bean.CacheBean;
import org.jboss.as.test.clustering.cluster.infinispan.bean.Key;
import org.jboss.as.test.clustering.cluster.infinispan.bean.Value;
/**
* @author Paul Ferraro
*/
@Local(Cache.class)
@Singleton
@Startup
public class ManagedCacheBean extends CacheBean {
@Resource(lookup = "java:jboss/infinispan/cache/server/default")
private org.infinispan.Cache<Key, Value> cache;
@Override
public BasicCache<Key, Value> get() {
return this.cache;
}
}
| 1,870
| 34.980769
| 70
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/counter/InfinispanCounterTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.counter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.UUID;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.infinispan.counter.api.Storage;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.clustering.cluster.infinispan.counter.deployment.InfinispanCounterServlet;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.as.test.shared.ManagementServerSetupTask;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test case to verify Infinispan counter module usage.
* Verifies both VOLATILE and PERSISTENT timers.
* The server setup configures a new cache container with org.infinispan.counter module and a default replicated cache.
* Test creates a counter on one node, then tests counter availability on the other node.
*
* @author Radoslav Husar
*/
@RunWith(Arquillian.class)
@ServerSetup(InfinispanCounterTestCase.ServerSetupTask.class)
public class InfinispanCounterTestCase extends AbstractClusteringTestCase {
private static final String MODULE_NAME = InfinispanCounterTestCase.class.getSimpleName();
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
return ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war")
.addPackage(InfinispanCounterServlet.class.getPackage())
.setManifest(new StringAsset("Manifest-Version: 1.0\nDependencies: org.infinispan, org.infinispan.commons, org.infinispan.counter\n"))
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
;
}
@Test
public void testVolatileCounters(@ArquillianResource(InfinispanCounterServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
@ArquillianResource(InfinispanCounterServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
throws IOException, URISyntaxException {
this.test(Storage.VOLATILE, baseURL1, baseURL2);
}
@Test
public void testPersistentCounters(@ArquillianResource(InfinispanCounterServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
@ArquillianResource(InfinispanCounterServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
throws IOException, URISyntaxException {
this.test(Storage.PERSISTENT, baseURL1, baseURL2);
}
public void test(Storage storage, URL baseURL1, URL baseURL2) throws IOException, URISyntaxException {
String counterName = storage.name() + UUID.randomUUID();
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanCounterServlet.createURI(baseURL1, counterName, storage.name())))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(1, Integer.parseInt(EntityUtils.toString(response.getEntity())));
}
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanCounterServlet.createURI(baseURL1, counterName)))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(2, Integer.parseInt(EntityUtils.toString(response.getEntity())));
}
// -> node2
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanCounterServlet.createURI(baseURL2, counterName)))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(3, Integer.parseInt(EntityUtils.toString(response.getEntity())));
}
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanCounterServlet.createURI(baseURL2, counterName)))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(4, Integer.parseInt(EntityUtils.toString(response.getEntity())));
}
// -> node1
try (CloseableHttpResponse response = client.execute(new HttpGet(InfinispanCounterServlet.createURI(baseURL1, counterName)))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals(5, Integer.parseInt(EntityUtils.toString(response.getEntity())));
}
}
}
public static class ServerSetupTask extends ManagementServerSetupTask {
public ServerSetupTask() {
super(NODE_1_2, createContainerConfigurationBuilder()
.setupScript(createScriptBuilder()
.startBatch()
.add("/subsystem=infinispan/cache-container=counter:add(default-cache=repl, modules=[org.infinispan.counter])")
.add("/subsystem=infinispan/cache-container=counter/transport=jgroups:add")
.add("/subsystem=infinispan/cache-container=counter/replicated-cache=repl:add")
.endBatch()
.build())
.tearDownScript(createScriptBuilder()
.startBatch()
.add("/subsystem=infinispan/cache-container=counter:remove")
.endBatch()
.build())
.build());
}
}
}
| 7,879
| 48.25
| 155
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/infinispan/counter/deployment/InfinispanCounterServlet.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.infinispan.counter.deployment;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.infinispan.counter.EmbeddedCounterManagerFactory;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterManager;
import org.infinispan.counter.api.CounterType;
import org.infinispan.counter.api.Storage;
import org.infinispan.counter.api.StrongCounter;
import org.infinispan.manager.EmbeddedCacheManager;
import org.jboss.logging.Logger;
/**
* @author Radoslav Husar
*/
@WebServlet(urlPatterns = { InfinispanCounterServlet.SERVLET_PATH })
public class InfinispanCounterServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(InfinispanCounterServlet.class);
private static final long serialVersionUID = 1L;
private static final String SERVLET_NAME = "counter";
static final String SERVLET_PATH = "/" + SERVLET_NAME;
public static final String COUNTER_NAME_PARAMETER = "counter-name";
public static final String STORAGE_PARAMETER = "define";
@Resource(lookup = "java:jboss/infinispan/container/counter")
private EmbeddedCacheManager ecm;
private CounterManager cm;
public static URI createURI(URL baseURL, String counterName) throws URISyntaxException {
return baseURL.toURI().resolve(buildQuery(counterName).toString());
}
public static URI createURI(URL baseURL, String counterName, String storage) throws URISyntaxException {
return baseURL.toURI().resolve(buildQuery(counterName).append('&').append(STORAGE_PARAMETER).append('=').append(storage).toString());
}
private static StringBuilder buildQuery(String counterName) {
return new StringBuilder(SERVLET_NAME).append('?').append(COUNTER_NAME_PARAMETER).append('=').append(counterName);
}
@Override
public void init() throws ServletException {
cm = EmbeddedCounterManagerFactory.asCounterManager(ecm);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String counterName = getRequiredParameter(request, COUNTER_NAME_PARAMETER);
String storage = request.getParameter(STORAGE_PARAMETER);
if (storage != null) {
CounterConfiguration cc = CounterConfiguration.builder(CounterType.UNBOUNDED_STRONG)
.storage(Storage.valueOf(storage))
.build();
cm.defineCounter(counterName, cc);
}
StrongCounter strongCounter = cm.getStrongCounter(counterName);
CompletableFuture<Long> longCompletableFuture = strongCounter.addAndGet(1);
try {
Long count = longCompletableFuture.get();
log.infof("Counter %s returned %s", counterName, count);
response.getWriter().print(count);
} catch (InterruptedException | ExecutionException e) {
throw new ServletException(e);
}
}
private static String getRequiredParameter(HttpServletRequest request, String name) throws ServletException {
String value = request.getParameter(name);
if (value == null) {
throw new ServletException(String.format("No %s specified", name));
}
return value;
}
}
| 4,754
| 39.991379
| 141
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/SingletonServiceTestCase.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.clustering.cluster.singleton;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.clustering.cluster.singleton.service.NodeServiceActivator;
import org.jboss.as.test.clustering.cluster.singleton.service.NodeServiceServlet;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class SingletonServiceTestCase extends AbstractClusteringTestCase {
private static final String MODULE_NAME = SingletonServiceTestCase.class.getSimpleName();
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war");
war.addPackage(NodeServiceServlet.class.getPackage());
war.addAsServiceProvider(org.jboss.msc.service.ServiceActivator.class, NodeServiceActivator.class);
war.setManifest(new StringAsset("Manifest-Version: 1.0\nDependencies: org.jboss.as.clustering.common\n"));
return war;
}
@Test
public void testSingletonService(
@ArquillianResource(NodeServiceServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
@ArquillianResource(NodeServiceServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
throws IOException, URISyntaxException {
// Needed to be able to inject ArquillianResource
stop(NODE_2);
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
HttpResponse response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL1, NodeServiceActivator.DEFAULT_SERVICE_NAME, NODE_1)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_1, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL1, NodeServiceActivator.QUORUM_SERVICE_NAME)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertFalse(response.containsHeader(NodeServiceServlet.NODE_HEADER));
} finally {
HttpClientUtils.closeQuietly(response);
}
start(NODE_2);
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL1, NodeServiceActivator.DEFAULT_SERVICE_NAME, NODE_1)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_2, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL1, NodeServiceActivator.QUORUM_SERVICE_NAME, NODE_2)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_2, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL2, NodeServiceActivator.DEFAULT_SERVICE_NAME, NODE_2)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_2, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL2, NodeServiceActivator.QUORUM_SERVICE_NAME, NODE_2)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_2, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
stop(NODE_2);
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL1, NodeServiceActivator.DEFAULT_SERVICE_NAME, NODE_1)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_1, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL1, NodeServiceActivator.QUORUM_SERVICE_NAME)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertFalse(response.containsHeader(NodeServiceServlet.NODE_HEADER));
} finally {
HttpClientUtils.closeQuietly(response);
}
start(NODE_2);
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL1, NodeServiceActivator.DEFAULT_SERVICE_NAME, NODE_2)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_2, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL1, NodeServiceActivator.QUORUM_SERVICE_NAME, NODE_2)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_2, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL2, NodeServiceActivator.DEFAULT_SERVICE_NAME, NODE_2)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_2, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL2, NodeServiceActivator.QUORUM_SERVICE_NAME, NODE_2)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_2, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
stop(NODE_1);
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL2, NodeServiceActivator.DEFAULT_SERVICE_NAME, NODE_2)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_2, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL2, NodeServiceActivator.QUORUM_SERVICE_NAME)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertFalse(response.containsHeader(NodeServiceServlet.NODE_HEADER));
} finally {
HttpClientUtils.closeQuietly(response);
}
start(NODE_1);
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL1, NodeServiceActivator.DEFAULT_SERVICE_NAME, NODE_2)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_2, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL1, NodeServiceActivator.QUORUM_SERVICE_NAME, NODE_2)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_2, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL2, NodeServiceActivator.DEFAULT_SERVICE_NAME, NODE_2)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_2, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(NodeServiceServlet.createURI(baseURL2, NodeServiceActivator.QUORUM_SERVICE_NAME, NODE_2)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
Assert.assertEquals(NODE_2, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
}
}
}
| 13,786
| 52.645914
| 155
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/SingletonPartitionTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.singleton;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.clustering.ClusterHttpClientUtil;
import org.jboss.as.test.clustering.ClusterTestUtil;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.clustering.cluster.singleton.partition.PartitionServlet;
import org.jboss.as.test.clustering.cluster.singleton.partition.SingletonServiceActivator;
import org.jboss.as.test.clustering.cluster.singleton.service.NodeServiceExecutorRegistry;
import org.jboss.as.test.clustering.cluster.singleton.service.NodeServiceServlet;
import org.jboss.as.test.clustering.cluster.singleton.service.SingletonElectionListenerService;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.msc.service.ServiceActivator;
import org.jboss.msc.service.ServiceName;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test case for BZ-1190029 and https://issues.jboss.org/browse/WFLY-4748.
* <p/>
* This test creates a cluster of two nodes running two singleton services. Communication between the clusters is then
* disabled (by inserting DISCARD protocol) so the cluster splits, and then enabled again so the two partitions merge.
* After the merge, each service is supposed to have only one provider.
*
* @author Tomas Hofman
* @author Radoslav Husar
*/
@RunWith(Arquillian.class)
public class SingletonPartitionTestCase extends AbstractClusteringTestCase {
// maximum time in ms to wait for cluster topology change in case the injected merge event fails for some reason
private static final long TOPOLOGY_CHANGE_TIMEOUT = TimeoutUtil.adjust(150_000);
// it takes a little extra time after merge for the singleton service to migrate
private static final int SERVICE_TIMEOUT = TimeoutUtil.adjust(5_000);
private static final String CONTAINER = "server";
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, SingletonPartitionTestCase.class.getSimpleName() + ".war");
war.addPackage(SingletonServiceActivator.class.getPackage());
war.addClasses(NodeServiceServlet.class, SingletonElectionListenerService.class, NodeServiceExecutorRegistry.class);
war.addAsServiceProvider(ServiceActivator.class, SingletonServiceActivator.class);
ClusterTestUtil.addTopologyListenerDependencies(war);
war.setManifest(new StringAsset("Manifest-Version: 1.0\nDependencies: org.jboss.as.clustering.common, org.jgroups, org.infinispan\n"));
return war;
}
@Test
public void testSingletonService(
@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws Exception {
// URLs look like "http://IP:PORT/singleton/service"
URI serviceANode1Uri = NodeServiceServlet.createURI(baseURL1, SingletonServiceActivator.SERVICE_A_NAME);
URI serviceANode2Uri = NodeServiceServlet.createURI(baseURL2, SingletonServiceActivator.SERVICE_A_NAME);
URI serviceBNode1Uri = NodeServiceServlet.createURI(baseURL1, SingletonServiceActivator.SERVICE_B_NAME);
URI serviceBNode2Uri = NodeServiceServlet.createURI(baseURL2, SingletonServiceActivator.SERVICE_B_NAME);
log.trace("URLs are:\n" + serviceANode1Uri
+ "\n" + serviceANode2Uri
+ "\n" + serviceBNode1Uri
+ "\n" + serviceBNode2Uri);
// 1. Begin with no partitions, both services should have a single provider
waitForView(baseURL1, NODE_1, NODE_2);
waitForView(baseURL2, NODE_1, NODE_2);
Thread.sleep(SERVICE_TIMEOUT);
// check service A
checkSingletonNode(baseURL1, SingletonServiceActivator.SERVICE_A_NAME, SingletonServiceActivator.SERVICE_A_PREFERRED_NODE);
checkSingletonNode(baseURL2, SingletonServiceActivator.SERVICE_A_NAME, SingletonServiceActivator.SERVICE_A_PREFERRED_NODE);
// check service B
checkSingletonNode(baseURL1, SingletonServiceActivator.SERVICE_B_NAME, SingletonServiceActivator.SERVICE_B_PREFERRED_NODE);
checkSingletonNode(baseURL2, SingletonServiceActivator.SERVICE_B_NAME, SingletonServiceActivator.SERVICE_B_PREFERRED_NODE);
// 2. Simulate network partition; each having it's own provider
partition(true, baseURL1, baseURL2);
waitForView(baseURL1, NODE_1);
waitForView(baseURL2, NODE_2);
Thread.sleep(SERVICE_TIMEOUT);
// check service A
checkSingletonNode(baseURL1, SingletonServiceActivator.SERVICE_A_NAME, NODE_1);
checkSingletonNode(baseURL2, SingletonServiceActivator.SERVICE_A_NAME, NODE_2);
// check service B
checkSingletonNode(baseURL1, SingletonServiceActivator.SERVICE_B_NAME, NODE_1);
checkSingletonNode(baseURL2, SingletonServiceActivator.SERVICE_B_NAME, NODE_2);
// 3. Stop partitioning, merge, each service is supposed to have a single provider again.
partition(false, baseURL1, baseURL2);
waitForView(baseURL1, NODE_1, NODE_2);
waitForView(baseURL2, NODE_1, NODE_2);
Thread.sleep(SERVICE_TIMEOUT);
// check service A
checkSingletonNode(baseURL1, SingletonServiceActivator.SERVICE_A_NAME, SingletonServiceActivator.SERVICE_A_PREFERRED_NODE);
checkSingletonNode(baseURL2, SingletonServiceActivator.SERVICE_A_NAME, SingletonServiceActivator.SERVICE_A_PREFERRED_NODE);
// check service B
checkSingletonNode(baseURL1, SingletonServiceActivator.SERVICE_B_NAME, SingletonServiceActivator.SERVICE_B_PREFERRED_NODE);
checkSingletonNode(baseURL2, SingletonServiceActivator.SERVICE_B_NAME, SingletonServiceActivator.SERVICE_B_PREFERRED_NODE);
// 4. Simulate network partition again, each node should start the service again. This verifies WFLY-4748.
partition(true, baseURL1, baseURL2);
waitForView(baseURL1, NODE_1);
waitForView(baseURL2, NODE_2);
Thread.sleep(SERVICE_TIMEOUT);
// check service A
checkSingletonNode(baseURL1, SingletonServiceActivator.SERVICE_A_NAME, NODE_1);
checkSingletonNode(baseURL2, SingletonServiceActivator.SERVICE_A_NAME, NODE_2);
// check service B
checkSingletonNode(baseURL1, SingletonServiceActivator.SERVICE_B_NAME, NODE_1);
checkSingletonNode(baseURL2, SingletonServiceActivator.SERVICE_B_NAME, NODE_2);
}
@Override
public void afterTestMethod() throws Exception {
super.afterTestMethod();
// Stop the container to ensure there aren't any remnants since the test operates on a live JGroups channels
stop(TWO_NODES);
}
private static void checkSingletonNode(URL baseURL, ServiceName serviceName, String expectedProviderNode) throws IOException, URISyntaxException {
URI uri = (expectedProviderNode != null) ? NodeServiceServlet.createURI(baseURL, serviceName, expectedProviderNode) : NodeServiceServlet.createURI(baseURL, serviceName);
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
HttpResponse response = client.execute(new HttpGet(uri));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Header header = response.getFirstHeader("node");
if (header != null) {
Assert.assertEquals("Expected different provider node", expectedProviderNode, header.getValue());
} else {
Assert.assertNull("Unexpected provider node", expectedProviderNode);
}
} finally {
HttpClientUtils.closeQuietly(response);
}
}
}
private static void waitForView(URL baseURL, String... members) throws IOException, URISyntaxException {
ClusterHttpClientUtil.establishTopology(baseURL, CONTAINER, "default", TOPOLOGY_CHANGE_TIMEOUT, members);
}
private static void partition(boolean partition, URL... baseURIs) {
Arrays.stream(baseURIs).parallel().forEach(baseURI -> {
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
HttpResponse response = client.execute(new HttpGet(PartitionServlet.createURI(baseURI, partition)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
} finally {
HttpClientUtils.closeQuietly(response);
}
} catch (Exception ignored) {
}
});
}
}
| 11,077
| 48.455357
| 177
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/SingletonBackupServiceTestCase.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.clustering.cluster.singleton;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.server.security.ServerPermission;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.clustering.cluster.singleton.service.ValueServiceActivator;
import org.jboss.as.test.clustering.cluster.singleton.service.ValueServiceServlet;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class SingletonBackupServiceTestCase extends AbstractClusteringTestCase {
private static final String MODULE_NAME = SingletonBackupServiceTestCase.class.getSimpleName();
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war");
war.addPackage(ValueServiceServlet.class.getPackage());
war.setManifest(new StringAsset("Manifest-Version: 1.0\nDependencies: org.jboss.as.server\n"));
war.addAsServiceProvider(org.jboss.msc.service.ServiceActivator.class, ValueServiceActivator.class);
war.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new ServerPermission("useServiceRegistry"), new ServerPermission("getCurrentServiceContainer")), "permissions.xml");
return war;
}
@Test
public void testSingletonService(
@ArquillianResource(ValueServiceServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
@ArquillianResource(ValueServiceServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
throws IOException, URISyntaxException {
// Needed to be able to inject ArquillianResource
stop(NODE_2);
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
HttpResponse response = client.execute(new HttpGet(ValueServiceServlet.createURI(baseURL1, ValueServiceActivator.SERVICE_NAME)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("true", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
start(NODE_2);
response = client.execute(new HttpGet(ValueServiceServlet.createURI(baseURL1, ValueServiceActivator.SERVICE_NAME)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("true", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(ValueServiceServlet.createURI(baseURL2, ValueServiceActivator.SERVICE_NAME)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("false", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
stop(NODE_2);
response = client.execute(new HttpGet(ValueServiceServlet.createURI(baseURL1, ValueServiceActivator.SERVICE_NAME)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("true", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
start(NODE_2);
response = client.execute(new HttpGet(ValueServiceServlet.createURI(baseURL1, ValueServiceActivator.SERVICE_NAME)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("true", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(ValueServiceServlet.createURI(baseURL2, ValueServiceActivator.SERVICE_NAME)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("false", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
stop(NODE_1);
response = client.execute(new HttpGet(ValueServiceServlet.createURI(baseURL2, ValueServiceActivator.SERVICE_NAME)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("true", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
start(NODE_1);
response = client.execute(new HttpGet(ValueServiceServlet.createURI(baseURL1, ValueServiceActivator.SERVICE_NAME)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("false", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
response = client.execute(new HttpGet(ValueServiceServlet.createURI(baseURL2, ValueServiceActivator.SERVICE_NAME)));
try {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("true", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
} finally {
HttpClientUtils.closeQuietly(response);
}
}
}
}
| 8,465
| 47.936416
| 192
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/SingletonDeploymentTestCase.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.clustering.cluster.singleton;
import static org.jboss.as.test.clustering.ClusterTestUtil.execute;
import java.net.URI;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.clustering.cluster.singleton.servlet.TraceServlet;
import org.jboss.as.test.http.util.TestHttpClientUtils;
import org.jboss.as.test.shared.ManagementServerSetupTask;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Paul Ferraro
*/
@RunWith(Arquillian.class)
@ServerSetup(SingletonDeploymentTestCase.ServerSetupTask.class)
public abstract class SingletonDeploymentTestCase extends AbstractClusteringTestCase {
static final String SINGLETON_DEPLOYMENT_1 = "singleton-deployment-1";
static final String SINGLETON_DEPLOYMENT_2 = "singleton-deployment-2";
private static final String MODULE_NAME = SingletonDeploymentTestCase.class.getSimpleName();
private static final String DEPLOYMENT_NAME = MODULE_NAME + ".war";
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deploymentHelper1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deploymentHelper2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_NAME);
war.addPackage(TraceServlet.class.getPackage());
return war;
}
public static final int DELAY = TimeoutUtil.adjust(5000);
private final String moduleName;
private final String deploymentName;
SingletonDeploymentTestCase(String moduleName, String deploymentName) {
this.moduleName = moduleName;
this.deploymentName = deploymentName;
}
@Test
public void test(
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) ManagementClient client1,
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) ManagementClient client2,
@ArquillianResource(TraceServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
@ArquillianResource(TraceServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
throws Exception {
this.deploy(SINGLETON_DEPLOYMENT_1);
Thread.sleep(DELAY);
this.deploy(SINGLETON_DEPLOYMENT_2);
Thread.sleep(DELAY);
String primaryProviderRequest = String.format("/subsystem=singleton/singleton-policy=default/deployment=%s:read-attribute(name=primary-provider)", this.deploymentName);
String isPrimaryRequest = String.format("/subsystem=singleton/singleton-policy=default/deployment=%s:read-attribute(name=is-primary)", this.deploymentName);
String getProvidersRequest = String.format("/subsystem=singleton/singleton-policy=default/deployment=%s:read-attribute(name=providers)", this.deploymentName);
Assert.assertEquals(NODE_1, execute(client1, primaryProviderRequest).asStringOrNull());
Assert.assertTrue(execute(client1, isPrimaryRequest).asBoolean(false));
Assert.assertEquals(List.of(NODE_1, NODE_2), execute(client1, getProvidersRequest).asList().stream().map(ModelNode::asString).sorted().collect(Collectors.toList()));
Assert.assertEquals(NODE_1, execute(client2, primaryProviderRequest).asStringOrNull());
Assert.assertFalse(execute(client2, isPrimaryRequest).asBoolean(true));
Assert.assertEquals(List.of(NODE_1, NODE_2), execute(client2, getProvidersRequest).asList().stream().map(ModelNode::asString).sorted().collect(Collectors.toList()));
URI uri1 = TraceServlet.createURI(new URL(baseURL1.getProtocol(), baseURL1.getHost(), baseURL1.getPort(), "/" + this.moduleName + "/"));
URI uri2 = TraceServlet.createURI(new URL(baseURL2.getProtocol(), baseURL2.getHost(), baseURL2.getPort(), "/" + this.moduleName + "/"));
try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
try (CloseableHttpResponse response = client.execute(new HttpGet(uri1))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
}
try (CloseableHttpResponse response = client.execute(new HttpGet(uri2))) {
Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
}
this.undeploy(SINGLETON_DEPLOYMENT_1);
Thread.sleep(DELAY);
Assert.assertEquals(NODE_2, execute(client2, primaryProviderRequest).asStringOrNull());
Assert.assertTrue(execute(client2, isPrimaryRequest).asBoolean(false));
Assert.assertEquals(Collections.singletonList(NODE_2), execute(client2, getProvidersRequest).asList().stream().map(ModelNode::asString).collect(Collectors.toList()));
try (CloseableHttpResponse response = client.execute(new HttpGet(uri1))) {
Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
}
try (CloseableHttpResponse response = client.execute(new HttpGet(uri2))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
}
this.deploy(SINGLETON_DEPLOYMENT_1);
Thread.sleep(DELAY);
Assert.assertEquals(NODE_1, execute(client1, primaryProviderRequest).asStringOrNull());
Assert.assertTrue(execute(client1, isPrimaryRequest).asBoolean(false));
Assert.assertEquals(List.of(NODE_1, NODE_2), execute(client1, getProvidersRequest).asList().stream().map(ModelNode::asString).sorted().collect(Collectors.toList()));
Assert.assertEquals(NODE_1, execute(client2, primaryProviderRequest).asStringOrNull());
Assert.assertFalse(execute(client2, isPrimaryRequest).asBoolean(true));
Assert.assertEquals(List.of(NODE_1, NODE_2), execute(client2, getProvidersRequest).asList().stream().map(ModelNode::asString).sorted().collect(Collectors.toList()));
try (CloseableHttpResponse response = client.execute(new HttpGet(uri1))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
}
try (CloseableHttpResponse response = client.execute(new HttpGet(uri2))) {
Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
}
this.undeploy(SINGLETON_DEPLOYMENT_2);
Thread.sleep(DELAY);
Assert.assertEquals(NODE_1, execute(client1, primaryProviderRequest).asStringOrNull());
Assert.assertTrue(execute(client1, isPrimaryRequest).asBoolean(false));
Assert.assertEquals(Collections.singletonList(NODE_1), execute(client1, getProvidersRequest).asList().stream().map(ModelNode::asString).collect(Collectors.toList()));
try (CloseableHttpResponse response = client.execute(new HttpGet(uri1))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
}
try (CloseableHttpResponse response = client.execute(new HttpGet(uri2))) {
Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
}
this.deploy(SINGLETON_DEPLOYMENT_2);
Thread.sleep(DELAY);
Assert.assertEquals(NODE_1, execute(client1, primaryProviderRequest).asStringOrNull());
Assert.assertTrue(execute(client1, isPrimaryRequest).asBoolean(false));
Assert.assertEquals(List.of(NODE_1, NODE_2), execute(client1, getProvidersRequest).asList().stream().map(ModelNode::asString).sorted().collect(Collectors.toList()));
Assert.assertEquals(NODE_1, execute(client2, primaryProviderRequest).asStringOrNull());
Assert.assertFalse(execute(client2, isPrimaryRequest).asBoolean(true));
Assert.assertEquals(List.of(NODE_1, NODE_2), execute(client2, getProvidersRequest).asList().stream().map(ModelNode::asString).sorted().collect(Collectors.toList()));
try (CloseableHttpResponse response = client.execute(new HttpGet(uri1))) {
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
}
try (CloseableHttpResponse response = client.execute(new HttpGet(uri2))) {
Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
}
} finally {
this.undeploy(SINGLETON_DEPLOYMENT_1);
Thread.sleep(DELAY);
this.undeploy(SINGLETON_DEPLOYMENT_2);
Thread.sleep(DELAY);
}
}
public static class ServerSetupTask extends ManagementServerSetupTask {
ServerSetupTask() {
super(NODE_1_2, createContainerConfigurationBuilder()
.setupScript(createScriptBuilder()
.add("/subsystem=singleton/singleton-policy=default/election-policy=simple:write-attribute(name=name-preferences,value=%s)", List.of(NODE_1, NODE_2))
.build())
.tearDownScript(createScriptBuilder()
.add("/subsystem=singleton/singleton-policy=default/election-policy=simple:undefine-attribute(name=name-preferences)")
.build())
.build());
}
}
}
| 11,651
| 50.786667
| 178
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/SingletonPolicyServiceTestCase.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.clustering.cluster.singleton;
import static org.jboss.as.test.clustering.ClusterTestUtil.execute;
import java.util.Arrays;
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.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase;
import org.jboss.as.test.clustering.cluster.singleton.service.NodeServicePolicyActivator;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceActivator;
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;
@RunWith(Arquillian.class)
public class SingletonPolicyServiceTestCase extends AbstractClusteringTestCase {
private static final String MODULE_NAME = SingletonPolicyServiceTestCase.class.getSimpleName();
@Deployment(name = DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment1() {
return createDeployment();
}
@Deployment(name = DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment2() {
return createDeployment();
}
private static Archive<?> createDeployment() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, MODULE_NAME + ".jar");
jar.addClass(NodeServicePolicyActivator.class);
jar.addAsServiceProvider(ServiceActivator.class, NodeServicePolicyActivator.class);
return jar;
}
@Test
public void testSingletonService(
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) ManagementClient client1,
@ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) ManagementClient client2)
throws Exception {
// Needed to be able to inject ArquillianResource
stop(NODE_2);
String primaryProviderRequest = String.format("/subsystem=singleton/singleton-policy=default/service=%s:read-attribute(name=primary-provider)", NodeServicePolicyActivator.SERVICE_NAME.getCanonicalName());
String isPrimaryRequest = String.format("/subsystem=singleton/singleton-policy=default/service=%s:read-attribute(name=is-primary)", NodeServicePolicyActivator.SERVICE_NAME.getCanonicalName());
String getProvidersRequest = String.format("/subsystem=singleton/singleton-policy=default/service=%s:read-attribute(name=providers)", NodeServicePolicyActivator.SERVICE_NAME.getCanonicalName());
Assert.assertEquals(NODE_1, execute(client1, primaryProviderRequest).asStringOrNull());
Assert.assertTrue(execute(client1, isPrimaryRequest).asBoolean(false));
Assert.assertEquals(Collections.singletonList(NODE_1), execute(client1, getProvidersRequest).asList().stream().map(ModelNode::asString).collect(Collectors.toList()));
start(NODE_2);
Assert.assertEquals(NODE_1, execute(client1, primaryProviderRequest).asStringOrNull());
Assert.assertTrue(execute(client1, isPrimaryRequest).asBoolean(false));
Assert.assertEquals(Arrays.asList(NODE_1, NODE_2), execute(client1, getProvidersRequest).asList().stream().map(ModelNode::asString).sorted().collect(Collectors.toList()));
Assert.assertEquals(NODE_1, execute(client2, primaryProviderRequest).asStringOrNull());
Assert.assertFalse(execute(client2, isPrimaryRequest).asBoolean(true));
Assert.assertEquals(Arrays.asList(NODE_1, NODE_2), execute(client2, getProvidersRequest).asList().stream().map(ModelNode::asString).sorted().collect(Collectors.toList()));
stop(NODE_2);
Assert.assertEquals(NODE_1, execute(client1, primaryProviderRequest).asStringOrNull());
Assert.assertTrue(execute(client1, isPrimaryRequest).asBoolean(false));
Assert.assertEquals(Collections.singletonList(NODE_1), execute(client1, getProvidersRequest).asList().stream().map(ModelNode::asString).collect(Collectors.toList()));
start(NODE_2);
Assert.assertEquals(NODE_1, execute(client1, primaryProviderRequest).asStringOrNull());
Assert.assertTrue(execute(client1, isPrimaryRequest).asBoolean(false));
Assert.assertEquals(Arrays.asList(NODE_1, NODE_2), execute(client1, getProvidersRequest).asList().stream().map(ModelNode::asString).sorted().collect(Collectors.toList()));
Assert.assertEquals(NODE_1, execute(client2, primaryProviderRequest).asStringOrNull());
Assert.assertFalse(execute(client2, isPrimaryRequest).asBoolean(true));
Assert.assertEquals(Arrays.asList(NODE_1, NODE_2), execute(client2, getProvidersRequest).asList().stream().map(ModelNode::asString).sorted().collect(Collectors.toList()));
stop(NODE_1);
Assert.assertEquals(NODE_2, execute(client2, primaryProviderRequest).asStringOrNull());
Assert.assertTrue(execute(client2, isPrimaryRequest).asBoolean(false));
Assert.assertEquals(Collections.singletonList(NODE_2), execute(client2, getProvidersRequest).asList().stream().map(ModelNode::asString).collect(Collectors.toList()));
start(NODE_1);
Assert.assertEquals(NODE_2, execute(client1, primaryProviderRequest).asStringOrNull());
Assert.assertFalse(execute(client1, isPrimaryRequest).asBoolean(true));
Assert.assertEquals(Arrays.asList(NODE_1, NODE_2), execute(client1, getProvidersRequest).asList().stream().map(ModelNode::asString).sorted().collect(Collectors.toList()));
Assert.assertEquals(NODE_2, execute(client2, primaryProviderRequest).asStringOrNull());
Assert.assertTrue(execute(client2, isPrimaryRequest).asBoolean(false));
Assert.assertEquals(Arrays.asList(NODE_1, NODE_2), execute(client2, getProvidersRequest).asList().stream().map(ModelNode::asString).sorted().collect(Collectors.toList()));
}
}
| 7,238
| 55.554688
| 212
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/SingletonDeploymentJBossAllTestCase.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.clustering.cluster.singleton;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.as.test.clustering.cluster.singleton.servlet.TraceServlet;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
/**
* @author Paul Ferraro
*/
@org.junit.Ignore("WFLY-16973")
public class SingletonDeploymentJBossAllTestCase extends SingletonDeploymentTestCase {
private static final String MODULE_NAME = SingletonDeploymentJBossAllTestCase.class.getSimpleName();
private static final String DEPLOYMENT_NAME = MODULE_NAME + ".war";
public SingletonDeploymentJBossAllTestCase() {
super(MODULE_NAME, DEPLOYMENT_NAME);
}
@Deployment(name = SINGLETON_DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment0() {
return createDeployment();
}
@Deployment(name = SINGLETON_DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment1() {
return createDeployment();
}
private static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_NAME);
war.addPackage(TraceServlet.class.getPackage());
war.addAsManifestResource(SingletonDeploymentJBossAllTestCase.class.getPackage(), "jboss-all.xml", "jboss-all.xml");
return war;
}
}
| 2,587
| 39.4375
| 124
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/SingletonDeploymentDescriptorTestCase.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.clustering.cluster.singleton;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.as.test.clustering.cluster.singleton.servlet.TraceServlet;
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.WebArchive;
/**
* @author Paul Ferraro
*/
@org.junit.Ignore("WFLY-16973")
public class SingletonDeploymentDescriptorTestCase extends SingletonDeploymentTestCase {
private static final String MODULE_NAME = SingletonDeploymentDescriptorTestCase.class.getSimpleName();
private static final String DEPLOYMENT_NAME = MODULE_NAME + ".ear";
public SingletonDeploymentDescriptorTestCase() {
super(MODULE_NAME, DEPLOYMENT_NAME);
}
@Deployment(name = SINGLETON_DEPLOYMENT_1, managed = false, testable = false)
@TargetsContainer(NODE_1)
public static Archive<?> deployment0() {
return createDeployment();
}
@Deployment(name = SINGLETON_DEPLOYMENT_2, managed = false, testable = false)
@TargetsContainer(NODE_2)
public static Archive<?> deployment1() {
return createDeployment();
}
private static Archive<?> createDeployment() {
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, DEPLOYMENT_NAME);
WebArchive war = ShrinkWrap.create(WebArchive.class, MODULE_NAME + ".war");
war.addPackage(TraceServlet.class.getPackage());
ear.addAsModule(war);
ear.addAsManifestResource(SingletonDeploymentDescriptorTestCase.class.getPackage(), "singleton-deployment.xml", "singleton-deployment.xml");
return ear;
}
}
| 2,801
| 40.820896
| 148
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/service/NodeServiceActivator.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.clustering.cluster.singleton.service;
import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.NODE_2;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.as.clustering.controller.ServiceValueCaptorServiceConfigurator;
import org.jboss.msc.service.ServiceActivator;
import org.jboss.msc.service.ServiceActivatorContext;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.clustering.service.ChildTargetService;
import org.wildfly.clustering.singleton.SingletonDefaultCacheRequirement;
import org.wildfly.clustering.singleton.election.NamePreference;
import org.wildfly.clustering.singleton.election.PreferredSingletonElectionPolicy;
import org.wildfly.clustering.singleton.election.SimpleSingletonElectionPolicy;
import org.wildfly.clustering.singleton.service.SingletonServiceConfiguratorFactory;
/**
* @author Paul Ferraro
*/
public class NodeServiceActivator implements ServiceActivator {
public static final ServiceName DEFAULT_SERVICE_NAME = ServiceName.JBOSS.append("test", "service", "default");
public static final ServiceName QUORUM_SERVICE_NAME = ServiceName.JBOSS.append("test", "service", "quorum");
private static final String CONTAINER_NAME = "server";
public static final String PREFERRED_NODE = NODE_2;
@Override
public void activate(ServiceActivatorContext context) {
ServiceBuilder<?> builder = context.getServiceTarget().addService(ServiceName.JBOSS.append("test", "service", "installer"));
Supplier<SingletonServiceConfiguratorFactory> factoryDependency = builder.requires(ServiceName.parse(SingletonDefaultCacheRequirement.SINGLETON_SERVICE_CONFIGURATOR_FACTORY.resolve(CONTAINER_NAME)));
Consumer<ServiceTarget> installer = target -> {
SingletonServiceConfiguratorFactory factory = factoryDependency.get();
install(target, factory, DEFAULT_SERVICE_NAME, 1);
install(target, factory, QUORUM_SERVICE_NAME, 2);
};
builder.setInstance(new ChildTargetService(installer)).install();
new ServiceValueCaptorServiceConfigurator<>(NodeServiceExecutorRegistry.INSTANCE.add(DEFAULT_SERVICE_NAME)).build(context.getServiceTarget()).install();
new ServiceValueCaptorServiceConfigurator<>(NodeServiceExecutorRegistry.INSTANCE.add(QUORUM_SERVICE_NAME)).build(context.getServiceTarget()).install();
}
private static void install(ServiceTarget target, SingletonServiceConfiguratorFactory factory, ServiceName name, int quorum) {
ServiceBuilder<?> builder = target.addService(name);
SingletonElectionListenerService listenerService = new SingletonElectionListenerService(builder.provides(name));
builder.setInstance(listenerService).install();
factory.createSingletonServiceConfigurator(name.append("singleton"))
.electionPolicy(new PreferredSingletonElectionPolicy(new SimpleSingletonElectionPolicy(), new NamePreference(PREFERRED_NODE)))
.electionListener(listenerService)
.requireQuorum(quorum)
.build(target)
.install();
}
}
| 4,290
| 51.329268
| 207
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/service/ValueServiceActivator.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.clustering.cluster.singleton.service;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceActivator;
import org.jboss.msc.service.ServiceActivatorContext;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.wildfly.clustering.service.ChildTargetService;
import org.wildfly.clustering.singleton.SingletonDefaultRequirement;
import org.wildfly.clustering.singleton.SingletonPolicy;
/**
* @author Paul Ferraro
*/
@SuppressWarnings("deprecation")
public class ValueServiceActivator implements ServiceActivator {
public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("test", "service", "value");
@Override
public void activate(ServiceActivatorContext context) {
ServiceBuilder<?> builder = context.getServiceTarget().addService(ServiceName.JBOSS.append("test", "service", "installer"));
Supplier<SingletonPolicy> policy = builder.requires(ServiceName.parse(SingletonDefaultRequirement.SINGLETON_POLICY.getName()));
Consumer<ServiceTarget> installer = target -> policy.get().createSingletonServiceBuilder(SERVICE_NAME, new ValueService<>(Boolean.TRUE), new ValueService<>(Boolean.FALSE)).build(context.getServiceTarget()).install();
builder.setInstance(new ChildTargetService(installer)).install();
}
private static final class ValueService<T> implements Service<T> {
private final T value;
ValueService(T value) {
this.value = value;
}
@Override
public void start(final StartContext context) {
// noop
}
@Override
public void stop(final StopContext context) {
// noop
}
@Override
public T getValue() {
return this.value;
}
}
}
| 3,071
| 37.886076
| 224
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/service/ValueServiceServlet.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.clustering.cluster.singleton.service;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
/**
* @author Paul Ferraro
*/
@WebServlet(urlPatterns = { ValueServiceServlet.SERVLET_PATH })
public class ValueServiceServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String SERVLET_NAME = "value";
static final String SERVLET_PATH = "/" + SERVLET_NAME;
private static final String SERVICE = "service";
public static final String PRIMARY_HEADER = "primary";
private static final String EXPECTED = "expected";
// private static final int RETRIES = 10;
public static URI createURI(URL baseURL, ServiceName serviceName) throws URISyntaxException {
return baseURL.toURI().resolve(buildQuery(serviceName).toString());
}
public static URI createURI(URL baseURL, ServiceName serviceName, boolean expected) throws URISyntaxException {
return baseURL.toURI().resolve(buildQuery(serviceName).append('&').append(EXPECTED).append('=').append(expected).toString());
}
private static StringBuilder buildQuery(ServiceName serviceName) {
return new StringBuilder(SERVLET_NAME).append('?').append(SERVICE).append('=').append(serviceName.getCanonicalName());
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String serviceName = getRequiredParameter(request, SERVICE);
this.log(String.format("Received request for %s", serviceName));
@SuppressWarnings("unchecked")
ServiceController<Boolean> service = (ServiceController<Boolean>) CurrentServiceContainer.getServiceContainer().getService(ServiceName.parse(serviceName));
try {
Boolean primary = service.awaitValue(5, TimeUnit.MINUTES);
response.setHeader(PRIMARY_HEADER, primary.toString());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (TimeoutException e) {
service.getServiceContainer().dumpServices();
throw new ServletException(String.format("ServiceController %s did not provide a value within 5 minutes; " +
"mode is %s and state is %s", serviceName, service.getMode(), service.getState()), e);
}
response.getWriter().write("Success");
}
private static String getRequiredParameter(HttpServletRequest request, String name) throws ServletException {
String value = request.getParameter(name);
if (value == null) {
throw new ServletException(String.format("No %s specified", name));
}
return value;
}
}
| 4,252
| 44.244681
| 163
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/service/NodeServicePolicyActivator.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.clustering.cluster.singleton.service;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.msc.service.ServiceActivator;
import org.jboss.msc.service.ServiceActivatorContext;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.clustering.service.ChildTargetService;
import org.wildfly.clustering.singleton.SingletonDefaultRequirement;
import org.wildfly.clustering.singleton.service.SingletonPolicy;
/**
* @author Paul Ferraro
*/
public class NodeServicePolicyActivator implements ServiceActivator {
public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("test", "service", "default-policy");
@Override
public void activate(ServiceActivatorContext context) {
ServiceBuilder<?> builder = context.getServiceTarget().addService(ServiceName.JBOSS.append("test", "service", "installer"));
Supplier<SingletonPolicy> policy = builder.requires(ServiceName.parse(SingletonDefaultRequirement.POLICY.getName()));
Consumer<ServiceTarget> installer = target -> policy.get().createSingletonServiceConfigurator(SERVICE_NAME).build(target).install();
builder.setInstance(new ChildTargetService(installer)).install();
}
}
| 2,361
| 44.423077
| 140
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/service/NodeServiceServlet.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.clustering.cluster.singleton.service;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.Duration;
import java.time.Instant;
import java.util.function.Supplier;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jboss.as.clustering.controller.FunctionExecutor;
import org.jboss.msc.service.ServiceName;
import org.wildfly.clustering.group.Node;
import org.wildfly.common.function.ExceptionFunction;
@WebServlet(urlPatterns = { NodeServiceServlet.SERVLET_PATH })
public class NodeServiceServlet extends HttpServlet {
private static final long serialVersionUID = -592774116315946908L;
public static final String NODE_HEADER = "node";
private static final String SERVLET_NAME = "node";
static final String SERVLET_PATH = "/" + SERVLET_NAME;
private static final String SERVICE = "service";
private static final String EXPECTED = "expected";
private static final Duration TIMEOUT = Duration.ofSeconds(10);
public static URI createURI(URL baseURL, ServiceName serviceName) throws URISyntaxException {
return baseURL.toURI().resolve(buildQuery(serviceName).toString());
}
public static URI createURI(URL baseURL, ServiceName serviceName, String expected) throws URISyntaxException {
return baseURL.toURI().resolve(buildQuery(serviceName).append('&').append(EXPECTED).append('=').append(expected).toString());
}
private static StringBuilder buildQuery(ServiceName serviceName) {
return new StringBuilder(SERVLET_NAME).append('?').append(SERVICE).append('=').append(serviceName.getCanonicalName());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String serviceName = getRequiredParameter(req, SERVICE);
String expected = req.getParameter(EXPECTED);
this.log(String.format("Received request for %s, expecting %s", serviceName, expected));
FunctionExecutor<Supplier<Node>> executor = NodeServiceExecutorRegistry.INSTANCE.get(ServiceName.parse(serviceName));
Instant stop = Instant.now().plus(TIMEOUT);
ExceptionFunction<Supplier<Node>, Node, RuntimeException> function = Supplier::get;
Node node = executor.execute(function);
if (expected != null) {
while (Instant.now().isBefore(stop)) {
if ((node != null) && expected.equals(node.getName())) break;
Thread.yield();
node = executor.execute(function);
}
}
if (node != null) {
resp.setHeader(NODE_HEADER, node.getName());
}
resp.getWriter().write("Success");
}
private static String getRequiredParameter(HttpServletRequest req, String name) throws ServletException {
String value = req.getParameter(name);
if (value == null) {
throw new ServletException(String.format("No %s specified", name));
}
return value;
}
}
| 4,264
| 43.894737
| 133
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/service/NodeServiceExecutorRegistry.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.clustering.cluster.singleton.service;
import java.util.function.Supplier;
import org.jboss.as.clustering.controller.FunctionExecutor;
import org.jboss.as.clustering.controller.FunctionExecutorRegistry;
import org.jboss.as.clustering.controller.ServiceValueCaptor;
import org.jboss.as.clustering.controller.ServiceValueExecutorRegistry;
import org.jboss.as.clustering.controller.ServiceValueRegistry;
import org.jboss.msc.service.ServiceName;
import org.wildfly.clustering.group.Node;
/**
* @author Paul Ferraro
*/
public enum NodeServiceExecutorRegistry implements FunctionExecutorRegistry<Supplier<Node>>, ServiceValueRegistry<Supplier<Node>> {
INSTANCE;
private final ServiceValueExecutorRegistry<Supplier<Node>> registry = new ServiceValueExecutorRegistry<>();
@Override
public ServiceValueCaptor<Supplier<Node>> add(ServiceName name) {
return this.registry.add(name);
}
@Override
public ServiceValueCaptor<Supplier<Node>> remove(ServiceName name) {
return this.registry.remove(name);
}
@Override
public FunctionExecutor<Supplier<Node>> get(ServiceName name) {
return this.registry.get(name);
}
}
| 2,227
| 37.413793
| 131
|
java
|
null |
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/singleton/service/SingletonElectionListenerService.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.clustering.cluster.singleton.service;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.msc.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.wildfly.clustering.group.Node;
import org.wildfly.clustering.singleton.SingletonElectionListener;
/**
* @author Paul Ferraro
*/
public class SingletonElectionListenerService implements Service, SingletonElectionListener, Supplier<Node> {
private final Consumer<Supplier<Node>> injector;
private volatile Node primaryMember = null;
public SingletonElectionListenerService(Consumer<Supplier<Node>> injector) {
this.injector = injector;
}
@Override
public Node get() {
return this.primaryMember;
}
@Override
public void start(StartContext context) throws StartException {
this.injector.accept(this);
}
@Override
public void stop(StopContext context) {
}
@Override
public void elected(List<Node> candidateMembers, Node electedMember) {
this.primaryMember = electedMember;
}
}
| 2,232
| 32.833333
| 109
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.