private void doTestIdleConsumer(boolean transacted) throws Exception {
    Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);

    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createTextMessage("Msg1"));
    producer.send(session.createTextMessage("Msg2"));
    if (transacted) {
      session.commit();
    }
    // now lets receive it
    MessageConsumer consumer = session.createConsumer(queue);

    session.createConsumer(queue);
    TextMessage answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg1");
    if (transacted) {
      session.commit();
    }
    // this call would return null if prefetchSize > 0
    answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg2");
    if (transacted) {
      session.commit();
    }
    answer = (TextMessage) consumer.receiveNoWait();
    assertNull("Should have not received a message!", answer);
  }
示例#2
0
  /**
   * Receive a message from destination with timeout.
   *
   * @param destinationName destinationName
   * @param timeout timeout
   * @return message
   */
  public String receiveTextMessageFromDestinationWithTimeout(
      final String destinationName, final int timeout) {

    if (!this.isConnected()) {
      throw new JmsNotConnectedException("Not connected");
    }
    MessageConsumer consumer = getConsumer(destinationName);
    TextMessage message;
    try {
      if (timeout == 0) {
        message = (TextMessage) consumer.receiveNoWait();
      } else {
        message = (TextMessage) consumer.receive(timeout);
      }
      if (message != null) {

        if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) {
          message.acknowledge();
        }
        return message.getText();
      } else {
        return null;
      }
    } catch (JMSException e) {
      throw new IllegalStateException("Unable to receive message from " + destinationName, e);
    }
  }
示例#3
0
  public void testSendRequest_rpc_nil() throws Exception {
    String requestText =
        "<env:Envelope xmlns:env='"
            + SOAPConstants.URI_NS_SOAP_ENVELOPE
            + "'>"
            + "<env:Body>"
            + "<tns:op xmlns:tns='"
            + BpelConstants.NS_EXAMPLES
            + "' xmlns:xsi='"
            + BpelConstants.NS_XML_SCHEMA_INSTANCE
            + "'>"
            + "  <simplePart xsi:nil='true'>wazabi</simplePart>"
            + "  <complexPart xsi:nil='1'>"
            + "    <b on='true'>true</b>"
            + "    <c name='venus'/>"
            + "    <d amount='20'/>"
            + "    <e>30</e>"
            + "  </complexPart>"
            + "</tns:op>"
            + "</env:Body>"
            + "</env:Envelope>";

    SOAPMessage soapMessage =
        MessageFactory.newInstance()
            .createMessage(null, new ByteArrayInputStream(requestText.getBytes()));

    Connection connection = integrationControl.getJmsConnection();
    connection.start();

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    try {
      SoapHandler soapHandler = createRpcHandler();
      soapHandler.sendRequest(soapMessage, session, jbpmContext);

      PartnerLinkEntry entry =
          integrationControl.getPartnerLinkEntry(Q_RPC_PORT_TYPE, Q_SERVICE, RPC_PORT);
      MessageConsumer consumer = session.createConsumer(entry.getDestination());
      ObjectMessage message = (ObjectMessage) consumer.receiveNoWait();
      Map requestParts = (Map) message.getObject();

      // simple part
      Element simplePart = (Element) requestParts.get("simplePart");
      assertTrue(
          DatatypeUtil.toBoolean(
              simplePart.getAttributeNS(
                  BpelConstants.NS_XML_SCHEMA_INSTANCE, BpelConstants.ATTR_NIL)));
      assertFalse(simplePart.hasChildNodes());

      // complex part
      Element complexPart = (Element) requestParts.get("complexPart");
      assertTrue(
          DatatypeUtil.toBoolean(
              complexPart.getAttributeNS(
                  BpelConstants.NS_XML_SCHEMA_INSTANCE, BpelConstants.ATTR_NIL)));
      assertFalse(complexPart.hasChildNodes());
    } finally {
      session.close();
    }
  }
