public void testBrokerStatsReset() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue replyTo = session.createTemporaryQueue();
    MessageConsumer consumer = session.createConsumer(replyTo);
    Queue testQueue = session.createQueue("Test.Queue");
    Queue query = session.createQueue(StatisticsBroker.STATS_BROKER_PREFIX);
    MessageProducer producer = session.createProducer(null);

    producer.send(testQueue, session.createMessage());

    Message msg = session.createMessage();
    msg.setJMSReplyTo(replyTo);
    producer.send(query, msg);
    MapMessage reply = (MapMessage) consumer.receive(10 * 1000);
    assertNotNull(reply);
    assertTrue(reply.getMapNames().hasMoreElements());
    assertTrue(reply.getLong("enqueueCount") >= 1);

    msg = session.createMessage();
    msg.setBooleanProperty(StatisticsBroker.STATS_BROKER_RESET_HEADER, true);
    msg.setJMSReplyTo(replyTo);
    producer.send(query, msg);
    reply = (MapMessage) consumer.receive(10 * 1000);
    assertNotNull(reply);
    assertTrue(reply.getMapNames().hasMoreElements());
    assertEquals(0, reply.getLong("enqueueCount"));
    assertTrue(reply.getJMSTimestamp() > 0);
    assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority());
  }
  public void testDestinationStats() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue replyTo = session.createTemporaryQueue();
    MessageConsumer consumer = session.createConsumer(replyTo);
    Queue testQueue = session.createQueue("Test.Queue");
    MessageProducer producer = session.createProducer(null);
    Queue query =
        session.createQueue(StatisticsBroker.STATS_DESTINATION_PREFIX + testQueue.getQueueName());
    Message msg = session.createMessage();

    producer.send(testQueue, msg);

    msg.setJMSReplyTo(replyTo);
    producer.send(query, msg);
    MapMessage reply = (MapMessage) consumer.receive(10 * 1000);
    assertNotNull(reply);
    assertTrue(reply.getMapNames().hasMoreElements());
    assertTrue(reply.getJMSTimestamp() > 0);
    assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority());
    /*
    for (Enumeration e = reply.getMapNames();e.hasMoreElements();) {
        String name = e.nextElement().toString();
        System.err.println(name+"="+reply.getObject(name));
    }
    */
  }
예제 #3
0
  @Override
  public JMSProducer send(Destination destination, Message message) {
    if (message == null) {
      throw new MessageFormatRuntimeException("null message");
    }

    try {
      if (jmsHeaderCorrelationID != null) {
        message.setJMSCorrelationID(jmsHeaderCorrelationID);
      }
      if (jmsHeaderCorrelationIDAsBytes != null && jmsHeaderCorrelationIDAsBytes.length > 0) {
        message.setJMSCorrelationIDAsBytes(jmsHeaderCorrelationIDAsBytes);
      }
      if (jmsHeaderReplyTo != null) {
        message.setJMSReplyTo(jmsHeaderReplyTo);
      }
      if (jmsHeaderType != null) {
        message.setJMSType(jmsHeaderType);
      }
      // XXX HORNETQ-1209 "JMS 2.0" can this be a foreign msg?
      // if so, then "SimpleString" properties will trigger an error.
      setProperties(message);
      if (completionListener != null) {
        CompletionListener wrapped = new CompletionListenerWrapper(completionListener);
        producer.send(destination, message, wrapped);
      } else {
        producer.send(destination, message);
      }
    } catch (JMSException e) {
      throw JmsExceptionUtils.convertToRuntimeException(e);
    }
    return this;
  }
  /**
   * Set reply to
   *
   * @param replyTo The value
   * @throws JMSException Thrown if an error occurs
   */
  @Override
  public void setJMSReplyTo(final Destination replyTo) throws JMSException {
    if (ActiveMQRAMessage.trace) {
      ActiveMQRALogger.LOGGER.trace("setJMSReplyTo(" + replyTo + ")");
    }

    message.setJMSReplyTo(replyTo);
  }
  @Test
  public void testJMSDestinationNull() throws Exception {
    Message m = queueProducerSession.createMessage();
    m.setJMSReplyTo(null);

    queueProducer.send(m);
    queueConsumer.receive();
    ProxyAssertSupport.assertNull(m.getJMSReplyTo());
  }
  @Test
  public void testJMSDestinationSimple() throws Exception {
    Message m = queueProducerSession.createMessage();
    TemporaryQueue tempQ = queueProducerSession.createTemporaryQueue();
    m.setJMSReplyTo(tempQ);

    queueProducer.send(m);
    queueConsumer.receive();
    ProxyAssertSupport.assertEquals(tempQ, m.getJMSReplyTo());
  }
