Example usage for javax.jms TextMessage setText

List of usage examples for javax.jms TextMessage setText

Introduction

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

Prototype


void setText(String string) throws JMSException;

Source Link

Document

Sets the string containing this message's data.

Usage

From source file:org.addsimplicity.anicetus.io.jms.JsonMessageConverter.java

/**
 * Translate the telemetry to a JMS message. A JMS text message is used to
 * contain the translated payload.//from w ww .  j av  a  2  s. c  o m
 * 
 * @param obj
 *          The telemetry artifact.
 * @param jsmSess
 *          The JMS session.
 * @return a text message containing the translated payload.
 * 
 * @see org.springframework.jms.support.converter.MessageConverter#toMessage(java.lang.Object,
 *      javax.jms.Session)
 */
public Message toMessage(Object obj, Session jmsSess) throws JMSException, MessageConversionException {
    TextMessage m = jmsSess.createTextMessage();

    GlobalInfo telemetry = (GlobalInfo) obj;
    m.setJMSCorrelationID(telemetry.getEntityId().toString());
    m.setStringProperty(GlobalInfoFields.ReportingNode.name(), telemetry.getReportingNode());

    if (telemetry.containsKey(ExecInfoFields.OperationName.name())) {
        m.setStringProperty(ExecInfoFields.OperationName.name(),
                (String) telemetry.get(ExecInfoFields.OperationName.name()));
    }

    if (telemetry.containsKey(ExecInfoFields.Status.name())) {
        m.setStringProperty(ExecInfoFields.Status.name(),
                telemetry.get(ExecInfoFields.Status.name()).toString());
    }

    char[] body = m_translator.encode(telemetry);

    m.setText(new String(body));

    return m;
}

From source file:hermes.impl.DefaultXMLHelper.java

