Example #1
0
  public static void main(String[] args) {
    try { // Create and start connection
      InitialContext ctx = new InitialContext();
      QueueConnectionFactory f = (QueueConnectionFactory) ctx.lookup("myQueueConnectionFactory");
      QueueConnection con = f.createQueueConnection();
      con.start();
      // 2) create queue session
      QueueSession ses = con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      // 3) get the Queue object
      Queue t = (Queue) ctx.lookup("myQueue");
      // 4)create QueueSender object
      QueueSender sender = ses.createSender(t);
      // 5) create TextMessage object
      TextMessage msg = ses.createTextMessage();

      // 6) write message
      BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
      while (true) {
        System.out.println("Enter Msg, end to terminate:");
        String s = b.readLine();
        if (s.equals("end")) break;
        msg.setText(s);
        // 7) send message
        sender.send(msg);
        System.out.println("Message successfully sent.");
      }
      // 8) connection close
      con.close();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
Example #2
0
  public static QueueConnection getQueueConnection(Properties props)
      throws IOException, NamingException, JMSException {
    fixProviderUrl(props);
    String cnnFactoryName = props.getProperty(DEFAULT_JNDI_CONECTION_NAME_PROPERTY);
    if (cnnFactoryName == null) {
      throw new IOException(
          "You must set the property "
              + DEFAULT_JNDI_CONECTION_NAME_PROPERTY
              + "in the JNDI property file");
    }
    Context ctx = new InitialContext(props);
    Object obj = lookupObject(ctx, cnnFactoryName);
    QueueConnectionFactory qcf = (QueueConnectionFactory) obj;
    QueueConnection cnn;
    String username = (String) props.get("username");

    if (username != null) {
      String password = (String) props.get("password");
      cnn = qcf.createQueueConnection(username, password);
    } else {
      cnn = qcf.createQueueConnection();
    }
    cnn.start();
    return cnn;
  }
  public void onMessage(Message inMessage) {
    TextMessage msg = null;

    try {
      if (inMessage instanceof TextMessage) {
        msg = (TextMessage) inMessage;
        System.out.println("MESSAGE BEAN: Message received: " + msg.getText());
        long sleepTime = msg.getLongProperty("sleeptime");
        System.out.println("Sleeping for : " + sleepTime + " milli seconds ");
        Thread.sleep(sleepTime);
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        TextMessage message = queueSession.createTextMessage();

        message.setText("REPLIED:" + msg.getText());
        message.setIntProperty("replyid", msg.getIntProperty("id"));
        System.out.println("Sending message: " + message.getText());
        queueSender.send(message);
      } else {
        System.out.println("Message of wrong type: " + inMessage.getClass().getName());
      }
    } catch (JMSException e) {
      e.printStackTrace();
    } catch (Throwable te) {
      te.printStackTrace();
    } finally {
      try {
        queueSession.close();
        queueConnection.close();
      } catch (Exception e) {
      }
    }
  } // onMessage
Example #4
0
  public QLender(String queuecf, String requestQueue) {
    try {
      // Connect to the provider and get the JMS connection
      Context ctx = new InitialContext();
      QueueConnectionFactory qFactory = (QueueConnectionFactory) ctx.lookup(queuecf);
      qConnect = qFactory.createQueueConnection();

      // Create the JMS Session
      qSession = qConnect.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

      // Lookup the request queue
      requestQ = (Queue) ctx.lookup(requestQueue);

      // Now that setup is complete, start the Connection
      qConnect.start();

      // Create the message listener
      QueueReceiver qReceiver = qSession.createReceiver(requestQ);
      qReceiver.setMessageListener(this);

      System.out.println("Waiting for loan requests...");

    } catch (JMSException jmse) {
      jmse.printStackTrace();
      System.exit(1);
    } catch (NamingException jne) {
      jne.printStackTrace();
      System.exit(1);
    }
  }
Example #5
0
 public void cerrarConexion() {
   try {
     conexionCola.stop();
     conexionCola.close();
   } catch (JMSException ex) {
     System.out.println("Excepcion");
   }
 }
Example #6
0
  /**
   * Wait for 'count' messages on controlQueue before continuing. Called by a publisher to make sure
   * that subscribers have started before it begins publishing messages.
   *
   * <p>If controlQueue doesn't exist, the method throws an exception.
   *
   * @param prefix prefix (publisher or subscriber) to be displayed
   * @param controlQueueName name of control queue
   * @param count number of messages to receive
   */
  public static void receiveSynchronizeMessages(String prefix, String controlQueueName, int count)
      throws Exception {
    QueueConnectionFactory queueConnectionFactory = null;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    Queue controlQueue = null;
    QueueReceiver queueReceiver = null;

    try {
      queueConnectionFactory = SampleUtilities.getQueueConnectionFactory();
      queueConnection = queueConnectionFactory.createQueueConnection();
      queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      controlQueue = getQueue(controlQueueName, queueSession);
      queueConnection.start();
    } catch (Exception e) {
      System.out.println("Connection problem: " + e.toString());
      if (queueConnection != null) {
        try {
          queueConnection.close();
        } catch (JMSException ee) {
        }
      }
      throw e;
    }

    try {
      System.out.println(
          prefix
              + "Receiving synchronize messages from "
              + controlQueueName
              + "; count = "
              + count);
      queueReceiver = queueSession.createReceiver(controlQueue);
      while (count > 0) {
        queueReceiver.receive();
        count--;
        System.out.println(prefix + "Received synchronize message; expect " + count + " more");
      }
    } catch (JMSException e) {
      System.out.println("Exception occurred: " + e.toString());
      throw e;
    } finally {
      if (queueConnection != null) {
        try {
          queueConnection.close();
        } catch (JMSException e) {
        }
      }
    }
  }
Example #7
0
 public static QueueReceiver getQueueReceiver(QueueConnection cnn, String queueName)
     throws JMSException {
   QueueSession session = cnn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = session.createQueue(queueName);
   QueueReceiver receiver = session.createReceiver(queue);
   return receiver;
 }
Example #8
0
 private void exit() {
   try {
     qConnect.close();
   } catch (JMSException jmse) {
     jmse.printStackTrace();
   }
   System.exit(0);
 }
Example #9
0
  /**
   * Send a message to controlQueue. Called by a subscriber to notify a publisher that it is ready
   * to receive messages.
   *
   * <p>If controlQueue doesn't exist, the method throws an exception.
   *
   * @param prefix prefix (publisher or subscriber) to be displayed
   * @param controlQueueName name of control queue
   */
  public static void sendSynchronizeMessage(String prefix, String controlQueueName)
      throws Exception {
    QueueConnectionFactory queueConnectionFactory = null;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    Queue controlQueue = null;
    QueueSender queueSender = null;
    TextMessage message = null;

    try {
      queueConnectionFactory = SampleUtilities.getQueueConnectionFactory();
      queueConnection = queueConnectionFactory.createQueueConnection();
      queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      controlQueue = getQueue(controlQueueName, queueSession);
    } catch (Exception e) {
      System.out.println("Connection problem: " + e.toString());
      if (queueConnection != null) {
        try {
          queueConnection.close();
        } catch (JMSException ee) {
        }
      }
      throw e;
    }

    try {
      queueSender = queueSession.createSender(controlQueue);
      message = queueSession.createTextMessage();
      message.setText("synchronize");
      System.out.println(prefix + "Sending synchronize message to " + controlQueueName);
      queueSender.send(message);
    } catch (JMSException e) {
      System.out.println("Exception occurred: " + e.toString());
      throw e;
    } finally {
      if (queueConnection != null) {
        try {
          queueConnection.close();
        } catch (JMSException e) {
        }
      }
    }
  }
  public static void main(String[] args) {
    try {
      QueueConnectionFactory queueConnectionFactory;
      QueueConnection queueConnection;
      QueueSession queueSession;
      QueueReceiver queueReceiver;
      Queue queue;
      TextMessage msg;

      // JNDI InitialContextを作成します
      InitialContext ctx = new InitialContext();
      // Connection FactoryとQueueをLook upします
      queueConnectionFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
      queue = (Queue) ctx.lookup(QUEUE);

      // コネクションを作成
      queueConnection = queueConnectionFactory.createQueueConnection();
      // セッションを作成
      queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      // キューレシーバーを作成
      queueReceiver = queueSession.createReceiver(queue);
      // メッセージの配送をスタート
      queueConnection.start();
      // メッセージの受信
      while (true) {
        Message m = queueReceiver.receive(1);
        if (m != null) {
          if (m instanceof TextMessage) {
            msg = (TextMessage) m;
            System.out.println(msg.getText());
          } else {
            break;
          }
        }
      }
      // 接続を切断
      queueReceiver.close();
      queueSession.close();
      queueConnection.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #11
0
 public static Message queueReceiver(QueueConnection cnn, String queueName, long timeout)
     throws JMSException {
   QueueSession session = cnn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = session.createQueue(queueName);
   QueueReceiver receiver = session.createReceiver(queue);
   Message msg = receiver.receive(timeout);
   if (msg != null) msg.acknowledge();
   receiver.close();
   session.close();
   return msg;
 }
  /** Tasks to be carried out in the STARTUP_EVENT. Logs a message */
  private void onStartTask() {
    ctx.log("LifecycleTopic: STARTUP_EVENT");
    // my code
    QueueSession qsession[] = new QueueSession[10];
    Queue queue[] = new Queue[10];

    try {
      for (int i = 0; i < 10; i++) {
        // Get initial context
        ctx.log("Get initial context");
        InitialContext initialContext = new InitialContext();

        // look up the connection factory from the object store
        ctx.log("Looking up the queue connection factory from JNDI");
        QueueConnectionFactory factory =
            (QueueConnectionFactory) initialContext.lookup("jms/QCFactory");

        // look up queue from the object store
        ctx.log("Create queue connection");
        QueueConnection qconn = factory.createQueueConnection();

        ctx.log("Create queue session");
        qsession[i] = qconn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

        ctx.log("Looking up the queue from JNDI");
        queue[i] = (Queue) initialContext.lookup("jms/SampleQueue");
      }

      updateDB();

    } catch (Exception e) {
      ctx.log("Exception caught in test code");
      e.printStackTrace();
    }

    // end my code

    // my code
    // createAccount();
    // end my code
  }
  public static void main(String[] args) throws Exception {
    ActiveMQConnectionFactory connectionFactory =
        new ActiveMQConnectionFactory("admin", "admin", "tcp://localhost:61616");
    QueueConnection queueConnection = connectionFactory.createQueueConnection();

    QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = queueSession.createQueue("test-queue");

    MessageProducer producer = queueSession.createProducer(queue);

    queueConnection.start();

    TextMessage textMessage =
        queueSession.createTextMessage("Current time: " + System.currentTimeMillis());

    producer.send(textMessage);
    log.info("Message sent at {}", System.currentTimeMillis());

    producer.close();
    queueSession.close();
    queueConnection.close();
  }
Example #14
0
  public boolean inicializaCola() {
    try {

      if (contexto == null) {
        // Aun no se ha realizado la inicializacion. Una vez realizada
        // no tiene sentido volver a realizarla.
        contexto = new InitialContext(); // Obtiene contexto JNDI
        // Obtiene factoria de conexion a colas (ha debido ser creada externamente)
        factoria = (QueueConnectionFactory) contexto.lookup("jms/factoria");
        // Obtiene la cola (ha debido ser creada externamente)
        cola = (Queue) contexto.lookup(nombreCola);
        // Ahora crea la conexion a la cola
        conexionCola = factoria.createQueueConnection();
        // Crea la sesion
        sesionCola = conexionCola.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        conexionCola.start(); // Hay que activar la conexion para empezar.
      }
    } catch (NamingException | JMSException ex) {
      contexto = null;
      return false;
    }
    return true;
  }
Example #15
0
 public static void drainQueue(QueueConnection cnn, String queue) throws Exception {
   QueueSession session = cnn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue q = session.createQueue(queue);
   QueueReceiver receiver = session.createReceiver(q);
   // Add a delay so that activeMQ can fetch messages from the broker
   // Thread.sleep(5000);
   Message msg = null;
   while ((msg = receiver.receive(1000)) != null) {
     System.out.println("Removing message: " + msg);
     msg.acknowledge();
   }
   receiver.close();
   session.close();
 }
Example #16
0
  public static void queueSend(
      QueueConnection cnn,
      String queueName,
      String payload,
      boolean transacted,
      int ack,
      String replyTo)
      throws JMSException {
    QueueSession session = cnn.createQueueSession(transacted, ack);
    Queue queue = session.createQueue(queueName);
    QueueSender sender = session.createSender(queue);
    TextMessage msg = session.createTextMessage();
    msg.setText(payload);
    msg.setJMSDeliveryMode(ack);
    if (replyTo != null) {
      msg.setJMSReplyTo(session.createQueue(replyTo));
    }

    sender.send(msg);
    sender.close();
    session.close();
  }
 @Produces
 @Order
 public QueueSession createOrderSession(@Order QueueConnection conn) throws JMSException {
   return conn.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
 }
 public void closeOrderSession(@Disposes @Order QueueConnection conn) throws JMSException {
   conn.close();
 }