/**
  * Creates all the necessary objects for receiving messages from a JMS queue.
  *
  * @param ctx JNDI initial context
  * @param queueName name of queue
  * @exception NamingException if operation cannot be performed
  * @exception JMSException if JMS fails to initialize due to internal error
  */
 public void init(Context ctx, String queueName) throws NamingException, JMSException {
   qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
   qcon = qconFactory.createQueueConnection();
   qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
   queue = (Queue) ctx.lookup(queueName);
   qreceiver = qsession.createReceiver(queue);
   qreceiver.setMessageListener(this);
   qcon.start();
 }
  public void testConnectionFactory102WithQueue() throws JMSException {
    MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class);
    QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock();
    MockControl conControl = MockControl.createControl(QueueConnection.class);
    QueueConnection con = (QueueConnection) conControl.getMock();

    cf.createQueueConnection();
    cfControl.setReturnValue(con, 1);
    con.start();
    conControl.setVoidCallable(1);
    con.stop();
    conControl.setVoidCallable(1);
    con.close();
    conControl.setVoidCallable(1);

    cfControl.replay();
    conControl.replay();

    SingleConnectionFactory scf = new SingleConnectionFactory102(cf, false);
    QueueConnection con1 = scf.createQueueConnection();
    con1.start();
    con1.close(); // should be ignored
    QueueConnection con2 = scf.createQueueConnection();
    con2.start();
    con2.close(); // should be ignored
    scf.destroy(); // should trigger actual close

    cfControl.verify();
    conControl.verify();
  }
示例#3
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);
    }
  }
  @After
  public void removeTopic() throws Exception {

    if (conn != null) {
      conn.stop();
    }
    if (session != null) {
      session.close();
    }
    if (conn != null) {
      conn.close();
    }

    if (consumerConn != null) {
      consumerConn.stop();
    }
    if (consumerSession != null) {
      consumerSession.close();
    }
    if (consumerConn != null) {
      consumerConn.close();
    }

    adminSupport.removeJmsQueue(getQueueName());
    adminSupport.removeJmsQueue(getOtherQueueName());
  }
示例#5
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
  /** Constructor del encargado de enviar mensajes JMS. */
  public RespuestaConsultaValue() {
    try {
      final Properties env = new Properties();
      env.put("org.jboss.ejb.client.scoped.context", true);
      env.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
      env.put("endpoint.name", "endpoint-client");

      ictx = new InitialContext(env);

      Object tmp = ictx.lookup("ConnectionFactory");
      QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
      conn = qcf.createQueueConnection();
      this.cola = (Queue) ictx.lookup("queue/test");

      queueSession = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

      conn.start();

    } catch (JMSException e) {
      e.printStackTrace();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
示例#8
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);
    }
  }
  @AroundInvoke
  public Object checkArguments(InvocationContext ctx) throws Exception {
    try {
      log = Logger.getLogger(LogoutInterceptor.class);
      Object[] args = ctx.getParameters();
      String className = ctx.getTarget().getClass().getSimpleName();
      log.trace("Class name: " + className);
      String methodName = ctx.getMethod().getName();
      log.trace("Method: " + methodName);

      String sessionId = (String) args[0];
      if ((sessionId == null) || (sessionId.length() == 0)) {
        throw new Exception("sessionId should not be null");
      }

      cf = (QueueConnectionFactory) new InitialContext().lookup(QueueNames.CONNECTION_FACTORY);
      queue = (Queue) new InitialContext().lookup(QueueNames.LOGOUT_QUEUE);
      log.trace("Queue logout: " + queue.getQueueName());
      QueueConnection connection = cf.createQueueConnection();
      QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      QueueSender sender = session.createSender(queue);

      Message logoutMessage = session.createTextMessage(sessionId);
      Timestamp time = new Timestamp(new Date().getTime());
      // Messages will not accept timestamp property- must change to string
      logoutMessage.setStringProperty(PropertyNames.TIME, time.toString());
      sender.send(logoutMessage);
      session.close();

    } catch (Exception e) {
      log.fatal("Error in LogoutInterceptor", e);
    }
    return ctx.proceed();
  }
  /** use auto acknowledge which automatically has the client say OK */
  public void doReceiveAuto() {

    if (doSetup()) {
      try {
        queueConnection = queueConnectionFactory.createQueueConnection();
        QueueSession queueSession =
            queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        QueueReceiver queueReceiver = queueSession.createReceiver(queue);
        queueConnection.start();
        while (true) {
          Message m = queueReceiver.receive(1);
          if (m != null) {
            if (m instanceof TextMessage) {
              TextMessage message = (TextMessage) m;
              log.debug("Reading message:==> " + message.getText());
            } else {
              break;
            }
          }
        }
      } catch (JMSException e) {
        log.error("Listen Exception occurred: " + e.toString());
      } finally {
        doCleanup();
      }
    }
  }