public Message createMessage(MessageFactory hermes, XMLMessage message)
        throws JMSException, IOException, ClassNotFoundException, DecoderException {
    try {/*from  www .j a v a  2s  . co  m*/
        Message rval = hermes.createMessage();

        if (message instanceof XMLTextMessage) {
            rval = hermes.createTextMessage();

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

            if (BASE64_CODEC.equals(textMessage.getCodec())) {
                byte[] bytes = base64EncoderTL.get().decode(textMessage.getText().getBytes());
                textRval.setText(new String(bytes, "ASCII"));
            } else {
                textRval.setText(textMessage.getText());
            }
        } else if (message instanceof XMLMapMessage) {
            rval = hermes.createMapMessage();

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

            for (Iterator iter = mapMessage.getBodyProperty().iterator(); iter.hasNext();) {
                final Property property = (Property) iter.next();

                if (property.getValue() == null) {
                    mapRval.setObject(property.getName(), null);
                } else if (property.getType().equals(String.class.getName())) {
                    mapRval.setString(property.getName(), property.getValue());
                } else if (property.getType().equals(Long.class.getName())) {
                    mapRval.setLong(property.getName(), Long.parseLong(property.getValue()));
                } else if (property.getType().equals(Double.class.getName())) {
                    mapRval.setDouble(property.getName(), Double.parseDouble(property.getValue()));
                } else if (property.getType().equals(Boolean.class.getName())) {
                    mapRval.setBoolean(property.getName(), Boolean.getBoolean(property.getValue()));
                } else if (property.getType().equals(Character.class.getName())) {
                    mapRval.setChar(property.getName(), property.getValue().charAt(0));
                } else if (property.getType().equals(Short.class.getName())) {
                    mapRval.setShort(property.getName(), Short.parseShort(property.getValue()));
                } else if (property.getType().equals(Integer.class.getName())) {
                    mapRval.setInt(property.getName(), Integer.parseInt(property.getValue()));
                }
            }
        } else if (message instanceof XMLBytesMessage) {
            rval = hermes.createBytesMessage();

            XMLBytesMessage bytesMessage = (XMLBytesMessage) message;
            BytesMessage bytesRval = (BytesMessage) rval;

            bytesRval.writeBytes(base64EncoderTL.get().decode(bytesMessage.getBytes().getBytes()));
        } else if (message instanceof XMLObjectMessage) {
            rval = hermes.createObjectMessage();

            XMLObjectMessage objectMessage = (XMLObjectMessage) message;
            ObjectMessage objectRval = (ObjectMessage) rval;
            ByteArrayInputStream bistream = new ByteArrayInputStream(
                    base64EncoderTL.get().decode(objectMessage.getObject().getBytes()));

            ObjectInputStream oistream = new ObjectInputStream(bistream);

            objectRval.setObject((Serializable) oistream.readObject());
        }

        //
        // JMS Header properties

        try {
            rval.setJMSDeliveryMode(message.getJMSDeliveryMode());
        } catch (JMSException ex) {
            log.error("unable to set JMSDeliveryMode to " + message.getJMSDeliveryMode() + ": "
                    + ex.getMessage());
        }

        try {
            rval.setJMSMessageID(message.getJMSMessageID());
        } catch (JMSException ex) {
            log.error("unable to set JMSMessageID: " + ex.getMessage(), ex);
        }

        try {
            if (message.getJMSExpiration() != null) {
                rval.setJMSExpiration(message.getJMSExpiration());
            }
        } catch (JMSException ex) {
            log.error("unable to set JMSExpiration: " + ex.getMessage(), ex);
        }

        try {
            if (message.getJMSPriority() != null) {
                rval.setJMSPriority(message.getJMSPriority());
            }
        } catch (JMSException ex) {
            log.error("unable to set JMSPriority: " + ex.getMessage(), ex);
        }

        try {
            if (message.getJMSTimestamp() != null) {
                rval.setJMSTimestamp(message.getJMSTimestamp());
            }
        } catch (JMSException ex) {
            log.error("unable to set JMSTimestamp:" + ex.getMessage(), ex);
        }

        if (message.getJMSCorrelationID() != null) {
            rval.setJMSCorrelationID(message.getJMSCorrelationID());
        }

        if (message.getJMSReplyTo() != null && !message.getJMSReplyTo().equals("null")) {
            rval.setJMSReplyTo(hermes.getDestination(message.getJMSReplyTo(),
                    Domain.getDomain(message.getJMSReplyToDomain())));
        }

        if (message.getJMSType() != null) {
            rval.setJMSType(message.getJMSType());
        }

        if (message.getJMSDestination() != null) {
            if (message.isFromQueue()) {
                rval.setJMSDestination(hermes.getDestination(message.getJMSDestination(), Domain.QUEUE));
            } else {
                rval.setJMSDestination(hermes.getDestination(message.getJMSDestination(), Domain.TOPIC));
            }
        }

        for (Iterator iter = message.getHeaderProperty().iterator(); iter.hasNext();) {
            Property property = (Property) iter.next();

            if (property.getValue() == null) {
                rval.setObjectProperty(property.getName(), null);
            } else if (property.getType().equals(String.class.getName())) {
                rval.setStringProperty(property.getName(), StringEscapeUtils.unescapeXml(property.getValue()));
            } else if (property.getType().equals(Long.class.getName())) {
                rval.setLongProperty(property.getName(), Long.parseLong(property.getValue()));
            } else if (property.getType().equals(Double.class.getName())) {
                rval.setDoubleProperty(property.getName(), Double.parseDouble(property.getValue()));
            } else if (property.getType().equals(Boolean.class.getName())) {
                rval.setBooleanProperty(property.getName(), Boolean.parseBoolean(property.getValue()));
            } else if (property.getType().equals(Short.class.getName())) {
                rval.setShortProperty(property.getName(), Short.parseShort(property.getValue()));
            } else if (property.getType().equals(Integer.class.getName())) {
                rval.setIntProperty(property.getName(), Integer.parseInt(property.getValue()));
            }
        }

        return rval;
    } catch (NamingException e) {
        throw new HermesException(e);
    }

}

From source file:org.wso2.carbon.andes.core.QueueManagerServiceImpl.java

