示例#1
0
  protected void publish(String text, String subject) throws JMSException {
    Session session = createSession();

    Destination destination = createDestination(session, subject);

    MessageProducer publisher = session.createProducer(destination);
    if (isDurable()) {
      publisher.setDeliveryMode(DeliveryMode.PERSISTENT);
    } else {
      publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    }

    System.out.println(
        "Starting publisher on : " + destination + " of type: " + destination.getClass().getName());
    System.out.println("Message length: " + text.length());

    if (loops <= 0) {
      while (true) {
        publishLoop(session, publisher, text);
      }
    } else {
      for (int i = 0; i < loops; i++) {
        publishLoop(session, publisher, text);
      }
    }
  }
  public static void main(String args[]) {
    Connection connection = null;

    try {
      // JNDI lookup of JMS Connection Factory and JMS Destination
      Context context = new InitialContext();
      ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME);
      Destination destination = (Destination) context.lookup(DESTINATION_NAME);

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

      Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer consumer = session.createConsumer(destination);

      LOG.info(
          "Start consuming messages from "
              + destination.toString()
              + " with "
              + MESSAGE_TIMEOUT_MILLISECONDS
              + "ms timeout");

      // Synchronous message consumer
      int i = 1;
      while (true) {
        Message message = consumer.receive(MESSAGE_TIMEOUT_MILLISECONDS);
        if (message != null) {
          if (message instanceof TextMessage) {
            String text = ((TextMessage) message).getText();
            LOG.info("Got " + (i++) + ". message: " + text);
          }
        } else {
          break;
        }
      }

      consumer.close();
      session.close();
    } catch (Throwable t) {
      LOG.error("Error receiving message", t);
    } finally {
      // Cleanup code
      // In general, you should always close producers, consumers,
      // sessions, and connections in reverse order of creation.
      // For this simple example, a JMS connection.close will
      // clean up all other resources.
      if (connection != null) {
        try {
          connection.close();
        } catch (JMSException e) {
          LOG.error("Error closing connection", e);
        }
      }
    }
  }
  public void removeMessageConsumer(ProxyMessageConsumer messageConsumer) {
    Destination destination = messageConsumer.getDestination();
    String destinationName = destination.toString();
    List<ProxyMessageConsumer> messageConsumers = messageConsumerMap.get(destinationName);

    if (messageConsumers == null) {
      return;
    }

    messageConsumers.remove(messageConsumer);
  }
示例#4
0
 /**
  * Returns a new JMS Message Consumer.
  *
  * @param session A JMS Session
  * @return A JMS Message Consumer
  * @throws JMSException
  */
 public javax.jms.MessageConsumer newConsumer(Session session) throws JMSException {
   if (session == null) {
     logger.error(nameString() + " cannot create JMS Consumer. Invalid session.");
     return null;
   }
   if (!createDestIfAbsent(session)) {
     logger.error(
         nameString() + " cannot create JMS Consumer. " + "Destination queue is invalid.");
     return null;
   }
   javax.jms.MessageConsumer consumer;
   if (isVersion11) {
     consumer = session.createConsumer(queue);
   } else {
     consumer = ((QueueSession) session).createReceiver((Queue) queue);
   }
   if (logger.isDebugEnabled()) {
     logger.debug(
         nameString()
             + " created JMS Message Consumer to destination ["
             + queue.toString()
             + "].");
   }
   return consumer;
 }
