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
示例#2
0
  public void onMessage(Message message) {
    try {
      if (logger.isDebugEnabled()) {
        logger.debug("Message received it is of type: " + message.getClass().getName());
        if (message.getJMSDestination() != null) {
          logger.debug(
              "Message received on "
                  + message.getJMSDestination()
                  + " ("
                  + message.getJMSDestination().getClass().getName()
                  + ")");
        } else {
          logger.debug("Message received on unknown destination");
        }
        logger.debug("Message CorrelationId is: " + message.getJMSCorrelationID());
        logger.debug("Jms Message Id is: " + message.getJMSMessageID());
      }

      if (message.getJMSRedelivered()) {
        if (logger.isDebugEnabled()) {
          logger.debug(
              "Message with correlationId: "
                  + message.getJMSCorrelationID()
                  + " is redelivered. handing off to Exception Handler");
        }
        redeliveryHandler.handleRedelivery(message);
      }

      UMOMessageAdapter adapter = connector.getMessageAdapter(message);
      routeMessage(new MuleMessage(adapter));
    } catch (Exception e) {
      handleException(e);
    }
  }
示例#3
0
 public Message receive(Session session, MessageConsumer consumer) throws JMSException {
   Message message = consumer.receive(TIMEOUT);
   assertNotNull(message);
   assertTrue(TextMessage.class.isAssignableFrom(message.getClass()));
   assertEquals(DEFAULT_OUTPUT_MESSAGE, ((TextMessage) message).getText());
   applyTransaction(session);
   return message;
 }
  /**
   * Template method that allows for custom message mapping. Invoked when {@link #setTargetType} is
   * not {@link MessageType#TEXT} or {@link MessageType#BYTES}.
   *
   * <p>The default implementation throws an {@link IllegalArgumentException}.
   *
   * @param message the input message
   * @param targetJavaType the target type
   * @return the message converted to an object
   * @throws JMSException if thrown by JMS
   * @throws IOException in case of I/O errors
   */
  protected Object convertFromMessage(Message message, JavaType targetJavaType)
      throws JMSException, IOException {

    throw new IllegalArgumentException(
        "Unsupported message type ["
            + message.getClass()
            + "]. MappingJacksonMessageConverter by default only supports TextMessages and BytesMessages.");
  }
示例#5
0
 private static byte[] body(final javax.jms.Message message) throws JMSException {
   if (message == null) return null;
   else if (message instanceof TextMessage) {
     final TextMessage textMessage = (TextMessage) message;
     return textMessage.getText().getBytes();
   } else if (message instanceof BytesMessage) {
     final BytesMessage bytesMessage = (BytesMessage) message;
     final byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
     bytesMessage.readBytes(bytes);
     return bytes;
   } else throw new UnsupportedOperationException(message.getClass().getName());
 }
示例#6
0
 @Override
 public void onMessage(Message m) {
   if (m instanceof TextMessage) {
     try {
       String text = ((TextMessage) m).getText();
     } catch (JMSException e) {
       // Handle the error
     }
     // do something with "text" - log it, store in database, etc.
   } else {
     throw new IllegalArgumentException("Expected TextMessage, got " + m.getClass().getName());
   }
 }
示例#7
0
  public static void main(String[] args) throws JMSException {

    String user = env("ACTIVEMQ_USER", "");
    String password = env("ACTIVEMQ_PASSWORD", "");
    String host = env("ACTIVEMQ_HOST", "localhost");
    int port = Integer.parseInt(env("ACTIVEMQ_PORT", "61616"));
    String destination = arg(args, 0, "foo.bar");

    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://" + host + ":" + port);

    Connection connection = factory.createConnection(user, password);
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination dest = new ActiveMQQueue(destination);

    MessageConsumer consumer = session.createConsumer(dest);
    long start = System.currentTimeMillis();
    long count = 1;
    System.out.println("Waiting for messages...");
    while (true) {
      Message msg = consumer.receive();
      if (msg instanceof TextMessage) {
        String body = ((TextMessage) msg).getText();
        if ("THE.END".equals(body)) {
          long diff = System.currentTimeMillis() - start;
          System.out.println(
              String.format("Received %d in %.2f seconds", count, (1.0 * diff / 1000.0)));
          break;
        } else {
          if (count != msg.getIntProperty("id")) {
            System.out.println("mismatch: " + count + "!=" + msg.getIntProperty("id"));
          }
          count = msg.getIntProperty("id");

          if (count == 0) {
            start = System.currentTimeMillis();
          }
          if (count % 1000 == 0) {
            System.out.println(String.format("Received %d messages.", count));
          }
          count++;
        }

      } else {
        System.out.println("Unexpected message type: " + msg.getClass());
      }
    }
    connection.close();
  }
 @Override
 public void onMessage(Message message) {
   toConsume.countDown();
   try {
     if (message instanceof TextMessage) {
       TextMessage textMessage = (TextMessage) message;
       LOG.debug("Listener {} received [{}]", id, textMessage.getText());
     } else {
       LOG.error(
           "Listener {} Expected a TextMessage, got {}",
           id,
           message.getClass().getCanonicalName());
     }
   } catch (JMSException e) {
     LOG.error("Unexpected JMSException in Listener " + id, e);
   }
 }
