EAP 7: EJB state not replicated between stateful session beans in cluster mode - infinispan

I have running two EAP 7.0 instances, both with standalone-full-ha.xml
One is started with:
/opt/jboss-eap-7.0/bin/standalone.sh -Djboss.node.name=node1 -Djboss.server.base.dir=/opt/node1 -Djboss.messaging.cluster.password=message -c standalone-full-ha.xml
The other one with:
/opt/jboss-eap-7.0/bin/standalone.sh -Djboss.node.name=node2 -Djboss.server.base.dir=/opt/node2 -Djboss.messaging.cluster.password=message -c standalone-full-ha.xml -Djboss.socket.binding.port-offset=4
Both start with success and I can see they join the cluster channel:
[org.infinispan.remoting.transport.jgroups.JGroupsTransport] (MSC service thread 1-6) ISPN000078: Starting JGroups channel ejb
...
[org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 72) WFLYCLINF0002: Started eap.war cache from ejb container
I have a stateful session bean:
import javax.ejb.Stateful;
#Stateful
public class Counter {
int counter;
public int getCounter() {
++counter;
return counter;
}
}
A JSF application scoped bean:
import java.io.Serializable;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;
#ApplicationScoped
#Named
public class IndexBean implements Serializable {
#Inject
transient Counter counter;
public int getCounter() {
return counter.getCounter();
}
}
A JSF session scoped bean:
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#SessionScoped
#Named
public class SessionBean implements Serializable {
int counter;
public int getCounter() {
++counter;
return counter;
}
}
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" metadata-complete="false" version="3.1">
<distributable/>
</web-app>
And index.xhtml:
<html
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>EAP 7</title>
</h:head>
<h:body>
<h:outputText value="#{indexBean.counter}"></h:outputText>
<br />
<br />
<h:outputText value="#{sessionBean.counter}"></h:outputText>
</h:body>
</html>
Now when I navigate to node1 on localhost:8080/index.xhtml I have a webppage with two counters starting with 1. And every time I refresh the page it counts up.
When I navigate to node2 on localhost:8084/index.xhtml I expect to see both last incremented values from node1, but the counter coming from the #Stateful bean doesn't increment on the value from node1.
Example:
navigate to node1:
1
1
-> refresh node1
2
2
-> refresh node1
3
3
navigate to node2:
1
4
-> refresh node2
2
5
refresh again node1:
4
6
refresh again node2:
3
8
The two pages work independently, however the state between the stateful session beans should be replicated. I don't understand why it doesn't work. The state between the #SessionScoped beans is always replicated...
I was looking for some documentation and found this:
https://access.redhat.com/documentation/en-us/red_hat_jboss_enterprise_application_platform/7.0/html/developing_ejb_applications/clustered_enterprise_javabeans#cluster_topology_communication
Here is stated in the end of section 8.2:
Starting JBoss EAP 7, if JBoss EAP is started using an HA profile, the
state of your SFSBs will be replicated.
Is there more configuration needed for #Stateful beans?

The issue with your code above is that the #ApplicationScoped SFSB reference isn't shared between node1 and node2, even though the state itself is replicated.

Related

CDI doesn't work in a simple adapter