示例#4
0
  public void testSendRequest_rpc() throws Exception {
    String requestText =
        "<env:Envelope xmlns:env='"
            + SOAPConstants.URI_NS_SOAP_ENVELOPE
            + "'>"
            + "<env:Body>"
            + "<tns:op xmlns:tns='"
            + BpelConstants.NS_EXAMPLES
            + "'>"
            + "  <simplePart>wazabi</simplePart>"
            + "  <complexPart>"
            + "    <b on='true'>true</b>"
            + "    <c name='venus'/>"
            + "    <d amount='20'/>"
            + "    <e>30</e>"
            + "  </complexPart>"
            + "</tns:op>"
            + "</env:Body>"
            + "</env:Envelope>";
    SOAPMessage soapMessage =
        MessageFactory.newInstance()
            .createMessage(null, new ByteArrayInputStream(requestText.getBytes()));

    Connection connection = integrationControl.getJmsConnection();
    connection.start();

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    try {
      SoapHandler soapHandler = createRpcHandler();
      soapHandler.sendRequest(soapMessage, session, jbpmContext);

      PartnerLinkEntry entry =
          integrationControl.getPartnerLinkEntry(Q_RPC_PORT_TYPE, Q_SERVICE, RPC_PORT);
      MessageConsumer consumer = session.createConsumer(entry.getDestination());
      ObjectMessage message = (ObjectMessage) consumer.receiveNoWait();
      Map requestParts = (Map) message.getObject();

      // simple part
      Element simplePart = (Element) requestParts.get("simplePart");
      assertEquals("simplePart", simplePart.getLocalName());
      assertNull(simplePart.getNamespaceURI());
      assertEquals("wazabi", DatatypeUtil.toString(simplePart));

      // complex part
      Element complexPart = (Element) requestParts.get("complexPart");
      assertEquals("complexPart", complexPart.getLocalName());
      assertNull(complexPart.getNamespaceURI());
      assertTrue(complexPart.hasChildNodes());

      // message properties
      assertEquals(
          rpcPartnerLinkId, message.getLongProperty(IntegrationConstants.PARTNER_LINK_ID_PROP));
      assertEquals("op", message.getStringProperty(IntegrationConstants.OPERATION_NAME_PROP));
      assertEquals("venus", message.getStringProperty("nameProperty"));
      assertEquals("30", message.getStringProperty("idProperty"));
    } finally {
      session.close();
    }
  }
  /**
   * test messages are acknowledged and recovered properly
   *
   * @throws Exception
   */
  public void testClientAcknowledge() throws Exception {
    Destination destination = createDestination(getClass().getName());
    Connection connection = createConnection();
    connection.setClientID(idGen.generateId());
    connection.start();
    Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageConsumer consumer = consumerSession.createConsumer(destination);
    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = producerSession.createProducer(destination);
    producer.setDeliveryMode(deliveryMode);

    // send some messages

    TextMessage sent1 = producerSession.createTextMessage();
    sent1.setText("msg1");
    sent1.setStringProperty("str", "1");
    producer.send(sent1);

    TextMessage sent2 = producerSession.createTextMessage();
    sent2.setText("msg2");
    sent2.setStringProperty("str", "2");
    producer.send(sent2);

    TextMessage sent3 = producerSession.createTextMessage();
    sent2.setText("msg3");
    sent2.setStringProperty("str", "3");
    producer.send(sent3);

    TextMessage msgTest = (TextMessage) consumer.receive(RECEIVE_TIMEOUT);
    System.out.println("msgTest::" + msgTest + " // " + msgTest.getText());
    TextMessage rec2 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT);
    System.out.println("msgTest::" + rec2 + " // " + rec2.getText());
    assertNull(consumer.receiveNoWait());

    // ack rec2
    rec2.acknowledge();

    TextMessage sent4 = producerSession.createTextMessage();
    sent4.setText("msg4");
    producer.send(sent4);

    TextMessage rec4 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT);
    assertTrue(rec4.equals(sent4));
    consumerSession.recover();
    rec4 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT);
    assertTrue(rec4.equals(sent4));
    assertTrue(rec4.getJMSRedelivered());
    rec4.acknowledge();
    connection.close();
  }
  public void testPullConsumerWorks() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createTextMessage("Hello World!"));

    // now lets receive it
    MessageConsumer consumer = session.createConsumer(queue);
    Message answer = consumer.receive(5000);
    assertNotNull("Should have received a message!", answer);
    // check if method will return at all and will return a null
    answer = consumer.receive(1);
    assertNull("Should have not received a message!", answer);
    answer = consumer.receiveNoWait();
    assertNull("Should have not received a message!", answer);
  }
  public void testTwoConsumers() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createTextMessage("Msg1"));
    producer.send(session.createTextMessage("Msg2"));

    // now lets receive it
    MessageConsumer consumer1 = session.createConsumer(queue);
    MessageConsumer consumer2 = session.createConsumer(queue);
    TextMessage answer = (TextMessage) consumer1.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg1");
    answer = (TextMessage) consumer2.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg2");

    answer = (TextMessage) consumer2.receiveNoWait();
    assertNull("Should have not received a message!", answer);
  }