示例#9
0
 @Override
 public void onMessage(final Message message) {
   try {
     if (message instanceof ObjectMessage) {
       final Object body = ((ObjectMessage) message).getObject();
       if (body instanceof LogEvent) {
         log((LogEvent) body);
       } else {
         LOGGER.warn(
             "Expected ObjectMessage to contain LogEvent. Got type {} instead.", body.getClass());
       }
     } else {
       LOGGER.warn(
           "Received message of type {} and JMSType {} which cannot be handled.",
           message.getClass(),
           message.getJMSType());
     }
   } catch (final JMSException e) {
     LOGGER.catching(e);
   }
 }
示例#10
0
  public Object getBody() throws JMSException {
    Message message = getMessage();
    if (message instanceof TextMessage) {
      return ((TextMessage) message).getText();
    }
    if (message instanceof ObjectMessage) {
      try {
        return ((ObjectMessage) message).getObject();
      } catch (JMSException e) {
        // message could not be parsed, make the reason available
        return e;
      }
    }
    if (message instanceof MapMessage) {
      return createMapBody((MapMessage) message);
    }
    if (message instanceof BytesMessage) {
      BytesMessage msg = (BytesMessage) message;
      int len = (int) msg.getBodyLength();
      if (len > -1) {
        byte[] data = new byte[len];
        msg.readBytes(data);
        return new String(data);
      } else {
        return "";
      }
    }
    if (message instanceof StreamMessage) {
      return "StreamMessage is not viewable";
    }

    // unknown message type
    if (message != null) {
      return "Unknown message type [" + message.getClass().getName() + "] " + message;
    }

    return null;
  }
