1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
   | /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utils;
 
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
 
/**
 *
 * @author jerome
 */
public class JmsUtils {
    private static QueueConnectionFactory connectionFactory;
    private static Queue queue;
 
    private QueueSender producer;
    private QueueReceiver consumer;
    private QueueSession session;
    private QueueConnection connection;
 
    public JmsUtils(String id){
        try {
            Context ctx = new InitialContext();
            connectionFactory = (QueueConnectionFactory) ctx.lookup("jms/ConnectionFactory");
            queue = (Queue)ctx.lookup("jms/Queue");
 
 
 
            connection = connectionFactory.createQueueConnection();
            connection.start();
            session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            producer = session.createSender(queue);
 
            if(id != null)
                consumer = session.createReceiver(queue, "client = " + id);
            else
                consumer = session.createReceiver(queue);
 
        } catch (JMSException | NamingException ex) {
            Logger.getLogger(JmsUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
    public void send(Serializable mess, String dest){
        try {
            System.out.println("jms.send> "+dest);
            ObjectMessage message = session.createObjectMessage(mess);
            message.setStringProperty("client", dest);
            producer.send(message);
        } catch (JMSException ex) {
            Logger.getLogger(JmsUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
    public Serializable receive(){
        try {
            System.out.println("jms.rcv> "+consumer.getMessageSelector());
            ObjectMessage om = (ObjectMessage) consumer.receive();
            return om.getObject();
 
        } catch (JMSException ex) {
            Logger.getLogger(JmsUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
 
} | 
Partager