import java.util.Date;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class PSConsumer {
	public static void main(String[] args) {
		Topic t = null;
		TopicConnectionFactory tcf = null;
		TopicConnection tc = null;

		try {
			Context jndiContext = new InitialContext();
			tcf = (TopicConnectionFactory) jndiContext.lookup("jms/TopicConnectionFactory");
		} catch (NamingException ne) {
			System.err.println(ne+" does not exist");
			System.exit(1);
		}

		try {
			tc = tcf.createTopicConnection();
			tc.setClientID("MariosClient");
			TopicSession ts = tc.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
			t = ts.createTopic("StockQuote");

			TopicSubscriber tSubDCX=ts.createDurableSubscriber(t,"mySub", "Company LIKE '%DCX'",false);
			TopicSubscriber tSubAll=ts.createSubscriber(t);

			tSubDCX.setMessageListener( new MyTopicListener("DCX") );
			tSubAll.setMessageListener( new MyTopicListener("All"));

			tc.start();

			for (;;){
				System.out.println("("+new Date()+") waiting for messages...");
				try {
					Thread.sleep(1000);
				} catch(InterruptedException ie) {
					System.err.println("InterruptedException caught");
				}
			}

		} catch (JMSException e) {
			System.err.println("JMSException caught");
			e.printStackTrace();
		}
	}
}

class MyTopicListener implements MessageListener {
	private String title;

	public MyTopicListener(String title){
		this.title = title;
		System.out.println("Message listener "+title+" created");
	}

	public void onMessage(Message msg) {
		try {
		TextMessage tm = (TextMessage) msg;
		System.out.println("("+this.title+") Message received: "+tm.getText());
		System.out.println("Company="+tm.getStringProperty("Company"));
		System.out.println("USD="+tm.getDoubleProperty("USD"));
		System.out.println("EUR="+tm.getStringProperty("EUR"));
		System.out.println("---------------------------");
		} catch (JMSException je) {
			System.err.println("JMSException caught");
			je.printStackTrace();
		}
	}

}