示例#11
0
  private MuleMessage dispatchMessage(MuleEvent event) throws Exception {
    Session session = null;
    MessageProducer producer = null;
    MessageConsumer consumer = null;
    Destination replyTo = null;
    boolean transacted = false;
    boolean cached = false;
    boolean useReplyToDestination;

    final Transaction muleTx = TransactionCoordination.getInstance().getTransaction();

    if (logger.isDebugEnabled()) {
      logger.debug(
          "dispatching on endpoint: "
              + event.getEndpoint().getEndpointURI()
              + ". MuleEvent id is: "
              + event.getId()
              + ". Outbound transformers are: "
              + event.getEndpoint().getTransformers());
    }

    // assume session is transacted first, and thus, managed
    boolean sessionManaged = true;
    try {
      session = connector.getSessionFromTransaction();
      if (session != null) {
        transacted = true;
      }
      // Should we be caching sessions? Note this is not part of the JMS spec.
      // and is turned off by default.
      else if (event
          .getMessage()
          .getBooleanProperty(
              JmsConstants.CACHE_JMS_SESSIONS_PROPERTY, connector.isCacheJmsSessions())) {
        sessionManaged = false;
        cached = true;
        if (cachedSession != null) {
          session = cachedSession;
        } else {
          session = connector.getSession(event.getEndpoint());
          cachedSession = session;
        }
      } else {
        // by now we're running with a different connector and connection
        sessionManaged = muleTx != null && muleTx.isXA();

        session = connector.getSession(event.getEndpoint());
        if (event.getEndpoint().getTransactionConfig().isTransacted()) {
          transacted = true;
        }
      }

      // If a transaction is running, we can not receive any messages
      // in the same transaction using a replyTo destination
      useReplyToDestination = returnResponse(event) && !transacted;

      boolean topic = connector.getTopicResolver().isTopic(event.getEndpoint(), true);

      Destination dest = connector.getJmsSupport().createDestination(session, endpoint);
      producer = connector.getJmsSupport().createProducer(session, dest, topic);

      preTransformMessage(event.getMessage());

      Object message = event.transformMessage();
      if (!(message instanceof Message)) {
        throw new DispatchException(
            JmsMessages.checkTransformer("JMS message", message.getClass(), connector.getName()),
            event.getMessage(),
            event.getEndpoint());
      }

      Message msg = (Message) message;

      MuleMessage eventMsg = event.getMessage();

      replyTo = getReplyToDestination(msg, session, event, useReplyToDestination, topic);

      // Set the replyTo property
      if (replyTo != null) {
        msg.setJMSReplyTo(replyTo);
      }

      // Allow overrides to alter the message if necessary
      processMessage(msg, event);

      // QoS support
      String ttlString = (String) eventMsg.removeProperty(JmsConstants.TIME_TO_LIVE_PROPERTY);
      String priorityString = (String) eventMsg.removeProperty(JmsConstants.PRIORITY_PROPERTY);
      String persistentDeliveryString =
          (String) eventMsg.removeProperty(JmsConstants.PERSISTENT_DELIVERY_PROPERTY);

      long ttl =
          StringUtils.isNotBlank(ttlString)
              ? NumberUtils.toLong(ttlString)
              : Message.DEFAULT_TIME_TO_LIVE;
      int priority =
          StringUtils.isNotBlank(priorityString)
              ? NumberUtils.toInt(priorityString)
              : Message.DEFAULT_PRIORITY;
      boolean persistent =
          StringUtils.isNotBlank(persistentDeliveryString)
              ? BooleanUtils.toBoolean(persistentDeliveryString)
              : connector.isPersistentDelivery();

      // If we are honouring the current QoS message headers we need to use the ones set on the
      // current message
      if (connector.isHonorQosHeaders()) {
        Object priorityProp = eventMsg.getProperty(JmsConstants.JMS_PRIORITY);
        Object deliveryModeProp = eventMsg.getProperty(JmsConstants.JMS_DELIVERY_MODE);

        if (priorityProp != null) {
          priority = NumberUtils.toInt(priorityProp);
        }
        if (deliveryModeProp != null) {
          persistent = NumberUtils.toInt(deliveryModeProp) == DeliveryMode.PERSISTENT;
        }
      }

      if (logger.isDebugEnabled()) {
        logger.debug("Sending message of type " + ClassUtils.getSimpleName(msg.getClass()));
        logger.debug(
            "Sending JMS Message type "
                + msg.getJMSType()
                + "\n  JMSMessageID="
                + msg.getJMSMessageID()
                + "\n  JMSCorrelationID="
                + msg.getJMSCorrelationID()
                + "\n  JMSDeliveryMode="
                + (persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT)
                + "\n  JMSPriority="
                + priority
                + "\n  JMSReplyTo="
                + msg.getJMSReplyTo());
      }
      connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic, endpoint);

      if (useReplyToDestination && replyTo != null) {
        consumer = createReplyToConsumer(msg, event, session, replyTo, topic);

        if (topic) {
          // need to register a listener for a topic
          Latch l = new Latch();
          ReplyToListener listener = new ReplyToListener(l);
          consumer.setMessageListener(listener);

          connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic, endpoint);

          int timeout = event.getTimeout();

          if (logger.isDebugEnabled()) {
            logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo);
          }

          l.await(timeout, TimeUnit.MILLISECONDS);
          consumer.setMessageListener(null);
          listener.release();
          Message result = listener.getMessage();
          if (result == null) {
            logger.debug("No message was returned via replyTo destination");
            return new DefaultMuleMessage(NullPayload.getInstance(), connector.getMuleContext());
          } else {
            MessageAdapter adapter = connector.getMessageAdapter(result);
            return new DefaultMuleMessage(
                JmsMessageUtils.toObject(
                    result, connector.getSpecification(), endpoint.getEncoding()),
                adapter,
                connector.getMuleContext());
          }
        } else {
          int timeout = event.getTimeout();

          if (logger.isDebugEnabled()) {
            logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo);
          }

          Message result = consumer.receive(timeout);
          if (result == null) {
            logger.debug("No message was returned via replyTo destination " + replyTo);
            return new DefaultMuleMessage(NullPayload.getInstance(), connector.getMuleContext());
          } else {
            MessageAdapter adapter = connector.getMessageAdapter(result);
            return new DefaultMuleMessage(
                JmsMessageUtils.toObject(
                    result, connector.getSpecification(), endpoint.getEncoding()),
                adapter,
                connector.getMuleContext());
          }
        }
      }

      return new DefaultMuleMessage(
          returnOriginalMessageAsReply ? msg : NullPayload.getInstance(),
          connector.getMuleContext());
    } finally {
      connector.closeQuietly(producer);
      connector.closeQuietly(consumer);

      // TODO AP check if TopicResolver is to be utilized for temp destinations as well
      if (replyTo != null
          && (replyTo instanceof TemporaryQueue || replyTo instanceof TemporaryTopic)) {
        if (replyTo instanceof TemporaryQueue) {
          connector.closeQuietly((TemporaryQueue) replyTo);
        } else {
          // hope there are no more non-standard tricks from JMS vendors
          // here ;)
          connector.closeQuietly((TemporaryTopic) replyTo);
        }
      }

      if (!sessionManaged && transacted && muleTx instanceof TransactionCollection) {
        handleMultiTx(session);
      }

      // If the session is from the current transaction, it is up to the
      // transaction to close it.
      if (session != null && !cached && !transacted) {
        connector.closeQuietly(session);
      }
    }
  }