/**
 * Publish message to given JMS queue//w  ww .ja v  a 2  s.c  o  m
 *
 * @param nameOfQueue queue name
 * @param userName username
 * @param accessKey access key
 * @param jmsType jms type
 * @param jmsCorrelationID message correlation id
 * @param numberOfMessages number of messages to publish
 * @param message message body
 * @param deliveryMode delivery mode
 * @param priority message priority
 * @param expireTime message expire time
 * @throws QueueManagerException
 */
private void send(String nameOfQueue, String userName, String accessKey, String jmsType,
        String jmsCorrelationID, int numberOfMessages, String message, int deliveryMode, int priority,
        long expireTime) throws QueueManagerException {
    QueueConnectionFactory connFactory;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    QueueSender queueSender = null;
    try {
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, ANDES_ICF);
        properties.put(CF_NAME_PREFIX + CF_NAME, Utils.getTCPConnectionURL(userName, accessKey));
        properties.put(QUEUE_NAME_PREFIX + nameOfQueue, nameOfQueue);
        properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");
        InitialContext ctx = new InitialContext(properties);
        connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        queueConnection = connFactory.createQueueConnection();
        Queue queue = (Queue) ctx.lookup(nameOfQueue);
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        queueConnection.start();
        TextMessage textMessage = queueSession.createTextMessage();
        if (queueSender != null && textMessage != null) {
            if (jmsType != null) {
                textMessage.setJMSType(jmsType);
            }
            if (jmsCorrelationID != null) {
                textMessage.setJMSCorrelationID(jmsCorrelationID);
            }

            if (message != null) {
                textMessage.setText(message);
            } else {
                textMessage.setText("Type message here..");
            }

            for (int i = 0; i < numberOfMessages; i++) {
                queueSender.send(textMessage, deliveryMode, priority, expireTime);
            }
        }
    } catch (FileNotFoundException | NamingException | UnknownHostException | XMLStreamException
            | JMSException e) {
        throw new QueueManagerException("Unable to send message.", e);
    } finally {
        try {
            if (queueConnection != null) {
                queueConnection.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue connection", e);
        }
        try {
            if (queueSession != null) {
                queueSession.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue session", e);
        }
        try {
            if (queueSender != null) {
                queueSender.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue sender", e);
        }
    }
}

From source file:com.solveapuzzle.mapping.agnostic.JmsMessageListener.java

/**
 * Implementation of <code>MessageListener</code>.
 *//* w w w  .jav  a2s  . co  m*/
public void onMessage(Message message) {
    try {
        int messageCount = message.getIntProperty(JmsMessageProducer.MESSAGE_COUNT);

        logger.info("Processed message '{}'.  value={}", message, messageCount);

        counter.incrementAndGet();

        if (message instanceof TextMessage) {
            TextMessage tm = (TextMessage) message;
            String msg = tm.getText();

            logger.info(" Read Transform property " + message.getStringProperty(TRANSFORM));

            try {

                String parser = tm.getStringProperty(PARSER);
                String key = tm.getStringProperty(TRANSFORM);

                logger.info(" Read Transform propertys " + parser + " " + key);

                String response = engine.onTransformEvent(this.createConfig(parser, key), tm.getText(),
                        Charset.defaultCharset());

                logger.info(" Response " + response);

                logger.info("message ReplyTo ID " + tm.getJMSCorrelationID());

                tm.setJMSDestination(this.outDestination);

                javax.jms.Queue queue = (javax.jms.Queue) tm.getJMSDestination();
                logger.info("ReplyTo Queue name = " + queue.getQueueName());

                tm.clearBody();

                tm.setText(response);
                // Push to response queue

            } catch (MappingException e) {
                logger.error("Mapping exception from transformation ", e);
                // push to mapping error Queue?
                // May be fixable with input xml change or due to data quality, invalid against schema

                throw new RuntimeException(e);
            } catch (ConfigurationException e) {
                logger.error("Configuration exception from transformation", e);
                // Can't fix - dead letter queue - but worth tracing what config went missing?
                throw new RuntimeException(e);
            }

        }
    } catch (JMSException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:hermes.renderers.DefaultMessageRenderer.java

/**
 * Show the TextMessage in a JTextArea./*from   w  w w.  j  a v  a2 s.  c o m*/
 * 
 * @param textMessage
 * @return
 * @throws JMSException
 */
protected JComponent handleTextMessage(final TextMessage textMessage) throws JMSException {
    //
    // Show the text in a JTextArea, you can edit the message in place and
    // then drop it onto another queue/topic.

    final String text = textMessage.getText();
    final JTextArea textPane = new JTextArea();

    // final CharBuffer bytes = CharBuffer.wrap(text.subSequence(0,
    // text.length())) ;
    // final JTextArea textPane = new MyTextArea(new PlainDocument(new
    // MappedStringContent(bytes))) ;

    textPane.setEditable(false);
    textPane.setFont(Font.decode("Monospaced-PLAIN-12"));
    textPane.setLineWrap(true);
    textPane.setWrapStyleWord(true);

    textPane.append(text);

    textPane.getDocument().addDocumentListener(new DocumentListener() {
        public void doChange() {
            try {
                textMessage.setText(textPane.getText());
            } catch (JMSException e) {
                JOptionPane.showMessageDialog(textPane, "Unable to update the TextMessage: " + e.getMessage(),
                        "Error modifying message content", JOptionPane.ERROR_MESSAGE);

                try {
                    textPane.setText(textMessage.getText());
                } catch (JMSException e1) {
                    log.error(e1.getMessage(), e1);
                }

                textPane.setEditable(false);
                textPane.getDocument().removeDocumentListener(this);
            }
        }

        @Override
        public void changedUpdate(DocumentEvent arg0) {
            doChange();
        }

        @Override
        public void insertUpdate(DocumentEvent arg0) {
            doChange();
        }

        @Override
        public void removeUpdate(DocumentEvent arg0) {
            doChange();
        }
    });

    textPane.setCaretPosition(0);

    return textPane;
}

From source file:org.openanzo.combus.bayeux.BridgeConnectionManager.java

/**
 * Send a JMS message on behalf of the given client to a specific destination. The destination is a string that names an abstract queue such as that in
 * Constants.NOTIFICATION_SERVICE_QUEUE, etc.
 * //from w  w  w  .  j  av a  2  s  .  c  om
 * @param clientId
 * @param destination
 * @param messageProperties
 * @param msgBody
 * @return returns whether or not this message was published to a topic
 * @throws JMSException
 * @throws AnzoException
 */
protected boolean sendClientMessage(String clientId, AnzoPrincipal principal, String destination,
        Map<?, ?> messageProperties, String msgBody, IOperationContext opContext)
        throws JMSException, AnzoException {
    //long destinationProfiler = profiler.start("Resolving destination.");
    Destination dest = destinations.get(destination);
    //profiler.stop(destinationProfiler);
    if (dest == null && destination.startsWith("services/")) {
        dest = session.createQueue(destination);
        destinations.put(destination, dest);
    }
    if (dest == null) { // we probably have a statement channel
        //long nullDestProfiler = profiler.start("Sending client message with null destination.");
        if (destination == null || !destination.startsWith(NAMESPACES.STREAM_TOPIC_PREFIX)) {
            //profiler.stop(nullDestProfiler);
            throw new AnzoException(ExceptionConstants.COMBUS.INVALID_TOPIC, destination);
        }
        // first we have to get the named graph uri out of the statement channel topic.
        String uri = UriGenerator.stripEncapsulatedString(NAMESPACES.STREAM_TOPIC_PREFIX, destination);
        URI graphUri = Constants.valueFactory.createURI(uri);
        if (!userHasGraphAddAccess(graphUri, principal, opContext)) {
            //profiler.stop(nullDestProfiler);
            throw new AnzoException(ExceptionConstants.COMBUS.NOT_AUTHORIZED_FOR_TOPIC,
                    opContext.getOperationPrincipal().getUserURI().toString(), destination);
        }
        Topic topic = session.createTopic(destination);

        TextMessage tmsg = session.createTextMessage();
        for (Map.Entry<?, ?> prop : messageProperties.entrySet()) {
            tmsg.setStringProperty(prop.getKey().toString(), prop.getValue().toString());
        }
        tmsg.setText(msgBody);
        mp.send(topic, tmsg);
        //profiler.stop(nullDestProfiler);
        return true;
    } else {
        TemporaryTopic tempTopicForReply;
        //long = clientStateProfiler = profiler.start("Obtaining Bayeux client state.");
        mapLock.lock();
        try {
            ClientState state = clientIdToClientState.get(clientId);
            if (state == null) {
                throw new AnzoException(ExceptionConstants.CLIENT.CLIENT_NOT_CONNECTED);
            }
            tempTopicForReply = state.topic;
        } finally {
            mapLock.unlock();
            //profiler.stop(clientStateProfiler);
        }

        //long prepareJmsProfiler = profiler.start("Preparing JMS Message.");
        TextMessage tmsg = session.createTextMessage();
        int priority = 4;
        for (Map.Entry<?, ?> prop : messageProperties.entrySet()) {
            if (JMS_MSG_PROPERTY_CORRELATION_ID.equals(prop.getKey())) {
                tmsg.setJMSCorrelationID(prop.getValue().toString());
            }
            if (JMS_MSG_PROPERTY_PRIORITY.equals(prop.getKey())) {
                priority = Integer.parseInt(prop.getValue().toString());
            } else {
                tmsg.setStringProperty(prop.getKey().toString(), prop.getValue().toString());
            }
        }
        tmsg.setJMSPriority(priority);
        tmsg.setJMSReplyTo(tempTopicForReply);
        tmsg.setText(msgBody);
        String username = principal.getName();
        tmsg.setStringProperty("runAsUser", username);
        //profiler.stop(prepareJmsProfiler);
        long sendJmsProfiler = profiler.start("Sending JMS Message");
        mp.setPriority(priority);
        mp.send(dest, tmsg);
        profiler.stop(sendJmsProfiler);
        return false;
    }

}

From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

@Override
public boolean sendMessage(Run<?, ?> build, TaskListener listener, MessageUtils.MESSAGE_TYPE type, String props,
        String content) {//from  w  w  w .j  ava 2  s. c  o  m
    Connection connection = null;
    Session session = null;
    MessageProducer publisher = null;

    try {
        String ltopic = getTopic();
        if (provider.getAuthenticationMethod() != null && ltopic != null && provider.getBroker() != null) {
            ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();
            connection = connectionFactory.createConnection();
            connection.start();

            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createTopic(ltopic);
            publisher = session.createProducer(destination);

            TextMessage message;
            message = session.createTextMessage("");
            message.setJMSType(JSON_TYPE);

            message.setStringProperty("CI_NAME", build.getParent().getName());
            message.setStringProperty("CI_TYPE", type.getMessage());
            if (!build.isBuilding()) {
                message.setStringProperty("CI_STATUS",
                        (build.getResult() == Result.SUCCESS ? "passed" : "failed"));
            }

            StrSubstitutor sub = new StrSubstitutor(build.getEnvironment(listener));

            if (props != null && !props.trim().equals("")) {
                Properties p = new Properties();
                p.load(new StringReader(props));
                @SuppressWarnings("unchecked")
                Enumeration<String> e = (Enumeration<String>) p.propertyNames();
                while (e.hasMoreElements()) {
                    String key = e.nextElement();
                    message.setStringProperty(key, sub.replace(p.getProperty(key)));
                }
            }

            message.setText(sub.replace(content));

            publisher.send(message);
            log.info("Sent " + type.toString() + " message for job '" + build.getParent().getName()
                    + "' to topic '" + ltopic + "':\n" + formatMessage(message));
        } else {
            log.severe("One or more of the following is invalid (null): user, password, topic, broker.");
            return false;
        }

    } catch (Exception e) {
        log.log(Level.SEVERE, "Unhandled exception in perform.", e);
    } finally {
        if (publisher != null) {
            try {
                publisher.close();
            } catch (JMSException e) {
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
    return true;
}

From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java

public void enqEmail(SmtpMessage msg) throws IOException, JMSException {

    TextMessage bm = session.createTextMessage();
    Gson gson = new Gson();
    bm.setText(gson.toJson(msg));
    bm.setStringProperty("OriginalQueue", this.smtpQueue);
    bm.setStringProperty("nonce", UUID.randomUUID().toString());
    bm.setStringProperty("JMSXGroupID", "unison-email");
    mp.send(bm);/*w  ww  .ja va  2  s  .  c om*/
    //session.commit();

}

From source file:nl.nn.adapterframework.jms.JMSFacade.java

public TextMessage createTextMessage(Session session, String correlationID, String message)
        throws javax.naming.NamingException, JMSException {
    TextMessage textMessage = null;
    textMessage = session.createTextMessage();
    if (null != correlationID) {
        if (correlationIdMaxLength >= 0) {
            int cidlen;
            if (correlationID.startsWith(correlationIdToHexPrefix)) {
                cidlen = correlationID.length() - correlationIdToHexPrefix.length();
            } else {
                cidlen = correlationID.length();
            }// w w w.j a v  a  2 s . co  m
            if (cidlen > correlationIdMaxLength) {
                correlationID = correlationIdToHexPrefix
                        + correlationID.substring(correlationID.length() - correlationIdMaxLength);
                if (log.isDebugEnabled())
                    log.debug("correlationId shortened to [" + correlationID + "]");
            }
        }
        if (correlationIdToHex && correlationID.startsWith(correlationIdToHexPrefix)) {
            String hexCorrelationID = correlationIdToHexPrefix;
            int i;
            for (i = correlationIdToHexPrefix.length(); i < correlationID.length(); i++) {
                int c = correlationID.charAt(i);
                hexCorrelationID += Integer.toHexString(c);
            }
            ;
            correlationID = hexCorrelationID;
            if (log.isDebugEnabled())
                log.debug("correlationId changed, based on hexidecimal values, to [" + correlationID + "]");
        }
        textMessage.setJMSCorrelationID(correlationID);
    }
    textMessage.setText(message);
    return textMessage;
}

From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java

public void enqueue(WorkflowHolder wfHolder) throws ProvisioningException {

    TextMessage bm;
    try {/* w  w w.  java2  s  .  c o m*/

        MessageProducer mp;
        MessageProducerHolder mph = null;

        if (this.isInternalQueue()) {
            mp = this.taskMP;
            bm = taskSession.createTextMessage();
            bm.setStringProperty("OriginalQueue", this.taskQueue.getQueueName());
        } else {
            mph = this.getTaskMessageProducer();
            mp = mph.getProducer();
            bm = mph.getSession().createTextMessage();
            bm.setStringProperty("OriginalQueue",
                    ((javax.jms.Queue) mph.getProducer().getDestination()).getQueueName());
        }

        bm.setStringProperty("WorkflowName", wfHolder.getWorkflow().getName());
        bm.setStringProperty("WorkflowSubject", wfHolder.getUser().getUserID());
        bm.setStringProperty("JMSXGroupID", "unison");
        bm.setStringProperty("nonce", UUID.randomUUID().toString());

        TaskHolder holder = wfHolder.getWfStack().peek();
        WorkflowTask task = holder.getParent().get(holder.getPosition());

        bm.setStringProperty("WorkflowCurrentTask", task.getLabel());

        EncryptedMessage encMsg = this.encryptObject(wfHolder);

        String json = JsonWriter.objectToJson(encMsg);
        bm.setText(json);

        try {
            mp.send(bm);
        } finally {
            if (!this.isInternalQueue()) {
                this.returnMessageProducer(mph);
            }
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not enqueue message", e);
    }

}