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:hermes.impl.DefaultXMLHelper.java

public XMLMessage createXMLMessage(ObjectFactory factory, Message message)
        throws JMSException, IOException, EncoderException {
    try {//from   www  .  j a  v  a2 s  .c o m
        XMLMessage rval = factory.createXMLMessage();

        if (message instanceof TextMessage) {
            rval = factory.createXMLTextMessage();

            XMLTextMessage textRval = (XMLTextMessage) rval;
            TextMessage textMessage = (TextMessage) message;

            if (isBase64EncodeTextMessages()) {
                byte[] bytes = base64EncoderTL.get().encode(textMessage.getText().getBytes());
                textRval.setText(new String(bytes, "ASCII"));
                textRval.setCodec(BASE64_CODEC);
            } else {
                textRval.setText(textMessage.getText());
            }
        } else if (message instanceof MapMessage) {
            rval = factory.createXMLMapMessage();

            XMLMapMessage mapRval = (XMLMapMessage) rval;
            MapMessage mapMessage = (MapMessage) message;

            for (Enumeration iter = mapMessage.getMapNames(); iter.hasMoreElements();) {
                String propertyName = (String) iter.nextElement();
                Object propertyValue = mapMessage.getObject(propertyName);
                Property xmlProperty = factory.createProperty();

                if (propertyValue != null) {
                    xmlProperty.setValue(propertyValue.toString());
                    xmlProperty.setType(propertyValue.getClass().getName());
                }
                xmlProperty.setName(propertyName);

                mapRval.getBodyProperty().add(xmlProperty);
            }
        } else if (message instanceof BytesMessage) {
            rval = factory.createXMLBytesMessage();

            XMLBytesMessage bytesRval = (XMLBytesMessage) rval;
            BytesMessage bytesMessage = (BytesMessage) message;
            ByteArrayOutputStream bosream = new ByteArrayOutputStream();

            bytesMessage.reset();

            try {
                for (;;) {
                    bosream.write(bytesMessage.readByte());
                }
            } catch (MessageEOFException ex) {
                // NOP
            }

            bytesRval.setBytes(new String(base64EncoderTL.get().encode(bosream.toByteArray())));
        } else if (message instanceof ObjectMessage) {
            rval = factory.createXMLObjectMessage();

            XMLObjectMessage objectRval = (XMLObjectMessage) rval;
            ObjectMessage objectMessage = (ObjectMessage) message;

            ByteArrayOutputStream bostream = new ByteArrayOutputStream();
            ObjectOutputStream oostream = new ObjectOutputStream(bostream);

            oostream.writeObject(objectMessage.getObject());
            oostream.flush();
            byte b[] = base64EncoderTL.get().encode(bostream.toByteArray());
            String s = new String(b, "ASCII");
            objectRval.setObject(s);
        }

        if (message.getJMSReplyTo() != null) {
            rval.setJMSReplyTo(JMSUtils.getDestinationName(message.getJMSReplyTo()));
            rval.setJMSReplyToDomain(Domain.getDomain(message.getJMSReplyTo()).getId());
        }

        // try/catch each individually as we sometime find some JMS
        // providers
        // can barf
        try {
            rval.setJMSDeliveryMode(message.getJMSDeliveryMode());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSExpiration(message.getJMSExpiration());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSMessageID(message.getJMSMessageID());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSPriority(message.getJMSPriority());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSRedelivered(message.getJMSRedelivered());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        } catch (IllegalStateException ex) {
            // http://hermesjms.com/forum/viewtopic.php?f=4&t=346

            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSTimestamp(message.getJMSTimestamp());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSType(message.getJMSType());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSCorrelationID(message.getJMSCorrelationID());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            if (message.getJMSDestination() != null) {
                rval.setJMSDestination(JMSUtils.getDestinationName(message.getJMSDestination()));
                rval.setFromQueue(JMSUtils.isQueue(message.getJMSDestination()));
            }
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        for (final Enumeration iter = message.getPropertyNames(); iter.hasMoreElements();) {
            String propertyName = (String) iter.nextElement();

            if (!propertyName.startsWith("JMS")) {
                Object propertyValue = message.getObjectProperty(propertyName);
                Property property = factory.createProperty();

                property.setName(propertyName);

                if (propertyValue != null) {
                    property.setValue(StringEscapeUtils.escapeXml(propertyValue.toString()));
                    property.setType(propertyValue.getClass().getName());
                }

                rval.getHeaderProperty().add(property);
            }
        }

        return rval;
    } catch (Exception ex) {
        throw new HermesException(ex);
    }
}

From source file:nl.nn.adapterframework.extensions.ifsa.jms.PullingIfsaProviderListener.java

/**
 * Extracts string from message obtained from {@link #getRawMessage(Map)}. May also extract
 * other parameters from the message and put those in the threadContext.
 * @return input message for adapter./* w w w. j ava 2  s .c  o m*/
 */
public String getStringFromRawMessage(Object rawMessage, Map threadContext) throws ListenerException {
    if (rawMessage instanceof IMessageWrapper) {
        return getStringFromWrapper((IMessageWrapper) rawMessage, threadContext);
    }
    if (rawMessage instanceof IFSAPoisonMessage) {
        IFSAPoisonMessage pm = (IFSAPoisonMessage) rawMessage;
        IFSAHeader header = pm.getIFSAHeader();
        String source;
        try {
            source = header.getIFSA_Source();
        } catch (Exception e) {
            source = "unknown due to exeption:" + e.getMessage();
        }
        return "<poisonmessage>" + "  <source>" + source + "</source>" + "  <contents>"
                + XmlUtils.encodeChars(ToStringBuilder.reflectionToString(pm)) + "</contents>"
                + "</poisonmessage>";
    }

    TextMessage message = null;
    try {
        message = (TextMessage) rawMessage;
    } catch (ClassCastException e) {
        log.warn(getLogPrefix() + "message received was not of type TextMessage, but ["
                + rawMessage.getClass().getName() + "]", e);
        return null;
    }
    try {
        return message.getText();
    } catch (JMSException e) {
        throw new ListenerException(getLogPrefix(), e);
    }
}

From source file:org.codehaus.stomp.StompTest.java

public void testSendMessageWithCustomHeadersAndSelector() throws Exception {

    MessageConsumer consumer = session.createConsumer(queue, "foo = 'abc'");

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);/* ww w  . j ava 2 s . c o m*/

    frame = receiveFrame(10000);
    Assert.assertTrue(frame.startsWith("CONNECTED"));

    frame = "SEND\n" + "foo:abc\n" + "bar:123\n" + "destination:/queue/" + getQueueName() + "\n\n"
            + "Hello World" + Stomp.NULL;

    sendFrame(frame);

    TextMessage message = (TextMessage) consumer.receive(1000);
    Assert.assertNotNull(message);
    Assert.assertEquals("Hello World", message.getText());
    Assert.assertEquals("foo", "abc", message.getStringProperty("foo"));
    Assert.assertEquals("bar", "123", message.getStringProperty("bar"));
}

