I've developed a test Java EE application to send and receive messages through the MQTT protocol (tcp connection). Under JBoss 7.1 I got a @Singleton @Startup that instantiates an Eclipse Paho client and a callback class.
@Singleton
@Startup
public class PahoClient implements PahoClientLocal {
@EJB
VehicleStatusLocal vehicleS;
private MqttClient client;
SubscribeCallback callback;
private List<String> logStat = new ArrayList<String>();
@PostConstruct
public void start() throws MqttException {
try {
System.out.println("NM info: STARTING MQTT CLIENT");
client = new MqttClient("tcp://localhost", "NetworkManager", new MemoryPersistence());
//CLIENT CONNECTION OPTIONS
...
client.connect(mqttConnectOptions);
//MESSAGE LISTENER
callback = new SubscribeCallback(this, NM_STATUS_TOPIC, NM_ALARM_TOPIC);
client.setCallback(callback);
//TOPIC SUBSCRIBE
...
} catch (MqttException e) {
.....
}
public void sendMessage(String message) throws MqttPersistenceException, MqttException{
this.client.publish(DEVICE_STATUS_TOPIC, message.getBytes(), 2, false);
}
//
@Asynchronous
public void update(String matricola, String status, String latitude, String longitude, String battery){
vehicleS.updateVehicle(matricola, status, Double.parseDouble(latitude), Double.parseDouble(longitude), Integer.parseInt(battery));
}
I want to update received values to another bean. But in my Callback class i cannot inject any EJB (it breaks tcp connection) so i get the PahoClient instance in this way as you can see above:
callback = new SubscribeCallback(this, NM_STATUS_TOPIC, NM_ALARM_TOPIC)
So when i receive a message on my callback method i update values in this way public class SubscribeCallback implements MqttCallback{
public SubscribeCallback(PahoClient pahoClient, String topicNM, String topicALARM) {
this.client=pahoClient;
this.NM_STATUS_TOPIC = topicNM;
this.NM_ALARM_TOPIC = topicALARM;
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception{
..
pahoClient.update(msg);
It seems to work fine. But in the console I see the MQTT thread updating the message, not the EJB. And I don't know if with a lot connections this works. Any suggestion?
I was thinking about developing a JCA Adapter for my MQTT Client and my Java EE application, but I don't know if it's the right way.