예제 #7
0
  /** {@inheritDoc} */
  @Override
  public void mapTo(Context context, JMSBindingData target) throws Exception {
    super.mapTo(context, target);

    Message message = target.getMessage();
    for (Property property : context.getProperties()) {
      String name = property.getName();

      if (matches(name)) {
        Object value = property.getValue();
        if (value == null) {
          continue;
        }

        try {
          // process JMS headers
          if (name.equals(HEADER_JMS_DESTINATION)) {
            message.setJMSDestination(Destination.class.cast(value));
          } else if (name.equals(HEADER_JMS_DELIVERY_MODE)) {
            message.setJMSDeliveryMode(Integer.parseInt(value.toString()));
          } else if (name.equals(HEADER_JMS_EXPIRATION)) {
            message.setJMSExpiration(Long.parseLong(value.toString()));
          } else if (name.equals(HEADER_JMS_PRIORITY)) {
            message.setJMSPriority(Integer.parseInt(value.toString()));
          } else if (name.equals(HEADER_JMS_MESSAGE_ID)) {
            message.setJMSMessageID(value.toString());
          } else if (name.equals(HEADER_JMS_TIMESTAMP)) {
            message.setJMSTimestamp(Long.parseLong(value.toString()));
          } else if (name.equals(HEADER_JMS_CORRELATION_ID)) {
            message.setJMSCorrelationID(value.toString());
          } else if (name.equals(HEADER_JMS_REPLY_TO)) {
            message.setJMSReplyTo(Destination.class.cast(value));
          } else if (name.equals(HEADER_JMS_TYPE)) {
            message.setJMSType(value.toString());
          } else if (name.equals(HEADER_JMS_REDELIVERED)) {
            message.setJMSRedelivered(Boolean.parseBoolean(value.toString()));

            // process JMS properties
          } else {
            message.setObjectProperty(name, value);
          }
        } catch (Throwable t) {
          continue;
        }
      } else if (matches(name, getIncludeRegexes(), new ArrayList<Pattern>())) {
        Object value = property.getValue();
        if (value == null) {
          continue;
        }
        message.setObjectProperty(name, value);
      }
    }
  }