From source file:org.codehaus.stomp.StompTest.java

public void testSendMessage() throws Exception {

    MessageConsumer consumer = session.createConsumer(queue);

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);/*from   w w w  .  j  a v  a2 s .  c o  m*/

    frame = receiveFrame(10000);
    Assert.assertTrue(frame.startsWith("CONNECTED"));

    frame = "SEND\n" + "destination:/queue/" + getQueueName() + "\n\n" + "Hello World" + Stomp.NULL;

    sendFrame(frame);

    TextMessage message = (TextMessage) consumer.receive(1000);
    Assert.assertNotNull(message);
    Assert.assertEquals("Hello World", message.getText());

    // Make sure that the timestamp is valid - should
    // be very close to the current time.
    long tnow = System.currentTimeMillis();
    long tmsg = message.getJMSTimestamp();
    Assert.assertTrue(Math.abs(tnow - tmsg) < 1000);
}

From source file:org.codehaus.stomp.StompTest.java

public void testSendMessageWithReceipt() throws Exception {

    MessageConsumer consumer = session.createConsumer(queue);

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);/*from w  w w  .  ja  v a  2 s  .  c om*/

    frame = receiveFrame(10000);
    Assert.assertTrue(frame.startsWith("CONNECTED"));

    frame = "SEND\n" + "destination:/queue/" + getQueueName() + "\n" + "receipt: 1234\n\n" + "Hello World"
            + Stomp.NULL;

    sendFrame(frame);

    String f = receiveFrame(10000);
    System.out.println(f);
    Assert.assertTrue(f.startsWith("RECEIPT"));
    Assert.assertTrue(f.indexOf("receipt-id:1234") >= 0);

    TextMessage message = (TextMessage) consumer.receive(1000);
    Assert.assertNotNull(message);
    Assert.assertEquals("Hello World", message.getText());

    // Make sure that the timestamp is valid - should
    // be very close to the current time.
    long tnow = System.currentTimeMillis();
    long tmsg = message.getJMSTimestamp();
    Assert.assertTrue(Math.abs(tnow - tmsg) < 1000);
}

