Example usage for javax.jms TextMessage getText

List of usage examples for javax.jms TextMessage getText

Introduction

In this page you can find the example usage for javax.jms TextMessage getText.

Prototype


String getText() throws JMSException;

Source Link

Document

Gets the string containing this message's data.

Usage

From source file:org.mule.transport.jms.JmsMessageUtilsTestCase.java

@Test
public void testTextMessageNullContent() throws Exception {
    TextMessage mockMessage = mock(TextMessage.class);
    when(mockMessage.getText()).thenReturn(null);

    byte[] result = JmsMessageUtils.toByteArray(mockMessage, JmsConstants.JMS_SPECIFICATION_102B, ENCODING);
    assertNotNull(result);/*from w  w  w  .ja  va  2  s. c o m*/
    assertEquals("Should return an empty byte array.", 0, result.length);

    verify(mockMessage).getText();
}

From source file:fr.xebia.springframework.jms.support.converter.JaxbMessageConverter.java

/**
 * <p>/*from   w ww .j a  v  a  2  s  .  co m*/
 * Unmarshal given <code>message</code> into an <code>object</code>.
 * </p>
 * 
 * <p>
 * Should we raise an exception if the XML message encoding is not in sync with the underlying TextMessage encoding when the JMS
 * Provider supports MOM message's encoding ?
 * </p>
 * 
 * @param message
 *            message to unmarshal, MUST be an instance of {@link TextMessage} or of {@link BytesMessage}.
 * @see org.springframework.jms.support.converter.MessageConverter#fromMessage(javax.jms.Message)
 * @see org.springframework.oxm.Unmarshaller#unmarshal(Source)
 */
public Object fromMessage(Message message) throws JMSException, MessageConversionException {

    Source source;
    if (message instanceof TextMessage) {
        TextMessage textMessage = (TextMessage) message;
        source = new StringSource(textMessage.getText());

    } else if (message instanceof BytesMessage) {
        BytesMessage bytesMessage = (BytesMessage) message;
        byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
        bytesMessage.readBytes(bytes);
        source = new StreamSource(new ByteArrayInputStream(bytes));

    } else {
        throw new MessageConversionException("Unsupported JMS Message type " + message.getClass()
                + ", expected instance of TextMessage or BytesMessage for " + message);
    }
    Object result = jaxb2Marshaller.unmarshal(source);

    return result;
}

From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivityJMSMessageParser.java

/**
 * Parse JMS {@link TextMessage} activity info into activity data map.
 *
 * @param textMessage//w w  w .  j a va  2 s.  c om
 *            JMS text message
 * @param dataMap
 *            activity data map collected from JMS {@link TextMessage}
 * @throws JMSException
 *             if JMS exception occurs while getting text from message.
 */
protected void parseTextMessage(TextMessage textMessage, Map<String, Object> dataMap) throws JMSException {
    String text = textMessage.getText();
    if (StringUtils.isNotEmpty(text)) {
        dataMap.put(StreamsConstants.ACTIVITY_DATA_KEY, text);
    }
}

From source file:com.silverpeas.mailinglist.model.TestMailingListComponent.java