示例#12
0
  private MuleMessage dispatchMessage(MuleEvent event) throws Exception {
    Session session = null;
    MessageProducer producer = null;
    MessageConsumer consumer = null;
    Destination replyTo = null;
    boolean transacted = false;
    boolean cached = false;
    boolean remoteSync = useRemoteSync(event);

    if (logger.isDebugEnabled()) {
      logger.debug(
          "dispatching on endpoint: "
              + event.getEndpoint().getEndpointURI()
              + ". MuleEvent id is: "
              + event.getId()
              + ". Outbound transformers are: "
              + event.getEndpoint().getTransformers());
    }

    try {
      session = connector.getSessionFromTransaction();
      if (session != null) {
        transacted = true;

        // If a transaction is running, we can not receive any messages
        // in the same transaction.
        if (remoteSync) {
          throw new IllegalTransactionStateException(
              JmsMessages.connectorDoesNotSupportSyncReceiveWhenTransacted());
        }
      }
      // Should we be caching sessions? Note this is not part of the JMS spec.
      // and is turned off by default.
      else if (event
          .getMessage()
          .getBooleanProperty(
              JmsConstants.CACHE_JMS_SESSIONS_PROPERTY, connector.isCacheJmsSessions())) {
        cached = true;
        if (cachedSession != null) {
          session = cachedSession;
        } else {
          session = connector.getSession(event.getEndpoint());
          cachedSession = session;
        }
      } else {
        session = connector.getSession(event.getEndpoint());
        if (event.getEndpoint().getTransactionConfig().isTransacted()) {
          transacted = true;
        }
      }

      boolean topic = connector.getTopicResolver().isTopic(event.getEndpoint(), true);

      Destination dest = connector.createDestinationMule3858Backport(session, endpoint);
      producer = connector.getJmsSupport().createProducer(session, dest, topic);

      Object message = event.transformMessage();
      if (!(message instanceof Message)) {
        throw new DispatchException(
            JmsMessages.checkTransformer("JMS message", message.getClass(), connector.getName()),
            event.getMessage(),
            event.getEndpoint());
      }

      Message msg = (Message) message;
      if (event.getMessage().getCorrelationId() != null) {
        msg.setJMSCorrelationID(event.getMessage().getCorrelationId());
      }

      MuleMessage eventMsg = event.getMessage();

      // Some JMS implementations might not support the ReplyTo property.
      if (connector.supportsProperty(JmsConstants.JMS_REPLY_TO)) {
        Object tempReplyTo = eventMsg.removeProperty(JmsConstants.JMS_REPLY_TO);
        if (tempReplyTo == null) {
          // It may be a Mule URI or global endpoint Ref
          tempReplyTo = eventMsg.removeProperty(MuleProperties.MULE_REPLY_TO_PROPERTY);
          if (tempReplyTo != null) {
            if (tempReplyTo.toString().startsWith("jms://")) {
              tempReplyTo = tempReplyTo.toString().substring(6);
            } else {
              EndpointBuilder epb =
                  event
                      .getMuleContext()
                      .getRegistry()
                      .lookupEndpointBuilder(tempReplyTo.toString());
              if (epb != null) {
                tempReplyTo = epb.buildOutboundEndpoint().getEndpointURI().getAddress();
              }
            }
          }
        }
        if (tempReplyTo != null) {
          if (tempReplyTo instanceof Destination) {
            replyTo = (Destination) tempReplyTo;
          } else {
            // TODO AP should this drill-down be moved into the resolver as well?
            boolean replyToTopic = false;
            String reply = tempReplyTo.toString();
            int i = reply.indexOf(":");
            if (i > -1) {
              // TODO MULE-1409 this check will not work for ActiveMQ 4.x,
              // as they have temp-queue://<destination> and temp-topic://<destination> URIs
              // Extract to a custom resolver for ActiveMQ4.x
              // The code path can be exercised, e.g. by a LoanBrokerESBTestCase
              String qtype = reply.substring(0, i);
              replyToTopic = JmsConstants.TOPIC_PROPERTY.equalsIgnoreCase(qtype);
              reply = reply.substring(i + 1);
            }
            replyTo = connector.getJmsSupport().createDestination(session, reply, replyToTopic);
          }
        }
        // Are we going to wait for a return event ?
        if (remoteSync && replyTo == null) {
          replyTo = connector.getJmsSupport().createTemporaryDestination(session, topic);
        }
        // Set the replyTo property
        if (replyTo != null) {
          msg.setJMSReplyTo(replyTo);
        }

        // Are we going to wait for a return event ?
        if (remoteSync) {
          try {
            consumer = connector.getJmsSupport().createConsumer(session, replyTo, topic);
          } catch (Exception e) {
            logger.warn(e);
          }
        }
      }

      // QoS support
      String ttlString = (String) eventMsg.removeProperty(JmsConstants.TIME_TO_LIVE_PROPERTY);
      String priorityString = (String) eventMsg.removeProperty(JmsConstants.PRIORITY_PROPERTY);
      String persistentDeliveryString =
          (String) eventMsg.removeProperty(JmsConstants.PERSISTENT_DELIVERY_PROPERTY);

      long ttl =
          StringUtils.isNotBlank(ttlString)
              ? NumberUtils.toLong(ttlString)
              : Message.DEFAULT_TIME_TO_LIVE;
      int priority =
          StringUtils.isNotBlank(priorityString)
              ? NumberUtils.toInt(priorityString)
              : Message.DEFAULT_PRIORITY;
      boolean persistent =
          StringUtils.isNotBlank(persistentDeliveryString)
              ? BooleanUtils.toBoolean(persistentDeliveryString)
              : connector.isPersistentDelivery();

      if (connector.isHonorQosHeaders()) {
        int priorityProp =
            eventMsg.getIntProperty(JmsConstants.JMS_PRIORITY, Connector.INT_VALUE_NOT_SET);
        int deliveryModeProp =
            eventMsg.getIntProperty(JmsConstants.JMS_DELIVERY_MODE, Connector.INT_VALUE_NOT_SET);

        if (priorityProp != Connector.INT_VALUE_NOT_SET) {
          priority = priorityProp;
        }
        if (deliveryModeProp != Connector.INT_VALUE_NOT_SET) {
          persistent = deliveryModeProp == DeliveryMode.PERSISTENT;
        }
      }

      if (logger.isDebugEnabled()) {
        logger.debug("Sending message of type " + ClassUtils.getSimpleName(msg.getClass()));
      }

      if (consumer != null && topic) {
        // need to register a listener for a topic
        Latch l = new Latch();
        ReplyToListener listener = new ReplyToListener(l);
        consumer.setMessageListener(listener);

        connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic);

        int timeout = event.getTimeout();

        if (logger.isDebugEnabled()) {
          logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo);
        }

        l.await(timeout, TimeUnit.MILLISECONDS);
        consumer.setMessageListener(null);
        listener.release();
        Message result = listener.getMessage();
        if (result == null) {
          logger.debug("No message was returned via replyTo destination");
          return null;
        } else {
          MessageAdapter adapter = connector.getMessageAdapter(result);
          return new DefaultMuleMessage(
              JmsMessageUtils.toObject(
                  result, connector.getSpecification(), endpoint.getEncoding()),
              adapter);
        }
      } else {
        connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic);
        if (consumer != null) {
          int timeout = event.getTimeout();

          if (logger.isDebugEnabled()) {
            logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo);
          }

          Message result = consumer.receive(timeout);
          if (result == null) {
            logger.debug("No message was returned via replyTo destination");
            return null;
          } else {
            MessageAdapter adapter = connector.getMessageAdapter(result);
            return new DefaultMuleMessage(
                JmsMessageUtils.toObject(
                    result, connector.getSpecification(), endpoint.getEncoding()),
                adapter);
          }
        }
      }
      return null;
    } finally {
      connector.closeQuietly(producer);
      connector.closeQuietly(consumer);

      // TODO AP check if TopicResolver is to be utilized for temp destinations as well
      if (replyTo != null
          && (replyTo instanceof TemporaryQueue || replyTo instanceof TemporaryTopic)) {
        if (replyTo instanceof TemporaryQueue) {
          connector.closeQuietly((TemporaryQueue) replyTo);
        } else {
          // hope there are no more non-standard tricks from JMS vendors
          // here ;)
          connector.closeQuietly((TemporaryTopic) replyTo);
        }
      }

      // If the session is from the current transaction, it is up to the
      // transaction to close it.
      if (session != null && !cached && !transacted) {
        connector.closeQuietly(session);
      }
    }
  }