예제 #8
0
파일: JMSQueue.java 프로젝트: dlitz/resin
  public boolean send(@NotNull Value value, @Optional JMSQueue replyTo) throws JMSException {
    Message message = null;

    if (value.isArray()) {
      message = _session.createMapMessage();

      ArrayValue array = (ArrayValue) value;

      Set<Map.Entry<Value, Value>> entrySet = array.entrySet();

      for (Map.Entry<Value, Value> entry : entrySet) {
        if (entry.getValue() instanceof BinaryValue) {
          byte[] bytes = ((BinaryValue) entry.getValue()).toBytes();

          ((MapMessage) message).setBytes(entry.getKey().toString(), bytes);
        } else {
          // every primitive except for bytes can be translated from a string
          ((MapMessage) message).setString(entry.getKey().toString(), entry.getValue().toString());
        }
      }
    } else if (value instanceof BinaryValue) {
      message = _session.createBytesMessage();

      byte[] bytes = ((BinaryValue) value).toBytes();

      ((BytesMessage) message).writeBytes(bytes);
    } else if (value.isLongConvertible()) {
      message = _session.createStreamMessage();

      ((StreamMessage) message).writeLong(value.toLong());
    } else if (value.isDoubleConvertible()) {
      message = _session.createStreamMessage();

      ((StreamMessage) message).writeDouble(value.toDouble());
    } else if (value.toJavaObject() instanceof String) {
      message = _session.createTextMessage();

      ((TextMessage) message).setText(value.toString());
    } else if (value.toJavaObject() instanceof Serializable) {
      message = _session.createObjectMessage();

      ((ObjectMessage) message).setObject((Serializable) value.toJavaObject());
    } else {
      return false;
    }

    if (replyTo != null) message.setJMSReplyTo(replyTo._destination);

    _producer.send(message);

    return true;
  }
예제 #9
0
파일: JMSUtil.java 프로젝트: krakhee20/jbit
 public static void constructMessageHeaders(
     Message jmsMsg, MessageHeaders msgHeaders, Destination destination) throws JMSException {
   jmsMsg.setJMSCorrelationID(msgHeaders.getJMSCorrelationID());
   jmsMsg.setJMSDeliveryMode(msgHeaders.getJMSDeliveryMode());
   jmsMsg.setJMSExpiration(msgHeaders.getJMSExpiration());
   jmsMsg.setJMSMessageID(msgHeaders.getJMSMessageID());
   jmsMsg.setJMSPriority(msgHeaders.getJMSPriority());
   jmsMsg.setJMSRedelivered(msgHeaders.isJMSRedelivered());
   // currently we are setting the replyTo destination as null
   jmsMsg.setJMSReplyTo(null);
   jmsMsg.setJMSTimestamp(msgHeaders.getJMSTimestamp());
   jmsMsg.setJMSType(msgHeaders.getJMSType());
   jmsMsg.setJMSDestination(destination);
 }
  /*
   * http://blog.itpub.net/10742815/viewspace-580334/
   */
  public static void main(String[] args) throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");

    Connection connection = factory.createConnection();
    connection.start();

    // 消息发送到这个Queue
    Queue queue = new ActiveMQQueue("testQueue");

    // 消息回复到这个Queue
    Queue replyQueue = new ActiveMQQueue("replyQueue");

    final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    // 创建一个消息,并设置它的JMSReplyTo为replyQueue。
    Message message = session.createTextMessage("Andy");
    message.setJMSReplyTo(replyQueue);

    MessageProducer producer = session.createProducer(queue);
    producer.send(message);

    // 消息的接收者
    MessageConsumer comsumer = session.createConsumer(queue);
    comsumer.setMessageListener(
        new MessageListener() {
          public void onMessage(Message m) {
            try {
              // 创建一个新的MessageProducer来发送一个回复消息。
              MessageProducer producer = session.createProducer(m.getJMSReplyTo());
              producer.send(session.createTextMessage("Hello " + ((TextMessage) m).getText()));
            } catch (JMSException e1) {
              e1.printStackTrace();
            }
          }
        });

    // 这个接收者用来接收回复的消息
    MessageConsumer comsumer2 = session.createConsumer(replyQueue);
    comsumer2.setMessageListener(
        new MessageListener() {
          public void onMessage(Message m) {
            try {
              System.out.println(((TextMessage) m).getText());
            } catch (JMSException e) {
              e.printStackTrace();
            }
          }
        });
  }