@Test
public void testOnMessageNotModeratedNotify() throws Exception {
    MailingListComponent componentNotModerated = new MailingListComponent("101");
    MailingList list = ServicesFactory.getFactory().getMailingListService().findMailingList("101");
    assertNotNull(list);//from w w w.j av a  2  s . c  o m
    assertNotNull(list.getModerators());
    assertEquals(3, list.getModerators().size());
    assertNotNull(list.getReaders());
    assertEquals(2, list.getReaders().size());
    assertFalse(list.isModerated());
    assertTrue(list.isNotify());
    Message message = ServicesFactory.getFactory().getMessageService().getMessage("701");
    assertEquals(textEmailContent, message.getBody());
    message.setContentType("text/plain; charset=\"UTF-8\"");
    MessageEvent event = new MessageEvent();
    event.addMessage(message);
    componentNotModerated.onMessage(event);
    List<TextMessage> jmsMessages = MockObjectFactory.getMessages(JNDINames.JMS_QUEUE);
    assertNotNull(jmsMessages);
    assertEquals(5, jmsMessages.size());
    for (TextMessage alert : jmsMessages) {
        assertNotNull(alert.getText());
        NotificationData data = NotificationServerUtil.convertXMLToNotificationData(alert.getText());
        assertNotNull(data);
        String channel = data.getTargetChannel();
        assertEquals("SMTP", channel);
        String recipient = data.getTargetReceipt();
        assertNotNull(recipient);
        assertTrue("Erreur destinataire " + recipient,
                "bart.simpson@silverpeas.com".equals(recipient)
                        || "marge.simpson@silverpeas.com".equals(recipient)
                        || "homer.simpson@silverpeas.com".equals(recipient)
                        || "lisa.simpson@silverpeas.com".equals(recipient)
                        || "maggie.simpson@silverpeas.com".equals(recipient));
        assertEquals(message.getSummary(), data.getMessage());
        String url = (String) data.getTargetParam().get("URL");
        assertNotNull(url);
        assertEquals("http://localhost:8000/silverpeas//autoRedirect.jsp?domainId=0&"
                + "goto=%2FRmailinglist%2F101%2Fmessage%2F701", url);
        String source = (String) data.getTargetParam().get("SOURCE");
        assertNotNull(source);
        assertEquals("thesimpsons@silverpeas.com", source);
    }
    checkSimpleEmail("barney.gumble@silverpeas.com",
            "[Liste de diffusion de test non modre] : Simple Message");
    checkSimpleEmail("julius.hibbert@silverpeas.com",
            "[Liste de diffusion de test non modre] : Simple Message");
    checkSimpleEmail("carl.carlson@silverpeas.com",
            "[Liste de diffusion de test non modre] : Simple Message");
    checkSimpleEmail("edna.krabappel@silverpeas.com",
            "[Liste de diffusion de test non modre] : Simple Message");
    checkSimpleEmail("nelson.muntz@silverpeas.com",
            "[Liste de diffusion de test non modre] : Simple Message");
    checkSimpleEmail("ned.flanders@silverpeas.com",
            "[Liste de diffusion de test non modre] : Simple Message");
    checkSimpleEmail("maude.flanders@silverpeas.com",
            "[Liste de diffusion de test non modre] : Simple Message");
    checkSimpleEmail("rod.flanders@silverpeas.com",
            "[Liste de diffusion de test non modre] : Simple Message");
    checkSimpleEmail("todd.flanders@silverpeas.com",
            "[Liste de diffusion de test non modre] : Simple Message");
    checkSimpleEmail("herschel.krustofski@silverpeas.com",
            "[Liste de diffusion de test non modre] : Simple Message");
    checkSimpleEmail("selma.bouvier@silverpeas.com",
            "[Liste de diffusion de test non modre] : Simple Message");
    checkSimpleEmail("patty.bouvier@silverpeas.com",
            "[Liste de diffusion de test non modre] : Simple Message");
}

From source file:org.dawnsci.commandserver.core.producer.Broadcaster.java

/**
 * //from w ww. j a v  a2s  .  co m
 * @param bean
 * @throws Exception 
 */
private void updateQueue(StatusBean bean) throws Exception {

    QueueConnection qCon = null;

    try {

        QueueBrowser qb = qSes.createBrowser(queue);

        @SuppressWarnings("rawtypes")
        Enumeration e = qb.getEnumeration();

        ObjectMapper mapper = new ObjectMapper();
        String jMSMessageID = null;
        while (e.hasMoreElements()) {
            Message m = (Message) e.nextElement();
            if (m == null)
                continue;
            if (m instanceof TextMessage) {
                TextMessage t = (TextMessage) m;

                @SuppressWarnings("unchecked")
                final StatusBean qbean = mapper.readValue(t.getText(), bean.getClass());
                if (qbean == null)
                    continue;
                if (qbean.getUniqueId() == null)
                    continue; // Definitely not our bean
                if (qbean.getUniqueId().equals(bean.getUniqueId())) {
                    jMSMessageID = t.getJMSMessageID();
                    break;
                }
            }
        }

        qb.close();

        if (jMSMessageID != null) {
            MessageConsumer consumer = qSes.createConsumer(queue, "JMSMessageID = '" + jMSMessageID + "'");
            Message m = consumer.receive(1000);
            if (m != null && m instanceof TextMessage) {
                MessageProducer producer = qSes.createProducer(queue);
                producer.send(qSes.createTextMessage(mapper.writeValueAsString(bean)));
            }
        }
    } finally {
        if (qCon != null)
            qCon.close();
    }

}