示例#13
0
  @Test
  public void sendMessage() throws Exception {
    // WFLY-7346 - Ignore the test if the security manager is installed
    Assume.assumeTrue(System.getSecurityManager() == null);

    Connection senderConnection = null;
    Connection consumerConnection = null;
    Session senderSession = null;
    Session consumerSession = null;
    MessageConsumer consumer = null;
    try {
      // CREATE SUBSCRIBER
      logger.trace("******* Creating connection for consumer");
      consumerConnection = factory.createConnection();
      logger.trace("Creating session for consumer");
      consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      logger.trace("Creating consumer");
      consumer = consumerSession.createConsumer(topic);
      logger.trace("Start session");
      consumerConnection.start();

      // SEND A MESSAGE
      logger.trace("***** Start - sending message to topic");
      senderConnection = factory.createConnection();
      logger.trace("Creating session..");
      senderSession = senderConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = senderSession.createProducer(topic);
      TextMessage message = senderSession.createTextMessage("Hello world!");
      logger.trace("Sending..");
      producer.send(message);
      logger.trace("Message sent");
      senderConnection.start();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      logger.trace("Closing connections and sessions");
      if (senderSession != null) {
        senderSession.close();
      }
      if (senderConnection != null) {
        senderConnection.close();
      }
    }

    Message receivedMessage = null;
    try {
      logger.trace("Receiving");
      receivedMessage = consumer.receive(5000);
      logger.trace("Received: " + ((TextMessage) receivedMessage).getText());
    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail(e.getMessage());
    } finally {
      if (receivedMessage == null) {
        Assert.fail("received null instead of a TextMessage");
      }
      if (consumerSession != null) {
        consumerSession.close();
      }
      if (consumerConnection != null) {
        consumerConnection.close();
      }
    }

    Assert.assertTrue(
        "received a " + receivedMessage.getClass().getName() + " instead of a TextMessage",
        receivedMessage instanceof TextMessage);
    Assert.assertEquals(((TextMessage) receivedMessage).getText(), "Hello world!");
  }