示例#8
0
  /**
   * Make a specific request to the underlying transport
   *
   * @param endpoint the endpoint to use when connecting to the resource
   * @param timeout the maximum time the operation should block before returning. The call should
   *     return immediately if there is data available. If no data becomes available before the
   *     timeout elapses, null will be returned
   * @return the result of the request wrapped in a UMOMessage object. Null will be returned if no
   *     data was avaialable
   * @throws Exception if the call to the underlying protocal cuases an exception
   */
  protected UMOMessage doReceive(UMOImmutableEndpoint endpoint, long timeout) throws Exception {

    Session session = null;
    Destination dest = null;
    MessageConsumer consumer = null;
    try {
      boolean topic = false;
      String resourceInfo = endpoint.getEndpointURI().getResourceInfo();
      topic = (resourceInfo != null && JmsConstants.TOPIC_PROPERTY.equalsIgnoreCase(resourceInfo));

      session = connector.getSession(false, topic);
      dest =
          connector
              .getJmsSupport()
              .createDestination(session, endpoint.getEndpointURI().getAddress(), topic);
      consumer = connector.getJmsSupport().createConsumer(session, dest, topic);

      try {
        Message message = null;
        if (timeout == RECEIVE_NO_WAIT) {
          message = consumer.receiveNoWait();
        } else if (timeout == RECEIVE_WAIT_INDEFINITELY) {
          message = consumer.receive();
        } else {
          message = consumer.receive(timeout);
        }
        if (message == null) {
          return null;
        }

        message = connector.preProcessMessage(message, session);

        return new MuleMessage(connector.getMessageAdapter(message));
      } catch (Exception e) {
        connector.handleException(e);
        return null;
      }
    } finally {
      connector.closeQuietly(consumer);
      connector.closeQuietly(session);
    }
  }
示例#9
0
 /**
  * Get the next message or null. Never blocks for longer than the specified timeout.
  *
  * @param timeout in milliseconds
  * @return the next message or null
  * @throws JMSException
  */
 public Message getMessage(long timeout) throws JMSException {
   Message message = null;
   if (queue != null) { // Using onMessage Listener
     try {
       if (timeout < 10) { // Allow for short/negative times
         message = queue.poll();
       } else {
         message = queue.poll(timeout, TimeUnit.MILLISECONDS);
       }
     } catch (InterruptedException e) {
       // Ignored
     }
     return message;
   }
   if (timeout < 10) { // Allow for short/negative times
     message = SUBSCRIBER.receiveNoWait();
   } else {
     message = SUBSCRIBER.receive(timeout);
   }
   return message;
 }
  @Override
  public String receiveMessage(long timeout) throws MessengingException {
    System.out.printf("Receiving on %s\n", this.destination);

    try {
      if (consumer == null) {
        synchronized (this) {
          if (consumer == null) {
            consumer = getSession().createConsumer(getDestination());
          }
        }
      }

      consumer.setMessageListener(null);

      Message message = null;

      /* Wait forever */
      if (timeout < 0) {
        message = consumer.receive();

        /* Wait for specified timeout */
      } else if (timeout > 0) {
        message = consumer.receive(timeout);

        /* Nonblocking receive */
      } else {
        message = consumer.receiveNoWait();
      }

      if (message == null) {
        return null;
      }

      return ((TextMessage) message).getText();

    } catch (JMSException e) {
      throw new MessengingException(e);
    }
  }