示例#11
0
 public void cerrarConexion() {
   try {
     conexionCola.stop();
     conexionCola.close();
   } catch (JMSException ex) {
     System.out.println("Excepcion");
   }
 }
示例#12
0
 private QueueSession getQueueSession() throws Exception {
   if (queueSession == null) {
     Context ctx = getJndiInitialContext();
     QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup(CONNECTION_FACTORY_NAME);
     QueueConnection conn = factory.createQueueConnection();
     conn.start();
     queueSession = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
   }
   return queueSession;
 }
示例#13
0
  @Test
  public void receiver() throws Exception {
    QueueConnection connection = null;
    QueueSession session = null;
    try {
      // 创建链接工厂
      QueueConnectionFactory factory =
          new ActiveMQConnectionFactory(
              ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);
      // 通过工厂创建一个连接
      connection = factory.createQueueConnection();
      // 启动连接
      connection.start();
      // 创建一个session会话
      session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
      // 创建一个消息队列
      javax.jms.Queue queue = session.createQueue(TARGET);
      // 创建消息制作者
      javax.jms.QueueReceiver receiver = session.createReceiver(queue);

      receiver.setMessageListener(
          new MessageListener() {
            public void onMessage(Message msg) {
              if (msg != null) {
                // MapMessage map = (MapMessage) msg;
                try {
                  System.out.println(msg.getStringProperty("text"));

                  // System.out.println(map.getLong("time") + "接收#" +
                  // map.getString("text"));
                } catch (JMSException e) {
                  e.printStackTrace();
                }
              }
            }
          });
      // 休眠100ms再关闭
      Thread.sleep(1000 * 100);

      // 提交会话
      session.commit();

    } catch (Exception e) {
      throw e;
    } finally {
      // 关闭释放资源
      if (session != null) {
        session.close();
      }
      if (connection != null) {
        connection.close();
      }
    }
  }
示例#14
0
  protected synchronized void openConnection() {
    try {
      m_connection = m_factory.createQueueConnection();
      m_connection.start();

      m_session = m_connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

      m_sender = m_session.createSender(m_queue);
    } catch (final Exception e) {
      getErrorHandler().error("Error starting connection", e, null);
    }
  }
示例#15
0
  private void setupMessageListener()
      throws javax.jms.JMSException, javax.naming.NamingException, Exception {
    InitialContext ctx = new InitialContext();

    QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("jms/taskQueueFactory");
    connection = factory.createQueueConnection();
    session = connection.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
    Queue queue = (Queue) ctx.lookup("jms/taskQueue");

    receiver = session.createConsumer(queue);
    connection.start();
    ctx.close();
  }
  public void initialize() throws JMSException, NamingException {
    InitialContext iniCtx = new InitialContext();
    QueueConnectionFactory queueConnectionFactory =
        (QueueConnectionFactory) iniCtx.lookup("ConnectionFactory");

    connection = queueConnectionFactory.createQueueConnection();
    // connection = queueConnectionFactory.createQueueConnection(jmsSecurityPrincipal,
    // jmsSecurityCredential);

    queue = (Queue) iniCtx.lookup("queue/om.esb.jms.exception.persist.gw");
    session = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
    connection.start();
    System.out.println("Connected");
  }
示例#17
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) {
        }
      }
    }
  }
  public void execute(JobExecutionContext context) throws JobExecutionException {

    QueueConnectionFactory qcf = null;
    QueueConnection conn = null;
    QueueSession session = null;
    Queue queue = null;
    QueueSender sender = null;
    InitialContext ctx = null;

    final JobDetail detail = context.getJobDetail();
    final JobDataMap jobDataMap = detail.getJobDataMap();

    try {

      qcf =
          (QueueConnectionFactory)
              ctx.lookup(jobDataMap.getString(JmsHelper.JMS_CONNECTION_FACTORY_JNDI));
      ctx = JmsHelper.getInitialContext(jobDataMap);

      if (JmsHelper.isDestinationSecure(jobDataMap)) {
        String user = jobDataMap.getString(JmsHelper.JMS_USER);
        String pw = jobDataMap.getString(JmsHelper.JMS_PASSWORD);
        conn = qcf.createQueueConnection(user, pw);
      } else {
        conn = qcf.createQueueConnection();
      }

      boolean useTransactions = JmsHelper.useTransaction(jobDataMap);
      int ackMode = jobDataMap.getInt(JmsHelper.JMS_ACK_MODE);
      session = conn.createQueueSession(useTransactions, ackMode);
      String queueName = jobDataMap.getString(JmsHelper.JMS_DESTINATION_JNDI);
      queue = (Queue) ctx.lookup(queueName);
      sender = session.createSender(queue);
      String factoryClass = jobDataMap.getString(JmsHelper.JMS_MSG_FACTORY_CLASS_NAME);
      JmsMessageFactory factory = JmsHelper.getMessageFactory(factoryClass);
      Message m = factory.createMessage(jobDataMap, session);
      sender.send(m);
    } catch (NamingException e) {
      throw new JobExecutionException(e.getMessage());
    } catch (JMSException e) {
      throw new JobExecutionException(e.getMessage());
    } catch (JmsJobException e) {
      throw new JobExecutionException(e.getMessage());
    } finally {
      JmsHelper.closeResource(sender);
      JmsHelper.closeResource(session);
      JmsHelper.closeResource(conn);
    }
  }
  public static void main(String[] args) throws NamingException, JMSException {
    Context ctx = new InitialContext();
    QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) ctx.lookup("queueCF");
    QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();
    ConnectionMetaData connectionMetaData = queueConnection.getMetaData();

    System.out.println("jms version:" + connectionMetaData.getJMSVersion());
    System.out.println("jms provider:" + connectionMetaData.getJMSProviderName());
    System.out.println("supported:");
    Enumeration e = connectionMetaData.getJMSXPropertyNames();
    while (e.hasMoreElements()) {
      System.out.println(e.nextElement());
    }
    System.exit(1);
  }
