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/ejb/stateful/bean/JMSResourceManagerConnectionFactoryIncrementorBean.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.ejb.stateful.bean; import java.util.concurrent.atomic.AtomicInteger; import jakarta.annotation.Resource; import jakarta.ejb.Stateful; import jakarta.jms.QueueConnectionFactory; import jakarta.jms.TopicConnectionFactory; @Stateful public class JMSResourceManagerConnectionFactoryIncrementorBean implements Incrementor { @Resource private QueueConnectionFactory queueConnectionFactory; @Resource private TopicConnectionFactory topicConnectionFactory; private final AtomicInteger count = new AtomicInteger(0); @Override public int increment() { return this.count.incrementAndGet(); } }
1,698
35.148936
88
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/NestedIncrementorBean.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.ejb.stateful.bean; import jakarta.ejb.EJB; import jakarta.ejb.Stateful; import jakarta.interceptor.Interceptors; /** * @author Paul Ferraro */ @Stateful @Interceptors(IncrementorInterceptor.class) @Intercepted public class NestedIncrementorBean implements Incrementor { @EJB private Nested nested; @Override public int increment() { return this.nested.increment(); } }
1,472
31.733333
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/IncrementorDDInterceptor.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.ejb.stateful.bean; import java.io.Serializable; import java.util.concurrent.atomic.AtomicInteger; import jakarta.interceptor.AroundInvoke; import jakarta.interceptor.Interceptor; import jakarta.interceptor.InvocationContext; /** * @author Stuart Douglas */ @Intercepted @Interceptor public class IncrementorDDInterceptor implements Serializable { private static final long serialVersionUID = -3706191491067801021L; private final AtomicInteger count = new AtomicInteger(0); @AroundInvoke public Object invoke(final InvocationContext context) throws Exception { return ((Integer) context.proceed()) + this.count.addAndGet(10000); } }
1,735
36.73913
76
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/IncrementorInterceptor.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.ejb.stateful.bean; import java.io.Serializable; import java.util.concurrent.atomic.AtomicInteger; import jakarta.interceptor.AroundInvoke; import jakarta.interceptor.InvocationContext; /** * @author Stuart Douglas */ public class IncrementorInterceptor implements Serializable { private static final long serialVersionUID = 2147419195941582392L; private final AtomicInteger count = new AtomicInteger(0); @AroundInvoke public Object invoke(final InvocationContext context) throws Exception { return ((Integer) context.proceed()) + this.count.addAndGet(100); } }
1,664
37.72093
76
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/CounterDecorator.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.ejb.stateful.bean; import java.io.Serializable; import jakarta.decorator.Decorator; import jakarta.decorator.Delegate; import jakarta.inject.Inject; /** * @author Stuart Douglas */ @Decorator public class CounterDecorator implements Serializable, Counter { private static final long serialVersionUID = -3924798173306389949L; @Inject @Delegate private Counter counter; @Override public int getCount() { return this.counter.getCount() + 10000000; } }
1,560
32.934783
71
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/PassivationIncapableIncrementorBean.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.ejb.stateful.bean; import java.util.concurrent.atomic.AtomicInteger; import jakarta.ejb.PostActivate; import jakarta.ejb.PrePassivate; import jakarta.ejb.Stateful; @Stateful(passivationCapable = false) public class PassivationIncapableIncrementorBean implements Incrementor { private final AtomicInteger count = new AtomicInteger(0); private boolean passivated = false; private transient boolean activated = false; @Override public int increment() { assert !this.passivated; assert !this.activated; return this.count.incrementAndGet(); } @PrePassivate public void prePassivate() { this.passivated = true; } @PostActivate public void postActivate() { this.activated = true; } }
1,840
33.092593
73
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/SimpleIncrementorBean.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.ejb.stateful.bean; import java.util.concurrent.atomic.AtomicInteger; import jakarta.annotation.Resource; import jakarta.ejb.PostActivate; import jakarta.ejb.PrePassivate; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateful; @Stateful public class SimpleIncrementorBean implements Incrementor { @Resource private SessionContext context; private final AtomicInteger count = new AtomicInteger(0); private transient boolean activated = false; private boolean passivated = false; @Override public int increment() { if (this.count.get() > 0) { assert this.passivated; assert this.activated; this.passivated = false; } return this.count.incrementAndGet(); } @PrePassivate public void prePassivate() { this.passivated = true; } @PostActivate public void postActivate() { this.activated = true; } }
2,008
31.934426
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/Counter.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.ejb.stateful.bean; /** * @author Stuart Douglas */ public interface Counter { int getCount(); }
1,171
38.066667
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/Nested.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.ejb.stateful.bean; import jakarta.ejb.Local; /** * @author Paul Ferraro */ @Local public interface Nested extends Incrementor { }
1,203
35.484848
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/PersistenceIncrementorBean.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.ejb.stateful.bean; import java.util.concurrent.atomic.AtomicInteger; import jakarta.annotation.Resource; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceUnit; import jakarta.transaction.UserTransaction; @Stateful @TransactionManagement(TransactionManagementType.BEAN) public class PersistenceIncrementorBean implements Incrementor { @Resource private UserTransaction transaction; @PersistenceUnit(unitName = "test") private EntityManagerFactory factory; @PersistenceContext(unitName = "test") private EntityManager manager; private final AtomicInteger count = new AtomicInteger(0); @Override public int increment() { return this.count.incrementAndGet(); } }
2,027
35.214286
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/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.ejb.stateful.bean; import java.io.Serializable; /** * @author Stuart Douglas */ public class CounterBean implements Serializable, Counter { private static final long serialVersionUID = 5616577826029047421L; @Override public int getCount() { return 10000000; } }
1,359
35.756757
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/NestedBean.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.ejb.stateful.bean; import java.util.concurrent.atomic.AtomicInteger; import jakarta.ejb.Stateful; import jakarta.inject.Inject; /** * @author Paul Ferraro */ @Stateful public class NestedBean implements Nested { private final AtomicInteger count = new AtomicInteger(0); @Inject private Counter counter; @Override public int increment() { return this.count.incrementAndGet() + this.counter.getCount(); } }
1,514
31.934783
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/TimerIncrementorBean.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.ejb.stateful.bean; import java.util.concurrent.atomic.AtomicInteger; import jakarta.annotation.Resource; import jakarta.ejb.Stateful; import jakarta.ejb.TimerService; @Stateful public class TimerIncrementorBean implements Incrementor { @Resource private TimerService service; private final AtomicInteger count = new AtomicInteger(0); @Override public int increment() { return this.count.incrementAndGet(); } }
1,516
34.27907
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/Intercepted.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.clustering.cluster.ejb.stateful.bean; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import jakarta.interceptor.InterceptorBinding; /** * @author Stuart Douglas */ @Retention(RetentionPolicy.RUNTIME) @InterceptorBinding public @interface Intercepted { }
1,338
36.194444
73
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/JDBCResourceManagerConnectionFactoryIncrementorBean.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.ejb.stateful.bean; import java.util.concurrent.atomic.AtomicInteger; import jakarta.annotation.Resource; import jakarta.ejb.Stateful; import javax.sql.DataSource; /** * @author Paul Ferraro */ @Stateful public class JDBCResourceManagerConnectionFactoryIncrementorBean implements Incrementor { @Resource private DataSource dataSource; private final AtomicInteger count = new AtomicInteger(0); @Override public int increment() { return this.count.incrementAndGet(); } }
1,577
32.574468
89
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/SessionScopedIncrementorBean.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.ejb.stateful.bean; import java.util.concurrent.atomic.AtomicInteger; import jakarta.ejb.Stateful; import jakarta.enterprise.context.SessionScoped; /** * @author Paul Ferraro */ @SessionScoped @Stateful public class SessionScopedIncrementorBean implements ScopedIncrementor { private final AtomicInteger count = new AtomicInteger(0); @Override public int increment() { return this.count.incrementAndGet(); } }
1,509
33.318182
72
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/TimeoutIncrementorBean.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.ejb.stateful.bean; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.ejb.PostActivate; import jakarta.ejb.PrePassivate; import jakarta.ejb.Stateful; import jakarta.ejb.StatefulTimeout; @Stateful @StatefulTimeout(value = 1, unit = TimeUnit.SECONDS) public class TimeoutIncrementorBean implements Incrementor { private final AtomicInteger count = new AtomicInteger(0); private volatile boolean active = false; @Override public int increment() { return this.count.incrementAndGet(); } @PostActivate public void postActivate() { this.active = true; } @PrePassivate public void prePassivate() { this.active = false; } @PostConstruct public void postConstruct() { this.active = true; } @PreDestroy public void preDestroy() { if (!this.active) { throw new IllegalStateException("@PostActivate listener not triggered!"); } } }
2,155
31.179104
85
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/Incrementor.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.ejb.stateful.bean; import jakarta.ejb.Local; /** * @author Paul Ferraro */ @Local public interface Incrementor { int increment(); default void reset() { // Do nothing } }
1,265
32.315789
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/stateful/bean/ScopedIncrementor.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.ejb.stateful.bean; import jakarta.ejb.Local; /** * @author Paul Ferraro */ @Local public interface ScopedIncrementor extends Incrementor { }
1,215
34.764706
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/AbstractRemoteStatelessEJBFailoverTestCase.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.ejb.remote; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.PropertyPermission; import java.util.concurrent.Callable; import java.util.function.UnaryOperator; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Incrementor; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.IncrementorBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Result; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.SecureStatelessIncrementorBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.StatelessIncrementorBean; import org.jboss.as.test.clustering.ejb.EJBDirectory; import org.jboss.as.test.shared.TimeoutUtil; 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.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.common.function.ExceptionSupplier; /** * Validates failover behavior of a remotely accessed @Stateless EJB. * @author Paul Ferraro */ @RunWith(Arquillian.class) public abstract class AbstractRemoteStatelessEJBFailoverTestCase extends AbstractClusteringTestCase { private static final int COUNT = 20; private static final long CLIENT_TOPOLOGY_UPDATE_WAIT = TimeoutUtil.adjust(5000); private static final long INVOCATION_WAIT = TimeoutUtil.adjust(10); static Archive<?> createDeployment(String moduleName) { return ShrinkWrap.create(JavaArchive.class, moduleName + ".jar") .addPackage(EJBDirectory.class.getPackage()) .addClasses(Result.class, Incrementor.class, IncrementorBean.class, StatelessIncrementorBean.class, SecureStatelessIncrementorBean.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new PropertyPermission(NODE_NAME_PROPERTY, "read")), "permissions.xml") ; } private final ExceptionSupplier<EJBDirectory, Exception> directoryProvider; private final Class<? extends Incrementor> beanClass; private final UnaryOperator<Callable<Void>> configurator; AbstractRemoteStatelessEJBFailoverTestCase(ExceptionSupplier<EJBDirectory, Exception> directoryProvider, Class<? extends Incrementor> beanClass, UnaryOperator<Callable<Void>> configurator) { this.directoryProvider = directoryProvider; this.beanClass = beanClass; this.configurator = configurator; } @Test public void test() throws Exception { this.configurator.apply(() -> { try (EJBDirectory directory = this.directoryProvider.get()) { Incrementor bean = directory.lookupStateless(this.beanClass, Incrementor.class); // Allow sufficient time for client to receive full topology Thread.sleep(CLIENT_TOPOLOGY_UPDATE_WAIT); List<String> results = new ArrayList<>(COUNT); for (int i = 0; i < COUNT; ++i) { Result<Integer> result = bean.increment(); results.add(result.getNode()); Thread.sleep(INVOCATION_WAIT); } for (String node : TWO_NODES) { int frequency = Collections.frequency(results, node); assertTrue(String.valueOf(frequency) + " invocations were routed to " + node, frequency > 0); } undeploy(DEPLOYMENT_1); for (int i = 0; i < COUNT; ++i) { Result<Integer> result = bean.increment(); results.set(i, result.getNode()); Thread.sleep(INVOCATION_WAIT); } Assert.assertEquals(0, Collections.frequency(results, NODE_1)); Assert.assertEquals(COUNT, Collections.frequency(results, NODE_2)); deploy(DEPLOYMENT_1); // Allow sufficient time for client to receive new topology Thread.sleep(CLIENT_TOPOLOGY_UPDATE_WAIT); for (int i = 0; i < COUNT; ++i) { Result<Integer> result = bean.increment(); results.set(i, result.getNode()); Thread.sleep(INVOCATION_WAIT); } for (String node : TWO_NODES) { int frequency = Collections.frequency(results, node); assertTrue(String.valueOf(frequency) + " invocations were routed to " + node, frequency > 0); } stop(NODE_2); for (int i = 0; i < COUNT; ++i) { Result<Integer> result = bean.increment(); results.set(i, result.getNode()); Thread.sleep(INVOCATION_WAIT); } Assert.assertEquals(COUNT, Collections.frequency(results, NODE_1)); Assert.assertEquals(0, Collections.frequency(results, NODE_2)); start(NODE_2); // Allow sufficient time for client to receive new topology Thread.sleep(CLIENT_TOPOLOGY_UPDATE_WAIT); for (int i = 0; i < COUNT; ++i) { Result<Integer> result = bean.increment(); results.set(i, result.getNode()); Thread.sleep(INVOCATION_WAIT); } for (String node : TWO_NODES) { int frequency = Collections.frequency(results, node); assertTrue(String.valueOf(frequency) + " invocations were routed to " + node, frequency > 0); } } return null; }).call(); } }
6,994
42.71875
194
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/ClientRemoteStatelessEJBFailoverTestCase.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.ejb.remote; import java.util.function.UnaryOperator; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.StatelessIncrementorBean; import org.jboss.as.test.clustering.ejb.ClientEJBDirectory; import org.jboss.shrinkwrap.api.Archive; /** * @author Paul Ferraro */ public class ClientRemoteStatelessEJBFailoverTestCase extends AbstractRemoteStatelessEJBFailoverTestCase { private static final String MODULE_NAME = ClientRemoteStatelessEJBFailoverTestCase.class.getSimpleName(); @Deployment(name = DEPLOYMENT_1, managed = false, testable = false) @TargetsContainer(NODE_1) public static Archive<?> createDeploymentForContainer1() { return createDeployment(MODULE_NAME); } @Deployment(name = DEPLOYMENT_2, managed = false, testable = false) @TargetsContainer(NODE_2) public static Archive<?> createDeploymentForContainer2() { return createDeployment(MODULE_NAME); } public ClientRemoteStatelessEJBFailoverTestCase() { super(() -> new ClientEJBDirectory(MODULE_NAME), StatelessIncrementorBean.class, UnaryOperator.identity()); } }
2,302
40.872727
115
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/AuthContextRemoteStatelessEJBFailoverTestCase.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.ejb.remote; import java.util.concurrent.Callable; import java.util.function.UnaryOperator; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.SecureStatelessIncrementorBean; import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory; import org.jboss.shrinkwrap.api.Archive; import org.wildfly.security.auth.client.AuthenticationConfiguration; import org.wildfly.security.auth.client.AuthenticationContext; import org.wildfly.security.auth.client.MatchRule; /** * Validates failover behavior of a remotely accessed secure @Stateless EJB. * @author Paul Ferraro */ public abstract class AuthContextRemoteStatelessEJBFailoverTestCase extends AbstractRemoteStatelessEJBFailoverTestCase { private static final String MODULE_NAME = AuthContextRemoteStatelessEJBFailoverTestCase.class.getSimpleName(); static final AuthenticationContext AUTHENTICATION_CONTEXT = AuthenticationContext.captureCurrent().with( MatchRule.ALL.matchAbstractType("ejb", "jboss"), AuthenticationConfiguration.empty().useName("user1").usePassword("password1") ); @Deployment(name = DEPLOYMENT_1, managed = false, testable = false) @TargetsContainer(NODE_1) public static Archive<?> createDeploymentForContainer1() { return createDeployment(MODULE_NAME); } @Deployment(name = DEPLOYMENT_2, managed = false, testable = false) @TargetsContainer(NODE_2) public static Archive<?> createDeploymentForContainer2() { return createDeployment(MODULE_NAME); } public AuthContextRemoteStatelessEJBFailoverTestCase(UnaryOperator<Callable<Void>> configurator) { super(() -> new RemoteEJBDirectory(MODULE_NAME), SecureStatelessIncrementorBean.class, configurator); } }
2,939
43.545455
120
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/RemoteStatelessEJBFailoverTestCase.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.ejb.remote; import java.util.function.UnaryOperator; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.StatelessIncrementorBean; import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory; import org.jboss.shrinkwrap.api.Archive; /** * Validates failover behavior of a remotely accessed @Stateless EJB. * @author Paul Ferraro */ public class RemoteStatelessEJBFailoverTestCase extends AbstractRemoteStatelessEJBFailoverTestCase { private static final String MODULE_NAME = RemoteStatelessEJBFailoverTestCase.class.getSimpleName(); @Deployment(name = DEPLOYMENT_1, managed = false, testable = false) @TargetsContainer(NODE_1) public static Archive<?> createDeploymentForContainer1() { return createDeployment(MODULE_NAME); } @Deployment(name = DEPLOYMENT_2, managed = false, testable = false) @TargetsContainer(NODE_2) public static Archive<?> createDeploymentForContainer2() { return createDeployment(MODULE_NAME); } public RemoteStatelessEJBFailoverTestCase() { super(() -> new RemoteEJBDirectory(MODULE_NAME), StatelessIncrementorBean.class, UnaryOperator.identity()); } }
2,354
41.053571
115
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/PassivationDisabledRemoteStatefulEjbFailoverTestCase.java
package org.jboss.as.test.clustering.cluster.ejb.remote; import java.util.PropertyPermission; import jakarta.ejb.NoSuchEJBException; 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.ejb.remote.bean.Incrementor; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.IncrementorBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.PassivationDisabledStatefulIncrementorBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Result; import org.jboss.as.test.clustering.ejb.EJBDirectory; import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory; import org.jboss.as.test.shared.TimeoutUtil; 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.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.common.function.ExceptionSupplier; /** * Test the following properties of passivation-disabled SFSB when deployed in a cluster: * - stickiness of passivation-disabled SFSB to the node its is created on, as well as * - verify that it does not fail over to another node in the cluster when the node it is created on goes down * . * @author Paul Ferraro */ @RunWith(Arquillian.class) public class PassivationDisabledRemoteStatefulEjbFailoverTestCase extends AbstractClusteringTestCase { private static final int COUNT = 20; private static final long CLIENT_TOPOLOGY_UPDATE_WAIT = TimeoutUtil.adjust(5000); private static final String MODULE_NAME = PassivationDisabledRemoteStatefulEjbFailoverTestCase.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, Incrementor.class, IncrementorBean.class, PassivationDisabledStatefulIncrementorBean.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new PropertyPermission(NODE_NAME_PROPERTY, "read")), "permissions.xml") ; } private final ExceptionSupplier<EJBDirectory, Exception> directoryProvider; public PassivationDisabledRemoteStatefulEjbFailoverTestCase() { this.directoryProvider = () -> new RemoteEJBDirectory(MODULE_NAME); } @Test public void test() throws Exception { try (EJBDirectory directory = this.directoryProvider.get()) { Incrementor bean = directory.lookupStateful(PassivationDisabledStatefulIncrementorBean.class, Incrementor.class); Result<Integer> result = bean.increment(); String target = result.getNode(); int count = 1; Assert.assertEquals(count++, result.getValue().intValue()); // Bean should retain strong affinity for this node for (int i = 0; i < COUNT; ++i) { result = bean.increment(); Assert.assertEquals(count++, result.getValue().intValue()); Assert.assertEquals(String.valueOf(i), target, result.getNode()); } undeploy(this.findDeployment(target)); Thread.sleep(CLIENT_TOPOLOGY_UPDATE_WAIT); try { result = bean.increment(); // Bean should fail to failover to other node Assert.fail(result.getNode()); } catch (NoSuchEJBException e) { // Failover should fail } } } }
4,225
42.122449
152
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/AbstractRemoteStatefulEJBFailoverTestCase.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.ejb.remote; import java.util.PropertyPermission; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Incrementor; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.IncrementorBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Result; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.StatefulIncrementorBean; import org.jboss.as.test.clustering.ejb.EJBDirectory; import org.jboss.as.test.shared.TimeoutUtil; 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.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.common.function.ExceptionSupplier; /** * Validates failover behavior of a remotely accessed @Stateful EJB. * @author Paul Ferraro */ @RunWith(Arquillian.class) public abstract class AbstractRemoteStatefulEJBFailoverTestCase extends AbstractClusteringTestCase { private static final int COUNT = 20; private static final long CLIENT_TOPOLOGY_UPDATE_WAIT = TimeoutUtil.adjust(5000); static Archive<?> createDeployment(String moduleName) { return ShrinkWrap.create(JavaArchive.class, moduleName + ".jar") .addPackage(EJBDirectory.class.getPackage()) .addClasses(Result.class, Incrementor.class, IncrementorBean.class, StatefulIncrementorBean.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new PropertyPermission(NODE_NAME_PROPERTY, "read")), "permissions.xml") ; } private final ExceptionSupplier<EJBDirectory, Exception> directoryProvider; protected AbstractRemoteStatefulEJBFailoverTestCase(ExceptionSupplier<EJBDirectory, Exception> directoryProvider) { this.directoryProvider = directoryProvider; } @Test public void test() throws Exception { try (EJBDirectory directory = this.directoryProvider.get()) { Incrementor bean = directory.lookupStateful(StatefulIncrementorBean.class, Incrementor.class); Result<Integer> result = bean.increment(); String target = result.getNode(); int count = 1; Assert.assertEquals(count++, result.getValue().intValue()); // Bean should retain weak affinity for this node for (int i = 0; i < COUNT; ++i) { result = bean.increment(); Assert.assertEquals(count++, result.getValue().intValue()); Assert.assertEquals(String.valueOf(i), target, result.getNode()); } undeploy(this.findDeployment(target)); Thread.sleep(CLIENT_TOPOLOGY_UPDATE_WAIT); result = bean.increment(); // Bean should failover to other node String failoverTarget = result.getNode(); Assert.assertEquals(count++, result.getValue().intValue()); Assert.assertNotEquals(target, failoverTarget); deploy(this.findDeployment(target)); // Allow sufficient time for client to receive new topology Thread.sleep(CLIENT_TOPOLOGY_UPDATE_WAIT); result = bean.increment(); String failbackTarget = result.getNode(); Assert.assertEquals(count++, result.getValue().intValue()); // Bean should retain weak affinity for this node Assert.assertEquals(failoverTarget, failbackTarget); result = bean.increment(); // Bean may have acquired new weak affinity target = result.getNode(); Assert.assertEquals(count++, result.getValue().intValue()); // Bean should retain weak affinity for this node for (int i = 0; i < COUNT; ++i) { result = bean.increment(); Assert.assertEquals(count++, result.getValue().intValue()); Assert.assertEquals(String.valueOf(i), target, result.getNode()); } stop(target); result = bean.increment(); // Bean should failover to other node failoverTarget = result.getNode(); Assert.assertEquals(count++, result.getValue().intValue()); Assert.assertNotEquals(target, failoverTarget); start(target); // Allow sufficient time for client to receive new topology Thread.sleep(CLIENT_TOPOLOGY_UPDATE_WAIT); result = bean.increment(); failbackTarget = result.getNode(); Assert.assertEquals(count++, result.getValue().intValue()); // Bean should retain weak affinity for this node Assert.assertEquals(failoverTarget, failbackTarget); result = bean.increment(); // Bean may have acquired new weak affinity target = result.getNode(); Assert.assertEquals(count++, result.getValue().intValue()); // Bean should retain weak affinity for this node for (int i = 0; i < COUNT; ++i) { result = bean.increment(); Assert.assertEquals(count++, result.getValue().intValue()); Assert.assertEquals(String.valueOf(i), target, result.getNode()); } bean.remove(); } } }
6,547
41.245161
152
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/TwoConnectorsEJBFailoverTestCase.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.ejb.remote; import java.util.Properties; 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.arquillian.api.ServerSetup; import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Incrementor; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.IncrementorBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Result; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.StatefulIncrementorBean; import org.jboss.as.test.clustering.ejb.EJBDirectory; import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.TimeoutUtil; 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.JavaArchive; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.common.function.ExceptionSupplier; import javax.naming.Context; /** * A test of failover when both legacy remoting connector and HTTP Upgrade connector are enabled. * @author Richard Achmatowicz */ @ServerSetup(TwoConnectorsEJBFailoverTestCase.ServerSetupTask.class) @RunWith(Arquillian.class) @Ignore("WFLY-17605") public class TwoConnectorsEJBFailoverTestCase extends AbstractClusteringTestCase { private static final int COUNT = 20; private static final long CLIENT_TOPOLOGY_UPDATE_WAIT = TimeoutUtil.adjust(5000); private static final String MODULE_NAME = TwoConnectorsEJBFailoverTestCase.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, Incrementor.class, IncrementorBean.class, StatefulIncrementorBean.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new PropertyPermission(NODE_NAME_PROPERTY, "read")), "permissions.xml") ; } public TwoConnectorsEJBFailoverTestCase() { super(); } /* * Set up JNDI properties to support HTTP based Jakarta Enterprise Beans client invocations via HTTP Upgrade * * NOTE: there are several ways to connect to the Jakarta Enterprise Beans container on the server: * protocol URL * remoting remote://localhost:4447 * HTTP Upgrade remote+http://localhost:8080 * pure HTTP http://localhost:8080/wildfly-sevices */ private static Properties getProperties(boolean legacy) { Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, org.wildfly.naming.client.WildFlyInitialContextFactory.class.getName()); if (legacy) { props.put(Context.PROVIDER_URL, String.format("%s://%s:%s", "remote", "localhost", "4447")); } else { //props.put(Context.PROVIDER_URL, String.format("%s://%s:%s/wildfly-services", "https", "localhost", "8080")); props.put(Context.PROVIDER_URL, String.format("%s://%s:%s", "remote+http", "localhost", "8080")); } return props ; } /* * Run a failover test where the client communicates with the server via HTTP Upgrade over port 8080/8081 */ @Test public void testEJBClientUsingHttpUpgradeProtocol() throws Exception { log.infof(MODULE_NAME+ " : testing failover with client using HTTP Upgrade"); test(() -> new RemoteEJBDirectory(MODULE_NAME, getProperties(false))); } /* * Run a failover test where the client communicates with the server via legacy Remoting protocol over port 4447/4448 */ @Test public void testEJBClientUsingLegacyRemotingProtocol() throws Exception { log.infof(MODULE_NAME + " : testing failover with client using legacy Remoting"); test(() -> new RemoteEJBDirectory(MODULE_NAME, getProperties(true))); } /* * A SFSB failover test which accepts an EJBDirectory provider parameter to adjust client behaviour */ public void test(ExceptionSupplier<EJBDirectory, Exception> directoryProvider) throws Exception { try (EJBDirectory directory = directoryProvider.get()) { Incrementor bean = directory.lookupStateful(StatefulIncrementorBean.class, Incrementor.class); Result<Integer> result = bean.increment(); String target = result.getNode(); int count = 1; Assert.assertEquals(count++, result.getValue().intValue()); // Bean should retain weak affinity for this node for (int i = 0; i < COUNT; ++i) { result = bean.increment(); Assert.assertEquals(count++, result.getValue().intValue()); Assert.assertEquals(String.valueOf(i), target, result.getNode()); } undeploy(this.findDeployment(target)); Thread.sleep(CLIENT_TOPOLOGY_UPDATE_WAIT); result = bean.increment(); // Bean should failover to other node String failoverTarget = result.getNode(); Assert.assertEquals(count++, result.getValue().intValue()); Assert.assertNotEquals(target, failoverTarget); deploy(this.findDeployment(target)); // Allow sufficient time for client to receive new topology Thread.sleep(CLIENT_TOPOLOGY_UPDATE_WAIT); result = bean.increment(); String failbackTarget = result.getNode(); Assert.assertEquals(count++, result.getValue().intValue()); // Bean should retain weak affinity for this node Assert.assertEquals(failoverTarget, failbackTarget); result = bean.increment(); // Bean may have acquired new weak affinity target = result.getNode(); Assert.assertEquals(count++, result.getValue().intValue()); // Bean should retain weak affinity for this node for (int i = 0; i < COUNT; ++i) { result = bean.increment(); Assert.assertEquals(count++, result.getValue().intValue()); Assert.assertEquals(String.valueOf(i), target, result.getNode()); } stop(target); // Allow sufficient time for client to receive new topology Thread.sleep(CLIENT_TOPOLOGY_UPDATE_WAIT); result = bean.increment(); // Bean should failover to other node failoverTarget = result.getNode(); Assert.assertEquals(count++, result.getValue().intValue()); Assert.assertNotEquals(target, failoverTarget); start(target); // Allow sufficient time for client to receive new topology Thread.sleep(CLIENT_TOPOLOGY_UPDATE_WAIT); result = bean.increment(); failbackTarget = result.getNode(); Assert.assertEquals(count++, result.getValue().intValue()); // Bean should retain weak affinity for this node Assert.assertEquals(failoverTarget, failbackTarget); result = bean.increment(); // Bean may have acquired new weak affinity target = result.getNode(); Assert.assertEquals(count++, result.getValue().intValue()); // Bean should retain weak affinity for this node for (int i = 0; i < COUNT; ++i) { result = bean.increment(); Assert.assertEquals(count++, result.getValue().intValue()); Assert.assertEquals(String.valueOf(i), target, result.getNode()); } bean.remove(); } } /* * Set up the server to use both legacy and HTTP Upgrade remoting connectors */ public static class ServerSetupTask extends CLIServerSetupTask { public ServerSetupTask() { this.builder.node(TWO_NODES) .setup("/socket-binding-group=standard-sockets/socket-binding=remoting:add(port=4447)") .setup("/subsystem=remoting/connector=remoting-connector:add(socket-binding=remoting, sasl-authentication-factory=application-sasl-authentication)") .setup("/subsystem=remoting/connector=remoting-connector/property=SSL_ENABLED:add(value=false)") // this step results in a capabilities error if the list is not formatted correctly for CLI .setup("/subsystem=ejb3/service=remote:list-add(name=connectors, value=remoting-connector)") .teardown("/subsystem=ejb3/service=remote:list-remove(name=connectors, value=remoting-connector)") .teardown("/subsystem=remoting/connector=remoting-connector:remove") .teardown("/socket-binding-group=standard-sockets/socket-binding=remoting:remove") ; } } }
10,723
42.95082
168
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/ClientExceptionRemoteEJBTestCase.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.ejb.remote; import static org.junit.Assert.*; import java.util.PropertyPermission; import jakarta.ejb.EJBException; 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.ejb.remote.bean.Incrementor; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.IncrementorBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.InfinispanExceptionThrowingIncrementorBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Result; 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.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Test for WFLY-5788 and WFLY-9951. * * @author Radoslav Husar */ @RunWith(Arquillian.class) public class ClientExceptionRemoteEJBTestCase extends AbstractClusteringTestCase { private static final String MODULE_NAME = ClientExceptionRemoteEJBTestCase.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, Incrementor.class, IncrementorBean.class, InfinispanExceptionThrowingIncrementorBean.class) .setManifest(new StringAsset("Manifest-Version: 1.0\nDependencies: org.infinispan\n")) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new PropertyPermission(NODE_NAME_PROPERTY, "read")), "permissions.xml") ; } @Test public void test() throws Exception { try (EJBDirectory directory = new RemoteEJBDirectory(MODULE_NAME)) { Incrementor bean = directory.lookupStateful(InfinispanExceptionThrowingIncrementorBean.class, Incrementor.class); bean.increment(); fail("Expected EJBException but didn't catch it"); } catch (EJBException e) { assertNull("Cause of EJBException has not been removed", e.getCause()); } } }
3,973
42.195652
152
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/TransactionalRemoteStatefulEJBFailoverTestCase.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.ejb.remote; import java.util.PropertyPermission; import jakarta.ejb.NoSuchEJBException; import jakarta.transaction.UserTransaction; 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.ejb.remote.bean.Incrementor; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.IncrementorBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Result; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.StatefulIncrementorBean; import org.jboss.as.test.clustering.ejb.EJBDirectory; import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils; import org.jboss.ejb.client.EJBClient; 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; /** * Validates inhibition of failover behavior of a remotely accessed @Stateful EJB within the context of a transaction. * @author Paul Ferraro */ @RunWith(Arquillian.class) public class TransactionalRemoteStatefulEJBFailoverTestCase extends AbstractClusteringTestCase { private static final String MODULE_NAME = TransactionalRemoteStatefulEJBFailoverTestCase.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, Incrementor.class, IncrementorBean.class, StatefulIncrementorBean.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new PropertyPermission(NODE_NAME_PROPERTY, "read")), "permissions.xml") ; } @Test public void test( @ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) ManagementClient client1, @ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) ManagementClient client2 ) throws Exception { try (EJBDirectory directory = new RemoteEJBDirectory(MODULE_NAME)) { Incrementor bean = directory.lookupStateful(StatefulIncrementorBean.class, Incrementor.class); Result<Integer> result = bean.increment(); // Bean should retain weak affinity for this node String target = result.getNode(); int count = 1; Assert.assertEquals(count++, result.getValue().intValue()); // Validate that multi-invocations function correctly within a tx UserTransaction tx = EJBClient.getUserTransaction(target); // TODO Currently requires environment to be configured with provider URLs. // UserTransaction tx = directory.lookupUserTransaction(); tx.begin(); result = bean.increment(); Assert.assertEquals(count++, result.getValue().intValue()); Assert.assertEquals(target, result.getNode()); result = bean.increment(); Assert.assertEquals(count++, result.getValue().intValue()); Assert.assertEquals(target, result.getNode()); tx.commit(); // Validate that second invocation fails if target node is undeployed in middle of tx tx.begin(); result = bean.increment(); Assert.assertEquals(count++, result.getValue().intValue()); Assert.assertEquals(target, result.getNode()); undeploy(this.findDeployment(target)); try { result = bean.increment(); Assert.fail("Expected a NoSuchEJBException"); } catch (NoSuchEJBException e) { // Expected } finally { tx.rollback(); // TODO remove workaround for WFLY-12128 undeploy(TWO_DEPLOYMENTS); ServerReload.executeReloadAndWaitForCompletion(client1); ServerReload.executeReloadAndWaitForCompletion(client2); // Workaround the above yielding "DeploymentException: Cannot deploy StatefulFailoverTestCase.war: WFLYCTL0379: System boot is in process; execution of remote management operations is not currently available" Thread.sleep(GRACE_TIME_TOPOLOGY_CHANGE); } } } }
6,260
43.721429
224
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/ClientRemoteStatefulEJBFailoverTestCase.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.ejb.remote; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.as.test.clustering.ejb.ClientEJBDirectory; import org.jboss.shrinkwrap.api.Archive; public class ClientRemoteStatefulEJBFailoverTestCase extends AbstractRemoteStatefulEJBFailoverTestCase { private static final String MODULE_NAME = ClientRemoteStatefulEJBFailoverTestCase.class.getSimpleName(); @Deployment(name = DEPLOYMENT_1, managed = false, testable = false) @TargetsContainer(NODE_1) public static Archive<?> createDeploymentForContainer1() { return createDeployment(MODULE_NAME); } @Deployment(name = DEPLOYMENT_2, managed = false, testable = false) @TargetsContainer(NODE_2) public static Archive<?> createDeploymentForContainer2() { return createDeployment(MODULE_NAME); } public ClientRemoteStatefulEJBFailoverTestCase() { super(() -> new ClientEJBDirectory(MODULE_NAME)); } }
2,080
41.469388
108
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/ThreadAuthContextRemoteStatelessEJBFailoverTestCase.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.ejb.remote; /** * Validates failover behavior of a remotely accessed secure @Stateless EJB using a thread authentication context. * @author Paul Ferraro */ public class ThreadAuthContextRemoteStatelessEJBFailoverTestCase extends AuthContextRemoteStatelessEJBFailoverTestCase { public ThreadAuthContextRemoteStatelessEJBFailoverTestCase() { super(task -> () -> AUTHENTICATION_CONTEXT.runCallable(task)); } }
1,498
40.638889
120
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/ClientClusterNodeSelectorTestCase.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.ejb.remote; import org.apache.commons.lang3.RandomUtils; 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.ejb.remote.bean.Heartbeat; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.HeartbeatBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Result; import org.jboss.as.test.clustering.ejb.EJBDirectory; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils; import org.jboss.ejb.client.ClusterNodeSelector; import org.jboss.ejb.client.EJBClientConnection; import org.jboss.ejb.client.EJBClientContext; import org.jboss.ejb.protocol.remote.RemoteTransportProvider; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.naming.client.WildFlyInitialContextFactory; import javax.naming.Context; import javax.naming.InitialContext; import java.net.URI; import java.net.URL; import java.util.Date; import java.util.Properties; import java.util.PropertyPermission; /** * <p>Validates that the provided implementation of {@link ClusterNodeSelector} is being used by the Jakarta Enterprise Beans client to * select the node of the cluster to route the request to;</p> * <p>This relies on the cluster provisioning the client with a cluster view containing the correct affinity for the * Jakarta Enterprise Beans being invoked;</p> * <p>This test basically replicates test org.jboss.ejb.client.test.ClusterNodeSelectorTestCase in project * jboss-ejb-client (credits to <a href="mailto:rachmato@redhat.com">Richard Achmatowicz</a>);</p> * <p>This test was added after the functionality was broken because of the affinity not being correctly sent to the * client (refer to issue <a href="https://issues.jboss.org/browse/WFLY-10030">WFLY-10030</a>);</p> * <p>NOTE: this test can be run using the following command issued from the root directory of the whole WildFly project: * {@code ./integration-tests.sh test -Dts.noSmoke -Dts.clustering -Dtest=org.jboss.as.test.clustering.cluster.ejb.remote.ClientClusterNodeSelectorTestCase}</p> * * @author <a href="mailto:tborgato@redhat.com">Tommaso Borgato</a> */ @RunWith(Arquillian.class) public class ClientClusterNodeSelectorTestCase extends AbstractClusteringTestCase { private static final String MODULE_NAME = ClientClusterNodeSelectorTestCase.class.getSimpleName(); private static final long CLIENT_TOPOLOGY_UPDATE_WAIT = TimeoutUtil.adjust(2000); /** * Implementation of {@link ClusterNodeSelector} to be used for custom cluster node selection */ public static class CustomClusterNodeSelector implements ClusterNodeSelector { private static volatile String PICK_NODE = null; @Override public String selectNode(String clusterName, String[] connectedNodes, String[] totalAvailableNodes) { if (PICK_NODE != null) { return PICK_NODE; } return connectedNodes[0]; } } public ClientClusterNodeSelectorTestCase() { super(FOUR_NODES); } @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_3, managed = false, testable = false) @TargetsContainer(NODE_3) public static Archive<?> createDeploymentForContainer3() { return createDeployment(); } @Deployment(name = DEPLOYMENT_4, managed = false, testable = false) @TargetsContainer(NODE_4) public static Archive<?> createDeploymentForContainer4() { return createDeployment(); } /** * Instructs the ClusterNodeSelector on which node to call before each request and that checks that the response * comes from that very node; */ @Test public void test( @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1 ) throws Exception { EJBClientContext BKP = null; try { final EJBClientContext.Builder ejbClientBuilder = new EJBClientContext.Builder(); ejbClientBuilder.addTransportProvider(new RemoteTransportProvider()); final EJBClientConnection.Builder connBuilder = new EJBClientConnection.Builder(); connBuilder.setDestination(URI.create(String.format("remote+%s", baseURL1))); ejbClientBuilder.addClientConnection(connBuilder.build()); // ==================================================================================== // set the custom ClusterNodeSelector // ==================================================================================== ejbClientBuilder.setClusterNodeSelector(new CustomClusterNodeSelector()); BKP = EJBClientContext.getContextManager().getThreadDefault(); final EJBClientContext ejbCtx = ejbClientBuilder.build(); EJBClientContext.getContextManager().setThreadDefault(ejbCtx); Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, WildFlyInitialContextFactory.class.getName()); InitialContext ctx = new InitialContext(props); String lookupName = "ejb:/" + MODULE_NAME + "/" + HeartbeatBean.class.getSimpleName() + "!" + Heartbeat.class.getName(); Heartbeat bean = (Heartbeat) ctx.lookup(lookupName); // ==================================================================================== // first call goes to connected node regardless of CustomClusterNodeSelector // ==================================================================================== Result<Date> res = bean.pulse(); Thread.sleep(CLIENT_TOPOLOGY_UPDATE_WAIT); // ==================================================================================== // subsequent calls must be routed to the node selected by the CustomClusterNodeSelector // ==================================================================================== callBeanOnNode(bean, NODE_4); callBeanOnNode(bean, NODE_2); callBeanOnNode(bean, NODE_4); callBeanOnNode(bean, NODE_4); callBeanOnNode(bean, NODE_1); callBeanOnNode(bean, NODE_3); ctx.close(); } finally { EJBClientContext.getContextManager().setThreadDefault(BKP); } } /** * Calls the bean on the specified node and checks the response is coming from the specified node */ private void callBeanOnNode(Heartbeat bean, String node) { CustomClusterNodeSelector.PICK_NODE = node; Result<Date> res = bean.pulse(); Assert.assertEquals( String.format("%s not being used by the client to select cluster node! Request was routed to node %s instead of node %s! (check affinity value in logs)" , CustomClusterNodeSelector.class.getName() , res.getNode() , CustomClusterNodeSelector.PICK_NODE) , CustomClusterNodeSelector.PICK_NODE, res.getNode()); } /** * Test archive containing the Jakarta Enterprise Beans to call */ private static Archive<?> createDeployment() { return ShrinkWrap.create(JavaArchive.class, MODULE_NAME + ".jar") .addPackage(EJBDirectory.class.getPackage()) .addClasses(Result.class, Heartbeat.class, HeartbeatBean.class, RandomUtils.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new PropertyPermission(NODE_NAME_PROPERTY, "read")), "permissions.xml") ; } }
9,551
47.48731
168
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/TransactionalRemoteStatelessTestCase.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.ejb.remote; import java.net.URISyntaxException; import java.util.Hashtable; import java.util.PropertyPermission; import jakarta.ejb.NoSuchEJBException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.transaction.Status; import jakarta.transaction.UserTransaction; 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.container.ManagementClient; import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Incrementor; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.IncrementorBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Result; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.StatelessTransactionBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.StatelessTransactionNoResourceBean; import org.jboss.as.test.clustering.ejb.EJBDirectory; import org.jboss.as.test.integration.transactions.TransactionCheckerSingleton; import org.jboss.as.test.integration.transactions.TransactionCheckerSingletonRemote; import org.jboss.as.test.integration.transactions.RemoteLookups; 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.JavaArchive; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * <p> * This is a set of tests which verify how transaction affinity on standalone EJB client * works when client communicates with cluster. * When transaction is started then all EJB calls has to be strongly bound to the server * that the first call was run at.<br/> * A note: the subordinate transaction is not enlisted until it's used. It means the * <code>txn.begin()</code> does define affinity it's defined at time the bean call is run. * </p> * <p> * The client uses three different ways to define destination of the communication, * a.k.a. to define URL of the cluster where it aims to connect to. The test runs the three options: * <ul> * <li><code>wildfly-config.xml</code></li> * <li>during InitialContext creation, using <code>remote+http</code> protocol</li> * <li>during InitialContext creation, using <code>http</code> protocol * (see <a href="https://github.com/wildfly/wildfly-http-client">wildfly/wildfly-http-client</a></li> * </ul> * </p> */ @RunWith(Arquillian.class) @RunAsClient public class TransactionalRemoteStatelessTestCase extends AbstractClusteringTestCase { private static final String MODULE_NAME = TransactionalRemoteStatelessTestCase.class.getSimpleName(); private int node0Port = 8080; private int node1Port = 8180; private TransactionCheckerSingletonRemote checkerNode0, checkerNode1; private static enum InitialContextLookupType { REMOTE_HTTP, HTTP, WILDFLY_CONFIG } @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, Incrementor.class, IncrementorBean.class) .addClasses(StatelessTransactionBean.class, StatelessTransactionNoResourceBean.class) .addPackage(org.jboss.as.test.integration.transactions.TestXAResource.class.getPackage()) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( new PropertyPermission(NODE_NAME_PROPERTY, "read")), "permissions.xml"); } @Before public void setUp() { try { checkerNode0 = RemoteLookups.lookupEjbStateless( TESTSUITE_NODE0, node0Port, MODULE_NAME, TransactionCheckerSingleton.class, TransactionCheckerSingletonRemote.class); checkerNode1 = RemoteLookups.lookupEjbStateless( TESTSUITE_NODE1, node1Port, MODULE_NAME, TransactionCheckerSingleton.class, TransactionCheckerSingletonRemote.class); } catch (NamingException | URISyntaxException e) { new IllegalStateException(String.format("Cannot find singleton for checking " + "transaction state at '%s:%s'", TESTSUITE_NODE0, node0Port)); } checkerNode0.resetAll(); checkerNode1.resetAll(); checkAndCleanTransactionState(); } private void checkAndCleanTransactionState() { try { InitialContext initCtx = getInitialContext( InitialContextLookupType.WILDFLY_CONFIG, TESTSUITE_NODE0); UserTransaction txn = getUserTransaction(initCtx); if(txn.getStatus() == Status.STATUS_ACTIVE) { txn.rollback(); } } catch (Exception e) { log.errorf("Cannot check state and clean transaction to be obtained " + "from server defined in wildfly-config.xml", e); } } @Test public void affinityCommit_remoteHttp() throws Exception { affinityCommit(InitialContextLookupType.REMOTE_HTTP); } @Test public void affinityCommit_http() throws Exception { affinityCommit(InitialContextLookupType.HTTP); } @Test public void affinityCommit_wildflyConfig() throws Exception { affinityCommit(InitialContextLookupType.WILDFLY_CONFIG); } /** * Looking-up for two different beans under single transaction context. * The both beans should be called at the same node. * The node can be arbitrary but it has to be the one defined. */ private void affinityCommit(InitialContextLookupType lookupType) throws Exception { InitialContext initCtx = getInitialContext(lookupType, TESTSUITE_NODE0); String targetNode = null; UserTransaction txn = null; try { txn = getUserTransaction(initCtx); txn.begin(); Incrementor bean = getStatelessRemoteBean(initCtx, StatelessTransactionBean.class); Result<Integer> result = bean.increment(); Assert.assertEquals(1, result.getValue().intValue()); targetNode = result.getNode(); // lookup a different bean at the remote server while using the same context at client InitialContext initCtx2 = getInitialContext(lookupType, TESTSUITE_NODE1); Incrementor bean2 = getStatelessRemoteBean(initCtx2, StatelessTransactionNoResourceBean.class); Result<Integer> resultSecondCall = bean2.increment(); Assert.assertEquals(1, resultSecondCall.getValue().intValue()); Assert.assertEquals(targetNode, resultSecondCall.getNode()); txn.commit(); } catch (Exception e) { if(txn != null) txn.rollback(); throw e; } finally { initCtx.close(); } if(targetNode.equals(NODE_1)) { Assert.assertEquals("Transaction affinity was to '" + NODE_1 + "' the commit should be processed there", 1, checkerNode0.getCommitted()); Assert.assertEquals("Rollback at '" + NODE_1 + "' should not be called", 0, checkerNode0.getRolledback()); Assert.assertEquals("Two synchronizations were registered at '" + NODE_1 + "'", 2, checkerNode0.countSynchronizedAfterCommitted()); Assert.assertEquals("Expected no commit to be run at " + NODE_2, 0, checkerNode1.getCommitted()); Assert.assertEquals("Expected no rollback to be run at " + NODE_2, 0, checkerNode1.getRolledback()); } else if (targetNode.equals(NODE_2)) { Assert.assertEquals("Expected no commit to be run at " + NODE_1, 0, checkerNode0.getCommitted()); Assert.assertEquals("Expected no rollback to be run at " + NODE_1, 0, checkerNode0.getRolledback()); Assert.assertEquals("Transaction affinity was to '" + NODE_2 + "' the commit should be processed there", 1, checkerNode1.getCommitted()); Assert.assertEquals("Rollback at '" + NODE_2 + "' should not be called", 0, checkerNode1.getRolledback()); Assert.assertEquals("Two synchronizations were registered at '" + NODE_2 + "'", 2, checkerNode1.countSynchronizedAfterCommitted()); } else { Assert.fail(String.format("Expecting one of the nodes [%s,%s] should be hit " + "by the bean call but the target node was not expected '%s'", NODE_1, NODE_2, targetNode)); } } /** * Purpose of the test is to verify that <code>remote+http</code> {@link InitialContext} * lookup uses the URL hostname which is defined in the JNDI properties * during the context creation. When non-existing URL is provided * then the failure is expected. */ @Test public void directLookupFailure () throws Exception { InitialContext initCtx = getInitialContext(InitialContextLookupType.REMOTE_HTTP, "non-existing-hostname"); try { Incrementor bean = getStatelessRemoteBean(initCtx, StatelessTransactionBean.class); bean.increment(); Assert.fail("Expected a Exception as the bean is not deployed at 'node-3'" + "while the initial context points the lookup there"); } catch (org.jboss.ejb.client.RequestSendFailedException expected) { // expected as the deployment was removed from the node } } @Test public void rollback_remoteHttp() throws Exception { rollback(InitialContextLookupType.REMOTE_HTTP); } @Test public void rollback_http() throws Exception { rollback(InitialContextLookupType.HTTP); } @Test public void rollback_wildflyConfig() throws Exception { rollback(InitialContextLookupType.WILDFLY_CONFIG); } /** * Checking if the rollback is commanded to the remote node * when the remotely looked-up transaction is rolled-back on the client side. */ private void rollback (InitialContextLookupType lookupType) throws Exception { InitialContext initCtx = getInitialContext(lookupType, TESTSUITE_NODE0); String targetNode = null; UserTransaction txn = null; try { Incrementor bean = getStatelessRemoteBean(initCtx, StatelessTransactionBean.class); txn = getUserTransaction(initCtx); txn.begin(); Result<Integer> result = bean.increment(); Assert.assertEquals(1, result.getValue().intValue()); targetNode = result.getNode(); txn.rollback(); } catch (Exception e) { if(txn != null) txn.rollback(); throw e; } finally { initCtx.close(); } if(targetNode.equals(NODE_1)) { Assert.assertEquals("Commit at '" + NODE_1 + "' should not be called", 0, checkerNode0.getCommitted()); Assert.assertEquals("Transaction affinity was to '" + NODE_1 + "' the rollback should be processed there", 1, checkerNode0.getRolledback()); Assert.assertEquals("A synchronization was registered at '" + NODE_1 + "'", 1, checkerNode0.countSynchronizedAfterRolledBack()); Assert.assertEquals("Expected no commit to be run at " + NODE_2, 0, checkerNode1.getCommitted()); Assert.assertEquals("Expected no rollback to be run at " + NODE_2, 0, checkerNode1.getRolledback()); } else if (targetNode.equals(NODE_2)) { Assert.assertEquals("Expected no commit to be run at " + NODE_1, 0, checkerNode0.getCommitted()); Assert.assertEquals("Expected no rollback to be run at " + NODE_1, 0, checkerNode0.getRolledback()); Assert.assertEquals("Commit at '" + NODE_2 + "' should not be called", 0, checkerNode1.getCommitted()); Assert.assertEquals("Transaction affinity was to '" + NODE_2 + "' the rollback should be processed there", 1, checkerNode1.getRolledback()); Assert.assertEquals("A synchronization was registered at '" + NODE_2 + "'", 1, checkerNode1.countSynchronizedAfterRolledBack()); } else { Assert.fail(String.format("Expecting one of the nodes [%s,%s] should be hit " + "by the bean call but the target node was not expected '%s'", NODE_1, NODE_2, targetNode)); } } /** * Rollback has to be run when commanded at the client side * despite there is no real resource enlisted to the transaction at the server side. */ @Test public void rollbackWithNoXAResourceEnlistment () throws Exception { InitialContext initCtx = getInitialContext(InitialContextLookupType.REMOTE_HTTP, TESTSUITE_NODE0); Result<Integer> result = null; UserTransaction txn = null; try { Incrementor bean = getStatelessRemoteBean(initCtx, StatelessTransactionNoResourceBean.class); txn = getUserTransaction(initCtx); txn.begin(); result = bean.increment(); Assert.assertEquals(1, result.getValue().intValue()); txn.rollback(); } catch (Exception e) { if(txn != null) txn.rollback(); throw e; } finally { initCtx.close(); } if(result.getNode().equals(NODE_1)) { Assert.assertFalse("Transaction was rolled-back at " + NODE_1 + "Synchronization.beforeCompletion can't be called", checkerNode0.isSynchronizedBefore()); Assert.assertEquals("Transaction was rolled-back at " + NODE_1 + ", after synchronization callback needs to be called", 1, checkerNode0.countSynchronizedAfterRolledBack()); Assert.assertFalse("Expected no beforeCompletion to be run at " + NODE_2, checkerNode1.isSynchronizedBefore()); Assert.assertFalse("Expected no afterCompletion to be run at " + NODE_2, checkerNode1.isSynchronizedAfter()); } else if (result.getNode().equals(NODE_2)) { Assert.assertFalse("Expected no beforeCompletion to be run at " + NODE_1, checkerNode0.isSynchronizedBefore()); Assert.assertFalse("Expected no afterCompletion to be run at " + NODE_1, checkerNode0.isSynchronizedAfter()); Assert.assertFalse("Transaction was rolled-back at " + NODE_2 + "Synchronization.beforeCompletion can't be called", checkerNode1.isSynchronizedBefore()); Assert.assertEquals("Transaction was rolled-back at " + NODE_2 + ", after synchronization callback needs to be called", 1, checkerNode1.countSynchronizedAfterRolledBack()); } else { Assert.fail(String.format("Expecting one of the nodes [%s,%s] should be hit " + "by the bean call but the target node was not expected '%s'", NODE_1, NODE_2, result.getNode())); } } /** * This is a similar test to * {@link TransactionalRemoteStatefulEJBFailoverTestCase#test(ManagementClient, ManagementClient)} * but this test works with a stateless bean. */ @Test public void affinityNodeFailure () throws Exception { InitialContext initCtx = getInitialContext(InitialContextLookupType.REMOTE_HTTP, TESTSUITE_NODE0); String targetNode = null; UserTransaction txn = null; try { txn = getUserTransaction(initCtx); txn.begin(); Incrementor bean = getStatelessRemoteBean(initCtx, StatelessTransactionBean.class); Result<Integer> result = bean.increment(); int count = 1; Assert.assertEquals(count++, result.getValue().intValue()); targetNode = result.getNode(); undeploy(this.findDeployment(targetNode)); try { result = bean.increment(); Assert.fail("Expected a NoSuchEJBException as transaction affinity needs to be maintained"); } catch (NoSuchEJBException | AssertionError expected) { // expected as the deployment was removed from the node } } finally { if(txn != null) txn.rollback(); initCtx.close(); } } private Incrementor getStatelessRemoteBean(InitialContext ctx, Class<? extends Incrementor> beanClass) { return getRemoteBean(ctx, beanClass, false); } private Incrementor getRemoteBean(InitialContext ctx, Class<? extends Incrementor> beanClass, boolean isStateful) { String lookupBeanUrl = "ejb:/" + MODULE_NAME +"/" + beanClass.getSimpleName() + "!" + Incrementor.class.getName(); if(isStateful) lookupBeanUrl += "?stateful"; try { return (Incrementor) ctx.lookup(lookupBeanUrl); } catch (NamingException ne) { throw new IllegalStateException(String.format("Cannot find ejb bean '%s' while " + "looking up for name '%s'", beanClass, lookupBeanUrl), ne); } } private UserTransaction getUserTransaction(InitialContext ctx) { String lookupUserTransaction = "txn:RemoteUserTransaction"; try { return (UserTransaction) ctx.lookup(lookupUserTransaction); } catch (NamingException ne) { throw new IllegalStateException(String.format("Cannot look up '%s' at context: %s", ctx, lookupUserTransaction), ne); } } private InitialContext getInitialContext(InitialContextLookupType lookupType, String nodeHostName) { final Hashtable<String, String> jndiProperties = new Hashtable<>(); jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.wildfly.naming.client.WildFlyInitialContextFactory"); if(nodeHostName.contains(":") && !nodeHostName.contains("[")) { nodeHostName = "[" + nodeHostName + "]"; // escaping host and port for IPv6 } String lookupProviderUrl = "<see wildfly-config.xml>"; switch(lookupType) { case HTTP: lookupProviderUrl = String.format("http://%s:%s/wildfly-services", nodeHostName, node0Port); jndiProperties.put(Context.PROVIDER_URL, lookupProviderUrl); // see server/configuration/application-users.properties jndiProperties.put(Context.SECURITY_PRINCIPAL, "user1"); jndiProperties.put(Context.SECURITY_CREDENTIALS, "password1"); break; case REMOTE_HTTP: lookupProviderUrl = String.format("remote+http://%s:%s", nodeHostName, node0Port); jndiProperties.put(Context.PROVIDER_URL, lookupProviderUrl); break; case WILDFLY_CONFIG: default: // leaving as it is, remote host config taken from the client's wildfly-config.xml log.debugf("Not using value '%s' of nodeHostName parameter, " + "wildfly-config.xml defines the URL on its own", nodeHostName); } try { return new InitialContext(jndiProperties); } catch (NamingException ne) { throw new IllegalStateException(String.format( "Cannot create InitialContext with url provider '%s'", lookupProviderUrl), ne); } } }
21,190
45.986696
152
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/GlobalAuthContextRemoteStatelessEJBFailoverTestCase.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.ejb.remote; import java.util.function.UnaryOperator; import org.junit.AfterClass; import org.junit.BeforeClass; import org.wildfly.security.auth.client.AuthenticationContext; /** * Validates failover behavior of a remotely accessed secure @Stateless EJB using a global authentication context. * @author Farah Juma * @author Paul Ferraro */ public class GlobalAuthContextRemoteStatelessEJBFailoverTestCase extends AuthContextRemoteStatelessEJBFailoverTestCase { private static AuthenticationContext previousContext; @BeforeClass public static void before() { previousContext = AuthenticationContext.captureCurrent(); AuthenticationContext.getContextManager().setGlobalDefault(AUTHENTICATION_CONTEXT); } @AfterClass public static void after() { AuthenticationContext.getContextManager().setGlobalDefault(previousContext); } public GlobalAuthContextRemoteStatelessEJBFailoverTestCase() { super(UnaryOperator.identity()); } }
2,069
37.333333
120
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/SuspendResumeRemoteEJBTestCase.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.ejb.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.ejb.remote.bean.Heartbeat; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.HeartbeatBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Result; 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.SUCCESS; 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.NAME; /** * Test for WFLY-13871. * <p> * 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 SuspendResumeRemoteEJBTestCase extends AbstractClusteringTestCase { static final Logger LOGGER = Logger.getLogger(SuspendResumeRemoteEJBTestCase.class); private static final String MODULE_NAME = SuspendResumeRemoteEJBTestCase.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, Heartbeat.class, HeartbeatBean.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 = 10; final int SUSPEND_RESUME_LOOP_TIMES = 10; // 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. * <p> * 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)) { Heartbeat bean = directory.lookupStateless(HeartbeatBean.class, Heartbeat.class); 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. * <p> * 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); Heartbeat bean = directory.lookupStateless(HeartbeatBean.class, Heartbeat.class); 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. * <p> * 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)) { Heartbeat bean = directory.lookupStateless(HeartbeatBean.class, Heartbeat.class); ContinuousInvoker continuousInvoker = new ContinuousInvoker(bean); Thread thread = new Thread(continuousInvoker); LOGGER.info("Starting the invoker ..."); thread.start(); for (int i = 1; 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()); } finally { 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; Heartbeat bean = null; public ContinuousInvoker(Heartbeat 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(Heartbeat 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 } } }
15,622
37.012165
152
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/RemoteStatefulEJBFailoverTestCase.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.ejb.remote; import java.util.PropertyPermission; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Incrementor; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.IncrementorBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Result; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.StatefulIncrementorBean; 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.JavaArchive; /** * @author Paul Ferraro */ public class RemoteStatefulEJBFailoverTestCase extends AbstractRemoteStatefulEJBFailoverTestCase { private static final String MODULE_NAME = RemoteStatefulEJBFailoverTestCase.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, Incrementor.class, IncrementorBean.class, StatefulIncrementorBean.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new PropertyPermission(NODE_NAME_PROPERTY, "read")), "permissions.xml") ; } public RemoteStatefulEJBFailoverTestCase() { super(() -> new RemoteEJBDirectory(MODULE_NAME)); } }
3,114
43.5
152
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/RemoteStatefulEJBConcurrentFailoverTestCase.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.ejb.remote; import java.util.PropertyPermission; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; 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.ejb.remote.bean.Incrementor; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.IncrementorBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Result; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.SlowStatefulIncrementorBean; import org.jboss.as.test.clustering.ejb.EJBDirectory; import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory; import org.jboss.as.test.shared.TimeoutUtil; 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.JavaArchive; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; /** * Validates mid-invocation failover behavior of a remotely accessed @Stateful EJB. * @author Paul Ferraro */ @RunWith(Arquillian.class) @Ignore("WFLY-11322") public class RemoteStatefulEJBConcurrentFailoverTestCase extends AbstractClusteringTestCase { private static final String MODULE_NAME = RemoteStatefulEJBConcurrentFailoverTestCase.class.getSimpleName(); private static final long CLIENT_TOPOLOGY_UPDATE_WAIT = TimeoutUtil.adjust(5000); @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, Incrementor.class, IncrementorBean.class, SlowStatefulIncrementorBean.class) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new PropertyPermission(NODE_NAME_PROPERTY, "read")), "permissions.xml") ; } @Test public void test() throws Exception { this.test(new GracefulRestartLifecycle()); } public void test(Lifecycle lifecycle) throws Exception { try (EJBDirectory directory = new RemoteEJBDirectory(MODULE_NAME)) { Incrementor bean = directory.lookupStateful(SlowStatefulIncrementorBean.class, Incrementor.class); AtomicInteger count = new AtomicInteger(); // Allow sufficient time for client to receive full topology Thread.sleep(CLIENT_TOPOLOGY_UPDATE_WAIT); String target = bean.increment().getNode(); count.incrementAndGet(); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); try { CountDownLatch latch = new CountDownLatch(1); Future<?> future = executor.scheduleWithFixedDelay(new IncrementTask(bean, count, latch), 0, 1, TimeUnit.MILLISECONDS); latch.await(); lifecycle.stop(target); future.cancel(false); try { future.get(); } catch (CancellationException e) { // Ignore } bean.remove(); lifecycle.start(target); latch = new CountDownLatch(1); future = executor.scheduleWithFixedDelay(new LookupTask(directory, SlowStatefulIncrementorBean.class, latch), 0, 1, TimeUnit.MILLISECONDS); latch.await(); lifecycle.stop(target); future.cancel(false); try { future.get(); } catch (CancellationException e) { // Ignore } lifecycle.start(target); } finally { executor.shutdownNow(); } } } private class IncrementTask implements Runnable { private final Incrementor bean; private final CountDownLatch latch; private final AtomicInteger value; IncrementTask(Incrementor bean, AtomicInteger value, CountDownLatch latch) { this.bean = bean; this.value = value; this.latch = latch; } @Override public void run() { try { int value = this.bean.increment().getValue(); Assert.assertEquals(this.value.incrementAndGet(), value); } finally { this.latch.countDown(); } } } private class LookupTask implements Runnable { private final EJBDirectory directory; private final Class<? extends Incrementor> beanClass; private final CountDownLatch latch; LookupTask(EJBDirectory directory, Class<? extends Incrementor> beanClass, CountDownLatch latch) { this.directory = directory; this.beanClass = beanClass; this.latch = latch; } @Override public void run() { try { this.directory.lookupStateful(this.beanClass, Incrementor.class).remove(); } catch (Exception e) { throw new IllegalStateException(e); } finally { this.latch.countDown(); } } } }
7,147
38.274725
155
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/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.ejb.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,666
33.020408
89
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/bean/SlowHeartbeatBean.java
package org.jboss.as.test.clustering.cluster.ejb.remote.bean; import java.util.concurrent.TimeUnit; import jakarta.ejb.Remote; import jakarta.ejb.Stateless; import java.util.Date; @Stateless @Remote(Heartbeat.class) public class SlowHeartbeatBean implements Heartbeat { @Override 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); } } }
607
20.714286
61
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/bean/PassivationDisabledStatefulIncrementorBean.java
package org.jboss.as.test.clustering.cluster.ejb.remote.bean; import jakarta.ejb.Remote; import jakarta.ejb.Stateful; /** * SFSB with passivation disabled, behaves as a singleton bean even if deployed on a clustered node * * @author Paul Ferarro */ @Stateful(passivationCapable = false) @Remote(Incrementor.class) public class PassivationDisabledStatefulIncrementorBean extends IncrementorBean { }
404
26
99
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/bean/InfinispanExceptionThrowingIncrementorBean.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.ejb.remote.bean; import jakarta.ejb.Remote; import jakarta.ejb.Stateful; import org.infinispan.commons.CacheException; import org.infinispan.util.concurrent.TimeoutException; /** * Implementation of {@link Incrementor} which always throws a standard remotable (known to a client classloader) exception * which is caused by an Infinispan {@link RuntimeException} {@link CacheException} {@link TimeoutException} which the client * typically cannot load the class for. * * @author Radoslav Husar */ @Stateful @Remote(Incrementor.class) public class InfinispanExceptionThrowingIncrementorBean implements Incrementor { @Override public Result<Integer> increment() { throw new IllegalStateException("standard remotable exception that is caused by non-remotable infinispan CacheException", new TimeoutException("the non-remotable infinispan cause")); } }
1,947
40.446809
190
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/bean/SecureStatelessIncrementorBean.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.ejb.remote.bean; import jakarta.annotation.security.RolesAllowed; import jakarta.ejb.Remote; import jakarta.ejb.Stateless; import org.jboss.ejb3.annotation.SecurityDomain; @Stateless @SecurityDomain("other") @Remote(Incrementor.class) public class SecureStatelessIncrementorBean extends IncrementorBean { @RolesAllowed({"Role1", "Role2", "Users"}) @Override public Result<Integer> increment() { return super.increment(); } }
1,521
36.121951
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/bean/StatefulIncrementorBean.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.ejb.remote.bean; import jakarta.ejb.Remote; import jakarta.ejb.Stateful; @Stateful @Remote(Incrementor.class) public class StatefulIncrementorBean extends IncrementorBean { }
1,245
39.193548
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/bean/StatelessTransactionBean.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.ejb.remote.bean; import jakarta.annotation.Resource; import jakarta.ejb.EJB; import jakarta.ejb.Remote; import jakarta.ejb.Stateless; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import jakarta.transaction.TransactionManager; import org.jboss.as.test.integration.transactions.TransactionCheckerSingleton; import org.jboss.as.test.integration.transactions.TxTestUtil; @Stateless @Remote(Incrementor.class) @TransactionAttribute(TransactionAttributeType.MANDATORY) public class StatelessTransactionBean extends IncrementorBean { @EJB private TransactionCheckerSingleton txnChecker; @Resource(lookup = "java:/TransactionManager") private TransactionManager tm; @Override public Result<Integer> increment() { TxTestUtil.addSynchronization(tm, txnChecker); TxTestUtil.enlistTestXAResource(tm, txnChecker); return super.increment(); } }
1,997
37.423077
78
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/bean/SlowStatefulIncrementorBean.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.ejb.remote.bean; import java.util.concurrent.TimeUnit; import jakarta.annotation.PostConstruct; import jakarta.ejb.Remote; import jakarta.ejb.Stateful; @Stateful @Remote(Incrementor.class) public class SlowStatefulIncrementorBean extends IncrementorBean { @Override public Result<Integer> increment() { delay(); return super.increment(); } @PostConstruct public void init() { delay(); } private static void delay() { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { throw new IllegalStateException(e); } } }
1,705
31.188679
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/bean/StatelessIncrementorBean.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.ejb.remote.bean; import jakarta.ejb.Remote; import jakarta.ejb.Stateless; /** * @author Paul Ferraro */ @Stateless @Remote(Incrementor.class) public class StatelessIncrementorBean extends IncrementorBean { }
1,280
36.676471
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/bean/HeartbeatBean.java
package org.jboss.as.test.clustering.cluster.ejb.remote.bean; import jakarta.ejb.Remote; import jakarta.ejb.Stateless; import java.util.Date; @Stateless @Remote(Heartbeat.class) public class HeartbeatBean implements Heartbeat { @Override public Result<Date> pulse() { Date now = new Date(); return new Result<>(now); } }
352
19.764706
61
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/bean/ClientIncrementorBean.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.ejb.remote.bean; import jakarta.annotation.PostConstruct; import jakarta.ejb.Remote; import jakarta.ejb.Stateful; import javax.naming.NamingException; import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory; @Stateful(passivationCapable = false) @Remote(Incrementor.class) public class ClientIncrementorBean implements Incrementor { public static final String MODULE = "remote"; private Incrementor locator; @PostConstruct public void postConstruct() { try (RemoteEJBDirectory directory = new RemoteEJBDirectory(MODULE)) { this.locator = directory.lookupStateful(StatefulIncrementorBean.class, Incrementor.class); } catch (NamingException e) { throw new IllegalStateException(e); } } @Override public Result<Integer> increment() { return this.locator.increment(); } }
1,933
36.192308
102
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/bean/StatelessTransactionNoResourceBean.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.ejb.remote.bean; import jakarta.annotation.Resource; import jakarta.ejb.EJB; import jakarta.ejb.Remote; import jakarta.ejb.Stateless; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import jakarta.transaction.TransactionSynchronizationRegistry; import org.jboss.as.test.integration.transactions.TransactionCheckerSingleton; import org.jboss.as.test.integration.transactions.TxTestUtil; @Stateless @Remote(Incrementor.class) @TransactionAttribute(TransactionAttributeType.MANDATORY) public class StatelessTransactionNoResourceBean extends IncrementorBean { @EJB TransactionCheckerSingleton txnChecker; @Resource private TransactionSynchronizationRegistry transactionSynchronizationRegistry; @Override public Result<Integer> increment() { TxTestUtil.addSynchronization(transactionSynchronizationRegistry, txnChecker); return super.increment(); } }
2,001
38.254902
86
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/bean/Heartbeat.java
package org.jboss.as.test.clustering.cluster.ejb.remote.bean; import java.util.Date; public interface Heartbeat { Result<Date> pulse(); }
144
17.125
61
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/bean/IncrementorBean.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.ejb.remote.bean; import java.util.concurrent.atomic.AtomicInteger; public abstract class IncrementorBean implements Incrementor { private final AtomicInteger count = new AtomicInteger(); @Override public Result<Integer> increment() { return new Result<>(this.count.incrementAndGet()); } }
1,385
38.6
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/bean/Incrementor.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.ejb.remote.bean; import jakarta.ejb.Remove; public interface Incrementor { Result<Integer> increment(); @Remove default void remove() { // Do nothing } }
1,249
35.764706
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/byteman/LastNodeToLeaveTestHelper.java
package org.jboss.as.test.clustering.cluster.ejb.remote.byteman; import org.jboss.byteman.rule.helper.Helper; import org.jboss.byteman.rule.Rule; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; public class LastNodeToLeaveTestHelper extends Helper { private static final String NODE_LIST_MAP_NAME = "nodeListMap"; private static final String STARTED_NODES_MAP_NAME = "startedNodesMap"; private static final String STARTED_NODES_SET_NAME = "startedNodesSet"; public LastNodeToLeaveTestHelper(Rule rule) { super(rule); } /* * Create a map to store DNR data: one List per thread * * Sample rule: * * @BMRule(name = "Set up results linkMap (SETUP)", * targetClass = "org.jboss.ejb.protocol.remote.RemotingEJBDiscoveryProvider", * targetMethod = "<init>", * helper = "org.jboss.as.test.clustering.cluster.ejb.remote.byteman.LastNodeToLeaveTestHelper", * targetLocation = "EXIT", * condition = "debug(\" setting up the map \")", * action = "createNodeListMap();"), */ public void createNodeListMap() { createLinkMap(NODE_LIST_MAP_NAME); createLinkMap(STARTED_NODES_MAP_NAME); } /* * Create a map to store started nodes * * Sample rule: * */ public void updateStartedNodes(Set<String> startedNodes) { link(STARTED_NODES_MAP_NAME,STARTED_NODES_SET_NAME, startedNodes); } /* * Add node data current at the time of invocation to the list * * Sample rule: * * @BMRule(name = "Track calls to ClusterNodeSelector (COLLECT)", * isInterface = false, * targetClass = "LastNodeToLeaveRemoteEJBTestCase$CustomClusterNodeSelector", * targetMethod = "selectNode", * helper = "org.jboss.as.test.clustering.cluster.ejb.remote.byteman.LastNodeToLeaveTestHelper", * binding = "clusterName : String = $1;connectedNodes : String[] = $2; totalAvailableNodes : String[] = $3;", * condition = "debug(\"checking the condition\")", * action = "addConnectedNodesEntryForThread(clusterName, connectedNodes, totalAvailableNodes);"), */ @SuppressWarnings("unchecked") public void addConnectedNodesEntryForThread(String clusterName, String[] connectedNodes, String[] totalAvailableNodes) { String threadName = Thread.currentThread().getName(); Set<String> connectedNodesSet = Arrays.asList(connectedNodes).stream().collect(Collectors.toSet()); Set<String> totalNodesSet = Arrays.asList(totalAvailableNodes).stream().collect(Collectors.toSet()); Set<String> startedNodesSet = (Set<String>) linked(STARTED_NODES_MAP_NAME, STARTED_NODES_SET_NAME); List<Set<String>> nodesEntry = new ArrayList<>(); nodesEntry.add(startedNodesSet); nodesEntry.add(connectedNodesSet); nodesEntry.add(totalNodesSet); List<List<Set<String>>> threadNodesEntryList = (List<List<Set<String>>>) linked(NODE_LIST_MAP_NAME, threadName); if (threadNodesEntryList == null) { threadNodesEntryList = new ArrayList<>(); } threadNodesEntryList.add(nodesEntry); link(NODE_LIST_MAP_NAME, threadName, threadNodesEntryList); } /* * Add node data current at the time of invocation to the list * * Sample rule: * * @BMRule(name = "Track current state of nodes used for discovery (COLLECT)", * targetClass = "org.jboss.ejb.protocol.remote.RemotingEJBDiscoveryProvider", * targetMethod = "discover", * helper = "org.jboss.as.test.clustering.cluster.ejb.remote.byteman.LastNodeToLeaveTestHelper", * binding = "provider : RemotingEJBDiscoveryProvider = $0", * condition = "debug(\"checking the condition\")", * action = "addDNREntryForThread(provider.nodes.keySet());"), */ @SuppressWarnings("unchecked") public void addDNREntryForThread(Set<String> newNodeList) { String threadName = Thread.currentThread().getName(); List<Set<String>> threadNodeList = (List<Set<String>>) linked(NODE_LIST_MAP_NAME, threadName); if (threadNodeList == null) { threadNodeList = new ArrayList<>(); } threadNodeList.add(newNodeList); link(NODE_LIST_MAP_NAME, threadName, threadNodeList); } /* * Retrieve the node data from the rule and pass to the test case */ @SuppressWarnings("unchecked") public Map<String,List<List<Set<String>>>> getNodeListMap() { System.out.println("*** Getting results"); ConcurrentHashMap<String, List<List<Set<String>>>> results = new ConcurrentHashMap<>(); for (Object threadNameAsObject : linkNames(NODE_LIST_MAP_NAME)) { String threadNameAsString = (String) threadNameAsObject; List<List<Set<String>>> threadValues = (List<List<Set<String>>>) linked(NODE_LIST_MAP_NAME, threadNameAsString); results.put(threadNameAsString, threadValues); } return results; } }
5,194
39.271318
124
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/remote/byteman/LastNodeToLeaveRemoteEJBTestCase.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.ejb.remote.byteman; 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.extension.byteman.api.BMRules; import org.jboss.arquillian.extension.byteman.api.BMRule; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Incrementor; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.IncrementorBean; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.Result; import org.jboss.as.test.clustering.cluster.ejb.remote.bean.StatelessIncrementorBean; import org.jboss.as.test.clustering.ejb.EJBDirectory; import org.jboss.as.test.clustering.ejb.NamingEJBDirectory; import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils; import org.jboss.ejb.client.ClusterNodeSelector; import org.jboss.ejb.client.EJBClientConnection; import org.jboss.ejb.client.EJBClientContext; import org.jboss.ejb.protocol.remote.RemoteTransportProvider; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import jakarta.ejb.EJBException; import jakarta.ejb.NoSuchEJBException; import javax.naming.NamingException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PropertyPermission; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.stream.Collectors; import static org.junit.Assert.assertNull; /** * * Tests the ability of the the RemoteEJBDiscoveryProvider to detect the condition when a last node left in a cluster has crashed * and to remove that cluster from the discovered node registry (DNR). * The condition is as follows: if we get a ConnectException when trying to connect to a node X in cluster Y, and the DNR shows * X as being the only member of Y, then remove cluster Y from the DNR. * * This test implements a validation criterion which ensures that the following illegal scenario does not occur: * - start two cluster nodes A, B: // membership = {A,B} * - shutdown A // membership = {B} * - crash B // membership = {B} * - start A // membership = {A,B} * In this case, B is a member of the cluster (according to the DNR) but it has crashed. * * @author Richard Achmatowicz */ @RunWith(Arquillian.class) public class LastNodeToLeaveRemoteEJBTestCase extends AbstractClusteringTestCase { public LastNodeToLeaveRemoteEJBTestCase() throws Exception { super(THREE_NODES); } static final Logger LOGGER = Logger.getLogger(LastNodeToLeaveRemoteEJBTestCase.class); private static final String MODULE_NAME = LastNodeToLeaveRemoteEJBTestCase.class.getSimpleName(); private static final long INVOCATION_WAIT = TimeoutUtil.adjust(1000); private static final int THREADS = 2; @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_3, managed = false, testable = false) @TargetsContainer(NODE_3) public static Archive<?> createDeploymentForContainer3() { return createDeployment(); } private static Archive<?> createDeployment() { return ShrinkWrap.create(JavaArchive.class, MODULE_NAME + ".jar") .addPackage(EJBDirectory.class.getPackage()) .addClasses(Result.class, Incrementor.class, IncrementorBean.class, StatelessIncrementorBean.class) .setManifest(new StringAsset("Manifest-Version: 1.0\nDependencies: org.infinispan\n")) .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new PropertyPermission(NODE_NAME_PROPERTY, "read")), "permissions.xml") ; } public class CustomClusterNodeSelector implements ClusterNodeSelector { @Override public String selectNode(String clusterName, String[] connectedNodes, String[] totalAvailableNodes) { Set<String> connectedNodesSet = Arrays.asList(connectedNodes).stream().collect(Collectors.toSet()); Set<String> totalNodesSet = Arrays.asList(totalAvailableNodes).stream().collect(Collectors.toSet()); LOGGER.debugf("Calling ClusterNodeSelector.selectNode(%s,%s,%s)", clusterName, connectedNodesSet, totalNodesSet); return ClusterNodeSelector.DEFAULT.selectNode(clusterName, connectedNodes, totalAvailableNodes); } } // Byteman rules to capture the DNR contents after each invocation @BMRules({ @BMRule(name = "Set up results linkMap (SETUP)", targetClass = "org.jboss.ejb.protocol.remote.RemotingEJBDiscoveryProvider", targetMethod = "<init>", helper = "org.jboss.as.test.clustering.cluster.ejb.remote.byteman.LastNodeToLeaveTestHelper", targetLocation = "EXIT", condition = "debug(\" setting up the map \")", action = "createNodeListMap();"), @BMRule(name = "Track calls to start (COLLECT)", targetClass = "org.jboss.as.test.clustering.cluster.ejb.remote.byteman.LastNodeToLeaveRemoteEJBTestCase", targetMethod = "getStartedNodes", helper = "org.jboss.as.test.clustering.cluster.ejb.remote.byteman.LastNodeToLeaveTestHelper", targetLocation = "EXIT", binding = "startedNodes = $!;", condition = "debug(\"checking for started nodes\")", action = "updateStartedNodes(startedNodes);"), @BMRule(name = "Track calls to ClusterNodeSelector (COLLECT)", targetClass = "org.jboss.as.test.clustering.cluster.ejb.remote.byteman.LastNodeToLeaveRemoteEJBTestCase$CustomClusterNodeSelector", targetMethod = "selectNode", helper = "org.jboss.as.test.clustering.cluster.ejb.remote.byteman.LastNodeToLeaveTestHelper", binding = "clusterName : String = $1;connectedNodes : String[] = $2; totalAvailableNodes : String[] = $3;", condition = "debug(\"checking call to cluster node selector\")", action = "addConnectedNodesEntryForThread(clusterName, connectedNodes, totalAvailableNodes);"), @BMRule(name="Return test result to test case (RETURN)", targetClass = "org.jboss.as.test.clustering.cluster.ejb.remote.byteman.LastNodeToLeaveRemoteEJBTestCase", targetMethod = "getTestResult", helper = "org.jboss.as.test.clustering.cluster.ejb.remote.byteman.LastNodeToLeaveTestHelper", targetLocation = "ENTRY", condition = "debug(\"returning the result\")", action = "return getNodeListMap();") }) @Test @RunAsClient public void testDNRContentsAfterLastNodeToLeave() throws Exception { List<Future<?>> futures = new ArrayList<>(THREADS); LOGGER.debugf("%n *** Starting test case test()%n"); LOGGER.debugf("*** Started nodes = %s", getStartedNodes()); ExecutorService executorService = Executors.newFixedThreadPool(THREADS); for (int i = 0; i < THREADS; ++i) { // start a client thread Runnable task = () -> { LOGGER.debugf("%s *** Starting test thread %s%s", Thread.currentThread().getName()); EJBClientContext oldContext = null; try { // install the correct Jakarta Enterprise Beans client context oldContext = EJBClientContext.getContextManager().getGlobalDefault(); EJBClientContext newContext = createModifiedEJBClientContext(oldContext); EJBClientContext.getContextManager().setThreadDefault(newContext); // look up the IncrementorBean and repeatedly invoke on it try (NamingEJBDirectory directory = new RemoteEJBDirectory(MODULE_NAME)) { Incrementor bean = directory.lookupStateless(StatelessIncrementorBean.class, Incrementor.class); LOGGER.debugf("%s +++ Looked up bean for thread %s%n", Thread.currentThread().getName()); while (!Thread.currentThread().isInterrupted()) { try { // invoke on the incrementor bean and note where it executes LOGGER.debugf("%s +++ Thread %s invoking on bean...%n", Thread.currentThread().getName()); Result<Integer> result = bean.increment(); String target = result.getNode(); LOGGER.debugf("%s +++ Thread %s got result %s from node %s%n", Thread.currentThread().getName(), result.getValue(), target); Thread.sleep(INVOCATION_WAIT); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (NoSuchEJBException e) { LOGGER.debugf("%n +++ Got NoSuchEJBException from node, skipping...%n"); } } } catch (NamingException | EJBException e) { LOGGER.errorf("%n +++ Exception looking up bean for thread %s%n", Thread.currentThread().getName()); assertNull("Cause of EJBException has not been removed", e.getCause()); } LOGGER.debugf("%n *** Stopping test thread %s%n", Thread.currentThread().getName()); } finally { if (oldContext != null) { EJBClientContext.getContextManager().setThreadDefault(null); } } }; futures.add(executorService.submit(task)); } // Let the system stabilize Thread.sleep(GRACE_TIME_TO_REPLICATE); // now shutdown the entire cluster then start one node back up again, to check last node behaviour LOGGER.debugf("%n *** Stopping node %s%n", NODE_3); stop(NODE_3); LOGGER.debugf("*** Started nodes = %s", getStartedNodes()); // Let the system stabilize Thread.sleep(GRACE_TIME_TO_MEMBERSHIP_CHANGE); LOGGER.debugf("%n*** Stopping node %s%n", NODE_2); stop(NODE_2); LOGGER.debugf("*** Started nodes = %s", getStartedNodes()); // Let the system stabilize Thread.sleep(GRACE_TIME_TO_MEMBERSHIP_CHANGE); LOGGER.debugf("%n *** Stopping node %s%n", NODE_1); stop(NODE_1); LOGGER.debugf("*** Started nodes = %s", getStartedNodes()); // Let the system stabilize Thread.sleep(GRACE_TIME_TO_MEMBERSHIP_CHANGE); LOGGER.debugf("%n *** Starting node %s%n", NODE_1); start(NODE_1); LOGGER.debugf("*** Started nodes = %s", getStartedNodes()); // Let the system stabilize Thread.sleep(GRACE_TIME_TO_MEMBERSHIP_CHANGE); // stop the client for (Future<?> future : futures) { future.cancel(true); } executorService.shutdown(); // get the test results for all threads from the rule Map<String, List<List<Set<String>>>> results = getTestResult(); // validate the test for (Map.Entry<String, List<List<Set<String>>>> entry: results.entrySet()) { String thread = entry.getKey(); LOGGER.debugf("Collected data for thread: %s", thread); List<List<Set<String>>> nodeEntries = entry.getValue(); for (List<Set<String>> nodeEntry : nodeEntries) { Set<String> startedNodes = nodeEntry.get(0); Set<String> connectedNodes = nodeEntry.get(1); Set<String> totalAvailableNodes = nodeEntry.get(2); LOGGER.debugf("started nodes = %s, connected nodes = %s, total available nodes = %s", startedNodes, connectedNodes, totalAvailableNodes); Assert.assertTrue("Assertion violation: thread " + thread + " has stale nodes in discovered node registry(DNR): " + " started = " + startedNodes + ", connected = " + connectedNodes + ", total available = " + totalAvailableNodes, startedNodes.containsAll(connectedNodes) && startedNodes.containsAll(totalAvailableNodes)); } } System.out.println("\n *** Stopping test case test() \n"); } /* * Dummy method to allow returning Rule-collected results back to the test case for validation * Byteman will populate the return value when the method is called. */ @SuppressWarnings("static-method") private Map<String, List<List<Set<String>>>> getTestResult() { // injected code will return the actual result return null; } /* * Method to allow determining the set of started nodes so that a Byteman rule * can keep track of them. */ private Set<String> getStartedNodes() { List<String> nodes = Arrays.asList(THREE_NODES); Set<String> startedNodes = new HashSet<>(); for (String node : nodes) { if (isStarted(node)) { startedNodes.add(node); } } return startedNodes; } /* * Create a sort-of copy of the current context with a different cluster node selector * * TODO: We need an easier way to create modified EJB client contexts */ private EJBClientContext createModifiedEJBClientContext(EJBClientContext oldContext) { final EJBClientContext.Builder ejbClientBuilder = new EJBClientContext.Builder(); // transport ejbClientBuilder.addTransportProvider(new RemoteTransportProvider()); // configured connections for (EJBClientConnection connection : oldContext.getConfiguredConnections()) { EJBClientConnection.Builder builder = new EJBClientConnection.Builder(); builder.setDestination(connection.getDestination()); builder.setForDiscovery(connection.isForDiscovery()); ejbClientBuilder.addClientConnection(builder.build()); } // cluster node selector ejbClientBuilder.setClusterNodeSelector(new CustomClusterNodeSelector()); return ejbClientBuilder.build(); } }
16,313
48.138554
156
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/DistributedTimerServiceTestCase.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.ejb.timer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.shrinkwrap.api.Archive; /** * @author Paul Ferraro */ public class DistributedTimerServiceTestCase extends AbstractTimerServiceTestCase { @Deployment(name = DEPLOYMENT_1, managed = false, testable = false) @TargetsContainer(NODE_1) public static Archive<?> deployment0() { return createArchive(); } @Deployment(name = DEPLOYMENT_2, managed = false, testable = false) @TargetsContainer(NODE_2) public static Archive<?> deployment1() { return createArchive(); } private static Archive<?> createArchive() { return createArchive(DistributedTimerServiceTestCase.class); } }
1,861
36.24
83
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/AbstractTimerServiceTestCase.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.clustering.cluster.ejb.timer; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.time.Instant; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import jakarta.servlet.http.HttpServletResponse; import org.apache.http.Header; 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.HttpHead; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.utils.DateUtils; import org.apache.http.impl.client.CloseableHttpClient; 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.ejb.timer.beans.AutoTimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.beans.AutoTransientTimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.beans.ManualTimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.beans.SingleActionPersistentTimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.beans.SingleActionTransientTimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.beans.TimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.servlet.TimerServlet; import org.jboss.as.test.clustering.ejb.EJBDirectory; import org.jboss.as.test.http.util.TestHttpClientUtils; 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; /** * Validates failover of distributed EJB timers. * @author Paul Ferraro */ @RunWith(Arquillian.class) public abstract class AbstractTimerServiceTestCase extends AbstractClusteringTestCase { protected static WebArchive createArchive(Class<? extends AbstractTimerServiceTestCase> testClass) { return ShrinkWrap.create(WebArchive.class, testClass.getSimpleName() + ".war") .addPackage(TimerServlet.class.getPackage()) .addPackage(EJBDirectory.class.getPackage()) .addPackage(TimerBean.class.getPackage()) ; } private final String moduleName; protected AbstractTimerServiceTestCase() { this.moduleName = this.getClass().getSimpleName(); } @Test public void test(@ArquillianResource(TimerServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource(TimerServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException, URISyntaxException { Map<String, URI> uris = new TreeMap<>(); uris.put(NODE_1, TimerServlet.createURI(baseURL1, this.moduleName)); uris.put(NODE_2, TimerServlet.createURI(baseURL2, this.moduleName)); List<Class<? extends TimerBean>> singleActionTimerBeanClasses = List.of(SingleActionPersistentTimerBean.class, SingleActionTransientTimerBean.class); try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) { TimeUnit.SECONDS.sleep(2); // Create manual timers on node 1 only try (CloseableHttpResponse response = client.execute(new HttpPut(uris.get(NODE_1)))) { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); } for (Map.Entry<String, URI> entry : uris.entrySet()) { try (CloseableHttpResponse response = client.execute(new HttpHead(entry.getValue()))) { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); for (Class<? extends TimerBean> beanClass : TimerServlet.TIMER_CLASSES) { int count = Integer.parseInt(response.getFirstHeader(beanClass.getName()).getValue()); if (TimerServlet.MANUAL_TRANSIENT_TIMER_CLASSES.contains(beanClass) && entry.getKey().equals(NODE_2)) { Assert.assertEquals(entry.getKey() + ": " + beanClass.getName(), 0, count); } else { Assert.assertEquals(entry.getKey() + ": " + beanClass.getName(), 1, count); } } } } TimeUnit.SECONDS.sleep(2); Map<Class<? extends TimerBean>, Map<String, List<Instant>>> timeouts = new IdentityHashMap<>(); for (Class<? extends TimerBean> beanClass : TimerServlet.TIMER_CLASSES) { timeouts.put(beanClass, new TreeMap<>()); } for (Map.Entry<String, URI> entry : uris.entrySet()) { try (CloseableHttpResponse response = client.execute(new HttpGet(entry.getValue()))) { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); for (Map.Entry<Class<? extends TimerBean>, Map<String, List<Instant>>> beanEntry : timeouts.entrySet()) { beanEntry.getValue().put(entry.getKey(), parseTimeouts(response.getHeaders(beanEntry.getKey().getName()))); } } } // Single action timer should have exactly 1 timeout on node 1 for (Class<? extends TimerBean> beanClass : singleActionTimerBeanClasses) { Map<String, List<Instant>> singleActionTimeouts = timeouts.remove(beanClass); Assert.assertEquals(singleActionTimeouts.toString(), 1, singleActionTimeouts.get(NODE_1).size()); Assert.assertEquals(singleActionTimeouts.toString(), 0, singleActionTimeouts.get(NODE_2).size()); } for (Map.Entry<Class<? extends TimerBean>, Map<String, List<Instant>>> beanEntry : timeouts.entrySet()) { if (ManualTimerBean.class.isAssignableFrom(beanEntry.getKey())) { // Other timer timeouts should only have been received on node 1 Assert.assertFalse(beanEntry.toString(), beanEntry.getValue().get(NODE_1).isEmpty()); Assert.assertTrue(beanEntry.toString(), beanEntry.getValue().get(NODE_2).isEmpty()); } else if (AutoTransientTimerBean.class.equals(beanEntry.getKey())) { // Transient auto-timers will exist on both nodes Assert.assertFalse(beanEntry.toString(), beanEntry.getValue().get(NODE_1).isEmpty()); Assert.assertFalse(beanEntry.toString(), beanEntry.getValue().get(NODE_2).isEmpty()); } else { // Auto-timers might have been rescheduled during startup Assert.assertTrue(beanEntry.toString(), !beanEntry.getValue().get(NODE_1).isEmpty() || !beanEntry.getValue().get(NODE_2).isEmpty()); } } for (Map.Entry<String, URI> entry : uris.entrySet()) { try (CloseableHttpResponse response = client.execute(new HttpHead(entry.getValue()))) { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); for (Class<? extends TimerBean> beanClass : TimerServlet.TIMER_CLASSES) { int count = Integer.parseInt(response.getFirstHeader(beanClass.getName()).getValue()); if (TimerServlet.SINGLE_ACTION_TIMER_CLASSES.contains(beanClass) || (TimerServlet.MANUAL_TRANSIENT_TIMER_CLASSES.contains(beanClass) && entry.getKey().equals(NODE_2))) { Assert.assertEquals(entry.getKey() + ": " + beanClass.getName(), 0, count); } else { Assert.assertEquals(entry.getKey() + ": " + beanClass.getName(), 1, count); } } } } TimeUnit.SECONDS.sleep(2); for (Map<String, List<Instant>> beanTimeouts : timeouts.values()) { beanTimeouts.clear(); } for (Class<? extends TimerBean> singleActionTimerBeanClass : singleActionTimerBeanClasses) { timeouts.put(singleActionTimerBeanClass, new TreeMap<>()); } for (Map.Entry<String, URI> entry : uris.entrySet()) { try (CloseableHttpResponse response = client.execute(new HttpGet(entry.getValue()))) { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); for (Map.Entry<Class<? extends TimerBean>, Map<String, List<Instant>>> beanEntry : timeouts.entrySet()) { beanEntry.getValue().put(entry.getKey(), parseTimeouts(response.getHeaders(beanEntry.getKey().getName()))); } } } // Single action timers will already have expired for (Class<? extends TimerBean> singleActionTimerBeanClass : singleActionTimerBeanClasses) { Map<String, List<Instant>> singleActionTimers = timeouts.remove(singleActionTimerBeanClass); Assert.assertEquals(singleActionTimers.toString(), 0, singleActionTimers.get(NODE_1).size()); Assert.assertEquals(singleActionTimers.toString(), 0, singleActionTimers.get(NODE_2).size()); } // Other timer timeouts should only have been received on one member or the other for (Map.Entry<Class<? extends TimerBean>, Map<String, List<Instant>>> beanEntry : timeouts.entrySet()) { if (ManualTimerBean.class.isAssignableFrom(beanEntry.getKey())) { Assert.assertFalse(beanEntry.toString(), beanEntry.getValue().get(NODE_1).isEmpty()); Assert.assertTrue(beanEntry.toString(), beanEntry.getValue().get(NODE_2).isEmpty()); } else { // Auto-timers might have been rescheduled during startup Assert.assertTrue(beanEntry.toString(), !beanEntry.getValue().get(NODE_1).isEmpty() || !beanEntry.getValue().get(NODE_2).isEmpty()); } } this.stop(NODE_1); TimeUnit.SECONDS.sleep(2); try (CloseableHttpResponse response = client.execute(new HttpHead(uris.get(NODE_2)))) { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); for (Class<? extends TimerBean> beanClass : TimerServlet.TIMER_CLASSES) { int count = Integer.parseInt(response.getFirstHeader(beanClass.getName()).getValue()); if (TimerServlet.SINGLE_ACTION_TIMER_CLASSES.contains(beanClass) || TimerServlet.MANUAL_TRANSIENT_TIMER_CLASSES.contains(beanClass)) { Assert.assertEquals(beanClass.getName(), 0, count); } else { Assert.assertEquals(beanClass.getName(), 1, count); } } } for (Map<String, List<Instant>> beanTimeouts : timeouts.values()) { beanTimeouts.clear(); } try (CloseableHttpResponse response = client.execute(new HttpGet(uris.get(NODE_2)))) { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); for (Map.Entry<Class<? extends TimerBean>, Map<String, List<Instant>>> beanEntry : timeouts.entrySet()) { beanEntry.getValue().put(NODE_2, parseTimeouts(response.getHeaders(beanEntry.getKey().getName()))); } } for (Map.Entry<Class<? extends TimerBean>, Map<String, List<Instant>>> entry : timeouts.entrySet()) { if (TimerServlet.PERSISTENT_TIMER_CLASSES.contains(entry.getKey()) || AutoTimerBean.class.isAssignableFrom(entry.getKey())) { Assert.assertNotEquals(entry.toString(), 0, entry.getValue().get(NODE_2).size()); } else { // Manual transient timers were never created on node 2 Assert.assertEquals(entry.toString(), 0, entry.getValue().get(NODE_2).size()); } } this.start(NODE_1); TimeUnit.SECONDS.sleep(2); for (Map<String, List<Instant>> beanTimeouts : timeouts.values()) { beanTimeouts.clear(); } for (Map.Entry<String, URI> entry : uris.entrySet()) { try (CloseableHttpResponse response = client.execute(new HttpGet(entry.getValue()))) { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); for (Map.Entry<Class<? extends TimerBean>, Map<String, List<Instant>>> beanEntry : timeouts.entrySet()) { beanEntry.getValue().put(entry.getKey(), parseTimeouts(response.getHeaders(beanEntry.getKey().getName()))); } } } for (Map.Entry<Class<? extends TimerBean>, Map<String, List<Instant>>> entry : timeouts.entrySet()) { if (AutoTransientTimerBean.class.equals(entry.getKey())) { // Manual auto timers will be triggered on both nodes Assert.assertFalse(entry.toString(), entry.getValue().get(NODE_1).isEmpty()); Assert.assertFalse(entry.toString(), entry.getValue().get(NODE_2).isEmpty()); } else if (TimerServlet.TRANSIENT_TIMER_CLASSES.contains(entry.getKey())) { // Manual transient timers will not exist on either node Assert.assertTrue(entry.toString(), entry.getValue().get(NODE_1).isEmpty()); Assert.assertTrue(entry.toString(), entry.getValue().get(NODE_2).isEmpty()); } else { // Verify that at least 1 timeout was received on either member Assert.assertFalse(entry.toString(), entry.getValue().get(NODE_1).isEmpty() && entry.getValue().get(NODE_2).isEmpty()); } } TimeUnit.SECONDS.sleep(2); for (Map<String, List<Instant>> beanTimeouts : timeouts.values()) { beanTimeouts.clear(); } for (Map.Entry<String, URI> entry : uris.entrySet()) { try (CloseableHttpResponse response = client.execute(new HttpGet(entry.getValue()))) { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); for (Map.Entry<Class<? extends TimerBean>, Map<String, List<Instant>>> beanEntry : timeouts.entrySet()) { beanEntry.getValue().put(entry.getKey(), parseTimeouts(response.getHeaders(beanEntry.getKey().getName()))); } } } for (Map.Entry<Class<? extends TimerBean>, Map<String, List<Instant>>> entry : timeouts.entrySet()) { if (AutoTransientTimerBean.class.equals(entry.getKey())) { // Manual auto timers will be triggered on both nodes Assert.assertFalse(entry.toString(), entry.getValue().get(NODE_1).isEmpty()); Assert.assertFalse(entry.toString(), entry.getValue().get(NODE_2).isEmpty()); } else if (TimerServlet.TRANSIENT_TIMER_CLASSES.contains(entry.getKey())) { // Manual transient timers will not exist on either node Assert.assertTrue(entry.toString(), entry.getValue().get(NODE_1).isEmpty()); Assert.assertTrue(entry.toString(), entry.getValue().get(NODE_2).isEmpty()); } else { // Verify that at least 1 timeout was received on a single member Assert.assertTrue(entry.toString(), entry.getValue().get(NODE_1).isEmpty() ^ entry.getValue().get(NODE_2).isEmpty()); } } this.stop(NODE_2); TimeUnit.SECONDS.sleep(2); for (Map<String, List<Instant>> beanTimeouts : timeouts.values()) { beanTimeouts.clear(); } try (CloseableHttpResponse response = client.execute(new HttpGet(uris.get(NODE_1)))) { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); for (Map.Entry<Class<? extends TimerBean>, Map<String, List<Instant>>> beanEntry : timeouts.entrySet()) { beanEntry.getValue().put(NODE_1, parseTimeouts(response.getHeaders(beanEntry.getKey().getName()))); } } for (Map.Entry<Class<? extends TimerBean>, Map<String, List<Instant>>> entry : timeouts.entrySet()) { if (TimerServlet.PERSISTENT_TIMER_CLASSES.contains(entry.getKey()) || AutoTimerBean.class.isAssignableFrom(entry.getKey())) { Assert.assertNotEquals(entry.toString(), 0, entry.getValue().get(NODE_1).size()); } else { // Manual transient timers were never created on node 2 Assert.assertEquals(entry.toString(), 0, entry.getValue().get(NODE_1).size()); } } this.start(NODE_2); TimeUnit.SECONDS.sleep(2); try (CloseableHttpResponse response = client.execute(new HttpDelete(uris.get(NODE_1)))) { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); } Instant cancellation = Instant.now(); TimeUnit.SECONDS.sleep(2); for (Map<String, List<Instant>> beanTimeouts : timeouts.values()) { beanTimeouts.clear(); } for (Map.Entry<String, URI> entry : uris.entrySet()) { try (CloseableHttpResponse response = client.execute(new HttpGet(entry.getValue()))) { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); for (Map.Entry<Class<? extends TimerBean>, Map<String, List<Instant>>> beanEntry : timeouts.entrySet()) { beanEntry.getValue().put(entry.getKey(), parseTimeouts(response.getHeaders(beanEntry.getKey().getName()))); } } } // Ensure all timeouts were received before cancellation was initiated. for (Map.Entry<Class<? extends TimerBean>, Map<String, List<Instant>>> entry : timeouts.entrySet()) { for (String node : uris.keySet()) { if (ManualTimerBean.class.isAssignableFrom(entry.getKey())) { Assert.assertTrue(cancellation + " " + entry.toString(), entry.getValue().get(node).stream().allMatch(instant -> instant.isBefore(cancellation))); } else { Assert.assertTrue(entry.toString(), !entry.getValue().get(NODE_1).isEmpty() || !entry.getValue().get(NODE_2).isEmpty()); } } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } private static List<Instant> parseTimeouts(Header[] headers) { List<Instant> timeouts = new ArrayList<>(headers.length); for (Header header : headers) { timeouts.add(DateUtils.parseDate(header.getValue()).toInstant()); } return timeouts; } }
20,795
54.604278
239
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/remote/InfinispanServerSetupTask.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.ejb.timer.remote; import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.INFINISPAN_APPLICATION_PASSWORD; import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.INFINISPAN_APPLICATION_USER; import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.INFINISPAN_SERVER_ADDRESS; import static org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase.INFINISPAN_SERVER_PORT; import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase; import org.jboss.as.test.shared.ManagementServerSetupTask; /** * Server setup task that configures a hotrod client to connect to an Infinispan server. * @author Paul Ferraro */ public class InfinispanServerSetupTask extends ManagementServerSetupTask { public InfinispanServerSetupTask() { super(AbstractClusteringTestCase.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=ejb:add(default-remote-cluster=infinispan-server-cluster, tcp-keep-alive=true, marshaller=PROTOSTREAM, modules=[org.wildfly.clustering.ejb.infinispan], properties={infinispan.client.hotrod.auth_username=%s, infinispan.client.hotrod.auth_password=%s}, statistics-enabled=true)", INFINISPAN_APPLICATION_USER, INFINISPAN_APPLICATION_PASSWORD) .add("/subsystem=infinispan/remote-cache-container=ejb/remote-cluster=infinispan-server-cluster:add(socket-bindings=[infinispan-server])") .endBatch() .build()) .tearDownScript(createScriptBuilder() .startBatch() .add("/subsystem=infinispan/remote-cache-container=ejb:remove") .add("/socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=infinispan-server:remove") .endBatch() .build()) .build()); } }
3,313
58.178571
414
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/remote/HotRodPersistentTimerServiceTestCase.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.ejb.timer.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.ejb.timer.AbstractTimerServiceTestCase; import org.jboss.as.test.shared.IntermittentFailure; import org.jboss.as.test.shared.ManagementServerSetupTask; import org.jboss.shrinkwrap.api.Archive; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.rules.TestRule; /** * @author Paul Ferraro */ @ServerSetup({ InfinispanServerSetupTask.class, HotRodPersistentTimerServiceTestCase.TimerManagementSetupTask.class }) public class HotRodPersistentTimerServiceTestCase extends AbstractTimerServiceTestCase { @BeforeClass public static void beforeClass() { IntermittentFailure.thisTestIsFailingIntermittently("https://issues.redhat.com/browse/WFLY-17801 Intermittent failures in HotRodPersistentTimerServiceTestCase"); } @ClassRule public static final TestRule INFINISPAN_SERVER_RULE = infinispanServerTestRule(); @Deployment(name = DEPLOYMENT_1, managed = false, testable = false) @TargetsContainer(NODE_1) public static Archive<?> deployment0() { return createArchive(); } @Deployment(name = DEPLOYMENT_2, managed = false, testable = false) @TargetsContainer(NODE_2) public static Archive<?> deployment1() { return createArchive(); } private static Archive<?> createArchive() { return createArchive(HotRodPersistentTimerServiceTestCase.class).addAsWebInfResource(HotRodPersistentTimerServiceTestCase.class.getPackage(), "jboss-ejb3.xml", "jboss-ejb3.xml"); } static class TimerManagementSetupTask extends ManagementServerSetupTask { TimerManagementSetupTask() { super(NODE_1_2, createContainerConfigurationBuilder() .setupScript(createScriptBuilder() .startBatch() .add("/subsystem=infinispan/cache-container=ejb/invalidation-cache=hotrod-persistent:add") .add("/subsystem=infinispan/cache-container=ejb/invalidation-cache=hotrod-persistent/component=expiration:add(interval=0)") .add("/subsystem=infinispan/cache-container=ejb/invalidation-cache=hotrod-persistent/component=locking:add(isolation=REPEATABLE_READ)") .add("/subsystem=infinispan/cache-container=ejb/invalidation-cache=hotrod-persistent/component=transaction:add(mode=BATCH)") .add("/subsystem=infinispan/cache-container=ejb/invalidation-cache=hotrod-persistent/store=hotrod:add(remote-cache-container=ejb, cache-configuration=default, fetch-state=false, shared=true)") .add("/subsystem=distributable-ejb/infinispan-timer-management=hotrod:add(cache-container=ejb, cache=hotrod-persistent, marshaller=PROTOSTREAM)") .endBatch() .build()) .tearDownScript(createScriptBuilder() .startBatch() .add("/subsystem=distributable-ejb/infinispan-timer-management=hotrod:remove") .add("/subsystem=infinispan/cache-container=ejb/invalidation-cache=hotrod-persistent:remove") .endBatch() .build()) .build()); } } }
4,641
50.010989
220
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/servlet/TimerServlet.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.ejb.timer.servlet; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.time.Instant; import java.util.IdentityHashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; 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.ejb.timer.beans.AutoPersistentTimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.beans.AutoTransientTimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.beans.CalendarPersistentTimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.beans.CalendarTransientTimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.beans.IntervalPersistentTimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.beans.IntervalTransientTimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.beans.ManualTimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.beans.SingleActionPersistentTimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.beans.SingleActionTransientTimerBean; import org.jboss.as.test.clustering.cluster.ejb.timer.beans.TimerBean; import org.jboss.as.test.clustering.ejb.EJBDirectory; import org.jboss.as.test.clustering.ejb.LocalEJBDirectory; /** * @author Paul Ferraro */ @WebServlet(urlPatterns = { TimerServlet.SERVLET_PATH }) public class TimerServlet extends HttpServlet { private static final long serialVersionUID = 5393197778939188763L; private static final String SERVLET_NAME = "timer"; static final String SERVLET_PATH = "/" + SERVLET_NAME; private static final String MODULE = "module"; public static final Set<Class<? extends TimerBean>> PERSISTENT_TIMER_CLASSES = Set.of(AutoPersistentTimerBean.class, CalendarPersistentTimerBean.class, IntervalPersistentTimerBean.class, SingleActionPersistentTimerBean.class); public static final Set<Class<? extends TimerBean>> TRANSIENT_TIMER_CLASSES = Set.of(AutoTransientTimerBean.class, CalendarTransientTimerBean.class, IntervalTransientTimerBean.class, SingleActionTransientTimerBean.class); public static final Set<Class<? extends TimerBean>> TIMER_CLASSES = Stream.of(PERSISTENT_TIMER_CLASSES, TRANSIENT_TIMER_CLASSES).flatMap(Set::stream).collect(Collectors.toSet()); public static final Set<Class<? extends ManualTimerBean>> MANUAL_PERSISTENT_TIMER_CLASSES = Set.of(CalendarPersistentTimerBean.class, IntervalPersistentTimerBean.class, SingleActionPersistentTimerBean.class); public static final Set<Class<? extends ManualTimerBean>> MANUAL_TRANSIENT_TIMER_CLASSES = Set.of(CalendarTransientTimerBean.class, IntervalTransientTimerBean.class, SingleActionTransientTimerBean.class); public static final Set<Class<? extends ManualTimerBean>> MANUAL_TIMER_CLASSES = Stream.of(MANUAL_PERSISTENT_TIMER_CLASSES, MANUAL_TRANSIENT_TIMER_CLASSES).flatMap(Set::stream).collect(Collectors.toSet()); public static final Set<Class<? extends TimerBean>> AUTO_TIMER_CLASSES = Set.of(AutoPersistentTimerBean.class, AutoTransientTimerBean.class); public static final Set<Class<? extends TimerBean>> SINGLE_ACTION_TIMER_CLASSES = Set.of(SingleActionPersistentTimerBean.class, SingleActionTransientTimerBean.class); public static URI createURI(URL baseURL, String module) throws URISyntaxException { return baseURL.toURI().resolve(new StringBuilder(SERVLET_NAME).append('?').append(MODULE).append('=').append(module).toString()); } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getServletContext().log(String.format("%s: http://%s:%s%s?%s", request.getMethod(), request.getServerName(), request.getServerPort(), request.getRequestURI(), request.getQueryString())); super.service(request, response); } @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String module = request.getParameter(MODULE); try (EJBDirectory directory = new LocalEJBDirectory(module)) { for (Class<? extends ManualTimerBean> beanClass : MANUAL_TIMER_CLASSES) { ManualTimerBean bean = directory.lookupSingleton(beanClass, ManualTimerBean.class); bean.cancel(); } } catch (Exception e) { throw new ServletException(e); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String module = request.getParameter(MODULE); try (EJBDirectory directory = new LocalEJBDirectory(module)) { Map<Class<? extends TimerBean>, TimerBean> beans = new IdentityHashMap<>(); for (Class<? extends ManualTimerBean> beanClass : MANUAL_TIMER_CLASSES) { beans.put(beanClass, directory.lookupSingleton(beanClass, ManualTimerBean.class)); } for (Class<? extends TimerBean> beanClass : AUTO_TIMER_CLASSES) { beans.put(beanClass, directory.lookupSingleton(beanClass, TimerBean.class)); } for (Map.Entry<Class<? extends TimerBean>, TimerBean> entry : beans.entrySet()) { for (Instant timeout : entry.getValue().getTimeouts()) { response.addDateHeader(entry.getKey().getName(), timeout.toEpochMilli()); } } } catch (Exception e) { throw new ServletException(e); } } @Override protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String module = request.getParameter(MODULE); try (EJBDirectory directory = new LocalEJBDirectory(module)) { Map<Class<? extends TimerBean>, TimerBean> beans = new IdentityHashMap<>(); for (Class<? extends ManualTimerBean> beanClass : MANUAL_TIMER_CLASSES) { beans.put(beanClass, directory.lookupSingleton(beanClass, ManualTimerBean.class)); } for (Class<? extends TimerBean> beanClass : AUTO_TIMER_CLASSES) { beans.put(beanClass, directory.lookupSingleton(beanClass, TimerBean.class)); } for (Map.Entry<Class<? extends TimerBean>, TimerBean> entry : beans.entrySet()) { response.addIntHeader(entry.getKey().getName(), entry.getValue().getTimers()); } } catch (Exception e) { throw new ServletException(e); } } @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String module = request.getParameter(MODULE); try (EJBDirectory directory = new LocalEJBDirectory(module)) { for (Class<? extends ManualTimerBean> beanClass : MANUAL_TIMER_CLASSES) { directory.lookupSingleton(beanClass, ManualTimerBean.class).createTimer(); } } catch (Exception e) { throw new ServletException(e); } } }
8,432
55.22
230
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/AbstractIntervalTimerBean.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.ejb.timer.beans; import jakarta.ejb.TimerConfig; /** * @author Paul Ferraro */ public class AbstractIntervalTimerBean extends AbstractManualTimerBean { public AbstractIntervalTimerBean(boolean persistent) { super(service -> service.createIntervalTimer(1000, 1000, new TimerConfig("interval", persistent))); } }
1,401
37.944444
107
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/AutoPersistentTimerBean.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.ejb.timer.beans; import jakarta.ejb.Local; import jakarta.ejb.Schedule; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; import jakarta.ejb.Timer; /** * @author Paul Ferraro */ @Singleton @Startup @Local(TimerBean.class) public class AutoPersistentTimerBean extends AbstractTimerBean implements AutoTimerBean { @Override @Schedule(year = "*", month = "*", dayOfMonth = "*", hour = "*", minute = "*", second = "*", info = "auto", persistent = true) public void timeout(Timer timer) { this.record(timer); } }
1,614
34.888889
130
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/TimerRecorder.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.ejb.timer.beans; import jakarta.ejb.Timer; /** * @author Paul Ferraro */ public interface TimerRecorder { void record(Timer timer); }
1,212
34.676471
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/ManualTimerBean.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.ejb.timer.beans; /** * @author Paul Ferraro */ public interface ManualTimerBean extends TimerBean { void createTimer(); void cancel(); }
1,219
34.882353
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/AbstractCalendarTimerBean.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.ejb.timer.beans; import jakarta.ejb.ScheduleExpression; import jakarta.ejb.TimerConfig; /** * @author Paul Ferraro */ public class AbstractCalendarTimerBean extends AbstractManualTimerBean { public AbstractCalendarTimerBean(boolean persistent) { super(service -> service.createCalendarTimer(new ScheduleExpression().second("*").minute("*").hour("*").dayOfMonth("*").year("*"), new TimerConfig("calendar", persistent))); } }
1,514
39.945946
181
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/AutoTransientTimerBean.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.ejb.timer.beans; import jakarta.ejb.Local; import jakarta.ejb.Schedule; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; import jakarta.ejb.Timer; /** * @author Paul Ferraro */ @Singleton @Startup @Local(TimerBean.class) public class AutoTransientTimerBean extends AbstractTimerBean implements AutoTimerBean { @Override @Schedule(year = "*", month = "*", dayOfMonth = "*", hour = "*", minute = "*", second = "*", info = "auto", persistent = false) public void timeout(Timer timer) { this.record(timer); } }
1,614
34.888889
131
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/TimerBean.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.ejb.timer.beans; import java.time.Instant; import java.util.List; /** * @author Paul Ferraro */ public interface TimerBean { String getNodeName(); boolean isCoordinator(); List<Instant> getTimeouts(); int getTimers(); }
1,313
31.04878
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/IntervalPersistentTimerBean.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.ejb.timer.beans; import jakarta.ejb.Local; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; /** * @author Paul Ferraro */ @Singleton @Startup @Local(ManualTimerBean.class) public class IntervalPersistentTimerBean extends AbstractIntervalTimerBean { public IntervalPersistentTimerBean() { super(true); } }
1,404
33.268293
76
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/AbstractManualTimerBean.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.ejb.timer.beans; import java.util.function.Function; import jakarta.ejb.NoSuchObjectLocalException; import jakarta.ejb.Timeout; import jakarta.ejb.Timer; import jakarta.ejb.TimerService; /** * @author Paul Ferraro */ public abstract class AbstractManualTimerBean extends AbstractTimerBean implements ManualTimerBean { private final Function<TimerService, Timer> factory; protected AbstractManualTimerBean(Function<TimerService, Timer> factory) { this.factory = factory; } @Override public void createTimer() { this.factory.apply(this.service); java.util.Collection<Timer> timers = this.service.getTimers(); assert timers.size() == 1 : timers.toString(); } @Override public void cancel() { for (Timer timer : this.service.getTimers()) { try { timer.cancel(); } catch (NoSuchObjectLocalException e) { // This can happen if timer expired concurrently // In this case, verify that a fresh call to getTimers() no longer returns it. if (this.service.getTimers().contains(timer)) { throw e; } } } } @Timeout public void timeout(Timer timer) { this.record(timer); } }
2,379
33
100
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/AbstractTimerBean.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.ejb.timer.beans; import java.time.Instant; import java.util.LinkedList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import jakarta.annotation.Resource; import jakarta.ejb.Timer; import jakarta.ejb.TimerService; import org.wildfly.clustering.group.Group; /** * @author Paul Ferraro */ public abstract class AbstractTimerBean implements TimerBean, TimerRecorder { private final BlockingQueue<Instant> timeouts = new LinkedBlockingQueue<>(); @Resource TimerService service; @Resource(lookup = "java:jboss/clustering/group/ejb") private Group group; @Override public String getNodeName() { return this.group.getLocalMember().getName(); } @Override public boolean isCoordinator() { return this.group.getMembership().isCoordinator(); } @Override public void record(Timer timer) { Instant now = Instant.now(); System.out.println(String.format("%s received %s(info=%s, persistent=%s) timeout @ %s", this.getNodeName(), this.getClass().getName(), timer.getInfo(), timer.isPersistent(), now)); this.timeouts.add(now); } @Override public List<Instant> getTimeouts() { List<Instant> result = new LinkedList<>(); this.timeouts.drainTo(result); return result; } @Override public int getTimers() { return this.service.getTimers().size(); } }
2,532
31.474359
188
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/CalendarPersistentTimerBean.java
/* * JBoss, Home of Professional Open Source * Copyright 2021, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.clustering.cluster.ejb.timer.beans; import jakarta.ejb.Local; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; /** * @author Paul Ferraro */ @Singleton @Startup @Local(ManualTimerBean.class) public class CalendarPersistentTimerBean extends AbstractCalendarTimerBean { public CalendarPersistentTimerBean() { super(true); } }
1,396
33.925
76
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/AbstractSingleActionTimerBean.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.ejb.timer.beans; import jakarta.ejb.TimerConfig; /** * @author Paul Ferraro */ public class AbstractSingleActionTimerBean extends AbstractManualTimerBean { public AbstractSingleActionTimerBean(boolean persistent) { super(service -> service.createSingleActionTimer(1000, new TimerConfig("single", persistent))); } }
1,405
38.055556
103
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/SingleActionPersistentTimerBean.java
/* * JBoss, Home of Professional Open Source * Copyright 2021, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.clustering.cluster.ejb.timer.beans; import jakarta.ejb.Local; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; /** * @author Paul Ferraro */ @Singleton @Startup @Local(ManualTimerBean.class) public class SingleActionPersistentTimerBean extends AbstractSingleActionTimerBean { public SingleActionPersistentTimerBean() { super(true); } }
1,408
34.225
84
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/AutoTimerBean.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.ejb.timer.beans; import jakarta.ejb.Timer; /** * @author Paul Ferraro */ public interface AutoTimerBean { void timeout(Timer timer); }
1,213
34.705882
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/SingleActionTransientTimerBean.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.ejb.timer.beans; import jakarta.ejb.Local; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; /** * @author Paul Ferraro */ @Singleton @Startup @Local(ManualTimerBean.class) public class SingleActionTransientTimerBean extends AbstractSingleActionTimerBean { public SingleActionTransientTimerBean() { super(false); } }
1,415
33.536585
83
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/CalendarTransientTimerBean.java
/* * JBoss, Home of Professional Open Source * Copyright 2021, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.clustering.cluster.ejb.timer.beans; import jakarta.ejb.Local; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; /** * @author Paul Ferraro */ @Singleton @Startup @Local(ManualTimerBean.class) public class CalendarTransientTimerBean extends AbstractCalendarTimerBean { public CalendarTransientTimerBean() { super(false); } }
1,395
33.9
75
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/timer/beans/IntervalTransientTimerBean.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.ejb.timer.beans; import jakarta.ejb.Local; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; /** * @author Paul Ferraro */ @Singleton @Startup @Local(ManualTimerBean.class) public class IntervalTransientTimerBean extends AbstractIntervalTimerBean { public IntervalTransientTimerBean() { super(false); } }
1,403
33.243902
75
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/forwarding/AbstractRemoteEJBForwardingTestCase.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.ejb.forwarding; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.junit.Assert.fail; import java.net.SocketPermission; import java.util.PropertyPermission; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.naming.NamingException; 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.arquillian.api.ServerSetup; import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase; import org.jboss.as.test.clustering.cluster.ejb.forwarding.bean.common.CommonStatefulSB; import org.jboss.as.test.clustering.cluster.ejb.forwarding.bean.forwarding.AbstractForwardingStatefulSBImpl; import org.jboss.as.test.clustering.cluster.ejb.forwarding.bean.forwarding.ForwardingStatefulSBImpl; import org.jboss.as.test.clustering.cluster.ejb.forwarding.bean.forwarding.NonTxForwardingStatefulSBImpl; import org.jboss.as.test.clustering.cluster.ejb.forwarding.bean.stateful.RemoteStatefulSB; import org.jboss.as.test.clustering.ejb.EJBDirectory; import org.jboss.as.test.clustering.ejb.NamingEJBDirectory; import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory; import org.jboss.as.test.shared.CLIServerSetupTask; import org.jboss.as.test.shared.IntermittentFailure; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.ejb.client.EJBClientPermission; 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.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.common.function.ExceptionSupplier; /** * Test Jakarta Enterprise Beans Client functionality across two clusters with fail-over. * <p/> * A client makes an invocation on one clustered app (on cluster A) which in turn * forwards the invocation on a second clustered app (on cluster B). * <p/> * cluster A = {node0, node1} * cluster B = {node2, node3} * <p/> * Under constant client load, we stop and then restart individual servers. * <p/> * We expect that client invocations will not be affected. * * @author Richard Achmatowicz * @author Radoslav Husar */ @RunWith(Arquillian.class) @ServerSetup(AbstractRemoteEJBForwardingTestCase.ServerSetupTask.class) public abstract class AbstractRemoteEJBForwardingTestCase extends AbstractClusteringTestCase { @BeforeClass public static void beforeClass() { IntermittentFailure.thisTestIsFailingIntermittently("https://issues.redhat.com/browse/WFLY-10607"); } private static final long FAILURE_FREE_TIME = TimeoutUtil.adjust(5_000); private static final long SERVER_DOWN_TIME = TimeoutUtil.adjust(5_000); private static final long INVOCATION_WAIT = TimeoutUtil.adjust(1_000); private final ExceptionSupplier<EJBDirectory, NamingException> directorySupplier; private final String implementationClass; private static final Logger logger = Logger.getLogger(AbstractRemoteEJBForwardingTestCase.class); AbstractRemoteEJBForwardingTestCase(ExceptionSupplier<EJBDirectory, NamingException> directorySupplier, String implementationClass) { super(FOUR_NODES); this.directorySupplier = directorySupplier; this.implementationClass = implementationClass; } @Deployment(name = DEPLOYMENT_3, managed = false, testable = false) @TargetsContainer(NODE_3) public static Archive<?> deployment3() { return createNonForwardingDeployment(); } @Deployment(name = DEPLOYMENT_4, managed = false, testable = false) @TargetsContainer(NODE_4) public static Archive<?> deployment4() { return createNonForwardingDeployment(); } public static Archive<?> createForwardingDeployment(String moduleName, boolean tx) { JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, moduleName + ".jar"); ejbJar.addClass(CommonStatefulSB.class); ejbJar.addClass(RemoteStatefulSB.class); // the forwarding classes ejbJar.addClass(AbstractForwardingStatefulSBImpl.class); if (tx) { ejbJar.addClass(ForwardingStatefulSBImpl.class); } else { ejbJar.addClass(NonTxForwardingStatefulSBImpl.class); } ejbJar.addClasses(EJBDirectory.class, NamingEJBDirectory.class, RemoteEJBDirectory.class); // remote outbound connection configuration ejbJar.addAsManifestResource(AbstractRemoteEJBForwardingTestCase.class.getPackage(), "jboss-ejb-client.xml", "jboss-ejb-client.xml"); ejbJar.addAsResource(createPermissionsXmlAsset( new SocketPermission("localhost", "resolve"), new EJBClientPermission("changeWeakAffinity"), new PropertyPermission("jboss.node.name", "read") ), "META-INF/jboss-permissions.xml"); return ejbJar; } public static Archive<?> createNonForwardingDeployment() { JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, AbstractForwardingStatefulSBImpl.MODULE_NAME + ".jar"); ejbJar.addPackage(CommonStatefulSB.class.getPackage()); ejbJar.addPackage(RemoteStatefulSB.class.getPackage()); ejbJar.addAsResource(createPermissionsXmlAsset( new PropertyPermission("jboss.node.name", "read") ), "META-INF/jboss-permissions.xml"); return ejbJar; } /** * Tests that Jakarta Enterprise Beans Client invocations on stateful session beans can still successfully be processed * as long as one node in each cluster is available. */ @Test public void test() throws Exception { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); try (EJBDirectory directory = directorySupplier.get()) { // get the correct forwarder deployment on cluster A RemoteStatefulSB bean = directory.lookupStateful(implementationClass, RemoteStatefulSB.class); // Allow sufficient time for client to receive full topology logger.debug("Waiting for clusters to form."); Thread.sleep(FAILURE_FREE_TIME); int newSerialValue = bean.getSerialAndIncrement(); logger.debugf("First invocation: serial = %d", newSerialValue); ClientInvocationTask client = new ClientInvocationTask(bean, newSerialValue); // set up the client invocations executor.scheduleWithFixedDelay(client, 0, INVOCATION_WAIT, TimeUnit.MILLISECONDS); // a few seconds of non-failure behaviour Thread.sleep(FAILURE_FREE_TIME); client.assertNoExceptions("at the beginning of the test"); logger.debugf("------ Shutdown clusterA-node0 -----"); stop(GRACEFUL_SHUTDOWN_TIMEOUT, NODE_1); Thread.sleep(SERVER_DOWN_TIME); client.assertNoExceptions("after clusterA-node0 was shut down"); logger.debug("------ Startup clusterA-node0 -----"); start(NODE_1); Thread.sleep(FAILURE_FREE_TIME); client.assertNoExceptions("after clusterA-node0 was brought up"); logger.debug("----- Shutdown clusterA-node1 -----"); stop(GRACEFUL_SHUTDOWN_TIMEOUT, NODE_2); Thread.sleep(SERVER_DOWN_TIME); logger.debug("------ Startup clusterA-node1 -----"); start(NODE_2); Thread.sleep(FAILURE_FREE_TIME); client.assertNoExceptions("after clusterA-node1 was brought back up"); logger.debug("----- Shutdown clusterB-node0 -----"); stop(GRACEFUL_SHUTDOWN_TIMEOUT, NODE_3); Thread.sleep(SERVER_DOWN_TIME); client.assertNoExceptions("after clusterB-node0 was shut down"); logger.debug("------ Startup clusterB-node0 -----"); start(NODE_3); Thread.sleep(FAILURE_FREE_TIME); client.assertNoExceptions("after clusterB-node0 was brought back up"); logger.debug("----- Shutdown clusterB-node1 -----"); stop(GRACEFUL_SHUTDOWN_TIMEOUT, NODE_4); Thread.sleep(SERVER_DOWN_TIME); logger.debug("------ Startup clusterB-node1 -----"); start(NODE_4); Thread.sleep(FAILURE_FREE_TIME); // final assert client.assertNoExceptions("after clusterB-node1 was brought back up"); } finally { executor.shutdownNow(); } } private class ClientInvocationTask implements Runnable { private final RemoteStatefulSB bean; private int expectedSerial; private volatile Exception firstException; private int invocationCount; ClientInvocationTask(RemoteStatefulSB bean, int serial) { this.bean = bean; this.expectedSerial = serial; } /** * Asserts that there were no exception during the last test period. */ void assertNoExceptions(String when) { if (firstException != null) { logger.error(firstException); fail("Client threw an exception " + when + ": " + firstException); // Arrays.stream(firstException.getStackTrace()).map(StackTraceElement::toString).collect(Collectors.joining("\n"))); } } @Override public void run() { invocationCount++; try { int serial = this.bean.getSerialAndIncrement(); logger.debugf("Jakarta Enterprise Beans client invocation #%d on bean, received serial #%d.", this.invocationCount, serial); if (serial != ++expectedSerial) { logger.warnf("Expected (%d) and received serial (%d) numbers do not match! Resetting.", expectedSerial, serial); expectedSerial = serial; } } catch (Exception clientException) { logger.warnf("Jakarta Enterprise Beans client invocation #%d on bean, exception occurred %s", this.invocationCount, clientException); if (this.firstException == null) { this.firstException = clientException; } } } } public static class ServerSetupTask extends CLIServerSetupTask { public ServerSetupTask() { this.builder // clusterA is called 'ejb-forwarder'; clusterB uses default name 'ejb' .node(NODE_1, NODE_2) .setup("/subsystem=jgroups/channel=ee:write-attribute(name=cluster,value=ejb-forwarder)") .setup(String.format("/socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=binding-remote-ejb-connection:add(host=%s,port=8280)", TESTSUITE_NODE3)) .setup("/core-service=management/security-realm=PasswordRealm:add") .setup("/core-service=management/security-realm=PasswordRealm/server-identity=secret:add(value=\"cmVtQHRlZWpicGFzc3dkMQ==\")") .setup("/subsystem=remoting/remote-outbound-connection=remote-ejb-connection:add(outbound-socket-binding-ref=binding-remote-ejb-connection,protocol=http-remoting,security-realm=PasswordRealm,username=remoteejbuser)") .teardown("/subsystem=remoting/remote-outbound-connection=remote-ejb-connection:remove") .teardown("/core-service=management/security-realm=PasswordRealm:remove") .teardown("/socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=binding-remote-ejb-connection:remove") .teardown("/subsystem=jgroups/channel=ee:write-attribute(name=cluster,value=ejb)") ; } } }
13,033
45.884892
236
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/forwarding/TxClientEJBForwardingTestCase.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.ejb.forwarding; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.as.test.clustering.cluster.ejb.forwarding.bean.forwarding.ForwardingStatefulSBImpl; import org.jboss.as.test.clustering.ejb.ClientEJBDirectory; import org.jboss.shrinkwrap.api.Archive; /** * Tests concurrent fail-over with a managed transaction context on the forwarder and using the client "API". * * @author Radoslav Husar */ public class TxClientEJBForwardingTestCase extends AbstractRemoteEJBForwardingTestCase { public static final String MODULE_NAME = TxClientEJBForwardingTestCase.class.getSimpleName(); public TxClientEJBForwardingTestCase() { super(() -> new ClientEJBDirectory(MODULE_NAME), ForwardingStatefulSBImpl.class.getSimpleName()); } @Deployment(name = DEPLOYMENT_1, managed = false, testable = false) @TargetsContainer(NODE_1) public static Archive<?> deployment1() { return createForwardingDeployment(MODULE_NAME, true); } @Deployment(name = DEPLOYMENT_2, managed = false, testable = false) @TargetsContainer(NODE_2) public static Archive<?> deployment2() { return createForwardingDeployment(MODULE_NAME, true); } }
2,349
40.964286
109
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/forwarding/TxRemoteEJBForwardingTestCase.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.ejb.forwarding; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.as.test.clustering.cluster.ejb.forwarding.bean.forwarding.ForwardingStatefulSBImpl; import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory; import org.jboss.shrinkwrap.api.Archive; /** * Tests concurrent fail-over with a managed transaction context on the forwarder. * * @author Radoslav Husar */ public class TxRemoteEJBForwardingTestCase extends AbstractRemoteEJBForwardingTestCase { public static final String MODULE_NAME = TxRemoteEJBForwardingTestCase.class.getSimpleName(); public TxRemoteEJBForwardingTestCase() { super(() -> new RemoteEJBDirectory(MODULE_NAME), ForwardingStatefulSBImpl.class.getSimpleName()); } @Deployment(name = DEPLOYMENT_1, managed = false, testable = false) @TargetsContainer(NODE_1) public static Archive<?> deployment1() { return createForwardingDeployment(MODULE_NAME, true); } @Deployment(name = DEPLOYMENT_2, managed = false, testable = false) @TargetsContainer(NODE_2) public static Archive<?> deployment2() { return createForwardingDeployment(MODULE_NAME, true); } }
2,313
40.321429
105
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/forwarding/NonTxRemoteEJBForwardingTestCase.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.ejb.forwarding; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.as.test.clustering.cluster.ejb.forwarding.bean.forwarding.NonTxForwardingStatefulSBImpl; import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory; import org.jboss.shrinkwrap.api.Archive; /** * Tests concurrent fail-over without a managed transaction context on the forwarder. * * @author Radoslav Husar */ public class NonTxRemoteEJBForwardingTestCase extends AbstractRemoteEJBForwardingTestCase { public static final String MODULE_NAME = NonTxRemoteEJBForwardingTestCase.class.getSimpleName(); public NonTxRemoteEJBForwardingTestCase() { super(() -> new RemoteEJBDirectory(MODULE_NAME), NonTxForwardingStatefulSBImpl.class.getSimpleName()); } @Deployment(name = DEPLOYMENT_1, managed = false, testable = false) @TargetsContainer(NODE_1) public static Archive<?> deployment1() { return createForwardingDeployment(MODULE_NAME, false); } @Deployment(name = DEPLOYMENT_2, managed = false, testable = false) @TargetsContainer(NODE_2) public static Archive<?> deployment2() { return createForwardingDeployment(MODULE_NAME, false); } }
2,346
40.910714
110
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/forwarding/NonTxClientEJBForwardingTestCase.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.ejb.forwarding; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.as.test.clustering.cluster.ejb.forwarding.bean.forwarding.NonTxForwardingStatefulSBImpl; import org.jboss.as.test.clustering.ejb.ClientEJBDirectory; import org.jboss.shrinkwrap.api.Archive; /** * Tests concurrent fail-over without a managed transaction context on the forwarder and using the client "API". * * @author Radoslav Husar */ public class NonTxClientEJBForwardingTestCase extends AbstractRemoteEJBForwardingTestCase { public static final String MODULE_NAME = NonTxClientEJBForwardingTestCase.class.getSimpleName(); public NonTxClientEJBForwardingTestCase() { super(() -> new ClientEJBDirectory(MODULE_NAME), NonTxForwardingStatefulSBImpl.class.getSimpleName()); } @Deployment(name = DEPLOYMENT_1, managed = false, testable = false) @TargetsContainer(NODE_1) public static Archive<?> deployment1() { return createForwardingDeployment(MODULE_NAME, false); } @Deployment(name = DEPLOYMENT_2, managed = false, testable = false) @TargetsContainer(NODE_2) public static Archive<?> deployment2() { return createForwardingDeployment(MODULE_NAME, false); } }
2,373
41.392857
112
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/forwarding/bean/stateful/RemoteStatefulSB.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.ejb.forwarding.bean.stateful; import org.jboss.as.test.clustering.cluster.ejb.forwarding.bean.common.CommonStatefulSB; import jakarta.ejb.Remote; /** * The enterprise bean must implement a business interface. That is, remote clients may not access an enterprise bean through a * no-interface view. * * @author Radoslav Husar */ @Remote public interface RemoteStatefulSB extends CommonStatefulSB { }
1,475
38.891892
127
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/forwarding/bean/stateful/RemoteStatefulSBImpl.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.ejb.forwarding.bean.stateful; import jakarta.ejb.Stateful; import org.jboss.as.test.clustering.cluster.ejb.forwarding.bean.common.CommonStatefulSBImpl; /** * @author Radoslav Husar */ @Stateful public class RemoteStatefulSBImpl extends CommonStatefulSBImpl implements RemoteStatefulSB { }
1,363
37.971429
92
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/forwarding/bean/common/CommonStatefulSB.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.ejb.forwarding.bean.common; public interface CommonStatefulSB { int getSerialAndIncrement(); }
1,170
39.37931
72
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/forwarding/bean/common/CommonStatefulSBImpl.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.ejb.forwarding.bean.common; import jakarta.annotation.PostConstruct; import jakarta.ejb.Remove; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import org.jboss.logging.Logger; @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public class CommonStatefulSBImpl implements CommonStatefulSB { private int serial; private static final Logger log = Logger.getLogger(CommonStatefulSBImpl.class.getName()); @PostConstruct private void init() { serial = 0; log.debugf("New SFSB created: %s.", this); } @Override public int getSerialAndIncrement() { log.debugf("getSerialAndIncrement() called on non-forwarding node %s", getCurrentNode()); return serial++; } @Remove private void destroy() { serial = -1; } private static String getCurrentNode() { return System.getProperty("jboss.node.name", "unknown"); } }
2,028
33.389831
97
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/forwarding/bean/forwarding/ForwardingStatefulSBImpl.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.ejb.forwarding.bean.forwarding; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import org.jboss.as.test.clustering.cluster.ejb.forwarding.bean.stateful.RemoteStatefulSB; @Stateful @TransactionAttribute(TransactionAttributeType.REQUIRED) // this is the default anyway public class ForwardingStatefulSBImpl extends AbstractForwardingStatefulSBImpl implements RemoteStatefulSB { // We need to override these methods so that the TransactionAttribute gets processed on this class! @Override public int getSerialAndIncrement() { return super.getSerialAndIncrement(); } }
1,731
40.238095
108
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/forwarding/bean/forwarding/AbstractForwardingStatefulSBImpl.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.ejb.forwarding.bean.forwarding; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import org.jboss.as.test.clustering.cluster.ejb.forwarding.bean.stateful.RemoteStatefulSB; import org.jboss.as.test.clustering.ejb.EJBDirectory; import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory; import org.jboss.logging.Logger; /** * @author Radoslav Husar */ @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public abstract class AbstractForwardingStatefulSBImpl { private static final Logger log = Logger.getLogger(AbstractForwardingStatefulSBImpl.class.getName()); public static final String MODULE_NAME = AbstractForwardingStatefulSBImpl.class.getSimpleName() + "-terminus"; private RemoteStatefulSB bean; private RemoteStatefulSB forward() { if (bean == null) { try (EJBDirectory directory = new RemoteEJBDirectory(MODULE_NAME)) { bean = directory.lookupStateful("RemoteStatefulSBImpl", RemoteStatefulSB.class); } catch (Exception e) { log.infof("exception occurred looking up ejb on forwarding node %s", getCurrentNode()); throw new RuntimeException(e); } } return bean; } public int getSerialAndIncrement() { log.debugf("getSerialAndIncrement() called on forwarding node %s", getCurrentNode()); return forward().getSerialAndIncrement(); } private static String getCurrentNode() { return System.getProperty("jboss.node.name", "unknown"); } }
2,636
39.569231
114
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/forwarding/bean/forwarding/NonTxForwardingStatefulSBImpl.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.ejb.forwarding.bean.forwarding; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import org.jboss.as.test.clustering.cluster.ejb.forwarding.bean.stateful.RemoteStatefulSB; @Stateful @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public class NonTxForwardingStatefulSBImpl extends AbstractForwardingStatefulSBImpl implements RemoteStatefulSB { }
1,498
41.828571
113
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/xpc/StatefulWithXPCFailoverTestCase.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.ejb.xpc; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Date; import jakarta.servlet.http.HttpServletResponse; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; 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.ejb.xpc.bean.StatefulBean; import org.jboss.as.test.clustering.cluster.ejb.xpc.servlet.StatefulServlet; import org.jboss.as.test.clustering.ejb.EJBDirectory; 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; /** * @author Paul Ferraro * @author Scott Marlow */ @RunWith(Arquillian.class) public class StatefulWithXPCFailoverTestCase extends AbstractClusteringTestCase { private static final String persistence_xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> " + "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">" + " <persistence-unit name=\"mypc\">" + " <description>Persistence Unit." + " </description>" + " <jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>" + "<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>" + "<properties> <property name=\"hibernate.hbm2ddl.auto\" value=\"create-drop\"/>" + "<property name=\"hibernate.cache.use_second_level_cache\" value=\"true\" />" + "<property name=\"hibernate.generate_statistics\" value=\"true\" />" + "<property name=\"hibernate.show_sql\" value=\"true\"/>" + "</properties>" + " </persistence-unit>" + "</persistence>"; @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, StatefulBean.MODULE + ".war"); war.addPackage(StatefulBean.class.getPackage()); war.addPackage(StatefulServlet.class.getPackage()); war.addPackage(EJBDirectory.class.getPackage()); war.setWebXML(StatefulServlet.class.getPackage(), "web.xml"); war.addAsResource(new StringAsset(persistence_xml), "META-INF/persistence.xml"); return war; } /** * Use the second level cache statistics to ensure that deleting an entity on a cluster node, will * remove the entity from the second level cache on other nodes. * <p/> * Note that this test writes to the separate databases on both cluster nodes (so that both nodes can * read the entity from the database). The important thing is that the second level cache entries are * invalidated when the entity is deleted from either database. * * @param baseURL1 * @param baseURL2 * @throws IOException * @throws InterruptedException * @throws URISyntaxException */ @Test public void testSecondLevelCache( @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException, URISyntaxException { URI xpc1_create_url = StatefulServlet.createEmployeeURI(baseURL1); URI xpc2_create_url = StatefulServlet.createEmployeeURI(baseURL2); URI xpc1_flush_url = StatefulServlet.flushURI(baseURL1); URI xpc2_flush_url = StatefulServlet.flushURI(baseURL2); URI xpc1_clear_url = StatefulServlet.clearURI(baseURL1); URI xpc2_clear_url = StatefulServlet.clearURI(baseURL2); URI xpc1_get_url = StatefulServlet.getEmployeeURI(baseURL1); URI xpc2_get_url = StatefulServlet.getEmployeeURI(baseURL2); URI xpc1_getdestroy_url = StatefulServlet.destroyURI(baseURL2); URI xpc1_delete_url = StatefulServlet.deleteEmployeeURI(baseURL1); URI xpc2_delete_url = StatefulServlet.deleteEmployeeURI(baseURL2); URI xpc1_secondLevelCacheEntries_url = StatefulServlet.getEmployeesIn2LCURI(baseURL1); URI xpc2_secondLevelCacheEntries_url = StatefulServlet.getEmployeesIn2LCURI(baseURL2); try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) { assertExecuteUrl(client, StatefulServlet.echoURI(baseURL1, "StartingTestSecondLevelCache")); // echo message to server.log assertExecuteUrl(client, StatefulServlet.echoURI(baseURL2, "StartingTestSecondLevelCache")); // echo message to server.log String employeeName = executeUrlWithAnswer(client, xpc1_create_url, "create entity in node1 in memory db"); assertEquals(employeeName, "Tom Brady"); log.trace(new Date() + "about to read entity on node1 (from xpc queue)"); employeeName = executeUrlWithAnswer(client, xpc1_get_url, "on node1, node1 should be able to read entity on node1"); assertEquals(employeeName, "Tom Brady"); String employeesInCache = executeUrlWithAnswer(client, xpc1_secondLevelCacheEntries_url, "get number of elements in node1 second level cache (should be zero)"); assertEquals(employeesInCache, "0"); // we read the entity from the extended persistence context (hasn't been flushed yet) assertExecuteUrl(client, xpc1_flush_url); // flush changes to db assertExecuteUrl(client, xpc1_clear_url); // clear xpc state so we have to reload employeeName = executeUrlWithAnswer(client, xpc2_create_url, "create entity in node2 in memory db (each node has its own database)"); assertEquals(employeeName, "Tom Brady"); assertExecuteUrl(client, xpc2_flush_url); // flush changes to db on second node assertExecuteUrl(client, xpc2_clear_url); // clear xpc state so we have to reload employeeName = executeUrlWithAnswer(client, xpc2_get_url, "node2 should be able to read entity from 2lc"); assertEquals(employeeName, "Tom Brady"); // we should of read one Employee entity on node2, ensure the second level cache contains one entry employeesInCache = executeUrlWithAnswer(client, xpc2_secondLevelCacheEntries_url, "get number of elements in node2 second level cache (should be zero)"); assertEquals(employeesInCache, "1"); assertExecuteUrl(client, StatefulServlet.echoURI(baseURL1, "testSecondLevelCacheclearedXPC")); assertExecuteUrl(client, StatefulServlet.echoURI(baseURL2, "testSecondLevelCacheclearedXPC")); assertExecuteUrl(client, xpc2_delete_url); // deleting the entity on one node should remove it from both nodes second level cache assertExecuteUrl(client, StatefulServlet.echoURI(baseURL1, "testSecondLevelCachedeletedEnityOnNode2")); assertExecuteUrl(client, StatefulServlet.echoURI(baseURL1, "2lcOnNode1ShouldHaveZeroElemementsLoaded")); employeesInCache = executeUrlWithAnswer(client, xpc1_secondLevelCacheEntries_url, "get number of elements in node1 second level cache (should be zero)"); assertEquals(employeesInCache, "0"); employeesInCache = executeUrlWithAnswer(client, xpc2_secondLevelCacheEntries_url, "get number of elements in node2 second level cache (should be zero)"); assertEquals(employeesInCache, "0"); assertExecuteUrl(client, xpc1_delete_url); String destroyed = executeUrlWithAnswer(client, xpc1_getdestroy_url, "destroy the bean on node1"); assertEquals(destroyed, "DESTROY"); } } @Test public void testBasicXPC( @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException, URISyntaxException { URI xpc1_create_url = StatefulServlet.createEmployeeURI(baseURL1); URI xpc1_get_url = StatefulServlet.getEmployeeURI(baseURL1); URI xpc2_get_url = StatefulServlet.getEmployeeURI(baseURL2); URI xpc1_getempsecond_url = StatefulServlet.get2ndBeanEmployeeURI(baseURL1); URI xpc2_getempsecond_url = StatefulServlet.get2ndBeanEmployeeURI(baseURL2); URI xpc2_getdestroy_url = StatefulServlet.destroyURI(baseURL2); try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) { stop(NODE_2); // extended persistence context is available on node1 log.trace(new Date() + "create employee entity "); String employeeName = executeUrlWithAnswer(client, xpc1_create_url, "create entity that lives in the extended persistence context that this test will verify is always available"); assertEquals(employeeName, "Tom Brady"); log.trace(new Date() + "1. about to read entity on node1"); // ensure that we can get it from node 1 employeeName = executeUrlWithAnswer(client, xpc1_get_url, "1. xpc on node1, node1 should be able to read entity on node1"); assertEquals(employeeName, "Tom Brady"); employeeName = executeUrlWithAnswer(client, xpc1_getempsecond_url, "1. xpc on node1, node1 should be able to read entity from second bean on node1"); assertEquals(employeeName, "Tom Brady"); start(NODE_2); log.trace(new Date() + "2. started node2 + deployed, about to read entity on node1"); employeeName = executeUrlWithAnswer(client, xpc2_get_url, "2. started node2, xpc on node1, node1 should be able to read entity on node1"); assertEquals(employeeName, "Tom Brady"); employeeName = executeUrlWithAnswer(client, xpc2_getempsecond_url, "2. started node2, xpc on node1, node1 should be able to read entity from second bean on node1"); assertEquals(employeeName, "Tom Brady"); // failover to deployment2 stop(NODE_1); // failover #1 to node 2 log.trace(new Date() + "3. stopped node1 to force failover, about to read entity on node2"); employeeName = executeUrlWithAnswer(client, xpc2_get_url, "3. stopped deployment on node1, xpc should failover to node2, node2 should be able to read entity from xpc"); assertEquals(employeeName, "Tom Brady"); employeeName = executeUrlWithAnswer(client, xpc2_getempsecond_url, "3. stopped deployment on node1, xpc should failover to node2, node2 should be able to read entity from xpc that is on node2 (second bean)"); assertEquals(employeeName, "Tom Brady"); String destroyed = executeUrlWithAnswer(client, xpc2_getdestroy_url, "4. destroy the bean on node2"); assertEquals(destroyed, "DESTROY"); log.trace(new Date() + "4. test is done"); } } private static String executeUrlWithAnswer(HttpClient client, URI url, String message) throws IOException { HttpResponse response = client.execute(new HttpGet(url)); try { assertEquals(200, response.getStatusLine().getStatusCode()); Header header = response.getFirstHeader("answer"); Assert.assertNotNull(message, header); return header.getValue(); } finally { HttpClientUtils.closeQuietly(response); } } private static void assertExecuteUrl(HttpClient client, URI url) throws IOException { HttpResponse response = client.execute(new HttpGet(url)); try { assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } } }
13,961
51.886364
220
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/xpc/servlet/StatefulServlet.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.ejb.xpc.servlet; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import javax.naming.NamingException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.jboss.as.test.clustering.cluster.ejb.xpc.bean.Employee; import org.jboss.as.test.clustering.cluster.ejb.xpc.bean.Stateful; import org.jboss.as.test.clustering.cluster.ejb.xpc.bean.StatefulBean; import org.jboss.as.test.clustering.ejb.LocalEJBDirectory; import org.jboss.logging.Logger; /** * @author Paul Ferraro */ @WebServlet(urlPatterns = { StatefulServlet.SERVLET_PATH }) public class StatefulServlet extends HttpServlet { private static final long serialVersionUID = -592774116315946908L; private static final String SERVLET_NAME = "count"; static final String SERVLET_PATH = "/" + SERVLET_NAME; public static final String ANSWER = "answer"; private static final String COMMAND = "command"; private static final String BEAN = "bean"; private static final String MESSAGE = "message"; private enum Command { CREATE_EMPLOYEE, GET_EMPLOYEE, DELETE_EMPLOYEE, GET_EMPLOYEES_IN_2LC, GET_2ND_BEAN_EMPLOYEE, DESTROY, FLUSH, ECHO, CLEAR, DELETE_EMPLOYEE_DIRECT, ; } private static final Logger log = Logger.getLogger(StatefulServlet.class); private static URI createURI(URL baseURL, Command command) throws URISyntaxException { return baseURL.toURI().resolve(buildCommandQuery(command).toString()); } private static StringBuilder buildCommandQuery(Command command) { return new StringBuilder(SERVLET_NAME).append('?').append(COMMAND).append('=').append(command); } public static URI createEmployeeURI(URL baseURL) throws URISyntaxException { return createURI(baseURL, Command.CREATE_EMPLOYEE); } public static URI getEmployeeURI(URL baseURL) throws URISyntaxException { return createURI(baseURL, Command.GET_EMPLOYEE); } public static URI deleteEmployeeURI(URL baseURL) throws URISyntaxException { return createURI(baseURL, Command.DELETE_EMPLOYEE); } public static URI getEmployeesIn2LCURI(URL baseURL) throws URISyntaxException { return createURI(baseURL, Command.GET_EMPLOYEES_IN_2LC); } public static URI get2ndBeanEmployeeURI(URL baseURL) throws URISyntaxException { return createURI(baseURL, Command.GET_2ND_BEAN_EMPLOYEE); } public static URI destroyURI(URL baseURL) throws URISyntaxException { return createURI(baseURL, Command.DESTROY); } public static URI flushURI(URL baseURL) throws URISyntaxException { return createURI(baseURL, Command.FLUSH); } public static URI echoURI(URL baseURL, String message) throws URISyntaxException, UnsupportedEncodingException { StringBuilder builder = buildCommandQuery(Command.ECHO); builder.append('&').append(MESSAGE).append('=').append(URLEncoder.encode(message, "UTF-8")); return baseURL.toURI().resolve(builder.toString()); } public static URI clearURI(URL baseURL) throws URISyntaxException { return createURI(baseURL, Command.CLEAR); } public static URI deleteEmployeeDirectURI(URL baseURL) throws URISyntaxException { return createURI(baseURL, Command.DELETE_EMPLOYEE_DIRECT); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(true); Stateful bean = (Stateful) session.getAttribute(BEAN); if (bean == null) { try (LocalEJBDirectory directory = new LocalEJBDirectory(StatefulBean.MODULE)) { bean = directory.lookupStateful(StatefulBean.class, Stateful.class); } catch (NamingException e) { throw new ServletException(e); } } Command command = Command.valueOf(req.getParameter(COMMAND)); log.trace(StatefulServlet.class.getName() + ": command = " + command); String answer = null; switch (command) { case CREATE_EMPLOYEE: { bean.createEmployee("Tom Brady", "New England Patriots", 1); answer = bean.getEmployee(1).getName(); break; } case GET_EMPLOYEE: { Employee employee = bean.getEmployee(1); if (employee == null) { throw new ServletException("couldn't load Employee entity (with id=1) from database"); } answer = employee.getName(); break; } case DELETE_EMPLOYEE: { bean.deleteEmployee(1); answer = command.toString(); break; } case GET_EMPLOYEES_IN_2LC: { long count = bean.getEmployeesInMemory(); if (count == -1) { throw new ServletException("couldn't get number of employees in second level cache"); } answer = String.valueOf(count); break; } case GET_2ND_BEAN_EMPLOYEE: { Employee employee = bean.getSecondBeanEmployee(1); answer = employee.getName(); break; } case DESTROY: { bean.destroy(); answer = command.toString(); break; } case FLUSH: { bean.flush(); break; } case ECHO: { bean.echo(req.getParameter(MESSAGE)); break; } case CLEAR: { bean.clear(); break; } case DELETE_EMPLOYEE_DIRECT: { // delete all employees in db int deleted = bean.executeNativeSQL("delete from Employee where id=1"); if (deleted < 1) { throw new ServletException("couldn't delete entity in database, deleted row count =" + deleted); } break; } } if (answer != null) { resp.setHeader(ANSWER, answer); } resp.getWriter().write("Success"); session.setAttribute(BEAN, bean); log.trace(StatefulServlet.class.getName() + ": command = " + command + " finished"); } }
7,877
37.057971
116
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/xpc/bean/Employee.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.clustering.cluster.ejb.xpc.bean; import java.io.Serializable; import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.Id; /** * Employee entity class * * @author Scott Marlow */ @Entity @Cacheable(true) // allow second level cache to cache Employee public class Employee implements Serializable { private static final long serialVersionUID = 6836274800449981797L; @Id private int id; private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return name; } }
2,019
24.897436
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/xpc/bean/StatefulBean.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.ejb.xpc.bean; import jakarta.ejb.Remove; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import jakarta.persistence.EntityManager; import jakarta.persistence.LockModeType; import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceContextType; import org.hibernate.Session; import org.hibernate.stat.CacheRegionStatistics; import org.jboss.logging.Logger; import java.util.HashMap; import java.util.Map; /** * @author Paul Ferraro * @author Scott Marlow */ @jakarta.ejb.Stateful(name = "StatefulBean") public class StatefulBean implements Stateful { private static final Logger log = Logger.getLogger(StatefulBean.class); public static final String MODULE = "stateful"; @PersistenceContext(unitName = "mypc", type = PersistenceContextType.EXTENDED) EntityManager em; String version = "initial"; Map<String, String> valueBag = new HashMap<>(); /** * Create the employee but don't commit the change to the database, instead keep it in the * extended persistence context. * * @param name * @param address * @param id */ @Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public void createEmployee(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); em.persist(emp); logStats("createEmployee"); version = "created"; valueBag.put("version", "created"); } @Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public Employee getEmployee(int id) { logStats("getEmployee " + id); return em.find(Employee.class, id, LockModeType.NONE); } @Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public Employee getSecondBeanEmployee(int id) { logStats("getSecondBeanEmployee"); //return secondBean.getEmployee(id); return em.find(Employee.class, id, LockModeType.NONE); } @Override @Remove public void destroy() { logStats("destroy"); version = "destroyed"; valueBag.put("version", version); } @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void deleteEmployee(int id) { Employee employee = em.find(Employee.class, id, LockModeType.NONE); em.remove(employee); logStats("deleteEmployee"); version = "deletedEmployee"; valueBag.put("version", version); } @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void flush() { logStats("flush"); version = "flushed"; valueBag.put("version", version); } @Override public void clear() { em.clear(); logStats("clear"); version = "cleared"; valueBag.put("version", version); } @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) @Override public void echo(String message) { log.trace("echo entered for " + message); logStats("echo " + message); log.trace("echo completed for " + message); } @TransactionAttribute(TransactionAttributeType.REQUIRED) @Override public int executeNativeSQL(String nativeSql) { logStats("executeNativeSQL"); return em.createNativeQuery(nativeSql).executeUpdate(); } @Override public String getVersion() { return version; } @Override public long getEmployeesInMemory() { Session session = em.unwrap(Session.class); String[] entityRegionNames = session.getSessionFactory().getStatistics().getSecondLevelCacheRegionNames(); String legacyPrefix = session.getSessionFactory().getSessionFactoryOptions().getCacheRegionPrefix() + "."; for (String qualifiedName : entityRegionNames) { if (qualifiedName.contains(Employee.class.getName())) { String name = qualifiedName.startsWith(legacyPrefix) ? qualifiedName.substring(legacyPrefix.length()) : qualifiedName; CacheRegionStatistics stats = session.getSessionFactory().getStatistics().getDomainDataRegionStatistics(name); return stats.getElementCountInMemory(); } } return -1; } private void logStats(String methodName) { Session session = em.unwrap(Session.class); log.trace(methodName + "(version=" + version + ", HashMap version=" + valueBag.get("version") + ") logging statistics for session = " + session); session.getSessionFactory().getStatistics().setStatisticsEnabled(true); session.getSessionFactory().getStatistics().logSummary(); String[] entityRegionNames = session.getSessionFactory().getStatistics().getSecondLevelCacheRegionNames(); String legacyPrefix = session.getSessionFactory().getSessionFactoryOptions().getCacheRegionPrefix() + "."; for (String qualifiedName : entityRegionNames) { log.trace("qualified cache entity region name = " + qualifiedName); String name = qualifiedName.startsWith(legacyPrefix) ? qualifiedName.substring(legacyPrefix.length()) : qualifiedName; log.trace("cache entity region name = " + name); CacheRegionStatistics stats = session.getSessionFactory().getStatistics().getCacheRegionStatistics(name); log.trace("2lc for " + name + ": " + stats.toString()); } // we will want to return the SecondLevelCacheStatistics for Employee } }
6,691
35.172973
153
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/xpc/bean/Stateful.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.ejb.xpc.bean; import jakarta.ejb.Remove; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; /** * Interface to see if that helps avoid the * error: * <p/> * WFLYEJB0034: EJB Invocation failed on component StatefulBean for method * public org.jboss.as.test.clustering.unmanaged.ejb3.xpc.bean.Employee * org.jboss.as.test.clustering.unmanaged.ejb3.xpc.bean.StatefulBean.getEmployee(int): * java.lang.IllegalArgumentException: object is not an instance of declaring class * * @author Scott Marlow */ public interface Stateful { @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) void createEmployee(String name, String address, int id); @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) Employee getEmployee(int id); @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) Employee getSecondBeanEmployee(int id); @Remove void destroy(); void flush(); void clear(); void deleteEmployee(int id); void echo(String message); int executeNativeSQL(String nativeSql); String getVersion(); long getEmployeesInMemory(); }
2,225
32.223881
86
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/ejb/xpc/bean/SecondBean.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.ejb.xpc.bean; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import jakarta.persistence.EntityManager; import jakarta.persistence.LockModeType; import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceContextType; /** * test bean that uses the same extended persistence context as StatefulBean and therefor should always be able to * retrieve the same entities that are only in the extended persistence context (purposely not persisted to the database). * * @author Scott Marlow */ @jakarta.ejb.Stateful public class SecondBean { @PersistenceContext(unitName = "mypc", type = PersistenceContextType.EXTENDED) EntityManager em; @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public Employee getEmployee(int id) { return em.find(Employee.class, id, LockModeType.NONE); } }
1,959
39
122
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/dispatcher/CommandDispatcherTestCase.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; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; 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.dispatcher.bean.ClusterTopology; import org.jboss.as.test.clustering.cluster.dispatcher.bean.ClusterTopologyRetriever; import org.jboss.as.test.clustering.cluster.dispatcher.bean.ClusterTopologyRetrieverBean; import org.jboss.as.test.clustering.ejb.EJBDirectory; import org.jboss.as.test.clustering.ejb.RemoteEJBDirectory; import org.jboss.as.test.shared.TimeoutUtil; 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 CommandDispatcherTestCase extends AbstractClusteringTestCase { private static final String MODULE_NAME = CommandDispatcherTestCase.class.getSimpleName(); private static final long VIEW_CHANGE_WAIT = TimeoutUtil.adjust(2000); @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(ClusterTopologyRetriever.class.getPackage()); war.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new RuntimePermission("getClassLoader")), "permissions.xml"); war.setWebXML(CommandDispatcherTestCase.class.getPackage(), "web.xml"); return war; } @Test public void test() throws Exception { try (EJBDirectory directory = new RemoteEJBDirectory(MODULE_NAME)) { ClusterTopologyRetriever bean = directory.lookupStateless(ClusterTopologyRetrieverBean.class, ClusterTopologyRetriever.class); ClusterTopology topology = bean.getClusterTopology(); assertEquals(2, topology.getNodes().size()); assertTrue(topology.getNodes().toString(), topology.getNodes().contains(NODE_1)); assertTrue(topology.getNodes().toString(), topology.getNodes().contains(NODE_2)); assertFalse(topology.getRemoteNodes().toString() + " should not contain " + topology.getLocalNode(), topology.getRemoteNodes().contains(topology.getLocalNode())); undeploy(DEPLOYMENT_2); topology = bean.getClusterTopology(); assertEquals(1, topology.getNodes().size()); assertTrue(topology.getNodes().contains(NODE_1)); assertEquals(NODE_1, topology.getLocalNode()); assertTrue(topology.getRemoteNodes().toString(), topology.getRemoteNodes().isEmpty()); deploy(DEPLOYMENT_2); Thread.sleep(VIEW_CHANGE_WAIT); topology = bean.getClusterTopology(); assertEquals(2, topology.getNodes().size()); assertTrue(topology.getNodes().contains(NODE_1)); assertTrue(topology.getNodes().contains(NODE_2)); assertFalse(topology.getRemoteNodes().toString() + " should not contain " + topology.getLocalNode(), topology.getRemoteNodes().contains(topology.getLocalNode())); stop(NODE_1); topology = bean.getClusterTopology(); assertEquals(1, topology.getNodes().size()); assertTrue(topology.getNodes().contains(NODE_2)); assertEquals(NODE_2, topology.getLocalNode()); assertTrue(topology.getRemoteNodes().toString(), topology.getRemoteNodes().isEmpty()); start(NODE_1); Thread.sleep(VIEW_CHANGE_WAIT); topology = bean.getClusterTopology(); assertEquals(topology.getNodes().toString(), 2, topology.getNodes().size()); assertTrue(topology.getNodes().toString() + " should contain " + NODE_1, topology.getNodes().contains(NODE_1)); assertTrue(topology.getNodes().toString() + " should contain " + NODE_2, topology.getNodes().contains(NODE_2)); assertFalse(topology.getRemoteNodes().toString() + " should not contain " + topology.getLocalNode(), topology.getRemoteNodes().contains(topology.getLocalNode())); } } }
5,851
47.766667
174
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/dispatcher/bean/CommandDispatcherBean.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 java.util.Map; import java.util.concurrent.CompletionStage; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.ejb.EJB; import jakarta.ejb.Local; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; import org.wildfly.clustering.dispatcher.Command; import org.wildfly.clustering.dispatcher.CommandDispatcher; import org.wildfly.clustering.dispatcher.CommandDispatcherException; import org.wildfly.clustering.dispatcher.CommandDispatcherFactory; import org.wildfly.clustering.group.Node; @Singleton @Startup @Local(CommandDispatcher.class) public class CommandDispatcherBean implements CommandDispatcher<Node> { @EJB private CommandDispatcherFactory factory; private CommandDispatcher<Node> dispatcher; @PostConstruct public void init() { this.dispatcher = this.factory.createCommandDispatcher(this.getClass().getSimpleName(), this.getContext()); } @PreDestroy public void destroy() { this.close(); } @Override public <R> CompletionStage<R> executeOnMember(Command<R, ? super Node> command, Node member) throws CommandDispatcherException { return this.dispatcher.executeOnMember(command, member); } @Override public <R> Map<Node, CompletionStage<R>> executeOnGroup(Command<R, ? super Node> command, Node... excludedMembers) throws CommandDispatcherException { return this.dispatcher.executeOnGroup(command, excludedMembers); } @Override public void close() { this.dispatcher.close(); } @Override public Node getContext() { return this.factory.getGroup().getLocalMember(); } }
2,757
34.358974
154
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/dispatcher/bean/CommandDispatcherFactoryBean.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 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.dispatcher.CommandDispatcher; import org.wildfly.clustering.dispatcher.CommandDispatcherFactory; import org.wildfly.clustering.group.Group; import org.wildfly.clustering.group.GroupListener; import org.wildfly.clustering.group.Membership; @Singleton @Startup @Local(CommandDispatcherFactory.class) public class CommandDispatcherFactoryBean implements CommandDispatcherFactory, GroupListener { @Resource(name = "clustering/dispatcher") private CommandDispatcherFactory factory; private Registration registration; @PostConstruct public void init() { this.registration = this.factory.getGroup().register(this); } @PreDestroy public void destroy() { this.registration.close(); } @Override public <C> CommandDispatcher<C> createCommandDispatcher(Object service, C context) { return this.factory.createCommandDispatcher(service, context); } @Override public Group getGroup() { return this.factory.getGroup(); } @Override public void membershipChanged(Membership previousMembership, Membership membership, boolean merged) { 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/dispatcher"); } finally { context.close(); } } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } catch (NamingException e) { throw new IllegalStateException(e); } System.out.println(String.format("Previous membership = %s, current membership = %s, merged = %s", previousMembership, membership, merged)); } }
3,395
36.733333
148
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/dispatcher/bean/ClusterTopologyRetrieverBean.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 java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import jakarta.ejb.EJB; import jakarta.ejb.Remote; import jakarta.ejb.Stateless; import org.wildfly.clustering.dispatcher.Command; import org.wildfly.clustering.dispatcher.CommandDispatcher; import org.wildfly.clustering.dispatcher.CommandDispatcherException; import org.wildfly.clustering.dispatcher.CommandDispatcherFactory; import org.wildfly.clustering.group.Node; @Stateless @Remote(ClusterTopologyRetriever.class) public class ClusterTopologyRetrieverBean implements ClusterTopologyRetriever { @EJB private CommandDispatcher<Node> dispatcher; @EJB private CommandDispatcherFactory factory; private final Command<String, Node> command = new TestCommand(); private final Command<Void, Node> exceptionCommand = new ExceptionCommand(); @Override public ClusterTopology getClusterTopology() { try { Collection<CompletionStage<String>> responses = this.dispatcher.executeOnGroup(this.command).values(); List<String> nodes = new ArrayList<>(responses.size()); for (CompletionStage<String> response: responses) { try { nodes.add(response.toCompletableFuture().join()); } catch (CancellationException e) { // Ignore } } Node localNode = this.factory.getGroup().getLocalMember(); String local = this.dispatcher.executeOnMember(this.command, localNode).toCompletableFuture().join(); responses = this.dispatcher.executeOnGroup(this.command, localNode).values(); List<String> remote = new ArrayList<>(responses.size()); for (CompletionStage<String> response: responses) { try { remote.add(response.toCompletableFuture().join()); } catch (CancellationException e) { // Ignore } } for (CompletionStage<Void> response: this.dispatcher.executeOnGroup(this.exceptionCommand).values()) { try { response.toCompletableFuture().join(); throw new IllegalStateException("Exception expected"); } catch (CancellationException e) { // Ignore } catch (CompletionException e) { e.printStackTrace(System.err); assert Exception.class.equals(e.getCause().getClass()) : e.getCause().getClass().getName(); } } return new ClusterTopology(nodes, local, remote); } catch (CommandDispatcherException e) { throw new IllegalStateException(e.getCause()); } } }
4,013
41.252632
114
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/dispatcher/bean/ClusterTopologyRetriever.java
package org.jboss.as.test.clustering.cluster.dispatcher.bean; public interface ClusterTopologyRetriever { ClusterTopology getClusterTopology(); }
152
20.857143
61
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/dispatcher/bean/ExceptionCommand.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 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 org.wildfly.clustering.dispatcher.Command; import org.wildfly.clustering.group.Node; /** * @author Paul Ferraro */ public class ExceptionCommand implements Command<Void, Node> { private static final long serialVersionUID = 8799161775551957641L; @Override public Void execute(Node context) throws Exception { throw new Exception(); } }
1,457
36.384615
70
java
null
wildfly-main/testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/dispatcher/bean/ClusterTopology.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 java.io.Serializable; import java.util.Collection; public class ClusterTopology implements Serializable { private static final long serialVersionUID = 413628123168918069L; private final Collection<String> nodes; private final String localNode; private final Collection<String> remoteNodes; public ClusterTopology(Collection<String> nodes, String localNode, Collection<String> remoteNodes) { this.nodes = nodes; this.localNode = localNode; this.remoteNodes = remoteNodes; } public Collection<String> getNodes() { return this.nodes; } public String getLocalNode() { return this.localNode; } public Collection<String> getRemoteNodes() { return this.remoteNodes; } }
1,858
34.75
104
java