Unsubscribe durable subscribers with ActiveMQ - java

I'm trying to UNSUBSCRIBE durable subscribers from TOPICS.
My app is a kind of social network : each user is a topic for other users. So, each time a user is doing something, his friends are notified. Of course, a subscriber may unsubscribe from a topic, wanting to receive notifications about a user no more.
Each time I'm trying to unsubscribe a subscriber from a topic, I've got an error telling me that : "javax.jms.JMSException: Durable consumer is in use"
Here are my 2 classes, the SENDER one and the RECEIVER one. Can someone tell me what I'm doing wrong ??
SENDER Class :
package com.citizenweb.classes;
import java.util.Date;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageFormatException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.ObjectMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQSession;
import com.citizenweb.interfaces.PostIF;
import com.citizenweb.interfaces.UserIF;
public class Sender {
private ActiveMQConnectionFactory factory = null;
private ActiveMQConnection connection = null;
private ActiveMQSession session = null;
private Destination destination = null;
private MessageProducer producer = null;
public Sender() {
}
public void connect(){
try{
factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
// TODO Mécanisme de sécurité d'ActiveMQ à rétablir en production
factory.setTrustAllPackages(true);
connection = (ActiveMQConnection) factory.createConnection();
connection.start();
session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
} catch (JMSException e){
e.printStackTrace();
}
}
public void sendPost(UserIF user,PostIF post) {
if(session==null){connect();}
try {
destination = session.createTopic(user.toString());
producer = session.createProducer(destination);
ObjectMessage postMessage = session.createObjectMessage();
postMessage.setObject(post);
producer.send(postMessage);
System.out.println("\n SENDER Object message sent");
} catch (MessageFormatException e) {
e.printStackTrace();
} catch (JMSException e) {
e.printStackTrace();
}
}
public void sendInformation(UserIF user,String info){
if(session==null){connect();}
try {
destination = session.createTopic(user.toString());
producer = session.createProducer(destination);
TextMessage infoMessage = session.createTextMessage();
infoMessage.setText(info);
producer.send(infoMessage);
System.out.println("\n SENDER Information message sent");
} catch (JMSException e) {
e.printStackTrace();
}
}
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
UserIF u1, u2, u3;
String[] nom = new String[5];
String[] prenom = new String[5];
String[] login = new String[5];
String[] password = new String[5];
Date[] naiss = new Date[5];
String[] mail = new String[5];
for (int i = 0; i < 5; i++) {
nom[i] = "nom_" + i;
prenom[i] = "prenom_" + i;
login[i] = "login_" + i;
password[i] = "password_" + i;
naiss[i] = new Date();
mail[i] = "mail_" + i;
}
System.out.println("\n SENDER AFFECTATION DES NOMS");
u1 = new User(nom[0], prenom[0], login[0], password[0], naiss[0], mail[0]);
u2 = new User(nom[1], prenom[1], login[1], password[1], naiss[1], mail[1]);
u3 = new User(nom[2], prenom[2], login[2], password[2], naiss[2], mail[2]);
Sender sender = new Sender();
sender.sendInformation(u1, "U1 notification");
sender.sendInformation(u2, "U2 notification");
sender.sendInformation(u3, "U3 notification");
//PostIF post = new Post("Mon Post","Ceci est mon message",u1,u1,"Classe Sender",((User) u1).getIdUser(),0);
//sender.sendPost(user, post);
sender.session.close();
sender.connection.close();
}
}
RECEIVER Class :
package com.citizenweb.classes;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQSession;
import org.apache.activemq.broker.region.Destination;
import com.citizenweb.interfaces.PostIF;
import com.citizenweb.interfaces.UserIF;
import com.citizenweb.classes.Post;
public class Receiver implements MessageListener, Serializable {
private static final long serialVersionUID = 1L;
private ActiveMQConnectionFactory factory = null;
private ActiveMQConnection connection = null;
private ActiveMQSession session = null;
private Topic destination = null;
private MessageConsumer consumer = null;
UserIF userTopic = new User();
UserIF userSubscriber = new User();
List<Message> listeMsg = new ArrayList<Message>();
public Receiver(UserIF subscriber) {
this.userSubscriber = subscriber;
}
public void connect() {
try {
factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
// TODO Mécanisme de sécurité d'ActiveMQ à rétablir en production
factory.setTrustAllPackages(true);
connection = (ActiveMQConnection) factory.createConnection();
// ClientID :
// https://qnalist.com/questions/2068823/create-durable-topic-subscriber
connection.setClientID(userSubscriber.toString());
connection.start();
session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
} catch (JMSException e) {
e.printStackTrace();
}
}
public void receiveMessage(UserIF topic) {
try {
if (session == null) {
connect();
}
destination = session.createTopic(topic.toString());
String nomAbonnement = topic.toString() + "->" + userSubscriber.toString();
//String nomAbonnement = userSubscriber.toString();
consumer = session.createDurableSubscriber(destination, nomAbonnement);
consumer.setMessageListener(this);
} catch (JMSException e) {
e.printStackTrace();
}
}
public void unsubscribe(UserIF topic) {
try {
if (session == null) {
connect();
}
System.out.println("\n RECEIVER Désinscription du topic " + topic.toString());
//consumer.close();
String nomAbonnement = topic.toString() + "->" + userSubscriber.toString();
//String nomAbonnement = userSubscriber.toString();
System.out.println("\n RECEIVER Abonnement à clore = " + nomAbonnement);
session.unsubscribe(nomAbonnement);
System.out.println("\n RECEIVER " + userSubscriber.toString() + " s'est désinscrit de " + nomAbonnement);
} catch (JMSException e) {
e.printStackTrace();
}
}
#Override
public void onMessage(Message message) {
System.out.println("\n RECEIVER OnMessage triggered for " + userSubscriber.toString());
listeMsg.add(message);
System.out.println("\n RECEIVER Nombre de messages reçus par " + userSubscriber + " = " + listeMsg.size());
String classe = message.getClass().getSimpleName();
System.out.println("\n RECEIVER Classe de message : " + classe);
try {
if (message instanceof TextMessage) {
TextMessage text = (TextMessage) message;
System.out.println("\n RECEIVER Information : " + text.getText());
}
if (message instanceof ObjectMessage) {
System.out.println("\n RECEIVER ObjectMessage");
ObjectMessage oMessage = (ObjectMessage) message;
if (oMessage.getObject() instanceof PostIF) {
PostIF post = (PostIF) oMessage.getObject();
String s = ((Post) post).getCorpsMessage();
System.out.println("\n RECEIVER Post : " + s);
}
}
} catch (JMSException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws JMSException {
/*
* EACH USER IS A TOPIC FOR OTHER USERS
* WHATEVER A USER DOES RESULTS IN A NOTIFICATION TO SUBSCRIBERS
*/
//CREATE USER
UserIF u1, u2, u3;
String[] nom = new String[5];
String[] prenom = new String[5];
String[] login = new String[5];
String[] password = new String[5];
Date[] naiss = new Date[5];
String[] mail = new String[5];
for (int i = 0; i < 5; i++) {
nom[i] = "nom_" + i;
prenom[i] = "prenom_" + i;
login[i] = "login_" + i;
password[i] = "password_" + i;
naiss[i] = new Date();
mail[i] = "mail_" + i;
}
u1 = new User(nom[0], prenom[0], login[0], password[0], naiss[0], mail[0]);
u2 = new User(nom[1], prenom[1], login[1], password[1], naiss[1], mail[1]);
u3 = new User(nom[2], prenom[2], login[2], password[2], naiss[2], mail[2]);
/*
* MAKE EACH USER A SUBSCRIBER
*/
Receiver receiver1 = new Receiver(u1);
Receiver receiver2 = new Receiver(u2);
Receiver receiver3 = new Receiver(u3);
/*
* PUT A MESSAGE LISTENER FOR EACH USER
*/
receiver1.receiveMessage(u2);
receiver1.receiveMessage(u3);
receiver2.receiveMessage(u1);
receiver2.receiveMessage(u3);
receiver3.receiveMessage(u1);
receiver3.receiveMessage(u2);
/*
* CALL THE SENDER CLASS TO SEND MESSAGES
*/
try {
Sender.main(args);
} catch (Exception e1) {
e1.printStackTrace();
}
/*
* A SLEEP TO HAVE ENOUGH TIME TO LOOK AT THE ACTIVEMQ CONSOLE
* CAN BE REMOVE
*/
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
/*
* UNSUBSCRIBE SUBSCRIBERS FROM TOPICS
*/
receiver1.unsubscribe(u2);
receiver1.unsubscribe(u3);
receiver2.unsubscribe(u1);
receiver2.unsubscribe(u3);
receiver3.unsubscribe(u1);
receiver3.unsubscribe(u2);
}
}

Each connection needs a unique ClientID : connection.setClientID("clientID");
My mistake was to misunderstand this unicity for a given client.
When a client subscribes to a Topic, there is one connection for this Topic. So, for a given client subscribed to 3 topics (for instance), 3 ClientID are needed because 3 connections are needed.
A ClientID has to be unique because it identifies one connection of one client for one topic.
That's why I had so many JMSException telling that "Durable Consumer was In Use" when I wanted to end its subscription.

You can only unsubscribe a durable subscription if there is no active subscriber currently consuming from it. It looks like your code creates several subscriptions and does not stop the consumers so of course the unsubscribe will fail, if you close down the consumers and then do the unsubscribe you should get the result you are looking for.
An example of durable subscription unsubscribe is here.

Related

SNMP-CAMEL-KAFKA

I am looking for reference where I can get simple program to send a SNMP trap to Apache Kafka topic using Apache Camel.
Please help me if someone can explain the it using simple java program.
My RouteBuilder configuration
import org.apache.camel.builder.RouteBuilder;
public class SimpleRouteBuilder extends RouteBuilder{
#Override
public void configure() throws Exception {
String topicName = "topic=first_topic";
String kafkaServer = "kafka:localhost:9092";
String zooKeeperHost = "zookeeperHost=localhost&zookeeperPort=2181";
String serializerClass = "serializerClass=kafka.serializer.StringEncoder";
String toKafka = new StringBuilder().append(kafkaServer).append("?").append(topicName).append("&")
.append(zooKeeperHost).append("&").append(serializerClass).toString();
System.out.println(toKafka);
from("snmp:127.0.0.1:161?protocol=udp&type=POLL&oids=1.3.6.1.2.1.1.5.0").split().tokenize("\n").to(toKafka);
}
}
Main Method
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import org.snmp4j.Snmp;
public class MainApp {
public static void main(String[] args) {
SimpleRouteBuilder routeBuilder = new SimpleRouteBuilder();
CamelContext ctx = new DefaultCamelContext();
try {
ctx.addRoutes(routeBuilder);
ctx.start();
Thread.sleep(5 * 60 * 1000);
ctx.stop();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
I was in wrong direction. The write direction is as below -
Create a Trap sender program.
Create Trap receiver/listener program.
Inside Trap receiver or listener, receive trap and send it to Apache Kafka topic through Apache camel.
POM.XML
add below dependencies -
camel-core
snmp4j
camel-kafka
Trap Sender Program
package <>;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.snmp4j.*;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MPv2c;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.*;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import java.util.Date;
public class Trapsender {
public static final String community = "public";
public static final String Oid = ".1.3.6.1.2.1.1.8";
public static final String ipAddress = "127.0.0.1";
public static final int port = 162;
public static void main(String[] args) {
Trapsender trapv3 = new Trapsender();
trapv3.sendTrap_Version3();
}
public void sendTrap_Version3() {
try {
// Create Transport Mapping
TransportMapping transport = new DefaultUdpTransportMapping();
transport.listen();
// Create Target
CommunityTarget cTarget = new CommunityTarget();
cTarget.setCommunity(new OctetString(community));
cTarget.setVersion(SnmpConstants.version2c);
cTarget.setAddress(new UdpAddress(ipAddress + "/" + port));
cTarget.setRetries(2);
cTarget.setTimeout(10000);
// Create PDU for V3
PDU pdu = new PDU();
pdu.setType(PDU.TRAP);
// need to specify the system up time
pdu.add(new VariableBinding(SnmpConstants.sysUpTime, new OctetString(new Date().toString())));
pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, new OID(Oid)));
pdu.add(new VariableBinding(new OID(Oid), new OctetString("Major")));
// Send the PDU
Snmp snmp = new Snmp(transport);
System.out.println("Sending V2 Trap... Check Wheather NMS is Listening or not? ");
ResponseEvent send = snmp.send(pdu, cTarget);
snmp.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Receiver Trap with Apache Camel
package <>;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.snmp4j.*;
import org.snmp4j.mp.MPv1;
import org.snmp4j.mp.MPv2c;
import org.snmp4j.security.Priv3DES;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TcpAddress;
import org.snmp4j.smi.TransportIpAddress;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.transport.AbstractTransportMapping;
import org.snmp4j.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.MultiThreadedMessageDispatcher;
import org.snmp4j.util.ThreadPool;
import java.io.IOException;
public class Trapreceiver implements CommandResponder {
public static CamelContext ctx=null;
public static ProducerTemplate producer=null;
public static void main(String[] args) {
Trapreceiver snmp4jTrapReceiver = new Trapreceiver();
SimpleRouteBuilder routeBuilder = new SimpleRouteBuilder();
ctx = new DefaultCamelContext();
producer = ctx.createProducerTemplate();
try {
ctx.addRoutes(routeBuilder);
ctx.start();
}
catch (Exception e) {
e.printStackTrace();
}
// producer.sendBody("direct:start", snmp);
try {
snmp4jTrapReceiver.listen(new UdpAddress("localhost/162"), producer);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Trap Listner
*/
public synchronized void listen(TransportIpAddress address, ProducerTemplate producer)
throws IOException {
AbstractTransportMapping transport;
if (address instanceof TcpAddress) {
transport = new DefaultTcpTransportMapping((TcpAddress) address);
} else {
transport = new DefaultUdpTransportMapping((UdpAddress) address);
}
ThreadPool threadPool = ThreadPool.create("DispatcherPool", 10);
MessageDispatcher mDispathcher = new MultiThreadedMessageDispatcher(
threadPool, new MessageDispatcherImpl());
// add message processing models
mDispathcher.addMessageProcessingModel(new MPv1());
mDispathcher.addMessageProcessingModel(new MPv2c());
// add all security protocols
SecurityProtocols.getInstance().addDefaultProtocols();
SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());
// Create Target
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
Snmp snmp = new Snmp(mDispathcher, transport);
snmp.addCommandResponder(this);
transport.listen();
System.out.println("Listening on " + address);
try {
this.wait();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/**
* This method will be called whenever a pdu is received on the given port
* specified in the listen() method
*/
public synchronized void processPdu(CommandResponderEvent cmdRespEvent) {
System.out.println("Received PDU...");
PDU pdu = cmdRespEvent.getPDU();
if (pdu != null) {
System.out.println("Trap Type = " + pdu.getType());
System.out.println("Variables = " + pdu.getVariableBindings());
producer.sendBody("direct:start","Variables = " + pdu.getVariableBindings() );
}
}
}

Why am I getting only one message?

So I have a simple JMS app, using a topic, powered by activeMQ. It works, but only 1 message is being sent (even though I am writing more lines in the console and so trying to send more stuff).
When I check the web console of ActiveMq, only 1 message is being sent (I also get this message in the ReceiverTopic class)...Why is this happening?
Below you can see my sender code:
package topic;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
public class SenderTopic {
private ConnectionFactory factory = null;
private Connection connection = null;
private Session session = null;
private Destination destination = null;
private MessageProducer producer = null;
private boolean jmsInitialized = false;
public SenderTopic() {
}
private void initJMS() throws JMSException {
factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
connection = factory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createTopic("SAMPLE_TOPIC");
producer = session.createProducer(destination);
jmsInitialized = true;
}
private void sendMessage(String message) {
if (!jmsInitialized) {
try {
initJMS();
sendTextMessage(message);
} catch (JMSException e) {
jmsInitialized = false;
e.printStackTrace();
}
}
}
private void sendTextMessage(String message) throws JMSException {
TextMessage textMessage = session.createTextMessage(message);
producer.send(textMessage);
}
public static void main(String[] args) throws IOException {
SenderTopic receiver = new SenderTopic();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String message = reader.readLine();
receiver.sendMessage(message);
}
}
}
Intially the value of jmsInitialized is false, so your if condition (!jmsInitialized) will be true.
On second call of sendMessage the value of jmsInitialized will be true and the if condition fails because you are using not on boolean value.
You can add a else condition with only call to sendTextMessage.
try out this
private void sendMessage(String message) {
try {
if (!jmsInitialized) {
initJMS();
sendTextMessage(message);
}else{
sendTextMessage(message);
}
} catch (JMSException e) {
jmsInitialized = false;
e.printStackTrace();
}
}
}

Error when import HashMap

Hi I'm using eclips indigo for developing my project and I'm getting error in my package - like this
Multiple markers at this line
- The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from
required .class files
- The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from
required .class files
Does anyone know why I'm getting error when I import Hashmap,util.map,common.collect.map in my java class
package info.sample.project;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.common.collect.Maps;
#ServerEndpoint("/chat")
public class SocketServer {
// set to store all the live sessions
private static final Set<Session> sessions = Collections
.synchronizedSet(new HashSet<Session>());
// Mapping between session and person name
private static final HashMap<String, String> nameSessionPair = new HashMap<String, String>();
private JSONUtils jsonUtils = new JSONUtils();
// Getting query params
public static Map<String, String> getQueryMap(String query) {
Map<String, String> map = Maps.newHashMap();
if (query != null) {
String[] params = query.split("&");
for (String param : params) {
String[] nameval = param.split("=");
map.put(nameval[0], nameval[1]);
}
}
return map;
}
/**
* Called when a socket connection opened
* */
#OnOpen
public void onOpen(Session session) {
System.out.println(session.getId() + " has opened a connection");
Map<String, String> queryParams = getQueryMap(session.getQueryString());
String name = "";
if (queryParams.containsKey("name")) {
// Getting client name via query param
name = queryParams.get("name");
try {
name = URLDecoder.decode(name, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Mapping client name and session id
nameSessionPair.put(session.getId(), name);
}
// Adding session to session list
sessions.add(session);
try {
// Sending session id to the client that just connected
session.getBasicRemote().sendText(
jsonUtils.getClientDetailsJson(session.getId(),
"Your session details"));
} catch (IOException e) {
e.printStackTrace();
}
// Notifying all the clients about new person joined
sendMessageToAll(session.getId(), name, " joined conversation!", true,
false);
}
/**
* method called when new message received from any client
*
* #param message
* JSON message from client
* */
#OnMessage
public void onMessage(String message, Session session) {
System.out.println("Message from " + session.getId() + ": " + message);
String msg = null;
// Parsing the json and getting message
try {
JSONObject jObj = new JSONObject(message);
msg = jObj.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
// Sending the message to all clients
sendMessageToAll(session.getId(), nameSessionPair.get(session.getId()),
msg, false, false);
}
/**
* Method called when a connection is closed
* */
#OnClose
public void onClose(Session session) {
System.out.println("Session " + session.getId() + " has ended");
// Getting the client name that exited
String name = nameSessionPair.get(session.getId());
// removing the session from sessions list
sessions.remove(session);
// Notifying all the clients about person exit
sendMessageToAll(session.getId(), name, " left conversation!", false,
true);
}
/**
* Method to send message to all clients
*
* #param sessionId
* #param message
* message to be sent to clients
* #param isNewClient
* flag to identify that message is about new person joined
* #param isExit
* flag to identify that a person left the conversation
* */
private void sendMessageToAll(String sessionId, String name,
String message, boolean isNewClient, boolean isExit) {
// Looping through all the sessions and sending the message individually
for (Session s : sessions) {
String json = null;
// Checking if the message is about new client joined
if (isNewClient) {
json = jsonUtils.getNewClientJson(sessionId, name, message,
sessions.size());
} else if (isExit) {
// Checking if the person left the conversation
json = jsonUtils.getClientExitJson(sessionId, name, message,
sessions.size());
} else {
// Normal chat conversation message
json = jsonUtils
.getSendAllMessageJson(sessionId, name, message);
}
try {
System.out.println("Sending Message To: " + sessionId + ", "
+ json);
s.getBasicRemote().sendText(json);
} catch (IOException e) {
System.out.println("error in sending. " + s.getId() + ", "
+ e.getMessage());
e.printStackTrace();
}
}
}
}
Try importing java.util.Map.Entry as well.

JFOREX SDK - How to send HTTPS GET request to www server ssl connection

how to add this
public class JavaHttpsExample
{
public static void main(String[] args)
throws Exception
{
String httpsURL = "https://localhost/send.php&json=somevalue";
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
}
in.close();
}
}
to
Jforex maven sdk for eclipse:
http://www.dukascopy.com/client/jforexlib/JForex-SDK.zip
and
http://www.dukascopy.com/wiki/#IClient_functionality
package singlejartest_old;
import com.dukascopy.api.system.ISystemListener;
import com.dukascopy.api.system.IClient;
import com.dukascopy.api.system.ClientFactory;
import com.dukascopy.api.*;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
/**
* This small program demonstrates how to initialize Dukascopy client and start a strategy
*/
public class MainStopFromConsole {
private static final Logger LOGGER = LoggerFactory.getLogger(MainStopFromConsole.class);
private static String jnlpUrl = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
private static String userName = "";
private static String password = "";
public static void main(String[] args) throws Exception {
//get the instance of the IClient interface
final IClient client = ClientFactory.getDefaultInstance();
//set the listener that will receive system events
client.setSystemListener(new ISystemListener() {
private int lightReconnects = 3;
#Override
public void onStart(long processId) {
LOGGER.info("Strategy started: " + processId);
}
#Override
public void onStop(long processId) {
LOGGER.info("Strategy stopped: " + processId);
if (client.getStartedStrategies().size() == 0) {
System.exit(0);
}
}
#Override
public void onConnect() {
LOGGER.info("Connected");
lightReconnects = 3;
}
#Override
public void onDisconnect() {
LOGGER.warn("Disconnected");
if (lightReconnects > 0) {
LOGGER.error("TRY TO RECONNECT, reconnects left: " + lightReconnects);
client.reconnect();
--lightReconnects;
} else {
try {
//sleep for 10 seconds before attempting to reconnect
Thread.sleep(10000);
} catch (InterruptedException e) {
//ignore
}
try {
client.connect(jnlpUrl, userName, password);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
});
LOGGER.info("Connecting...");
//connect to the server using jnlp, user name and password
client.connect(jnlpUrl, userName, password);
//wait for it to connect
int i = 10; //wait max ten seconds
while (i > 0 && !client.isConnected()) {
Thread.sleep(1000);
i--;
}
if (!client.isConnected()) {
LOGGER.error("Failed to connect Dukascopy servers");
System.exit(1);
}
//subscribe to the instruments
Set<Instrument> instruments = new HashSet<Instrument>();
instruments.add(Instrument.EURUSD);
LOGGER.info("Subscribing instruments...");
client.setSubscribedInstruments(instruments);
//start the strategy
LOGGER.info("Starting strategy");
final long strategyId = client.startStrategy(new IStrategy(){
public Instrument instrument = Instrument.EURUSD;
private IConsole console;
public void onStart(IContext context) throws JFException {
console = context.getConsole();
}
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
if ( instrument == this.instrument){
console.getOut().println(" bar: " + period + " " + askBar);
}
}
public void onTick(Instrument instrument, ITick tick) throws JFException { }
public void onMessage(IMessage message) throws JFException { }
public void onAccount(IAccount account) throws JFException { }
public void onStop() throws JFException { }
});
//now it's running
//every second check if "stop" had been typed in the console - if so - then stop the strategy
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Scanner s = new Scanner(System.in);
while(true){
while(s.hasNext()){
String str = s.next();
if(str.equalsIgnoreCase("stop")){
System.out.println("Strategy stop by console command.");
client.stopStrategy(strategyId);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}
i need send some values(account balance or open positions) to WWW serwer from strategy
Thanks
zix
package master;
import com.dukascopy.api.system.ISystemListener;
import com.dukascopy.api.system.IClient;
import com.dukascopy.api.system.ClientFactory;
import com.dukascopy.api.*;
import java.awt.Color;
import java.awt.List;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Array;
import java.net.URL;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;
import javax.swing.JFrame;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import singlejartest.JavaHttpsExample;
public class MainStopFromConsole {
private static final Logger LOGGER = LoggerFactory.getLogger(MainStopFromConsole.class);
private static String jnlpUrl = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
private static String userName = "DEMO2PRFwj";
private static String password = "PRFwj";
//static String[] columns = {"Open Time", "Id", "Label", "Comment", "Instrument", "Side", "Amount", "Original Amount", "Open Price", "Stop Loss", "Take Profit", "Profit (Pips)", "Profit Currency", "Profit in USD", "Commission", "Commission USD"};
static String[] columns = {"Id", "Instrument", "Side", "Amount", "Open Price", "Stop Loss", "Take Profit"};
//static String[][] data = {{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"},
static String[][] data = new String[50][11];
//static String[][] data = null;
//static JFrame jf = new JFrame();
public static void main(String[] args) throws Exception {
//get the instance of the IClient interface
final IClient client = ClientFactory.getDefaultInstance();
//set the listener that will receive system events
client.setSystemListener(new ISystemListener() {
private int lightReconnects = 3;
public void onStart(long procid) {
//IConsole console = context.getConsole();
LOGGER.info("Strategy started: ");
}
public void onStop(long processId) {
LOGGER.info("Strategy stopped: " + processId);
if (client.getStartedStrategies().size() == 0) {
System.exit(0);
}
}
#Override
public void onConnect() {
LOGGER.info("Connected");
lightReconnects = 3;
}
#Override
public void onDisconnect() {
LOGGER.warn("Disconnected");
if (lightReconnects > 0) {
LOGGER.error("TRY TO RECONNECT, reconnects left: " + lightReconnects);
client.reconnect();
--lightReconnects;
} else {
try {
//sleep for 10 seconds before attempting to reconnect
Thread.sleep(10000);
} catch (InterruptedException e) {
//ignore
}
try {
client.connect(jnlpUrl, userName, password);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
});
LOGGER.info("Connecting...");
//connect to the server using jnlp, user name and password
client.connect(jnlpUrl, userName, password);
//wait for it to connect
int i = 10; //wait max ten seconds
while (i > 0 && !client.isConnected()) {
Thread.sleep(1000);
i--;
}
if (!client.isConnected()) {
LOGGER.error("Failed to connect Dukascopy servers");
System.exit(1);
}
//subscribe to the instruments
Set<Instrument> instruments = new HashSet<Instrument>();
instruments.add(Instrument.EURUSD);
LOGGER.info("Subscribing instruments...");
client.setSubscribedInstruments(instruments);
//start the strategy
LOGGER.info("Starting strategy");
final long strategyId = client.startStrategy(new IStrategy(){
public Instrument instrument = Instrument.EURUSD;
private IConsole console;
private IEngine engine;
public void onStart(IContext context) throws JFException {
console = context.getConsole();
engine = context.getEngine();
}
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
if ( instrument == this.instrument){
//console.getOut().println(" bar: " + period + " " + askBar);
}
}
public void onTick(Instrument instrument, ITick tick) throws JFException {
try {
int xx = 0;
//data[0][1] = "1";
for(IOrder o : engine.getOrders()){
if(o.getProfitLossInUSD() != 987654231){
console.getOut().println("Order: " + o.getInstrument() + " " + o.getProfitLossInPips() + " " + o.getOrderCommand());
// Copy orders to array
String userHash = "1";
String positionOpenTime = "" + o.getFillTime();
String positionId = "" + o.getId();
String positionInstrument = "" + o.getInstrument();
String positionIsbuy = "" + o.getOrderCommand().isLong();
String positionVolume = "" + o.getAmount();
String positionOpen = "" + o.getOpenPrice();
String positionSl = "" + o.getStopLossPrice();
String positionTp = "" + o.getTakeProfitPrice();
String positionComment = "" + o.getComment();
data[xx][0] = userHash;
data[xx][1] = positionOpenTime;
data[xx][2] = positionId;
data[xx][3] = positionInstrument;
data[xx][4] = positionIsbuy;
data[xx][5] = positionVolume;
data[xx][6] = positionOpen;
data[xx][7] = positionSl;
data[xx][8] = positionTp;
data[xx][9] = positionComment;
xx++;
}
}
xx=0;
/*
int i = 0;
int j = 0;
String string = "";
for(j = 0; j<10; j++){
for(i = 0; i<10; i++){
string += data[j][i] + "#";
}
string += "$$";
}
}
console.getOut().println("=====================================================================================" );
console.getOut().println(string);
*/
console.getOut().println("=====================================================================================" );
String txt ="";
txt = Arrays.deepToString(data);
txt = txt.replaceAll(",", "aa");
txt = txt.replaceAll(" ", "zz");
System.out.println(txt);
console.getOut().println("=====================================================================================" );
//=================================================================== send get == need commerciall ssl like startssl.com and serveralias and servername in virtualhost
URL hp = new URL("https://breakermind.com/index.php?line="+txt);
HttpsURLConnection hpCon = (HttpsURLConnection) hp.openConnection();
boolean isProxy = hpCon.usingProxy();
System.out.println("is using proxy " + isProxy);
InputStream obj = hpCon.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(obj));
String s;
while ((s = br.readLine()) != null) {
s = s.replaceAll("zz", " ");
s = s.replaceAll("aa", ",");
System.out.println(">>>" + s);
}
//===================================================================== end
} catch (Exception e) {
console.getErr().println(e.getMessage());
e.printStackTrace(console.getErr());
// context.stop();
}
console.getOut().println("=====================================================================================" );
}
public void onMessage(IMessage message) throws JFException { }
public void onAccount(IAccount account) throws JFException { }
public void onStop() throws JFException { }
});
//now it's running
//every second check if "stop" had been typed in the console - if so - then stop the strategy
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Scanner s = new Scanner(System.in);
while(true){
while(s.hasNext()){
String str = s.next();
if(str.equalsIgnoreCase("stop")){
System.out.println("Strategy stop by console command.");
client.stopStrategy(strategyId);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}

ActiveMQ some consumers not picking up tasks if they arrive after producer

Im just getting starting with ActiveMQ and i seem to have a weird problem. (Source below)
There are 2 scenarios
Consumers connect to broker, waits for tasks on the queue. Producer arrives later, drops the list of tasks and they are rightly taken up by the different consumers and performed. This works fine and i have simulated it as well.
Producer connects first, drops the list of tasks. No consumers are connected at this point. Now when lets say 3 consumers - C1, C2 and C3 connect to the broker (in that order) i see that only C1 picks up and does the tasks that are dropped by the producer. C2 and C3 stay idle. Why does this happen?
I've also noticed 1 more thing in regards to the 2nd scenario -- If the producer keeps on dropping tasks inside the queue, C2 and C3 pick up tasks but if the producer has dropped tasks before (as mentioned) then C2 and C3 dont do anything.
Producer code
package com.activemq.apps;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import com.commons.helpers.Maths;
public class Publisher implements MessageListener {
private static String _URL;
private static String _TOPIC_PUBLISH;
private static String _TOPIC_CONSUME;
public Publisher (String URL, String TOPIC) {
_URL = URL;
_TOPIC_PUBLISH = TOPIC + "_REQUESTS";
_TOPIC_CONSUME = TOPIC + "_RESPONSES";
}
public void initialize() {
try
{
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(_URL);
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destinationProducer = session.createQueue(_TOPIC_PUBLISH);
Destination destinationConsumers = session.createQueue(_TOPIC_CONSUME);
MessageProducer producer = session.createProducer(destinationProducer);
MessageConsumer consumer = session.createConsumer(destinationConsumers);
consumer.setMessageListener(this);
int count = 0;
System.out.println("Sending requests");
while (true)
{
int randomSleepTime = Maths.rand(1000, 5000);
String messageToSend = count + "_" + randomSleepTime;
TextMessage message = session.createTextMessage(messageToSend);
producer.send(message);
System.out.println("Job #" + count + " | " + (randomSleepTime/1000) + "s");
if (count++%10 == 0)
Thread.sleep(10000);
}
}
catch (JMSException ex)
{
ex.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void onMessage(Message message) {
if (message instanceof TextMessage)
{
TextMessage msg = (TextMessage) message;
try {
String response = msg.getText();
String[] responseSplit = response.split("_");
String clientId = responseSplit[1];
String count = responseSplit[0];
System.out.println("Got response from " + clientId + " Job #" + count);
}
catch (JMSException e) {
e.printStackTrace();
}
}
}
}
Consumer code
package com.activemq.apps;
import java.util.UUID;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
public class Consumer implements MessageListener {
private static String _URL;
private static String _TOPIC_PUBLISH;
private static String _TOPIC_CONSUME;
private static String _CLIENTID;
private MessageProducer producer;
private Session session;
public Consumer (String URL, String TOPIC) {
_URL = URL;
_TOPIC_PUBLISH = TOPIC + "_RESPONSES";
_TOPIC_CONSUME = TOPIC + "_REQUESTS";
}
public void initialize() {
try
{
_CLIENTID = UUID.randomUUID().toString();
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(_URL);
Connection connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destinationProducer = session.createQueue(_TOPIC_PUBLISH);
Destination destinationConsumers = session.createQueue(_TOPIC_CONSUME);
producer = session.createProducer(destinationProducer);
MessageConsumer consumer = session.createConsumer(destinationConsumers);
consumer.setMessageListener(this);
System.out.println("Client: " + _CLIENTID + "\nWaiting to pick up tasks");
}
catch (JMSException ex)
{
ex.printStackTrace();
}
}
#Override
public void onMessage(Message message) {
if (message instanceof TextMessage)
{
TextMessage msg = (TextMessage) message;
try
{
String[] messageSplits = msg.getText().split("_");
String count = messageSplits[0];
String timeString = messageSplits[1];
int sleepFor = Integer.parseInt(timeString);
System.out.println("Job #" + count + " | Sleeping for " + (sleepFor/1000) + "s");
Thread.sleep(sleepFor);
TextMessage sendToProducer = session.createTextMessage(count + "_" + _CLIENTID);
producer.send(sendToProducer);
}
catch (JMSException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
You have mentioned
Now when lets say 3 consumers - C1, C2 and C3 connect to the broker
(in that order)
Since C1 connects first it starts getting all the messages on the queue immediately after it connects. That is expected. So i dont see any issue here. C2, C3 are not idle but C1 has got hold of the messages before C2 and C3 could.
I am not sure how many messages were sent by the producer. I assume the number of messages are less. To see what you expect try sending many messages from the producer, like thousands or millions and then start the consumers. The high number of messages are subjective and depends on the memory, network and other resources. You might see what you are expecting.
I dont think there is anything weird here. Queues represent P2P mode which is supposed to have only one consumer. In our case we have 3 consumers, it's not forbidden, but there is no guarantee of any specific order in which consumers will receive messages.
I believe you should check prefetchPolicy param for your consumer. By default, prefetch policy has default value 1000. It means that the first consumer fetches up to 1000 messages and other consumers are not able to fetch anything else. If you are trying load balance your messages across consumers consider to modify this param to 0 or 1.

Categories

Resources