示例#20
0
    private synchronized QueueConnection newQueueConnection() throws Exception {

      if (connectionFactory == null) {
        connectionFactory = new ActiveMQConnectionFactory(amqUser, amqPassword, activemqURL);
      }

      // Set the redelivery count to -1 (infinite), or else messages will start dropping
      // after the queue has had a certain number of failures (default is 6)
      RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy();
      policy.setMaximumRedeliveries(-1);

      QueueConnection amqConnection = connectionFactory.createQueueConnection();
      amqConnection.start();
      return amqConnection;
    }
  @Override
  public void setUp() throws Exception {
    super.setUp();
    try {
      queueConnection = queueConnectionFactory.createQueueConnection();
      queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      topicConnection = topicConnectionFactory.createTopicConnection();
      topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

      queueConnection.start();
      topicConnection.start();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
示例#22
0
  @Test
  public void testCreateQueueConnection() throws Exception {

    server.getSecurityManager().addUser("IDo", "Exist");
    try {
      QueueConnection queueC =
          ((QueueConnectionFactory) cf).createQueueConnection("IDont", "Exist");
      fail("supposed to throw exception");
      queueC.close();
    } catch (JMSSecurityException e) {
      // expected
    }
    JMSContext ctx = cf.createContext("IDo", "Exist");
    ctx.close();
    ;
  }
示例#23
0
 private void closeReceiver() {
   try {
     connection.close();
   } catch (JMSException e) {
     e.printStackTrace(System.err);
   }
 }
  public void doSend() {

    QueueSession queueSession = null;
    QueueSender queueSender = null;
    TextMessage message = null;

    if (doSetup()) {

      try {
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        message = queueSession.createTextMessage();
        for (int i = 0; i < NUM_MSGS; i++) {
          message.setText("This is message " + (i + 1));
          System.out.println("Sending message: " + message.getText());
          queueSender.send(message);
        }

        /*
         * Send a non-text control message indicating end of messages.
         */
        queueSender.send(queueSession.createMessage());
      } catch (JMSException e) {
        log.error("JMS Send Exception occurred: " + e.toString());
      } finally {
        doCleanup();
      }
    }
  }
示例#25
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;
 }
示例#26
0
文件: FaultTest.java 项目: ncdc/qpid
 public void tearDown() throws Exception {
   if (!isBroker08()) {
     _xaqueueConnection.close();
     _queueConnection.close();
   }
   super.tearDown();
 }
  public void testQueueConnectionFactory() throws Exception {
    QueueConnectionFactory cf = null;
    QueueConnection c = null;

    try {
      cf = new QpidConnectionFactoryProxy();
      ((QpidConnectionFactoryProxy) cf).setConnectionURL(URL);
      c = cf.createQueueConnection();
      assertTrue(c instanceof QueueConnection);

    } finally {
      if (c != null) {
        c.close();
      }
    }
  }
 private void doCleanup() {
   if (queueConnection != null) {
     try {
       queueConnection.close();
     } catch (JMSException e) {
     }
   }
 }
 private void close(QueueConnection conn) {
   try {
     if (conn != null) {
       conn.close();
     }
   } catch (Exception e) {
   }
 }
示例#30
0
 @AroundInvoke
 public Object log(InvocationContext context) throws Exception {
   System.out.println("---" + context.getMethod());
   QueueConnection conn = qcf.createQueueConnection();
   conn.start();
   QueueSession session = conn.createQueueSession(true, Session.SESSION_TRANSACTED);
   TextMessage msg = session.createTextMessage();
   msg.setText(
       context.getMethod().getDeclaringClass().getSimpleName()
           + ";"
           + context.getMethod().getName()
           + ";"
           + sessionContext.getCallerPrincipal().getName());
   QueueSender queueSender = session.createSender(queue);
   queueSender.send(msg);
   return context.proceed();
 }