From source file:org.codehaus.stomp.StompTest.java

public void testSendMessageWithStandardHeaders() throws Exception {

    MessageConsumer consumer = session.createConsumer(queue);

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);/*  w w w  .  j a va 2  s . co  m*/

    frame = receiveFrame(10000);
    Assert.assertTrue(frame.startsWith("CONNECTED"));

    frame = "SEND\n" + "correlation-id:c123\n" + "priority:3\n" + "type:t345\n" + "JMSXGroupID:abc\n"
            + "foo:abc\n" + "bar:123\n" + "destination:/queue/" + getQueueName() + "\n\n" + "Hello World"
            + Stomp.NULL;

    sendFrame(frame);

    TextMessage message = (TextMessage) consumer.receive(1000);
    Assert.assertNotNull(message);
    Assert.assertEquals("Hello World", message.getText());
    Assert.assertEquals("JMSCorrelationID", "c123", message.getJMSCorrelationID());
    Assert.assertEquals("getJMSType", "t345", message.getJMSType());
    Assert.assertEquals("getJMSPriority", 3, message.getJMSPriority());
    Assert.assertEquals(DeliveryMode.PERSISTENT, message.getJMSDeliveryMode());
    Assert.assertEquals("foo", "abc", message.getStringProperty("foo"));
    Assert.assertEquals("bar", "123", message.getStringProperty("bar"));

    Assert.assertEquals("JMSXGroupID", "abc", message.getStringProperty("JMSXGroupID"));
    ActiveMQTextMessage amqMessage = (ActiveMQTextMessage) message;
    Assert.assertEquals("GroupID", "abc", amqMessage.getGroupID());
}

From source file:nl.nn.adapterframework.extensions.ifsa.jms.PushingIfsaProviderListener.java

/**
 * Extracts string from message obtained from {@link #getRawMessage(Map)}. May also extract
 * other parameters from the message and put those in the threadContext.
 * @return input message for adapter.//from  ww w.ja v  a  2s  .co  m
 */
public String getStringFromRawMessage(Object rawMessage, Map threadContext) throws ListenerException {
    if (rawMessage instanceof IMessageWrapper) {
        return getStringFromWrapper((IMessageWrapper) rawMessage, threadContext);
    }
    if (rawMessage instanceof IFSAPoisonMessage) {
        IFSAPoisonMessage pm = (IFSAPoisonMessage) rawMessage;
        IFSAHeader header = pm.getIFSAHeader();
        String source;
        try {
            source = header.getIFSA_Source();
        } catch (Exception e) {
            source = "unknown due to exeption:" + e.getMessage();
        }
        return "<poisonmessage>" + "  <source>" + source + "</source>" + "  <contents>"
                + XmlUtils.encodeChars(ToStringBuilder.reflectionToString(pm)) + "</contents>"
                + "</poisonmessage>";
    }

    TextMessage message = null;
    try {
        message = (TextMessage) rawMessage;
    } catch (ClassCastException e) {
        log.warn(getLogPrefix() + "message received was not of type TextMessage, but ["
                + rawMessage.getClass().getName() + "]", e);
        return null;
    }
    try {
        String result = message.getText();
        threadContext.put(THREAD_CONTEXT_ORIGINAL_RAW_MESSAGE_KEY, message);
        return result;
    } catch (JMSException e) {
        throw new ListenerException(getLogPrefix(), e);
    }
}

