Example usage for javax.jms Session createMessage

List of usage examples for javax.jms Session createMessage

Introduction

In this page you can find the example usage for javax.jms Session createMessage.

Prototype


Message createMessage() throws JMSException;

Source Link

Document

Creates a Message object.

Usage

From source file:org.apache.camel.component.jms.JmsBinding.java

protected Message createJmsMessage(Exchange exchange, Object body, Map<String, Object> headers, Session session,
        CamelContext context) throws JMSException {
    JmsMessageType type = null;/*from  w w  w  .  j  a  v  a 2 s.  c  om*/

    // special for transferExchange
    if (endpoint != null && endpoint.isTransferExchange()) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Option transferExchange=true so we use JmsMessageType: Object");
        }
        Serializable holder = DefaultExchangeHolder.marshal(exchange);
        return session.createObjectMessage(holder);
    }

    // use a custom message converter
    if (endpoint != null && endpoint.getMessageConverter() != null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Creating JmsMessage using a custom MessageConverter: " + endpoint.getMessageConverter()
                    + " with body: " + body);
        }
        return endpoint.getMessageConverter().toMessage(body, session);
    }

    // check if header have a type set, if so we force to use it
    if (headers.containsKey(JmsConstants.JMS_MESSAGE_TYPE)) {
        type = context.getTypeConverter().convertTo(JmsMessageType.class,
                headers.get(JmsConstants.JMS_MESSAGE_TYPE));
    } else if (endpoint != null && endpoint.getConfiguration().getJmsMessageType() != null) {
        // force a specific type from the endpoint configuration
        type = endpoint.getConfiguration().getJmsMessageType();
    } else {
        type = getJMSMessageTypeForBody(exchange, body, headers, session, context);
    }

    // create the JmsMessage based on the type
    if (type != null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using JmsMessageType: " + type);
        }
        return createJmsMessageForType(exchange, body, headers, session, context, type);
    }

    // warn if the body could not be mapped
    if (body != null && LOG.isWarnEnabled()) {
        LOG.warn("Cannot determine specific JmsMessage type to use from body class."
                + " Will use generic JmsMessage." + " Body class: " + ObjectHelper.classCanonicalName(body)
                + ". If you want to send a POJO then your class might need to implement java.io.Serializable"
                + ", or you can force a specific type by setting the jmsMessageType option on the JMS endpoint.");
    }

    // return a default message
    return session.createMessage();
}

From source file:org.fcrepo.jms.headers.DefaultMessageFactory.java

@Override
public Message getMessage(final FedoraEvent jcrEvent, final javax.jms.Session jmsSession) throws JMSException {

    final Message message = jmsSession.createMessage();
    message.setLongProperty(TIMESTAMP_HEADER_NAME, jcrEvent.getDate());
    String path = jcrEvent.getPath();
    if (path.endsWith("/" + JCR_CONTENT)) {
        path = path.replaceAll("/" + JCR_CONTENT, "");
    }//from  w w w . j ava2  s .c om

    // extract baseURL and userAgent from event UserData
    try {
        final String userdata = jcrEvent.getUserData();
        if (!StringUtils.isBlank(userdata)) {
            final ObjectMapper mapper = new ObjectMapper();
            final JsonNode json = mapper.readTree(userdata);
            String url = json.get("baseURL").asText();
            while (url.endsWith("/")) {
                url = url.substring(0, url.length() - 1);
            }
            this.baseURL = url;
            this.userAgent = json.get("userAgent").asText();
            LOGGER.debug("MessageFactory baseURL: {}, userAgent: {}", baseURL, userAgent);

        } else {
            LOGGER.warn("MessageFactory event UserData is empty!");
        }

    } catch (final IOException ex) {
        LOGGER.warn("Error setting baseURL or userAgent", ex);
    }

    message.setStringProperty(IDENTIFIER_HEADER_NAME, path);
    message.setStringProperty(EVENT_TYPE_HEADER_NAME, getEventURIs(jcrEvent.getTypes()));
    message.setStringProperty(BASE_URL_HEADER_NAME, baseURL);
    message.setStringProperty(USER_HEADER_NAME, jcrEvent.getUserID());
    message.setStringProperty(USER_AGENT_HEADER_NAME, userAgent);
    message.setStringProperty(PROPERTIES_HEADER_NAME, String.join(",", jcrEvent.getProperties()));
    message.setStringProperty(EVENT_ID_HEADER_NAME, jcrEvent.getEventID());

    LOGGER.trace("getMessage() returning: {}", message);
    return message;
}