示例#11
0
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<html><head></head><body>");

    try {
      // Gather necessary JMS resources
      Context ctx = new InitialContext();
      ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/myConnectionFactory");
      Connection con = cf.createConnection();
      con.start(); // don't forget to start the connection
      QueueSession session = (QueueSession) con.createSession(false, Session.AUTO_ACKNOWLEDGE);

      // The PITsnapshot Queue is used for responses from the Players to this serverlet
      Queue q = (Queue) ctx.lookup("jms/PITsnapshot");
      MessageConsumer reader = session.createConsumer(q);

      /*
       * Throw out old PITsnapshot messages that may have been left from past
       * snapshots that did not complete (because of some error).
       */
      ObjectMessage m = null;
      while ((m = (ObjectMessage) reader.receiveNoWait()) != null) {
        System.out.println("Found an orphaned PITsnapshot message");
      }

      // Initialize the snapshot my sending a marker to a Player
      sendInitSnapshot();

      /*
       * Receive the snapshot messages from all Players.
       * Each snapshot is a HahsMap.  Put them into an array of HashMaps             *
       */
      HashMap state[] = new HashMap[numPlayers + 1];
      int stateResponses = 0;
      int failures = 0;
      while (stateResponses < numPlayers) {
        if ((m = (ObjectMessage) reader.receive(1000)) == null) {
          if (++failures > 10) {
            System.out.println("Not all players reported, giving up after " + stateResponses);
            break;
          }
          continue;
        }
        state[stateResponses++] = (HashMap) m.getObject();
      }

      /*
       * For each commodity, sum the number of them reported from
       * each Player.  Store these into a two dimensional table
       * that will then be used to generate the report back to the user.
       */
      String commodity[] = {"rice", "gold", "oil"};
      int total[][] = new int[numPlayers][commodity.length];
      for (int c = 0; c < commodity.length; c++) {
        for (int p = 0; p < stateResponses; p++) {
          try {
            Integer ccount = (Integer) state[p].get(commodity[c]);
            if (ccount == null) {
              total[p][c] = 0;
            } else {
              total[p][c] = (Integer) ccount.intValue();
            }
          } catch (Exception e) {
            System.out.println("Servlet threw exception " + e);
          }
        }
      }

      /*
       * Now turn the table of commodities, and the state from each Player
       * into a response to the user.
       */
      for (int c = 0; c < commodity.length; c++) {
        int ctotal = 0;
        out.print("<h2>Commodity: " + commodity[c] + "</h2>");
        out.print("<table border='1'><tr><th>Player</th><th>Quantity</th></tr>");
        for (int p = 0; p < stateResponses; p++) {
          out.print("<tr><td>" + p + "</td><td>" + total[p][c] + "</td></tr>");
          ctotal += total[p][c];
        }
        out.print("<tr><td><b>Total</b></td><td>" + ctotal + "</td></tr>");
        out.print("</table></br></br>");
      }

      // Close the connection
      con.close();

      out.println("</BODY></HTML>");

    } catch (Exception e) {
      System.out.println("Servlet threw exception " + e);
    } finally {
      out.println("</body></html>");
      out.close();
    }
  }
示例#12
0
  public Message receiveNoWait() throws JMSException {

    return consumer.receiveNoWait();
  }