示例#14
0
  private UMOMessage dispatchMessage(UMOEvent event) throws Exception {
    Session session = null;
    MessageProducer producer = null;
    MessageConsumer consumer = null;
    Destination replyTo = null;
    boolean transacted = false;
    boolean cached = false;
    boolean remoteSync = useRemoteSync(event);

    if (logger.isDebugEnabled()) {
      logger.debug(
          "dispatching on endpoint: "
              + event.getEndpoint().getEndpointURI()
              + ". Event id is: "
              + event.getId());
    }

    try {
      // Retrieve the session from the current transaction.
      session = connector.getSessionFromTransaction();
      if (session != null) {
        transacted = true;

        // If a transaction is running, we can not receive any messages
        // in the same transaction.
        if (remoteSync) {
          throw new IllegalTransactionStateException(new org.mule.config.i18n.Message("jms", 2));
        }
      }
      // Should we be caching sessions?  Note this is not part of the JMS spec.
      // and is turned off by default.
      else if (event
          .getMessage()
          .getBooleanProperty(
              JmsConstants.CACHE_JMS_SESSIONS_PROPERTY, connector.isCacheJmsSessions())) {
        cached = true;
        if (cachedSession != null) {
          session = cachedSession;
        } else {
          // Retrieve a session from the connector
          session = connector.getSession(event.getEndpoint());
          cachedSession = session;
        }
      } else {
        // Retrieve a session from the connector
        session = connector.getSession(event.getEndpoint());
        if (event.getEndpoint().getTransactionConfig().isTransacted()) {
          transacted = true;
        }
      }

      // Add a reference to the JMS session used so that an EventAwareTransformer
      // can later retrieve it.
      // TODO Figure out a better way to accomplish this: MULE-1079
      // event.getMessage().setProperty(MuleProperties.MULE_JMS_SESSION, session);

      UMOEndpointURI endpointUri = event.getEndpoint().getEndpointURI();

      // determine if endpointUri is a queue or topic
      // the format is topic:destination
      boolean topic = false;
      String resourceInfo = endpointUri.getResourceInfo();
      topic = (resourceInfo != null && JmsConstants.TOPIC_PROPERTY.equalsIgnoreCase(resourceInfo));
      // TODO MULE20 remove resource info support
      if (!topic) {
        topic =
            MapUtils.getBooleanValue(
                event.getEndpoint().getProperties(), JmsConstants.TOPIC_PROPERTY, false);
      }

      Destination dest =
          connector.getJmsSupport().createDestination(session, endpointUri.getAddress(), topic);
      producer = connector.getJmsSupport().createProducer(session, dest, topic);

      Object message = event.getTransformedMessage();
      if (!(message instanceof Message)) {
        throw new DispatchException(
            new org.mule.config.i18n.Message(
                Messages.MESSAGE_NOT_X_IT_IS_TYPE_X_CHECK_TRANSFORMER_ON_X,
                "JMS message",
                message.getClass().getName(),
                connector.getName()),
            event.getMessage(),
            event.getEndpoint());
      }

      Message msg = (Message) message;
      if (event.getMessage().getCorrelationId() != null) {
        msg.setJMSCorrelationID(event.getMessage().getCorrelationId());
      }

      UMOMessage eventMsg = event.getMessage();

      // Some JMS implementations might not support the ReplyTo property.
      if (connector.supportsProperty(JmsConstants.JMS_REPLY_TO)) {
        Object tempReplyTo = eventMsg.removeProperty(JmsConstants.JMS_REPLY_TO);
        if (tempReplyTo != null) {
          if (tempReplyTo instanceof Destination) {
            replyTo = (Destination) tempReplyTo;
          } else {
            boolean replyToTopic = false;
            String reply = tempReplyTo.toString();
            int i = reply.indexOf(":");
            if (i > -1) {
              String qtype = reply.substring(0, i);
              replyToTopic = "topic".equalsIgnoreCase(qtype);
              reply = reply.substring(i + 1);
            }
            replyTo = connector.getJmsSupport().createDestination(session, reply, replyToTopic);
          }
        }
        // Are we going to wait for a return event ?
        if (remoteSync && replyTo == null) {
          replyTo = connector.getJmsSupport().createTemporaryDestination(session, topic);
        }
        // Set the replyTo property
        if (replyTo != null) {
          msg.setJMSReplyTo(replyTo);
        }

        // Are we going to wait for a return event ?
        if (remoteSync) {
          consumer = connector.getJmsSupport().createConsumer(session, replyTo, topic);
        }
      }

      // QoS support
      String ttlString = (String) eventMsg.removeProperty(JmsConstants.TIME_TO_LIVE_PROPERTY);
      String priorityString = (String) eventMsg.removeProperty(JmsConstants.PRIORITY_PROPERTY);
      String persistentDeliveryString =
          (String) eventMsg.removeProperty(JmsConstants.PERSISTENT_DELIVERY_PROPERTY);

      long ttl = Message.DEFAULT_TIME_TO_LIVE;
      int priority = Message.DEFAULT_PRIORITY;
      boolean persistent = Message.DEFAULT_DELIVERY_MODE == DeliveryMode.PERSISTENT;

      if (ttlString != null) {
        ttl = Long.parseLong(ttlString);
      }
      if (priorityString != null) {
        priority = Integer.parseInt(priorityString);
      }
      if (persistentDeliveryString != null) {
        persistent = Boolean.valueOf(persistentDeliveryString).booleanValue();
      }

      logger.debug("Sending message of type " + msg.getClass().getName());
      if (consumer != null && topic) {
        // need to register a listener for a topic
        Latch l = new Latch();
        ReplyToListener listener = new ReplyToListener(l);
        consumer.setMessageListener(listener);

        connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic);

        int timeout = event.getTimeout();
        logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo);
        l.await(timeout, TimeUnit.MILLISECONDS);
        consumer.setMessageListener(null);
        listener.release();
        Message result = listener.getMessage();
        if (result == null) {
          logger.debug("No message was returned via replyTo destination");
          return null;
        } else {
          UMOMessageAdapter adapter = connector.getMessageAdapter(result);
          return new MuleMessage(JmsMessageUtils.getObjectForMessage(result), adapter);
        }
      } else {
        connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic);
        if (consumer != null) {
          int timeout = event.getTimeout();
          logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo);
          Message result = consumer.receive(timeout);
          if (result == null) {
            logger.debug("No message was returned via replyTo destination");
            return null;
          } else {
            UMOMessageAdapter adapter = connector.getMessageAdapter(result);
            return new MuleMessage(JmsMessageUtils.getObjectForMessage(result), adapter);
          }
        }
      }
      return null;
    } finally {
      connector.closeQuietly(consumer);
      connector.closeQuietly(producer);

      // TODO I wonder if those temporary destinations also implement BOTH interfaces...
      // keep it 'simple' for now
      if (replyTo != null
          && (replyTo instanceof TemporaryQueue || replyTo instanceof TemporaryTopic)) {
        if (replyTo instanceof TemporaryQueue) {
          connector.closeQuietly((TemporaryQueue) replyTo);
        } else {
          // hope there are no more non-standard tricks from jms vendors here ;)
          connector.closeQuietly((TemporaryTopic) replyTo);
        }
      }

      // If the session is from the current transaction, it is up to the
      // transaction to close it.
      if (session != null && !cached && !transacted) {
        connector.closeQuietly(session);
      }
    }
  }
  public Runnable listener() throws JMSException {
    long isbn;
    String bookTitle;
    String bookCategory;
    String webURL;
    Book tempBook = new Book();
    ArrayList<String> arrivals = new ArrayList<String>();
    StompJmsConnectionFactory factory = new StompJmsConnectionFactory();
    factory.setBrokerURI("tcp://" + apolloHost + ":" + apolloPort);
    System.currentTimeMillis();
    // System.out.println("Waiting for messages...");
    while (true) {
      Connection connection = factory.createConnection(apolloUser, apolloPassword);
      connection.start();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination dest = new StompJmsDestination(stompTopic);
      MessageConsumer consumer = session.createConsumer(dest);
      while (true) {
        Message msg = consumer.receive(500);
        if (msg == null) break;
        if (msg instanceof TextMessage) {
          String body = ((TextMessage) msg).getText();
          arrivals.add(body);

        } else {
          System.out.println("Unexpected message type: " + msg.getClass());
        }
      }
      connection.close();
      if (!arrivals.isEmpty()) {
        for (String arrival : arrivals) {
          isbn = Long.parseLong(arrival.split(":")[0]);
          bookTitle = arrival.split(":")[1].replaceAll("^\"|\"$", "");
          bookCategory = arrival.split(":")[2].replaceAll("^\"|\"$", "");
          webURL = arrival.split(":\"")[3];
          webURL = webURL.substring(0, webURL.length() - 1);
          tempBook = bookRepository.getBookByISBN(isbn);
          // System.out.println("tempBook is "+tempBook);
          // System.out.println("dummyBook is "+dummyBook);

          if (tempBook.getIsbn() == 0) {
            // System.out.println("reachable");
            tempBook.setIsbn(isbn);
            tempBook.setCategory(bookCategory);
            tempBook.setTitle(bookTitle);
            try {
              tempBook.setCoverimage(new URL(webURL));
            } catch (MalformedURLException e) {
              e.printStackTrace();
            }
            bookRepository.addBook(tempBook);

          } else {
            // System.out.println("reachable, changing to available");
            tempBook.setStatus(Status.available);
          }
        }
        arrivals.clear();
      }
    }
  }