From source file:org.codehaus.stomp.StompTest.java

public void testTransactionRollback() throws Exception {
    MessageConsumer consumer = session.createConsumer(queue);

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);/*from  w  ww  . j a  v  a  2 s.c  om*/

    String f = receiveFrame(1000);
    Assert.assertTrue(f.startsWith("CONNECTED"));

    frame = "BEGIN\n" + "transaction: tx1\n" + "\n\n" + Stomp.NULL;
    sendFrame(frame);

    frame = "SEND\n" + "destination:/queue/" + getQueueName() + "\n" + "transaction: tx1\n" + "\n"
            + "first message" + Stomp.NULL;
    sendFrame(frame);

    //rollback first message
    frame = "ABORT\n" + "transaction: tx1\n" + "\n\n" + Stomp.NULL;
    sendFrame(frame);

    frame = "BEGIN\n" + "transaction: tx1\n" + "\n\n" + Stomp.NULL;
    sendFrame(frame);

    frame = "SEND\n" + "destination:/queue/" + getQueueName() + "\n" + "transaction: tx1\n" + "\n"
            + "second message" + Stomp.NULL;
    sendFrame(frame);

    frame = "COMMIT\n" + "transaction: tx1\n" + "\n\n" + Stomp.NULL;
    sendFrame(frame);

    // This test case is currently failing
    waitForFrameToTakeEffect();

    //only second msg should be received since first msg was rolled back
    TextMessage message = (TextMessage) consumer.receive(1000);
    Assert.assertNotNull(message);
    Assert.assertEquals("second message", message.getText().trim());
}

From source file:org.apache.synapse.transport.jms.JMSUtils.java

/**
 * Get an InputStream to the JMS message payload
 *
 * @param message the JMS message//from   w ww  .ja  va  2s .  c  om
 * @return an InputStream to the payload
 */
public InputStream getInputStream(Object message) {

    try {
        if (message instanceof BytesMessage) {
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            BytesMessage byteMsg = (BytesMessage) message;
            for (int bytesRead = byteMsg.readBytes(buffer); bytesRead != -1; bytesRead = byteMsg
                    .readBytes(buffer)) {
                out.write(buffer, 0, bytesRead);
            }
            return new ByteArrayInputStream(out.toByteArray());

        } else if (message instanceof TextMessage) {
            TextMessage txtMsg = (TextMessage) message;
            String contentType = getProperty(txtMsg, BaseConstants.CONTENT_TYPE);

            if (contentType != null) {
                return new ByteArrayInputStream(
                        txtMsg.getText().getBytes(BuilderUtil.getCharSetEncoding(contentType)));
            } else {
                return new ByteArrayInputStream(txtMsg.getText().getBytes());
            }

        } else {
            handleException("Unsupported JMS message type : " + message.getClass().getName());
        }

    } catch (JMSException e) {
        handleException("JMS Exception reading message payload", e);
    } catch (UnsupportedEncodingException e) {
        handleException("Encoding exception getting InputStream into message", e);
    }
    return null;
}

From source file:org.dawnsci.commandserver.ui.view.StatusQueueView.java

protected Collection<StatusBean> getStatusBeans(final URI uri, final String queueName,
        final IProgressMonitor monitor) throws Exception {

    QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    monitor.worked(1);//ww  w  . j a va  2  s .  co  m
    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);
    monitor.worked(1);

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

    Class clazz = getBeanClass();
    ObjectMapper mapper = new ObjectMapper();

    final Collection<StatusBean> list = new TreeSet<StatusBean>(new Comparator<StatusBean>() {
        @Override
        public int compare(StatusBean o1, StatusBean o2) {
            // Newest first!
            long t1 = o2.getSubmissionTime();
            long t2 = o1.getSubmissionTime();
            return (t1 < t2 ? -1 : (t1 == t2 ? 0 : 1));
        }
    });

    while (e.hasMoreElements()) {
        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);
            list.add(bean);
        }
    }
    return list;
}