示例#13
0
  @Test
  public void testUINotifyAppender() throws Exception {
    DummyFrameAction act = DummyFrameAction.INSTANCE;

    // setup JMS topic/connection/session
    String brokerURL =
        "vm://hmp-test?waitForStart=1000&broker.persistent=false&broker.deleteAllMessagesOnStartup=true";
    ConnectionFactory fact = new ActiveMQConnectionFactory(brokerURL);
    Connection conn = fact.createConnection();
    conn.start();
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    // setup a JMS template
    JmsTemplate tpl = new JmsTemplate(fact);
    tpl.setPubSubDomain(true);
    tpl.setDefaultDestinationName("ui.notify");
    tpl.setReceiveTimeout(JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT);
    Topic dest = sess.createTopic("ui.notify");
    MessageConsumer consumer = sess.createConsumer(dest);
    assertNull(tpl.receive());

    // configure the runner
    runner.setTimeoutMS(60000); // 1m
    runner.addResource(tpl);

    // create a viewdef with a nested UINotifier viewdef that should be done in 100ms
    // the rest of the time (10x100ms) should run in parallel and be done in 200ms;
    ((DataGeneratorQuery) vd.getPrimaryQuery()).setDelay(100);
    ViewDef view = new TestViewDef();
    DataGeneratorQuery q1 = view.addQuery(new DataGeneratorQuery("id", "1st", 10, 5).setDelay(150));
    UINotifyQueryMapper q2 = view.addQuery(new UINotifyQueryMapper("subview", vd));

    // query should be done in ~150ms, rest will take another 200ms
    long start = System.currentTimeMillis();
    FrameTask task = runner.exec(view);
    RenderTask q = task.getAction(ViewRenderAction.class).getResults();
    assertTrue(task.getTotalTimeMS() <= 200); // generous fudge factor
    assertEquals(task.getTotalTimeMS(), (System.currentTimeMillis() - start), 50);

    // should return 10 placeholder values
    assertEquals(10, q.size());
    assertEquals(1, q1.execCount);
    List<String> uuids = new ArrayList<String>();
    for (int i = 0; i < q.size(); i++) {
      Object subview = q.getCellIdx(i, "subview");
      assertTrue(subview instanceof String);
      uuids.add(subview.toString());
    }

    // expecting the main task to have a single subtask (RenderTask)
    assertEquals(1, task.getSubTasks().size());
    assertTrue(task.getSubTasks().get(0) instanceof RenderTask);
    assertSame(q, task.getSubTasks().get(0));
    assertEquals(1, q.getSubTasks().size());

    // main render task has one empty subtask for the UINotifyQueryMapper
    RenderTask task2 = (RenderTask) q.getSubTasks().get(0);
    assertSame(q2, task2.getQuery());
    assertEquals(0, task2.getSubTasks().size());

    // check that the JMS topic has 10 items on it, with the corresponding UUIDs
    for (int i = 0; i < 10; i++) {
      Message msg = consumer.receive(500);
      assertNotNull(msg);
      String uuid = msg.getStringProperty("uid");
      uuids.remove(uuid);
    }
    assertNull(consumer.receiveNoWait()); // nothing left

    // vd should have been executed 10x and found all UUIDs
    DataGeneratorQuery q3 = (DataGeneratorQuery) vd.getPrimaryQuery();
    assertEquals(10, q3.execCount);
    assertEquals(0, uuids.size());
  }
示例#14
0
 public void testSynchronousReceiveNoWait() throws Exception {
   for (int msg = 0; msg < MSG_COUNT; msg++) {
     assertTrue("Failed to receive message " + msg, _consumer.receiveNoWait() != null);
   }
 }