I've added the CDI feature to the server.xml file<feature>cdi-1.2</feature>.
My maven module contains the beans.xml inside the <module_name>/src/main/resources/META-INF folder.
This is the beans.xml content:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
</beans>
But when I use the #Inject annotation it doesn't work, my bean is always null.
Code:
package ch.webapp.presentation;
...
#Path("/test/")
public class MyController {
#Inject
private MyService myService;
#GET
#Path("/foo/{count}")
#OAuthSecurity(scope = "login")
#Produces("application/json")
public Response news(#PathParam("count") int count) {
return Response
.ok(myService.getBar(count))
.build();
}
}
EDIT:
That's my bean
package ch.webapp.service;
...
#RequestScoped
public class MyService {
public String getBar(int count) {
return "foo";
}
}
I initialize jax-rs by extended the MFPJAXRSApplication class
package ch.webapp;
...
public class AccountApplication extends MFPJAXRSApplication {
#Override
protected void init() throws Exception {
}
#Override
protected void destroy() throws Exception {
}
#Override
protected String getPackageToScan() {
return getClass().getPackage().getName();
}
}
Environment details:
Launching mfp (WebSphere Application Server 8.5.5.8/wlp-1.0.11.cl50820151201-1942) on Java HotSpot(TM) 64-Bit Server VM, version 1.8.0_172-b11 (en_CH)
Console Product version: 8.0.0.00-20180717-175523
What's wrong?
First it seems that websphere jax-rs implementation does not integrate jax-rs resources automatically unless you annotate them appropriately.
Put the jax-rs in a CDI managed context by annotating it appropriately
#Path("/test/")
#javax.enterprise.context.RequestScoped
public class MyController {
#Inject
private MyService myService;
#GET
#Path("/foo/{count}")
#OAuthSecurity(scope = "login")
#Produces("application/json")
public Response news(#PathParam("count") int count) {
return Response
.ok(myService.getBar(count))
.build();
}
}
Also be sure that the annotation used for your service is
#javax.enterprise.context.RequestScoped
Based on the inputs provided by you please go through the below checklist.
Your services and controllers are in the same module and its packaging type is war, So you must place your beans.xml in this path src/main/resources/WEB-INF/beans.xml. (If this is Java EE 7 application then beans.xml is optional.
In your AccountApplication class try hardcoding the package name to ch.webapp.presentation
#Override
protected String getPackageToScan() {
return "ch.webapp.presentation";
}
This is just to check Behaviour of MFPJAXRSApplication.getPackageToScan() method whether it is scanning the specified package only or its child packages too.
Except these, everything seems fine to me. If this still doesn't work add complete application startup logs so that community can find the root cause of it.
This is classical mistake. CDI works for managed beans (for instance EJB's and servlets). If you want to enable it on your JAXRS bean, you have to make it "managed", that is annotate MyController as (for instance) javax.annotation.ManagedBean or as a javax.ejb.Stateless.
Also beware that in case of webapp (.war), the beans.xml file has to be located in the WEB-INF folder !

How to use Apache Apex Malhar RabbitMQ operator in DAG

I have an Apache Apex application DAG which reads RabbitMQ message from a queue. Which Apache Apex Malhar operator should I use? There are several operators but it's not clear which one to use and how to use it.
Have you looked at https://github.com/apache/apex-malhar/tree/master/contrib/src/main/java/com/datatorrent/contrib/rabbitmq ? There are also tests in https://github.com/apache/apex-malhar/tree/master/contrib/src/test/java/com/datatorrent/contrib/rabbitmq that show how to use the operator
https://github.com/apache/apex-malhar/blob/master/contrib/src/main/java/com/datatorrent/contrib/rabbitmq/AbstractRabbitMQInputOperator.java
That is the main operator code where the tuple type is a generic parameter and emitTuple() is an abstract method that subclasses need to implement.
AbstractSinglePortRabbitMQInputOperator is a simple subclass that provides a single output port and implements emitTuple() using another abstract method getTuple() which needs an implementation in its subclasses.
The tests that Sanjay pointed to show how to use these classes.
I also had problems finding out how to read messages from RabbitMQ to Apache Apex. With the help of the provided links of Sanjay's answer (https://stackoverflow.com/a/42210636/2350644) I finally managed to get it running. Here's how it works all together:
1. Setup a RabbitMQ Server
There are lot of ways installing RabbitMQ that are described here: https://www.rabbitmq.com/download.html
The simplest way for me was using docker (See: https://store.docker.com/images/rabbitmq)
docker pull rabbitmq
docker run -d --hostname my-rabbit --name some-rabbit -p 5672:5672 -p 15672:15672 rabbitmq:3-management
To check if RabbitMQ is working, open a browser and navigate to: http://localhost:15672/. You should see the Management page of RabbitMQ.
2. Write a Producer program
To send messages to the queue you can write a simple JAVA program like this:
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.util.ArrayList;
public class Send {
private final static String EXCHANGE = "myExchange";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE, BuiltinExchangeType.FANOUT);
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, EXCHANGE, "");
List<String> messages = Arrays.asList("Hello", "World", "!");
for (String msg : messages) {
channel.basicPublish(EXCHANGE, "", null, msg.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + msg + "'");
}
channel.close();
connection.close();
}
}
If you execute the JAVA program you should see some outputs in the Management UI of RabbitMQ.
3. Implement a sample Apex Application
3.1 Bootstrap a sample apex application
Follow the official apex documentation http://docs.datatorrent.com/beginner/
3.2 Add additional dependencies to pom.xml
To use the classes provided by malhar add the following dependencies:
<dependency>
<groupId>org.apache.apex</groupId>
<artifactId>malhar-contrib</artifactId>
<version>3.7.0</version>
</dependency>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>4.2.0</version>
</dependency>
3.3 Create a Consumer
We first need to create an InputOperator that consumes messages from RabbitMQ using available code from apex-malhar.
import com.datatorrent.contrib.rabbitmq.AbstractSinglePortRabbitMQInputOperator;
public class MyRabbitMQInputOperator extends AbstractSinglePortRabbitMQInputOperator<String> {
#Override
public String getTuple(byte[] message) {
return new String(message);
}
}
You only have to override the getTuple() method. In this case we simply return the message that was received from RabbitMQ.
3.4 Setup an Apex DAG
To test the application we simply add an InputOperator (MyRabbitMQInputOperator that we implemented before) that consumes data from RabbitMQ and a ConsoleOutputOperator that prints the received messages.
import com.rabbitmq.client.BuiltinExchangeType;
import org.apache.hadoop.conf.Configuration;
import com.datatorrent.api.annotation.ApplicationAnnotation;
import com.datatorrent.api.StreamingApplication;
import com.datatorrent.api.DAG;
import com.datatorrent.api.DAG.Locality;
import com.datatorrent.lib.io.ConsoleOutputOperator;
#ApplicationAnnotation(name="MyFirstApplication")
public class Application implements StreamingApplication
{
private final static String EXCHANGE = "myExchange";
#Override
public void populateDAG(DAG dag, Configuration conf)
{
MyRabbitMQInputOperator consumer = dag.addOperator("Consumer", new MyRabbitMQInputOperator());
consumer.setHost("localhost");
consumer.setExchange(EXCHANGE);
consumer.setExchangeType(BuiltinExchangeType.FANOUT.getType());
ConsoleOutputOperator cons = dag.addOperator("console", new ConsoleOutputOperator());
dag.addStream("myStream", consumer.outputPort, cons.input).setLocality(Locality.CONTAINER_LOCAL);
}
}
3.5 Test the Application
To simply test the created application we can write a UnitTest, so there is no need to setup a Hadoop/YARN cluster.
In the bootstrap application there is already a UnitTest namely ApplicationTest.java that we can use:
import java.io.IOException;
import javax.validation.ConstraintViolationException;
import org.junit.Assert;
import org.apache.hadoop.conf.Configuration;
import org.junit.Test;
import com.datatorrent.api.LocalMode;
/**
* Test the DAG declaration in local mode.
*/
public class ApplicationTest {
#Test
public void testApplication() throws IOException, Exception {
try {
LocalMode lma = LocalMode.newInstance();
Configuration conf = new Configuration(true);
//conf.addResource(this.getClass().getResourceAsStream("/META-INF/properties.xml"));
lma.prepareDAG(new Application(), conf);
LocalMode.Controller lc = lma.getController();
lc.run(10000); // runs for 10 seconds and quits
} catch (ConstraintViolationException e) {
Assert.fail("constraint violations: " + e.getConstraintViolations());
}
}
}
Since we don't need any properties for this application the only thing changed in this file is uncommenting the line:
conf.addResource(this.getClass().getResourceAsStream("/META-INF/properties.xml"));
If you execute the ApplicationTest.java and send messages to RabbitMQ using the Producer program as described in 2., the Test should output all the messages.
You might need to increase the time of the test to see all messages (It is set to 10sec currently).

