Example usage for javax.jms ObjectMessage getObject

List of usage examples for javax.jms ObjectMessage getObject

Introduction

In this page you can find the example usage for javax.jms ObjectMessage getObject.

Prototype


Serializable getObject() throws JMSException;

Source Link

Document

Gets the serializable object containing this message's data.

Usage

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

/**
 * Extracts the body from the JMS message
 *
 * @param exchange the exchange//from   ww  w . j av a 2  s  .c o  m
 * @param message  the message to extract its body
 * @return the body, can be <tt>null</tt>
 */
public Object extractBodyFromJms(Exchange exchange, Message message) {
    try {
        // is a custom message converter configured on endpoint then use it instead of doing the extraction
        // based on message type
        if (endpoint != null && endpoint.getMessageConverter() != null) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Extracting body using a custom MessageConverter: " + endpoint.getMessageConverter()
                        + " from JMS message: " + message);
            }
            return endpoint.getMessageConverter().fromMessage(message);
        }

        // if we are configured to not map the jms message then return it as body
        if (endpoint != null && !endpoint.getConfiguration().isMapJmsMessage()) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Option map JMS message is false so using JMS message as body: " + message);
            }
            return message;
        }

        if (message instanceof ObjectMessage) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Extracting body as a ObjectMessage from JMS message: " + message);
            }
            ObjectMessage objectMessage = (ObjectMessage) message;
            Object payload = objectMessage.getObject();
            if (payload instanceof DefaultExchangeHolder) {
                DefaultExchangeHolder holder = (DefaultExchangeHolder) payload;
                DefaultExchangeHolder.unmarshal(exchange, holder);
                return exchange.getIn().getBody();
            } else {
                return objectMessage.getObject();
            }
        } else if (message instanceof TextMessage) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Extracting body as a TextMessage from JMS message: " + message);
            }
            TextMessage textMessage = (TextMessage) message;
            return textMessage.getText();
        } else if (message instanceof MapMessage) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Extracting body as a MapMessage from JMS message: " + message);
            }
            return createMapFromMapMessage((MapMessage) message);
        } else if (message instanceof BytesMessage) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Extracting body as a BytesMessage from JMS message: " + message);
            }
            return createByteArrayFromBytesMessage((BytesMessage) message);
        } else if (message instanceof StreamMessage) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Extracting body as a StreamMessage from JMS message: " + message);
            }
            return message;
        } else {
            return null;
        }
    } catch (JMSException e) {
        throw new RuntimeCamelException("Failed to extract body due to: " + e + ". Message: " + message, e);
    }
}

From source file:org.apache.james.queue.jms.JMSMailQueue.java

/**
 * Create a copy of the given {@link Message}. This includes the properties
 * and the payload/*from w w w .ja v a  2  s .  co m*/
 *
 * @param session
 * @param m
 * @return copy
 * @throws JMSException
 */
@SuppressWarnings("unchecked")
protected Message copy(Session session, Message m) throws JMSException {
    ObjectMessage message = (ObjectMessage) m;
    ObjectMessage copy = session.createObjectMessage(message.getObject());

    Enumeration<String> properties = message.getPropertyNames();
    while (properties.hasMoreElements()) {
        String name = properties.nextElement();
        copy.setObjectProperty(name, message.getObjectProperty(name));
    }

    return copy;
}

From source file:org.apache.jmeter.protocol.jms.sampler.SubscriberSampler.java

private void extractContent(StringBuilder buffer, StringBuilder propBuffer, Message msg, boolean isLast) {
    if (msg != null) {
        try {/*from   ww w. j  av a2s . co  m*/
            if (msg instanceof TextMessage) {
                buffer.append(((TextMessage) msg).getText());
            } else if (msg instanceof ObjectMessage) {
                ObjectMessage objectMessage = (ObjectMessage) msg;
                if (objectMessage.getObject() != null) {
                    buffer.append(objectMessage.getObject().getClass());
                } else {
                    buffer.append("object is null");
                }
            } else if (msg instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage) msg;
                buffer.append(bytesMessage.getBodyLength() + " bytes received in BytesMessage");
            } else if (msg instanceof MapMessage) {
                MapMessage mapm = (MapMessage) msg;
                @SuppressWarnings("unchecked") // MapNames are Strings
                Enumeration<String> enumb = mapm.getMapNames();
                while (enumb.hasMoreElements()) {
                    String name = enumb.nextElement();
                    Object obj = mapm.getObject(name);
                    buffer.append(name);
                    buffer.append(",");
                    buffer.append(obj.getClass().getCanonicalName());
                    buffer.append(",");
                    buffer.append(obj);
                    buffer.append("\n");
                }
            }
            Utils.messageProperties(propBuffer, msg);
            if (!isLast && !StringUtils.isEmpty(separator)) {
                propBuffer.append(separator);
                buffer.append(separator);
            }
        } catch (JMSException e) {
            log.error(e.getMessage());
        }
    }
}

From source file:org.apache.synapse.message.store.impl.jms.JmsConsumer.java