From source file:de.adorsys.jmspojo.JMSMessageListenerServiceAdapterTest.java

@Test
public void testCreateAdapterWithReply() throws JMSException {
    TextMessage textMessage = queueSession.createTextMessage(OBJECT_MAPPER.serialize(new PingMessage("ping")));
    textMessage.setJMSReplyTo(reqlayQ);//  w ww  . j  a v a 2 s .  com

    SampleMessageServiceWithReply service = new SampleMessageServiceWithReply();
    JMSMessageListenerServiceAdapter<SampleMessageServiceWithReply> adapter = JMSMessageListenerServiceAdapter
            .createAdapter(service, cf, OBJECT_MAPPER);
    adapter.onMessage(textMessage);

    TextMessage message = (TextMessage) queueSession.createReceiver(reqlayQ).receive(1000);
    assertNotNull(message);
    assertNull(message.getStringProperty("ERROR"));
    assertEquals("{\"ping\":\"ping\"}", message.getText());
}

From source file:RequesterTool.java

protected void requestLoop() throws Exception {

    for (int i = 0; i < messageCount || messageCount == 0; i++) {

        TextMessage message = session.createTextMessage(createMessageText(i));
        message.setJMSReplyTo(replyDest);

        if (verbose) {
            String msg = message.getText();
            if (msg.length() > 50) {
                msg = msg.substring(0, 50) + "...";
            }//from w w w  .  ja  v a 2  s . co m
            System.out.println("Sending message: " + msg);
        }

        producer.send(message);
        if (transacted) {
            session.commit();
        }

        System.out.println("Waiting for reponse message...");
        Message message2 = consumer.receive();
        if (message2 instanceof TextMessage) {
            System.out.println("Reponse message: " + ((TextMessage) message2).getText());
        } else {
            System.out.println("Reponse message: " + message2);
        }
        if (transacted) {
            session.commit();
        }

        Thread.sleep(sleepTime);

    }
}

From source file:com.provenance.cloudprovenance.connector.traceability.TraceabilityEventConsumer.java