Arquillian with Windows and Glassfish 4.1 very slow

I've created a java web app with JSF 2.2.12, Prime Faces 6 and Omnifaces. In the backend I've the standard layers like Spring, Hibernate and my application server is Glassfish 4.1.1
I'm implementing some tests with Arquillian. The strangeness is that on Linux(Ubuntu 16) works but with Windows doesn't.
Here my Arquillian.xml file
<?xml version="1.0"?>
<arquillian xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://jboss.org/schema/arquillian"
xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<container qualifier="glassfish" default="true">
<configuration>
<property name="remoteServerAddress">localhost</property>
<property name="remoteServerHttpPort">8080</property>
<property name="remoteServerAdminPort">4848</property>
</configuration>
</container>
<extension qualifier="webdriver">
<property name="browser">chrome</property>
<property name="remoteReusable">true</property>
</extension>
</arquillian>
And here one example of test class
public class IndexFrontendTest extends BaseArquillianTest {
#Drone
private WebDriver browser;
#ArquillianResource
private URL deploymentUrl;
#Page
private IndexPage indexPage;
private FrontendTestComponent frontendTestComponent;
#Before
public void setUp() {
browser.manage().window().setSize(new Dimension(1920, 1080));
browser.get(deploymentUrl.toExternalForm());
frontendTestComponent = new FrontendTestComponent();
}
#RunAsClient
#Test
public void testCarManufacturersAndModels() {
indexPage.getCarManufacturersDropdown().selectByVisibleText("Ajax");
frontendTestComponent.waitForJStoLoad(browser);
frontendTestComponent.checkSelect(indexPage.getCarModelsDropdown(), 1, true);
}
#RunAsClient
#Test
public void testContinentsAndCountries() {
indexPage.getContinentsDropdown().selectByValue("1");
frontendTestComponent.waitForJStoLoad(browser);
frontendTestComponent.checkSelect(indexPage.getCountriesDropdown(), 45, true);
}
}
The BaseArquillianTest class has only the static method for the deploy
#RunWith(Arquillian.class)
public abstract class BaseArquillianTest {
#Deployment(testable = true)
public static WebArchive createDeployment() throws IOException {
...
...
}
}
My Dev machine have the dual boot.
On Linux my tests take 60 seconds.
On Windows takes 20 minutes and sometimes I see and error like "Bad Request".
I've tried 2 different browsers (phantomjs and chrome) but the situation is the same
I've tried to search on internet but seems to be anyone have this error. I suppose I'm making some mistakes on configurations.
Please can you help me?
The problem is a bug inside Glassfish.
I've switched to Payara and now it is fine, even if in order to complete 4 tests(and 2 deploys) it takes 2 minutes.
I don't know if that is an acceptable time?