public MessageContext receive() {
    boolean error;
    JMSException exception;/*from  w ww.ja va  2 s . c om*/
    if (!checkConnection()) {
        if (!reconnect()) {
            if (logger.isDebugEnabled()) {
                logger.debug(getId() + " cannot receive message from store. Cannot reconnect.");
            }
            return null;
        } else {
            logger.info(getId() + " reconnected to store.");
            isReceiveError = false;
        }

    }
    if (!checkConnection()) {
        if (logger.isDebugEnabled()) {
            logger.debug(getId() + " cannot receive message from store.");
        }
        return null;
    }
    try {
        Message message = consumer.receive(1);
        if (message == null) {
            return null;
        }
        if (!(message instanceof ObjectMessage)) {
            logger.warn(getId() + ". Did not receive a javax.jms.ObjectMessage");
            message.acknowledge(); // TODO:
            return null;
        }
        ObjectMessage msg = (ObjectMessage) message;
        String messageId = msg.getStringProperty(Constants.OriginalMessageID);
        if (!(msg.getObject() instanceof StorableMessage)) {
            logger.warn(getId() + ". Did not receive a valid message.");
            message.acknowledge();
            return null;
        }
        StorableMessage storableMessage = (StorableMessage) msg.getObject();
        org.apache.axis2.context.MessageContext axis2Mc = store.newAxis2Mc();
        MessageContext synapseMc = store.newSynapseMc(axis2Mc);
        synapseMc = MessageConverter.toMessageContext(storableMessage, axis2Mc, synapseMc);
        updateCache(message, synapseMc, messageId, false);
        if (logger.isDebugEnabled()) {
            logger.debug(
                    getId() + " Received MessageId:" + messageId + " priority:" + message.getJMSPriority());
        }
        return synapseMc;
    } catch (JMSException e) {
        error = true;
        exception = e;
    }
    if (error) {
        if (!isReceiveError) {
            logger.error(
                    getId() + " cannot receive message from store. Error:" + exception.getLocalizedMessage());//, exception);
        }
        updateCache(null, null, "", true);
        cleanup();
        return null;
    }
    return null;
}

From source file:org.audit4j.core.AsyncAuditEngine.java

/**
 * Listen.//w ww. j a  v  a 2 s. co  m
 */