예제 #11
0
  protected void processMessage(Message replyToMessage, MuleEvent event) throws JMSException {
    replyToMessage.setJMSReplyTo(null);

    // If JMS correlation ID exists in the incoming message - use it for the outbound message;
    // otherwise use JMS Message ID
    MuleMessage eventMsg = event.getMessage();
    Object jmsCorrelationId = eventMsg.getProperty("JMSCorrelationID");
    if (jmsCorrelationId == null) {
      jmsCorrelationId = eventMsg.getProperty("JMSMessageID");
    }
    if (jmsCorrelationId != null) {
      replyToMessage.setJMSCorrelationID(jmsCorrelationId.toString());
    }
    if (logger.isDebugEnabled()) {
      logger.debug("replyTomessage is " + replyToMessage);
    }
  }
  public static void copyJMSHeaders(Message inputMessage, Message outputMessage)
      throws JMSException {
    Object propValue;

    if (inputMessage == null || outputMessage == null) {
      return;
    }

    propValue = inputMessage.getJMSMessageID();
    if (propValue != null) {
      outputMessage.setJMSMessageID((String) propValue);
    }

    propValue = inputMessage.getJMSDestination();
    if (propValue != null) {
      outputMessage.setJMSDestination((Destination) propValue);
    }

    propValue = inputMessage.getJMSReplyTo();
    if (propValue != null) {
      outputMessage.setJMSReplyTo((Destination) propValue);
    }

    outputMessage.setJMSTimestamp(inputMessage.getJMSTimestamp());

    propValue = inputMessage.getJMSCorrelationID();
    if (!StringUtil.isEmpty((String) propValue)) {
      outputMessage.setJMSCorrelationID((String) propValue);
    }

    outputMessage.setJMSPriority(inputMessage.getJMSPriority());

    outputMessage.setJMSExpiration(inputMessage.getJMSExpiration());

    return;
  }
예제 #13
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);
      }
    }
  }
예제 #14
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);
      }
    }
  }
예제 #15
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);
      }
    }
  }
예제 #16
0
  /**
   * Try to use ActiveMQ StatisticsPlugin to get size and if that fails fallback to {@link
   * JMSMailQueue#getSize()}
   */
  @Override
  public long getSize() throws MailQueueException {

    Connection connection = null;
    Session session = null;
    MessageConsumer consumer = null;
    MessageProducer producer = null;
    TemporaryQueue replyTo = null;
    long size;

    try {
      connection = connectionFactory.createConnection();
      connection.start();

      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      replyTo = session.createTemporaryQueue();
      consumer = session.createConsumer(replyTo);

      Queue myQueue = session.createQueue(queueName);
      producer = session.createProducer(null);

      String queueName = "ActiveMQ.Statistics.Destination." + myQueue.getQueueName();
      Queue query = session.createQueue(queueName);

      Message msg = session.createMessage();
      msg.setJMSReplyTo(replyTo);
      producer.send(query, msg);
      MapMessage reply = (MapMessage) consumer.receive(2000);
      if (reply != null && reply.itemExists("size")) {
        try {
          size = reply.getLong("size");
          return size;
        } catch (NumberFormatException e) {
          // if we hit this we can't calculate the size so just catch
          // it
        }
      }

    } catch (Exception e) {
      throw new MailQueueException("Unable to remove mails", e);

    } finally {

      if (consumer != null) {

        try {
          consumer.close();
        } catch (JMSException e1) {
          e1.printStackTrace();
          // ignore on rollback
        }
      }

      if (producer != null) {

        try {
          producer.close();
        } catch (JMSException e1) {
          // ignore on rollback
        }
      }

      if (replyTo != null) {
        try {

          // we need to delete the temporary queue to be sure we will
          // free up memory if thats not done and a pool is used
          // its possible that we will register a new mbean in jmx for
          // every TemporaryQueue which will never get unregistered
          replyTo.delete();
        } catch (JMSException e) {
        }
      }
      try {
        if (session != null) session.close();
      } catch (JMSException e1) {
        // ignore here
      }

      try {
        if (connection != null) connection.close();
      } catch (JMSException e1) {
        // ignore here
      }
    }

    // if we came to this point we should just fallback to super method
    return super.getSize();
  }