How to execute a jar file on jboss7 startup?

I have a simple java class which displays "waiting" text on execution , in "TMSCore" java project.
package com.stock.bo;
public class example {
/**
* #param args
*/
public static void main(String[] args) {
// ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("================================> waiting");
}
}
I have created TMSCore.jar and have set this example.class as entry point ,of my jar file.
Then i have created a module for this project in C:\Jboss\jboss-as-7.1.1\modules\org\tms\main , and pasted the jar in the same path
then i have created module.xml and pasted in the same path
module.xml
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.tms">
<resources>
<resource-root path="TMSCore.jar"/>
</resources>
</module>
then i have created a jboss-deployment-structure.xml in my webproject/web-inf directory
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
<deployment>
<dependencies>
<module name="org.tms"/>
</dependencies>
</deployment>
</jboss-deployment-structure>
when i start the server with my war containing above jboss-deployment-structure.xml, in my console its showing deployed TMSCore.jar
but my "waiting" text in my jar is not displayed on console
my requirement is i should get "================================> waiting" on my console once jboss is started up
or else can any one can suggest how to make a jar to execute on starting jboss server?
BTW i am using JBOSS7.1
If I am right it's because JBoss doesn't execute a library, it only loads the classes contained in the jar file. So putting a main function and generating an executable jar will not help.
If your goal is to have an global module on the server, I suggest you these modifications:
Create the module (as you have already done)
Declare it as dependency in jboss-deployment-structure.xml (as you have already done)
Declare it as global module on the server, so it will be loaded only once by JBoss. Edit the configuration file standalone.xml and modify the section:
<subsystem xmlns="urn:jboss:domain:ee:1.0">
<global-modules>
<module name="org.tms" />
</global-modules>
</subsystem>
Now you have a module that have classes loaded only once. I you need to have only one instance of your Example class, the I suggest you to use an singleton:
public class Example {
// The only one instance
private static Example instance;
// Private constructor to avoid creation of other instances of this class
private Example()
{
System.out.println("================================> waiting");
}
public static Example getInstance()
{
if(instance == null)
{
instance = new Example();
}
return instance;
}
}
Then to use it in all projects on the server
Example ex = Example.getInstance();
will give you back the existing instance (or create one the first time).
Notice: I can't try, so no guarantee that that will work.
Edit: Maybe a small modification of the Example class can also make it run during the classes loading:
public class Example {
// The only one instance
private static Example instance = new Example();
// Private constructor to avoid creation of other instances of this class
private Example()
{
System.out.println("================================> waiting");
}
public static Example getInstance()
{
return instance;
}
}
Again: not tested.
You can't run a jar, but you can execute a startup method in a singleton.
#Startup
#Singleton
public class FooBean {
#PostConstruct
void atStartup() { ... }
#PreDestroy
void atShutdown() { ... }
}
This will happen at application start up and shutdown. I'd call the function you need from there.
See http://docs.oracle.com/javaee/6/tutorial/doc/gipvi.html