public void listen() {
    try {
        final MessageConsumer consumer = session.createConsumer(destination);

        final MessageListener listener = new MessageListener() {

            @Override
            public void onMessage(final Message message) {
                try {
                    final ObjectMessage objectMessage = (ObjectMessage) message;
                    final Object object = objectMessage.getObject();
                    if (object instanceof AnnotationAuditEvent) {
                        AsynchronousAnnotationProcessor processor = AsynchronousAnnotationProcessor
                                .getInstance();
                        processor.process((AnnotationAuditEvent) object);
                    } else if (object instanceof AsyncCallAuditDto) {

                    }
                } catch (final JMSException e) {
                    e.printStackTrace();
                }
                try {
                    message.acknowledge();
                } catch (final JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("Received Message");
            }
        };

        consumer.setMessageListener(listener);

    } catch (final Exception e) {
        System.out.println("Caught: " + e);
        e.printStackTrace();
    }
}

From source file:org.dcm4chex.archive.hsm.FileMoveService.java

public void onMessage(Message message) {
    ObjectMessage om = (ObjectMessage) message;
    try {//from   w  ww  . j  a v a  2  s.  c o  m
        DeleteStudyOrder order = (DeleteStudyOrder) om.getObject();
        log.info("Start processing " + order);
        try {
            process(order);
            log.info("Finished processing " + order);
        } catch (Exception e) {
            order.setThrowable(e);
            final int failureCount = order.getFailureCount() + 1;
            order.setFailureCount(failureCount);
            final long delay = retryIntervalls.getIntervall(failureCount);
            if (delay == -1L) {
                log.error("Give up to process " + order, e);
                jmsDelegate.fail(moveFilesOfStudyQueueName, order);
            } else {
                log.warn("Failed to process " + order + ". Scheduling retry.", e);
                jmsDelegate.queue(moveFilesOfStudyQueueName, order, 0, System.currentTimeMillis() + delay);
            }
        }
    } catch (JMSException e) {
        log.error("jms error during processing message: " + message, e);
    } catch (Throwable e) {
        log.error("unexpected error during processing message: " + message, e);
    }
}

From source file:org.hyperic.hq.bizapp.server.mdb.LoggingDispatcherImpl.java

@SuppressWarnings("unchecked")
public void onMessage(Message inMessage) {
    if (!(inMessage instanceof ObjectMessage)) {
        return;/*from  ww  w.  ja  va2 s  . co  m*/
    }

    ObjectMessage om = (ObjectMessage) inMessage;

    try {
        Object obj = om.getObject();

        if (obj instanceof AbstractEvent) {
            AbstractEvent event = (AbstractEvent) obj;
            logEvent(event);
        } else if (obj instanceof Collection<?>) {
            Collection<AbstractEvent> events = (Collection<AbstractEvent>) obj;
            logEvents(events);
        }
    } catch (JMSException e) {
        log.error("Cannot open message object", e);
    }

}

From source file:org.hyperic.hq.bizapp.server.mdb.RegisteredDispatcherImpl.java

/**
 * The onMessage method/*from  ww  w .  j  a v a  2  s  .  c o  m*/
 * 
 */
@SuppressWarnings("unchecked")
public void onMessage(Message inMessage) {
    if (!(inMessage instanceof ObjectMessage)) {
        return;
    }
    final boolean debug = log.isDebugEnabled();
    Object obj;
    try {
        ObjectMessage om = (ObjectMessage) inMessage;
        if (debug) {
            log.debug("Redelivering message=" + inMessage.getJMSRedelivered());
        }
        obj = om.getObject();
    } catch (JMSException e) {
        log.error("Cannot open message object", e);
        return;
    }

    if (obj instanceof HeartBeatEvent) {
        final HeartBeatEvent event = (HeartBeatEvent) obj;
        final long timestamp = event.getTimestamp();
        if (debug)
            log.debug("setting heartbeat timestamp to " + TimeUtil.toString(timestamp));
        heartbeatTime.set(timestamp);
    }

    if (obj instanceof AbstractEvent) {
        AbstractEvent event = (AbstractEvent) obj;
        if (debug) {
            log.debug("1 event in the message");
        }
        dispatchEvent(event);
    } else if (obj instanceof Collection<?>) {
        Collection<AbstractEvent> events = (Collection<AbstractEvent>) obj;
        if (debug) {
            log.debug(events.size() + " events in the message");
        }
        for (AbstractEvent event : events) {
            dispatchEvent(event);
        }
    }
}

From source file:org.jbpm.bpel.integration.jms.RequestListener.java

public void onMessage(Message message) {
    if (!(message instanceof ObjectMessage)) {
        log.error("received non-object message: " + message);
        return;//from  w  ww . j  av a  2  s  . com
    }
    try {
        ObjectMessage request = (ObjectMessage) message;
        log.debug("delivering request: " + RequestListener.messageToString(request));
        /*
         * LEAK WARNING. This listener must be removed from the integration control before passing
         * control to the inbound message activity, because loop structures could execute the same
         * activity again and overwrite the entry in the integration control with a new listener. If
         * removeRequestListener() was invoked after passing control to the activity, the new listener
         * would get removed instead of this, leaving the listener open but unreachable from
         * application code. CODE ORDER NOTE. Removing this listener early in the process prevents any
         * other thread from closing it. This effect is desirable because the orderly shutdown
         * mechanism of JMS never stops a running listener anyway. Furthermore, the mechanism is
         * specified to *block* the other thread until this listener returns.
         */
        if (oneShot)
            integrationControl.removeRequestListener(this);

        deliverRequest((Map) request.getObject(), request.getJMSReplyTo(), request.getJMSMessageID());
        request.acknowledge();

        if (oneShot)
            close();
    } catch (JMSException e) {
        log.error("request delivery failed due to jms exception, giving up", e);
    } catch (RuntimeException e) {
        if (isRecoverable(e)) {
            log.warn("request delivery failed due to recoverable exception, attempting recovery");
            try {
                // recover the session manually
                jmsSession.recover();
            } catch (JMSException je) {
                log.error("request recovery failed, giving up", je);
            }
        } else
            log.error("request delivery failed due to non-recoverable exception, giving up", e);
    }
}

From source file:org.jbpm.bpel.integration.jms.StartListener.java

public void onMessage(Message message) {
    if (!(message instanceof ObjectMessage)) {
        log.error("received non-object jms message: " + message);
        return;//from   w  ww  .  j  av a  2  s.c om
    }

    try {
        ObjectMessage request = (ObjectMessage) message;
        log.debug("delivering request: " + RequestListener.messageToString(request));

        /*
         * CODE ORDER NOTE. Removing this listener early in the process prevents any other thread from
         * closing it. This effect is desirable because the orderly shutdown mechanism of JMS never
         * stops a running listener anyway. Furthermore, the mechanism is specified to *block* the
         * other thread until this listener returns.
         */
        integrationControl.removeStartListener(this);

        // BPEL-282 create new start listener to improve concurrency
        StartListener startListener = new StartListener(this);
        startListener.open();

        deliverRequest((Map) request.getObject(), request.getJMSReplyTo(), request.getJMSMessageID());
        request.acknowledge();

        close();
    } catch (JMSException e) {
        log.error("request delivery failed due to jms exception, giving up", e);
    } catch (RuntimeException e) {
        if (RequestListener.isRecoverable(e)) {
            log.warn("request delivery failed due to recoverable exception, attempting recovery");
            try {
                // recover the session manually
                jmsSession.recover();
            } catch (JMSException je) {
                log.error("request recovery failed, giving up", je);
            }
        } else
            log.error("request delivery failed due to non-recoverable exception, giving up", e);
    }
}