From source file:org.jbpm.jms.JmsConnectorService.java

final void sendMessage(Job job) throws JMSException {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    try {/*  ww  w.  j a  v  a2  s  .c  o m*/
        Message message = session.createMessage();
        populateMessage(message, job);

        MessageProducer messageProducer = session.createProducer(serviceFactory.getDestination());
        messageProducer.send(message);
    } finally {
        // there is no need to close the producers of a closed session
        session.close();
    }
}

From source file:tools.ProducerTool.java

@Override
public void run() {
    Connection connection = null;
    Session session = null;
    try {//  w w  w  . ja v a 2s . c o m
        connection = connectionFactory.createConnection();
        if (clientId != null) {
            connection.setClientID(clientId);
        }
        session = connection.createSession(transacted, acknowledgeMode);
        Destination destination = null;
        if (jndiLookupDestinations) {
            destination = (Destination) context.lookup(destinationName);
        } else {
            if (useQueueDestinations) {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryQueue();
                } else {
                    destination = session.createQueue(destinationName);
                }
            } else {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryTopic();
                } else {
                    destination = session.createTopic(destinationName);
                }
            }
        }

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

        int numMessagesToSend = useFinalControlMessage ? numMessages - 1 : numMessages;

        for (int i = 0; i < numMessagesToSend; i++) {
            String messageText = "Message " + i + " at " + new Date();
            if (bytesLength > -1) {
                byte[] messageTextBytes = messageText.getBytes(StandardCharsets.UTF_8);
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(messageTextBytes);
                if (messageTextBytes.length < bytesLength) {
                    byte[] paddingBytes = new byte[bytesLength - messageTextBytes.length];
                    bytesMessage.writeBytes(paddingBytes);
                }
                if (messageGroupId != null) {
                    bytesMessage.setStringProperty("JMSXGroupID", messageGroupId);
                }
                LOGGER.info("Sending bytes message");
                producer.send(bytesMessage);
            } else {
                TextMessage textMessage = session.createTextMessage(messageText);
                if (messageGroupId != null) {
                    textMessage.setStringProperty("JMSXGroupID", messageGroupId);
                }
                LOGGER.info("Sending text message: " + messageText);
                producer.send(textMessage);
            }

            if (perMessageSleepMS > 0) {
                Thread.sleep(perMessageSleepMS);
            }
            if (transacted) {
                if ((i + 1) % batchSize == 0) {
                    session.commit();
                }
            }
        }
        if (useFinalControlMessage) {
            Message message = session.createMessage();
            if (messageGroupId != null) {
                message.setStringProperty("JMSXGroupID", messageGroupId);
            }
            LOGGER.info("Sending message");
            producer.send(message);
            if (transacted) {
                session.commit();
            }
        }
        producer.close();
    } catch (Exception ex) {
        LOGGER.error("ProducerTool hit exception: " + ex.getMessage(), ex);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
    }
}

From source file:ubic.gemma.job.grid.util.JMSBrokerMonitorImpl.java

private MapMessage sendTaskSubmissionQueueDiagnosticMessage() throws JMSException {
    MapMessage reply = jmsTemplate.execute(new SessionCallback<MapMessage>() {
        @Override//from ww w  . j  a v  a2s  .  c o m
        public MapMessage doInJms(Session session) throws JMSException {
            Queue replyTo = session.createTemporaryQueue();
            Message message = session.createMessage();
            message.setJMSReplyTo(replyTo);
            Queue queryQueue = session.createQueue("ActiveMQ.Statistics.Destination.tasks.submit");
            MessageProducer producer = session.createProducer(queryQueue);
            MessageConsumer consumer = session.createConsumer(replyTo);
            producer.send(message);
            return (MapMessage) consumer.receive(5000);
        }
    }, true);
    return reply;
}