示例#15
0
  @Test
  public void testAutomaticFailover() throws Exception {
    ActiveMQConnectionFactory jbcf =
        ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, livetc);
    jbcf.setReconnectAttempts(-1);
    jbcf.setBlockOnDurableSend(true);
    jbcf.setBlockOnNonDurableSend(true);

    // Note we set consumer window size to a value so we can verify that consumer credit re-sending
    // works properly on failover
    // The value is small enough that credits will have to be resent several time

    final int numMessages = 10;

    final int bodySize = 1000;

    jbcf.setConsumerWindowSize(numMessages * bodySize / 10);

    Connection conn = JMSUtil.createConnectionAndWaitForTopology(jbcf, 2, 5);

    MyExceptionListener listener = new MyExceptionListener();

    conn.setExceptionListener(listener);

    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    ClientSession coreSession = ((ActiveMQSession) sess).getCoreSession();

    SimpleString jmsQueueName =
        new SimpleString(ActiveMQDestination.JMS_QUEUE_ADDRESS_PREFIX + "myqueue");

    coreSession.createQueue(jmsQueueName, jmsQueueName, null, true);

    Queue queue = sess.createQueue("myqueue");

    MessageProducer producer = sess.createProducer(queue);

    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    MessageConsumer consumer = sess.createConsumer(queue);

    byte[] body = RandomUtil.randomBytes(bodySize);

    for (int i = 0; i < numMessages; i++) {
      BytesMessage bm = sess.createBytesMessage();

      bm.writeBytes(body);

      producer.send(bm);
    }

    conn.start();

    JMSFailoverTest.log.info("sent messages and started connection");

    Thread.sleep(2000);

    JMSUtil.crash(liveService, ((ActiveMQSession) sess).getCoreSession());

    for (int i = 0; i < numMessages; i++) {
      JMSFailoverTest.log.info("got message " + i);

      BytesMessage bm = (BytesMessage) consumer.receive(1000);

      Assert.assertNotNull(bm);

      Assert.assertEquals(body.length, bm.getBodyLength());
    }

    TextMessage tm = (TextMessage) consumer.receiveNoWait();

    Assert.assertNull(tm);

    conn.close();
  }
  private void doTestManyMessageConsumerWithSend(boolean transacted) throws Exception {
    Session session =
        connection.createSession(
            transacted, transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE);

    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createTextMessage("Msg1"));
    producer.send(session.createTextMessage("Msg2"));
    producer.send(session.createTextMessage("Msg3"));
    producer.send(session.createTextMessage("Msg4"));
    producer.send(session.createTextMessage("Msg5"));
    producer.send(session.createTextMessage("Msg6"));
    producer.send(session.createTextMessage("Msg7"));
    producer.send(session.createTextMessage("Msg8"));
    if (transacted) {
      session.commit();
    }
    // now lets receive it
    MessageConsumer consumer = session.createConsumer(queue);

    MessageConsumer consumer2 = session.createConsumer(queue);
    TextMessage answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg1");
    if (transacted) {
      session.commit();
    }
    answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg2");
    if (transacted) {
      session.commit();
    }
    answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg3");
    if (transacted) {
      session.commit();
    }
    // Now using other consumer take 2
    answer = (TextMessage) consumer2.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg4");
    answer = (TextMessage) consumer2.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg5");

    // ensure prefetch extension ok by sending another that could get dispatched
    producer.send(session.createTextMessage("Msg9"));
    if (transacted) {
      session.commit();
    }

    answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg6");
    // read one more message without commit
    // and using other consumer
    answer = (TextMessage) consumer2.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg7");
    if (transacted) {
      session.commit();
    }

    answer = (TextMessage) consumer2.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg8");
    if (transacted) {
      session.commit();
    }

    answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg9");
    if (transacted) {
      session.commit();
    }
    answer = (TextMessage) consumer.receiveNoWait();
    assertNull("Should have not received a message!", answer);
  }
  private void doTestManyMessageConsumer(boolean transacted) throws Exception {
    Session session =
        connection.createSession(
            transacted, transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE);

    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createTextMessage("Msg1"));
    producer.send(session.createTextMessage("Msg2"));
    producer.send(session.createTextMessage("Msg3"));
    producer.send(session.createTextMessage("Msg4"));
    producer.send(session.createTextMessage("Msg5"));
    producer.send(session.createTextMessage("Msg6"));
    producer.send(session.createTextMessage("Msg7"));
    producer.send(session.createTextMessage("Msg8"));
    if (transacted) {
      session.commit();
    }
    // now lets receive it
    MessageConsumer consumer = session.createConsumer(queue);

    MessageConsumer consumer2 = session.createConsumer(queue);
    TextMessage answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg1");
    if (transacted) {
      session.commit();
    }
    answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg2");
    if (transacted) {
      session.commit();
    }
    answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg3");
    if (transacted) {
      session.commit();
    }
    // this call would return null if prefetchSize > 0
    answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg4");
    if (transacted) {
      session.commit();
    }
    // Now using other consumer
    // this call should return the next message (Msg5) still left on the queue
    answer = (TextMessage) consumer2.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg5");
    if (transacted) {
      session.commit();
    }
    // Now using other consumer
    // this call should return the next message still left on the queue
    answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg6");
    // read one more message without commit
    // this call should return the next message still left on the queue
    answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg7");
    if (transacted) {
      session.commit();
    }
    // Now using other consumer
    // this call should return the next message (Msg5) still left on the queue
    answer = (TextMessage) consumer2.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg8");
    if (transacted) {
      session.commit();
    }
    answer = (TextMessage) consumer.receiveNoWait();
    assertNull("Should have not received a message!", answer);
  }