示例#5
0
  public void sendObject(
      Destination destination, final Serializable object, final String type, final String value) {
    try {
      jmsTemplate.send(
          destination,
          new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
              ObjectMessage objectMessage = session.createObjectMessage(object);
              objectMessage.setStringProperty(type, value);
              return objectMessage;
            }
          });

    } catch (Exception e) {
      logger.debug("消息发送失败" + destination.toString() + ":" + object);
      e.printStackTrace();
      FailedJms failedJms = new FailedJms();
      failedJms.setId(ObjectId.get());
      failedJms.setDestination(destination);
      failedJms.setMessage(object);
      failedJms.setFailedTime(new Date());
      Map<String, String> properties = new HashMap<String, String>();
      properties.put(type, value);
      failedJms.setProperties(properties);
      saveFailedJms(failedJms);
    }
  }
  // ~ ==================================================
  public void sendMessage(Destination destination, String text) {
    String destinationName = destination.toString();

    if (destination instanceof Topic) {
      sendTopic(destinationName, text);
    } else {
      sendQueue(destinationName, text);
    }
  }
  /**
   * Test if all the messages sent are being received.
   *
   * @throws Exception
   */
  public void testSendReceive() throws Exception {
    super.testSendReceive();
    messages.clear();
    Destination consumerDestination = consumeSession.createQueue("FOO.BAR.HUMBUG2");
    LOG.info(
        "Created  consumer destination: "
            + consumerDestination
            + " of type: "
            + consumerDestination.getClass());
    MessageConsumer consumer = null;
    if (durable) {
      LOG.info("Creating durable consumer");
      consumer = consumeSession.createDurableSubscriber((Topic) consumerDestination, getName());
    } else {
      consumer = consumeSession.createConsumer(consumerDestination);
    }
    consumer.setMessageListener(this);

    assertMessagesAreReceived();
    LOG.info("" + data.length + " messages(s) received, closing down connections");
  }
  public MessageConsumer createConsumer(Destination destination, ProxySession session) {
    String destinationName = destination.toString();
    List<ProxyMessageConsumer> messageConsumers = messageConsumerMap.get(destinationName);

    if (messageConsumers == null) {
      messageConsumers = new ArrayList<ProxyMessageConsumer>();
      messageConsumerMap.put(destinationName, messageConsumers);
    }

    ProxyMessageConsumer messageConsumer = new ProxyMessageConsumer(session);
    messageConsumer.setDestination(destination);
    messageConsumers.add(messageConsumer);

    return messageConsumer;
  }
  /**
   * Sends a message to a destination or manage subscriptions. If the the content type of the POST
   * is <code>application/x-www-form-urlencoded</code>, then the form parameters "destination",
   * "message" and "type" are used to pass a message or a subscription. If multiple messages or
   * subscriptions are passed in a single post, then additional parameters are shortened to "dN",
   * "mN" and "tN" where N is an index starting from 1. The type is either "send", "listen" or
   * "unlisten". For send types, the message is the text of the TextMessage, otherwise it is the ID
   * to be used for the subscription. If the content type is not <code>
   * application/x-www-form-urlencoded</code>, then the body of the post is sent as the message to a
   * destination that is derived from a query parameter, the URL or the default destination.
   *
   * @param request
   * @param response
   * @throws ServletException
   * @throws IOException
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // lets turn the HTTP post into a JMS Message
    AjaxWebClient client = getAjaxWebClient(request);
    String messageIds = "";

    synchronized (client) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "POST client="
                + client
                + " session="
                + request.getSession().getId()
                + " clientId="
                + request.getParameter("clientId")
                + " info="
                + request.getPathInfo()
                + " contentType="
                + request.getContentType());
        // dump(request.getParameterMap());
      }

      int messages = 0;

      // loop until no more messages
      while (true) {
        // Get the message parameters. Multiple messages are encoded
        // with more compact parameter names.
        String destinationName =
            request.getParameter(messages == 0 ? "destination" : ("d" + messages));

        if (destinationName == null) {
          destinationName = request.getHeader("destination");
        }

        String message = request.getParameter(messages == 0 ? "message" : ("m" + messages));
        String type = request.getParameter(messages == 0 ? "type" : ("t" + messages));

        if (destinationName == null || message == null || type == null) {
          break;
        }

        try {
          Destination destination = getDestination(client, request, destinationName);

          if (LOG.isDebugEnabled()) {
            LOG.debug(
                messages
                    + " destination="
                    + destinationName
                    + " message="
                    + message
                    + " type="
                    + type);
            LOG.debug(destination + " is a " + destination.getClass().getName());
          }

          messages++;

          if ("listen".equals(type)) {
            AjaxListener listener = client.getListener();
            Map<MessageAvailableConsumer, String> consumerIdMap = client.getIdMap();
            Map<MessageAvailableConsumer, String> consumerDestinationNameMap =
                client.getDestinationNameMap();
            client.closeConsumer(destination); // drop any existing
            // consumer.
            MessageAvailableConsumer consumer =
                (MessageAvailableConsumer)
                    client.getConsumer(destination, request.getHeader(WebClient.selectorName));

            consumer.setAvailableListener(listener);
            consumerIdMap.put(consumer, message);
            consumerDestinationNameMap.put(consumer, destinationName);
            if (LOG.isDebugEnabled()) {
              LOG.debug("Subscribed: " + consumer + " to " + destination + " id=" + message);
            }
          } else if ("unlisten".equals(type)) {
            Map<MessageAvailableConsumer, String> consumerIdMap = client.getIdMap();
            Map<MessageAvailableConsumer, String> consumerDestinationNameMap =
                client.getDestinationNameMap();
            MessageAvailableConsumer consumer =
                (MessageAvailableConsumer)
                    client.getConsumer(destination, request.getHeader(WebClient.selectorName));

            consumer.setAvailableListener(null);
            consumerIdMap.remove(consumer);
            consumerDestinationNameMap.remove(consumer);
            client.closeConsumer(destination);
            if (LOG.isDebugEnabled()) {
              LOG.debug("Unsubscribed: " + consumer);
            }
          } else if ("send".equals(type)) {
            TextMessage text = client.getSession().createTextMessage(message);
            appendParametersToMessage(request, text);

            client.send(destination, text);
            messageIds += text.getJMSMessageID() + "\n";
            if (LOG.isDebugEnabled()) {
              LOG.debug("Sent " + message + " to " + destination);
            }
          } else {
            LOG.warn("unknown type " + type);
          }

        } catch (JMSException e) {
          LOG.warn("jms", e);
        }
      }
    }

    if ("true".equals(request.getParameter("poll"))) {
      try {
        // TODO return message IDs
        doMessages(client, request, response);
      } catch (JMSException e) {
        throw new ServletException("JMS problem: " + e, e);
      }
    } else {
      // handle simple POST of a message
      if (request.getContentLength() != 0
          && (request.getContentType() == null
              || !request
                  .getContentType()
                  .toLowerCase()
                  .startsWith("application/x-www-form-urlencoded"))) {
        try {
          Destination destination = getDestination(client, request);
          String body = getPostedMessageBody(request);
          TextMessage message = client.getSession().createTextMessage(body);
          appendParametersToMessage(request, message);

          client.send(destination, message);
          if (LOG.isDebugEnabled()) {
            LOG.debug("Sent to destination: " + destination + " body: " + body);
          }
          messageIds += message.getJMSMessageID() + "\n";
        } catch (JMSException e) {
          throw new ServletException(e);
        }
      }

      response.setContentType("text/plain");
      response.setHeader("Cache-Control", "no-cache");
      response.getWriter().print(messageIds);
    }
  }
示例#10
0
  @Override
  public void processReplyTo(MuleEvent event, MuleMessage returnMessage, Object replyTo)
      throws MuleException {
    Destination replyToDestination = null;
    MessageProducer replyToProducer = null;
    Session session = null;
    try {
      // now we need to send the response
      if (replyTo instanceof Destination) {
        replyToDestination = (Destination) replyTo;
      }
      if (replyToDestination == null) {
        super.processReplyTo(event, returnMessage, replyTo);
        return;
      }

      // This is a work around for JmsTransformers where the current endpoint needs
      // to be set on the transformer so that a JMSMessage can be created correctly (the transformer
      // needs a Session)
      Class srcType = returnMessage.getPayload().getClass();
      for (Iterator iterator = getTransformers().iterator(); iterator.hasNext(); ) {
        Transformer t = (Transformer) iterator.next();
        if (t.isSourceDataTypeSupported(DataTypeFactory.create(srcType))) {
          if (t.getEndpoint() == null) {
            t.setEndpoint(getEndpoint(event, "jms://temporary"));
            break;
          }
        }
      }
      returnMessage.applyTransformers(getTransformers());
      Object payload = returnMessage.getPayload();

      if (replyToDestination instanceof Topic
          && replyToDestination instanceof Queue
          && connector.getJmsSupport() instanceof Jms102bSupport) {
        logger.error(
            StringMessageUtils.getBoilerPlate(
                "ReplyTo destination implements both Queue and Topic "
                    + "while complying with JMS 1.0.2b specification. "
                    + "Please report your application server or JMS vendor name and version "
                    + "to dev<_at_>mule.codehaus.org or http://mule.mulesource.org/jira"));
      }

      final boolean topic = connector.getTopicResolver().isTopic(replyToDestination);
      session = connector.getSession(false, topic);
      Message replyToMessage = JmsMessageUtils.toMessage(payload, session);

      processMessage(replyToMessage, event);
      if (logger.isDebugEnabled()) {
        logger.debug(
            "Sending jms reply to: "
                + replyToDestination
                + "("
                + replyToDestination.getClass().getName()
                + ")");
      }
      replyToProducer =
          connector.getJmsSupport().createProducer(session, replyToDestination, topic);

      // QoS support
      MuleMessage eventMsg = event.getMessage();
      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);

      String correlationIDString = replyToMessage.getJMSCorrelationID();
      if (StringUtils.isBlank(correlationIDString)) {
        correlationIDString = (String) eventMsg.getProperty(JmsConstants.JMS_MESSAGE_ID);
        replyToMessage.setJMSCorrelationID(correlationIDString);
      }

      event.getService().getStatistics().incSentReplyToEvent();

      final ImmutableEndpoint endpoint = event.getEndpoint();
      if (ttlString == null && priorityString == null && persistentDeliveryString == null) {
        connector.getJmsSupport().send(replyToProducer, replyToMessage, topic, endpoint);
      } else {
        long ttl = Message.DEFAULT_TIME_TO_LIVE;
        int priority = Message.DEFAULT_PRIORITY;

        if (ttlString != null) {
          ttl = Long.parseLong(ttlString);
        }
        if (priorityString != null) {
          priority = Integer.parseInt(priorityString);
        }
        boolean persistent =
            StringUtils.isNotBlank(persistentDeliveryString)
                ? Boolean.valueOf(persistentDeliveryString)
                : connector.isPersistentDelivery();

        connector
            .getJmsSupport()
            .send(replyToProducer, replyToMessage, persistent, priority, ttl, topic, endpoint);
      }

      logger.info(
          "Reply Message sent to: "
              + replyToDestination
              + " with correlationID:"
              + correlationIDString);
    } catch (Exception e) {
      throw new DispatchException(
          JmsMessages.failedToCreateAndDispatchResponse(replyToDestination),
          returnMessage,
          null,
          e);
    } finally {
      connector.closeQuietly(replyToProducer);

      final Transaction transaction = TransactionCoordination.getInstance().getTransaction();
      if (transaction == null) {
        if (logger.isDebugEnabled()) {
          logger.debug("Closing non-TX replyTo session: " + session);
        }
        connector.closeQuietly(session);
      } else if (logger.isDebugEnabled()) {
        logger.debug("Not closing TX replyTo session: " + session);
      }
    }
  }
示例#11
0
 public JMSProducerStatsImpl(JMSSessionStatsImpl sessionStats, Destination destination) {
   super(sessionStats);
   if (destination != null) {
     this.destination = destination.toString();
   }
 }
示例#12
0
 public String toString() {
   return (dest_ != null) ? dest_.toString() : "null";
 }