public void onMessage(final Message newMessage) {

    logger.info("Received Traceability Statements Message = " + counter++);

    if (newMessage instanceof TextMessage) {
        TextMessage textMessage = (TextMessage) newMessage;

        String traceabilityRecord = null;
        try {/*from www .j  av a 2  s.  c  o m*/
            traceabilityRecord = textMessage.getText();

            logger.info(" Traceability content: \n" + traceabilityRecord);

            /**
             * Get the record Id, if it is just use POST request, otherwise
             * use PUT reequest
             */

            if (traceabilityRecordUri == null || traceabilityRecordUri.equals("")) {

                logger.info("Calling get Resource URI ...");
                String traceabilityRecordResponse = trConnection.getCurrentTraceabilityRecordId(serviceID);

                if (traceabilityRecordResponse != null || traceabilityRecordResponse == "") {

                    logger.info("Resource URI does not exist, creation a new resource with content");

                    traceabilityRecordUri = (resExtraction.getResponseURI(traceabilityRecordResponse));

                    logger.info("New resource created URI is: " + traceabilityRecordUri);

                    trConnection.updateTraceabilityRecord(serviceID, traceabilityRecordUri, traceabilityRecord);

                    logger.info("Sucessfully updated the traceability record: " + traceabilityRecordUri);

                } else {
                    // get a new record Id
                    String response = trConnection.createNewTraceabilityRecord(serviceID, traceabilityRecord);

                    traceabilityRecordUri = (resExtraction.getResponseURI(response));// .split(":")[1];
                    logger.info("Sucessfully created a new traceability record: " + response + "\n"
                            + traceabilityRecordUri);
                }
            } else {
                logger.info("Updating record :" + traceabilityRecordUri);
                trConnection.updateTraceabilityRecord(serviceID, traceabilityRecordUri, traceabilityRecord);

                logger.info("Sucessfully updated the traceability record: " + traceabilityRecordUri);

            }

            // If an ack is required, use the reponse queue
            if (traceabilityStoreStorageAck) {
                logger.info("Sending an ACK to response tranceability queue" + traceabilityRecordUri);

                jmsTemplate.send(responseTraceabilityQueueName, new MessageCreator() {

                    public Message createMessage(Session session) throws JMSException {
                        TextMessage message = session.createTextMessage("Sucessfully Stored, ID: " + counter);
                        // message.setIntProperty("messageCount",
                        // i);
                        return message;
                    }
                });
            }

        } catch (JMSException e) {
            logger.error(e.toString());
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        logger.warn("Unknown message type, cannot process");
    }
}

From source file:org.dawnsci.commandserver.core.consumer.RemoteSubmission.java

/**
 * Monitors a given bean in the status queue. 
 * If the bean is not there throws exception.
 * If the bean is in a final state, returns the bean straight away.
 * /*from   w  ww. j  av  a 2 s.  c o  m*/
 * Polls the queue for the unique id of the bean we want until it
 * encounters a final state of that bean.
 * 
 * Polling rate is less than 1s
 * 
 * NOTE this class can poll forever if the job it is looking at never finishes.
 * 
 * @param obean
 * @param string
 * @return the bean once it is in a final state.
 * @throws exception if broker or queue absent
 */
public StatusBean monitor(StatusBean obean) throws Exception {

    if (getQueueName() == null || "".equals(getQueueName()))
        throw new Exception("Please specify a queue name!");

    QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    QueueConnection qCon = connectionFactory.createQueueConnection(); // This times out when the server is not there.
    QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = qSes.createQueue(queueName);
    qCon.start();

    QueueBrowser qb = qSes.createBrowser(queue);

    Class clazz = obean.getClass();
    ObjectMapper mapper = new ObjectMapper();

    try {
        POLL: while (true) {

            Thread.sleep(500);

            @SuppressWarnings("rawtypes")
            Enumeration e = qb.getEnumeration();

            while (e.hasMoreElements()) { // We must final the bean somewhere.
                Message m = (Message) e.nextElement();
                if (m == null)
                    continue;
                if (m instanceof TextMessage) {
                    TextMessage t = (TextMessage) m;
                    final StatusBean bean = mapper.readValue(t.getText(), clazz);
                    if (bean.getUniqueId().equals(obean.getUniqueId())) {
                        if (bean.getStatus().isFinal())
                            return bean;
                        System.out.println(bean.getPercentComplete());
                        continue POLL;
                    }
                }
            }

            throw new Exception(
                    "The bean with id " + obean.getUniqueId() + " does not exist in " + getQueueName() + "!");

        }
    } finally {
        qCon.close();
    }
}

From source file:com.silverpeas.mailinglist.model.TestMailingListComponent.java

@Test
public void testOnMessage() throws Exception {
    Message message = ServicesFactory.getFactory().getMessageService().getMessage("700");
    message.setContentType("text/plain; charset=\"UTF-8\"");
    MessageEvent event = new MessageEvent();
    event.addMessage(message);//w  w  w .j  a  v a2s  . co  m
    component.onMessage(event);
    List<TextMessage> jmsMessages = MockObjectFactory.getMessages(JNDINames.JMS_QUEUE);
    assertNotNull(jmsMessages);
    assertEquals(3, jmsMessages.size());
    for (TextMessage alert : jmsMessages) {
        assertNotNull(alert.getText());
        NotificationData data = NotificationServerUtil.convertXMLToNotificationData(alert.getText());
        assertNotNull(data);
        String channel = data.getTargetChannel();
        assertEquals("SMTP", channel);
        String recipient = data.getTargetReceipt();
        assertNotNull(recipient);
        assertTrue("Erreur destinataire " + recipient,
                "homer.simpson@silverpeas.com".equals(recipient)
                        || "marge.simpson@silverpeas.com".equals(recipient)
                        || "bart.simpson@silverpeas.com".equals(recipient));
        assertEquals(message.getSummary(), data.getMessage());
        String url = (String) data.getTargetParam().get("URL");
        assertNotNull(url);
        assertEquals("http://localhost:8000/silverpeas//autoRedirect.jsp?domainId=0&"
                + "goto=%2FRmailinglist%2F100%2FmoderationList%2F100", url);
        String source = (String) data.getTargetParam().get("SOURCE");
        assertNotNull(source);
        assertEquals("thesimpsons@silverpeas.com", source);
    }
    checkNoMessage("barney.gumble@silverpeas.com");
    checkNoMessage("julius.hibbert@silverpeas.com");
    checkNoMessage("carl.carlson@silverpeas.com");
    checkNoMessage("edna.krabappel@silverpeas.com");
    checkNoMessage("nelson.muntz@silverpeas.com");
    checkNoMessage("ned.flanders@silverpeas.com");
    checkNoMessage("maude.flanders@silverpeas.com");
    checkNoMessage("rod.flanders@silverpeas.com");
    checkNoMessage("todd.flanders@silverpeas.com");
    checkNoMessage("herschel.krustofski@silverpeas.com");
    checkNoMessage("selma.bouvier@silverpeas.com");
    checkNoMessage("patty.bouvier@silverpeas.com");

    message = ServicesFactory.getFactory().getMessageService().getMessage(message.getId());
    message.setModerated(true);
    event = new MessageEvent();
    event.addMessage(message);
    component.onMessage(event);
    jmsMessages = MockObjectFactory.getMessages(JNDINames.JMS_QUEUE);
    assertNotNull(jmsMessages);
    assertEquals(6, jmsMessages.size());
    for (TextMessage alert : jmsMessages) {
        assertNotNull(alert.getText());
        NotificationData data = NotificationServerUtil.convertXMLToNotificationData(alert.getText());
        assertNotNull(data);
        String channel = data.getTargetChannel();
        assertEquals("SMTP", channel);
        String recipient = data.getTargetReceipt();
        assertNotNull(recipient);
        assertTrue("Erreur destinataire " + recipient,
                "bart.simpson@silverpeas.com".equals(recipient)
                        || "homer.simpson@silverpeas.com".equals(recipient)
                        || "marge.simpson@silverpeas.com".equals(recipient));
        assertEquals(message.getSummary(), data.getMessage());
        String url = (String) data.getTargetParam().get("URL");
        assertNotNull(url);
        assertEquals("http://localhost:8000/silverpeas//autoRedirect.jsp?domainId=0&"
                + "goto=%2FRmailinglist%2F100%2FmoderationList%2F100", url);
        String source = (String) data.getTargetParam().get("SOURCE");
        assertNotNull(source);
        assertEquals("thesimpsons@silverpeas.com", source);
    }
    checkNoMessage("barney.gumble@silverpeas.com");
    checkNoMessage("julius.hibbert@silverpeas.com");
    checkNoMessage("carl.carlson@silverpeas.com");
    checkNoMessage("edna.krabappel@silverpeas.com");
    checkNoMessage("nelson.muntz@silverpeas.com");
    checkNoMessage("ned.flanders@silverpeas.com");
    checkNoMessage("maude.flanders@silverpeas.com");
    checkNoMessage("rod.flanders@silverpeas.com");
    checkNoMessage("todd.flanders@silverpeas.com");
    checkNoMessage("herschel.krustofski@silverpeas.com");
    checkNoMessage("selma.bouvier@silverpeas.com");
    checkNoMessage("patty.bouvier@silverpeas.com");
}