示例#18
0
  public void consume(
      final ProcessContext context,
      final ProcessSession session,
      final WrappedMessageConsumer wrappedConsumer)
      throws ProcessException {
    final ProcessorLog logger = getLogger();

    final MessageConsumer consumer = wrappedConsumer.getConsumer();
    final boolean clientAcknowledge =
        context.getProperty(ACKNOWLEDGEMENT_MODE).getValue().equalsIgnoreCase(ACK_MODE_CLIENT);
    final long timeout = context.getProperty(TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS);
    final boolean addAttributes = context.getProperty(JMS_PROPS_TO_ATTRIBUTES).asBoolean();
    final int batchSize = context.getProperty(BATCH_SIZE).asInteger();

    final JmsProcessingSummary processingSummary = new JmsProcessingSummary();

    final StopWatch stopWatch = new StopWatch(true);
    for (int i = 0; i < batchSize; i++) {

      final Message message;
      try {
        // If we haven't received a message, wait until one is available. If we have already
        // received at least one
        // message, then we are not willing to wait for more to become available, but we are willing
        // to keep receiving
        // all messages that are immediately available.
        if (processingSummary.getMessagesReceived() == 0) {
          message = consumer.receive(timeout);
        } else {
          message = consumer.receiveNoWait();
        }
      } catch (final JMSException e) {
        logger.error("Failed to receive JMS Message due to {}", e);
        wrappedConsumer.close(logger);
        break;
      }

      if (message == null) { // if no messages, we're done
        break;
      }

      try {
        processingSummary.add(map2FlowFile(context, session, message, addAttributes, logger));
      } catch (Exception e) {
        logger.error("Failed to receive JMS Message due to {}", e);
        wrappedConsumer.close(logger);
        break;
      }
    }

    if (processingSummary.getFlowFilesCreated() == 0) {
      context.yield();
      return;
    }

    session.commit();

    stopWatch.stop();
    if (processingSummary.getFlowFilesCreated() > 0) {
      final float secs = ((float) stopWatch.getDuration(TimeUnit.MILLISECONDS) / 1000F);
      float messagesPerSec = ((float) processingSummary.getMessagesReceived()) / secs;
      final String dataRate = stopWatch.calculateDataRate(processingSummary.getBytesReceived());
      logger.info(
          "Received {} messages in {} milliseconds, at a rate of {} messages/sec or {}",
          new Object[] {
            processingSummary.getMessagesReceived(),
            stopWatch.getDuration(TimeUnit.MILLISECONDS),
            messagesPerSec,
            dataRate
          });
    }

    // if we need to acknowledge the messages, do so now.
    final Message lastMessage = processingSummary.getLastMessageReceived();
    if (clientAcknowledge && lastMessage != null) {
      try {
        lastMessage
            .acknowledge(); // acknowledge all received messages by acknowledging only the last.
      } catch (final JMSException e) {
        logger.error(
            "Failed to acknowledge {} JMS Message(s). This may result in duplicate messages. Reason for failure: {}",
            new Object[] {processingSummary.getMessagesReceived(), e});
      }
    }
  }