How to start Camel routes on slave ActiveMQ only when slave becomes active in failover?

I have a durable consumer to a remote JMS queue in embedded Camel routing. Is it possible to have this kind of routing with master-slave configuration? Now it seems that the Camel routes are started and activated already when slave ActiveMQ is started and not when the actual failover happens.
Now it causes the slave instance to receive the same messages that are also sent to master and this causes duplicate messages to arrive to the queue on failover.
I'm using ActiveMQ 5.3 along with Apache Camel 2.1.
Unfortunately, when the slave broker starts so does the CamelContext along with the routes. However you can accomplish this by doing the following:
On the camelContext deployed with slave broker add the following autoStartup attribute to prevent the routes from starting:
<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring" autoStartup="false">
...
</camelContext>
Next you need to create a class that implements the ActiveMQ Service Interface. A sample of this would be as follows:
package com.fusesource.example;
import org.apache.activemq.Service;
import org.apache.camel.spring.SpringCamelContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Example used to start and stop the camel context using the ActiveMQ Service interface
*
*/
public class CamelContextService implements Service
{
private final Logger LOG = LoggerFactory.getLogger(CamelContextService.class);
SpringCamelContext camel;
#Override
public void start() throws Exception {
try {
camel.start();
} catch (Exception e) {
LOG.error("Unable to start camel context: " + camel);
e.printStackTrace();
}
}
#Override
public void stop() throws Exception {
try {
camel.stop();
} catch (Exception e) {
LOG.error("Unable to stop camel context: " + camel);
e.printStackTrace();
}
}
public SpringCamelContext getCamel() {
return camel;
}
public void setCamel(SpringCamelContext camel) {
this.camel = camel;
}
}
Then in broker's configuration file, activemq.xml, add the following to register the service:
<services>
<bean xmlns="http://www.springframework.org/schema/beans" class="com.fusesource.example.CamelContextService">
<property name="camel" ref="camel"/>
</bean>
</services>
Now, once the slave broker takes over as the master, the start method will be invoked on the service class and the routes will be started.
I have also posted a blog about this here: http://jason-sherman.blogspot.com/2012/04/activemq-how-to-startstop-camel-routes.html
this shouldn't be an issue because the Camel context/routes on the slave will not start until it becomes the master (when the message store file lock is released by the master)
With camel routepolicies you can decide to suspend/resume certain routes based on your own conditions.
http://camel.apache.org/routepolicy.html
There is an existing ZookeeperRoutePolicy that can be used to do leader election.
http://camel.apache.org/zookeeper.html (see bottom of the page)