示例#19
0
  @Test
  public void testManualFailover() throws Exception {
    ActiveMQConnectionFactory jbcfLive =
        ActiveMQJMSClient.createConnectionFactoryWithoutHA(
            JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY));

    jbcfLive.setBlockOnNonDurableSend(true);
    jbcfLive.setBlockOnDurableSend(true);

    ActiveMQConnectionFactory jbcfBackup =
        ActiveMQJMSClient.createConnectionFactoryWithoutHA(
            JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY, backupParams));
    jbcfBackup.setBlockOnNonDurableSend(true);
    jbcfBackup.setBlockOnDurableSend(true);
    jbcfBackup.setInitialConnectAttempts(-1);
    jbcfBackup.setReconnectAttempts(-1);

    Connection connLive = jbcfLive.createConnection();

    MyExceptionListener listener = new MyExceptionListener();

    connLive.setExceptionListener(listener);

    Session sessLive = connLive.createSession(false, Session.AUTO_ACKNOWLEDGE);

    ClientSession coreSessionLive = ((ActiveMQSession) sessLive).getCoreSession();

    RemotingConnection coreConnLive = ((ClientSessionInternal) coreSessionLive).getConnection();

    SimpleString jmsQueueName =
        new SimpleString(ActiveMQDestination.JMS_QUEUE_ADDRESS_PREFIX + "myqueue");

    coreSessionLive.createQueue(jmsQueueName, jmsQueueName, null, true);

    Queue queue = sessLive.createQueue("myqueue");

    final int numMessages = 1000;

    MessageProducer producerLive = sessLive.createProducer(queue);

    for (int i = 0; i < numMessages; i++) {
      TextMessage tm = sessLive.createTextMessage("message" + i);

      producerLive.send(tm);
    }

    // Note we block on P send to make sure all messages get to server before failover

    JMSUtil.crash(liveService, coreSessionLive);

    connLive.close();

    // Now recreate on backup

    Connection connBackup = jbcfBackup.createConnection();

    Session sessBackup = connBackup.createSession(false, Session.AUTO_ACKNOWLEDGE);

    MessageConsumer consumerBackup = sessBackup.createConsumer(queue);

    connBackup.start();

    for (int i = 0; i < numMessages; i++) {
      TextMessage tm = (TextMessage) consumerBackup.receive(1000);

      Assert.assertNotNull(tm);

      Assert.assertEquals("message" + i, tm.getText());
    }

    TextMessage tm = (TextMessage) consumerBackup.receiveNoWait();

    Assert.assertNull(tm);

    connBackup.close();
  }
  @Test
  public void testSendToSingleDisconnectedBindingWhenLocalAvailable() throws Exception {
    Connection conn1 = cf1.createConnection();

    conn1.setClientID("someClient2");

    Connection conn2 = cf2.createConnection();

    conn2.setClientID("someClient2");

    conn1.start();

    conn2.start();

    try {

      Topic topic1 = createTopic("t1", true);

      Topic topic2 = (Topic) context1.lookup("topic/t1");

      Session session1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE);

      Session session2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageConsumer cons1 = session1.createDurableSubscriber(topic1, "sub2");

      MessageConsumer cons2 = session2.createDurableSubscriber(topic2, "sub2");

      cons2.close();

      session2.close();

      conn2.close();

      Thread.sleep(500);

      MessageProducer prod1 = session1.createProducer(topic1);

      prod1.setDeliveryMode(DeliveryMode.PERSISTENT);

      prod1.send(session1.createTextMessage("m1"));

      printBindings(jmsServer1.getActiveMQServer(), "jms.topic.t1");
      printBindings(jmsServer2.getActiveMQServer(), "jms.topic.t1");

      crash();

      printBindings(jmsServer1.getActiveMQServer(), "jms.topic.t1");

      // send a few messages while the binding is disconnected
      prod1.send(session1.createTextMessage("m2"));
      prod1.send(session1.createTextMessage("m3"));
      prod1.send(session1.createTextMessage("m4"));

      restart();

      Thread.sleep(2000);

      printBindings(jmsServer1.getActiveMQServer(), "jms.topic.t1");
      printBindings(jmsServer2.getActiveMQServer(), "jms.topic.t1");

      prod1.send(session1.createTextMessage("m5"));
      prod1.send(session1.createTextMessage("m6"));

      cf2 =
          ActiveMQJMSClient.createConnectionFactoryWithoutHA(
              JMSFactoryType.CF,
              new TransportConfiguration(
                  InVMConnectorFactory.class.getName(), generateInVMParams(2)));

      conn2 = cf2.createConnection();

      conn2.setClientID("someClient2");

      session2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE);

      cons2 = session2.createDurableSubscriber(topic2, "sub2");

      conn2.start();

      TextMessage received = (TextMessage) cons2.receiveNoWait();

      assertNull(received);

      received = (TextMessage) cons1.receive(5000);

      assertNotNull(received);

      assertEquals("m1", received.getText());

      received = (TextMessage) cons1.receive(5000);

      assertNotNull(received);

      assertEquals("m2", received.getText());

      received = (TextMessage) cons1.receive(5000);

      assertNotNull(received);

      assertEquals("m3", received.getText());

      received = (TextMessage) cons1.receive(5000);

      assertNotNull(received);

      assertEquals("m4", received.getText());

      received = (TextMessage) cons1.receive(5000);

      assertNotNull(received);

      assertEquals("m5", received.getText());

      cons2.close();
    } finally {
      conn1.close();
      conn2.close();
    }

    jmsServer1.destroyTopic("t1");
    jmsServer2.destroyTopic("t1");
  }