Example usage for javax.jms Message getClass

List of usage examples for javax.jms Message getClass

Introduction

In this page you can find the example usage for javax.jms Message getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

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

/**
 * <p>/*from  w  ww.j a  va2s  .c o  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:org.bremersee.common.jms.DefaultJmsConverter.java

@Override
public Object fromMessage(Message message) throws JMSException {

    if (message == null) {
        return null;
    }/*from   w  w w.  j  a  va  2  s . c  o m*/

    Class<?> payloadClass;
    try {
        payloadClass = Class.forName(message.getJMSType());
    } catch (Throwable t) { // NOSONAR
        payloadClass = null;
    }

    Object payload;

    if (message instanceof TextMessage) {

        TextMessage msg = (TextMessage) message;
        payload = tryToGetPayload(msg, payloadClass);

    } else if (message instanceof BytesMessage) {

        BytesMessage msg = (BytesMessage) message;
        payload = tryToGetPayload(msg, payloadClass);

    } else {

        MessageConversionException e = new MessageConversionException(
                "Unsupported message type [" + message.getClass().getName() + "].");
        log.error("Could not convert message:", e);
        throw e;
    }

    return payload;
}

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

/**
 * Execute a request to the IFSA service.
 * @return in Request/Reply, the retrieved message or TIMEOUT, otherwise null
 *//*from  w  ww  . j  a  v  a 2s  .com*/
public String sendMessage(String dummyCorrelationId, String message, Map params, String bifName, byte btcData[])
        throws SenderException, TimeOutException {
    String result = null;
    QueueSession session = null;
    QueueSender sender = null;
    Map udzMap = null;

    try {
        log.debug(getLogPrefix() + "creating session and sender");
        session = createSession();
        IFSAQueue queue;
        if (params != null && params.size() > 0) {
            // Use first param as serviceId
            String serviceId = (String) params.get("serviceId");
            if (serviceId == null) {
                serviceId = getServiceId();
            }
            String occurrence = (String) params.get("occurrence");
            if (occurrence != null) {
                int i = serviceId.indexOf('/',
                        serviceId.indexOf('/', serviceId.indexOf('/', serviceId.indexOf('/') + 1) + 1) + 1);
                int j = serviceId.indexOf('/', i + 1);
                serviceId = serviceId.substring(0, i + 1) + occurrence + serviceId.substring(j);
            }
            queue = getMessagingSource().lookupService(getMessagingSource().polishServiceId(serviceId));
            if (queue == null) {
                throw new SenderException(
                        getLogPrefix() + "got null as queue for serviceId [" + serviceId + "]");
            }
            if (log.isDebugEnabled()) {
                log.info(getLogPrefix() + "got Queue to send messages on [" + queue.getQueueName() + "]");
            }
            // Use remaining params as outgoing UDZs
            udzMap = new HashMap();
            udzMap.putAll(params);
            udzMap.remove("serviceId");
            udzMap.remove("occurrence");
        } else {
            queue = getServiceQueue();
        }
        sender = createSender(session, queue);

        log.debug(getLogPrefix() + "sending message with bifName [" + bifName + "]");

        TextMessage sentMessage = sendMessage(session, sender, message, udzMap, bifName, btcData);
        log.debug(getLogPrefix() + "message sent");

        if (isSynchronous()) {

            log.debug(getLogPrefix() + "waiting for reply");
            Message msg = getRawReplyMessage(session, queue, sentMessage);
            try {
                long tsReplyReceived = System.currentTimeMillis();
                long tsRequestSent = sentMessage.getJMSTimestamp();
                long tsReplySent = msg.getJMSTimestamp();
                //               long jmsTimestampRcvd = msg.getJMSTimestamp();
                ////                  long businessProcFinishSent=0;
                //               long businessProcStartRcvd=0;
                //               long businessProcStartSent=0;
                //               long businessProcFinishRcvd=0;
                //               if (sentMessage instanceof IFSAMessage) {
                //                  businessProcStartSent=((IFSAMessage)sentMessage).getBusinessProcessingStartTime();
                ////                     businessProcFinishSent=((IFSAMessage)sentMessage).getBusinessProcessingFinishTime();
                //               }
                //               if (msg instanceof IFSAMessage) {
                //                  businessProcStartRcvd=((IFSAMessage)msg).getBusinessProcessingStartTime();
                //                  businessProcFinishRcvd=((IFSAMessage)msg).getBusinessProcessingFinishTime();
                //               }
                if (log.isInfoEnabled()) {
                    log.info(getLogPrefix() + "A) RequestSent   [" + DateUtils.format(tsRequestSent) + "]");
                    log.info(getLogPrefix() + "B) ReplySent     [" + DateUtils.format(tsReplySent)
                            + "] diff (~queing + processing) [" + (tsReplySent - tsRequestSent) + "]");
                    log.info(getLogPrefix() + "C) ReplyReceived [" + DateUtils.format(tsReplyReceived)
                            + "] diff (transport of reply )[" + (tsReplyReceived - tsReplySent) + "]");
                    //                  log.info(getLogPrefix()+"C2) msgRcvd.businessProcStartRcvd  ["+DateUtils.format(businessProcStartRcvd) +"] ");
                    //                  log.info(getLogPrefix()+"D)  msgRcvd.jmsTimestamp           ["+DateUtils.format(jmsTimestampRcvd)      +"] diff ["+(jmsTimestampRcvd-businessProcStartSent)+"]");
                    //                  log.info(getLogPrefix()+"E)  msgRcvd.businessProcFinishRcvd ["+DateUtils.format(businessProcFinishRcvd)+"] diff ["+(businessProcFinishRcvd-jmsTimestampRcvd)+"] (=time spend on IFSA bus sending result?)");
                    //                  log.info(getLogPrefix()+"F)  timestampAfterRcvd             ["+DateUtils.format(timestampAfterRcvd)    +"] diff ["+(timestampAfterRcvd-businessProcFinishRcvd)+"] ");
                    //                  log.info(getLogPrefix()+"business processing time (E-C1) ["+(businessProcFinishRcvd-businessProcStartSent)+"] ");
                }
                //               if (businessProcessTimes!=null) {                  
                //                  businessProcessTimes.addValue(businessProcFinishRcvd-businessProcStartSent);
                //               }
            } catch (JMSException e) {
                log.warn(getLogPrefix() + "exception determining processing times", e);
            }
            if (msg instanceof TextMessage) {
                result = ((TextMessage) msg).getText();
            } else {
                if (msg.getClass().getName().endsWith("IFSAReportMessage")) {
                    if (msg instanceof IFSAReportMessage) {
                        IFSAReportMessage irm = (IFSAReportMessage) msg;
                        if (isThrowExceptions()) {
                            throw new SenderException(getLogPrefix() + "received IFSAReportMessage ["
                                    + ToStringBuilder.reflectionToString(irm) + "], NoReplyReason ["
                                    + irm.getNoReplyReason() + "]");
                        }
                        log.warn(getLogPrefix() + "received IFSAReportMessage ["
                                + ToStringBuilder.reflectionToString(irm) + "], NoReplyReason ["
                                + irm.getNoReplyReason() + "]");
                        result = "<IFSAReport>" + "<NoReplyReason>" + irm.getNoReplyReason()
                                + "</NoReplyReason>" + "</IFSAReport>";

                    }
                } else {
                    log.warn(getLogPrefix() + "received neither TextMessage nor IFSAReportMessage but ["
                            + msg.getClass().getName() + "]");
                    result = msg.toString();
                }
            }
            if (result == null) {
                log.info(getLogPrefix() + "received null reply");
            } else {
                if (log.isDebugEnabled()) {
                    if (AppConstants.getInstance().getBoolean("log.logIntermediaryResults", false)) {
                        log.debug(getLogPrefix() + "received reply [" + result + "]");
                    } else {
                        log.debug(getLogPrefix() + "received reply");
                    }
                } else {
                    log.info(getLogPrefix() + "received reply");
                }
            }
        } else {
            result = sentMessage.getJMSMessageID();
        }
    } catch (JMSException e) {
        throw new SenderException(getLogPrefix() + "caught JMSException in sendMessage()", e);
    } catch (IfsaException e) {
        throw new SenderException(getLogPrefix() + "caught IfsaException in sendMessage()", e);
    } finally {
        if (sender != null) {
            try {
                log.debug(getLogPrefix() + "closing sender");
                sender.close();
            } catch (JMSException e) {
                log.debug(getLogPrefix() + "Exception closing sender", e);
            }
        }
        closeSession(session);
    }
    if (isThrowExceptions() && result != null && result.startsWith("<exception>")) {
        throw new SenderException("Retrieved exception message from IFSA bus: " + result);
    }
    return result;
}

From source file:org.ala.jms.service.JmsMessageListener.java

public Method getMethod(Message message) {
    try {//www  .ja v  a2  s.  c  om
        logger.debug("Message type: " + message.getClass().getName() + ", TextMessage: "
                + (message instanceof TextMessage));
        if (message.getStringProperty(MESSAGE_METHOD) != null
                && !"".equals(message.getStringProperty(MESSAGE_METHOD))) {
            return Method.valueOf(message.getStringProperty(MESSAGE_METHOD));
        }
        if (message instanceof TextMessage) {
            //parse the message
            TextMessage tm = (TextMessage) message;
            String json = tm.getText();
            if (StringUtils.isNotEmpty(json)) {
                Map<String, Object> omap = mapper.readValue(json, new TypeReference<HashMap<String, Object>>() {
                });
                String messageMethod = (String) omap.get("messageMethod");
                if (StringUtils.isNotEmpty(messageMethod)) {
                    return Method.valueOf(messageMethod);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:org.apache.activemq.usecases.RequestReplyToTopicViaThreeNetworkHopsTest.java

public static String fmtMsgInfo(Message msg) throws Exception {
    StringBuilder msg_desc;//from w ww  . ja  va  2 s  . c  o  m
    String prop;
    Enumeration<?> prop_enum;

    msg_desc = new StringBuilder();
    msg_desc = new StringBuilder();

    if (msg instanceof TextMessage) {
        msg_desc.append(((TextMessage) msg).getText());
    } else {
        msg_desc.append("[");
        msg_desc.append(msg.getClass().getName());
        msg_desc.append("]");
    }

    prop_enum = msg.getPropertyNames();
    while (prop_enum.hasMoreElements()) {
        prop = (String) prop_enum.nextElement();
        msg_desc.append("; ");
        msg_desc.append(prop);
        msg_desc.append("=");
        msg_desc.append(msg.getStringProperty(prop));
    }

    return msg_desc.toString();
}

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

/**
 * Set the SOAPEnvelope to the Axis2 MessageContext, from the JMS Message passed in
 * @param message the JMS message read/*from   w  ww. ja v  a  2 s. c  om*/
 * @param msgContext the Axis2 MessageContext to be populated
 * @param contentType content type for the message
 * @throws AxisFault
 * @throws JMSException
 */
public static void setSOAPEnvelope(Message message, MessageContext msgContext, String contentType)
        throws AxisFault, JMSException {

    if (contentType == null) {
        if (message instanceof TextMessage) {
            contentType = "text/plain";
        } else {
            contentType = "application/octet-stream";
        }
        if (log.isDebugEnabled()) {
            log.debug("No content type specified; assuming " + contentType);
        }
    }

    int index = contentType.indexOf(';');
    String type = index > 0 ? contentType.substring(0, index) : contentType;
    Builder builder = BuilderUtil.getBuilderFromSelector(type, msgContext);
    if (builder == null) {
        if (log.isDebugEnabled()) {
            log.debug("No message builder found for type '" + type + "'. Falling back to SOAP.");
        }
        builder = new SOAPBuilder();
    }

    OMElement documentElement;
    if (message instanceof BytesMessage) {
        // Extract the charset encoding from the content type and
        // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this.
        String charSetEnc = null;
        try {
            if (contentType != null) {
                charSetEnc = new ContentType(contentType).getParameter("charset");
            }
        } catch (ParseException ex) {
            // ignore
        }
        msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);

        if (builder instanceof DataSourceMessageBuilder) {
            documentElement = ((DataSourceMessageBuilder) builder).processDocument(
                    new BytesMessageDataSource((BytesMessage) message), contentType, msgContext);
        } else {
            documentElement = builder.processDocument(new BytesMessageInputStream((BytesMessage) message),
                    contentType, msgContext);
        }
    } else if (message instanceof TextMessage) {
        TextMessageBuilder textMessageBuilder;
        if (builder instanceof TextMessageBuilder) {
            textMessageBuilder = (TextMessageBuilder) builder;
        } else {
            textMessageBuilder = new TextMessageBuilderAdapter(builder);
        }
        String content = ((TextMessage) message).getText();
        documentElement = textMessageBuilder.processDocument(content, contentType, msgContext);
    } else {
        handleException("Unsupported JMS message type " + message.getClass().getName());
        return; // Make compiler happy
    }
    msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));
}

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

/**
 * Get the length of the message in bytes
 * @param message/* ww w . ja va 2s. c om*/
 * @return message size (or approximation) in bytes
 * @throws JMSException
 */
public static long getMessageSize(Message message) throws JMSException {
    if (message instanceof BytesMessage) {
        return JMSUtils.getBodyLength((BytesMessage) message);
    } else if (message instanceof TextMessage) {
        // TODO: Converting the whole message to a byte array is too much overhead just to determine the message size.
        //       Anyway, the result is not accurate since we don't know what encoding the JMS provider uses.
        return ((TextMessage) message).getText().getBytes().length;
    } else {
        log.warn("Can't determine size of JMS message; unsupported message type : "
                + message.getClass().getName());
        return 0;
    }
}

From source file:org.apache.axis2.transport.jms.LogAspect.java

@Before("(call(void javax.jms.MessageProducer.send(javax.jms.Message)) ||"
        + " call(void javax.jms.TopicPublisher.publish(javax.jms.Message))) && args(message)")
public void beforeSend(Message message) {
    try {//from w ww  .  j a v  a 2s  . c  o  m
        OutputStream out = LogManager.INSTANCE.createLog("jms");
        try {
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(out), false);
            pw.println("Type: " + message.getClass().getName());
            pw.println("JMS message ID: " + message.getJMSMessageID());
            pw.println("JMS correlation ID: " + message.getJMSCorrelationID());
            pw.println("JMS reply to: " + message.getJMSReplyTo());
            for (Enumeration<?> e = message.getPropertyNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                pw.print(name);
                pw.print(": ");
                pw.println(message.getStringProperty(name));
            }
            pw.println();
            pw.flush();
            if (message instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage) message;
                bytesMessage.reset();
                IOUtils.copy(new BytesMessageInputStream(bytesMessage), out);
            } else if (message instanceof TextMessage) {
                pw.print(((TextMessage) message).getText());
                pw.flush();
            }
        } finally {
            out.close();
        }
    } catch (Throwable ex) {
        log.error("Failed to dump JMS message", ex);
    }
}

From source file:org.apache.stratos.messaging.broker.connect.amqp.AmqpTopicSubscriber.java

@Override
public void subscribe() {
    try {//from  ww  w. ja va  2  s. c  om
        TopicSession topicSession = newSession();
        Topic topic = lookupTopic(topicName);
        if (topic == null) {
            // if topic doesn't exist, create it.
            topic = topicSession.createTopic(topicName);
        }
        javax.jms.TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic);
        topicSubscriber.setMessageListener(new javax.jms.MessageListener() {
            @Override
            public void onMessage(Message message) {
                try {
                    String topicName = null, messageText = null;

                    if (message instanceof ActiveMQTextMessage) {
                        ActiveMQTextMessage textMessage = (ActiveMQTextMessage) message;
                        topicName = textMessage.getDestination().getPhysicalName();
                        messageText = textMessage.getText();
                    } else if (message instanceof ActiveMQBytesMessage) {
                        ActiveMQBytesMessage bytesMessage = (ActiveMQBytesMessage) message;
                        topicName = bytesMessage.getDestination().getPhysicalName();
                        messageText = new String(bytesMessage.getContent().data);
                    } else {
                        throw new RuntimeException(
                                String.format("Could not receive message, " + "unknown JMS message type: %s",
                                        message.getClass().getName()));
                    }
                    org.apache.stratos.messaging.domain.Message message_ = new org.apache.stratos.messaging.domain.Message(
                            topicName, messageText);
                    messageListener.messageReceived(message_);
                } catch (Exception e) {
                    String error = "An error occurred when receiving message";
                    log.error(error, e);
                }
            }
        });
    } catch (Exception e) {
        String message = "Could not subscribe to topic: " + topicName;
        log.error(message, e);
        throw new MessagingException(message, e);
    }
}

From source file:org.jbpm.ejb.impl.CommandListenerBean.java

protected Command extractCommand(Message message) throws JMSException {
    Command command = null;//from   ww  w. j a  v  a  2s.  c  o  m
    if (message instanceof ObjectMessage) {
        log.debug("deserializing command from jms message...");
        ObjectMessage objectMessage = (ObjectMessage) message;
        Serializable object = objectMessage.getObject();
        if (object instanceof Command) {
            command = (Command) object;
        } else {
            log.warn("ignoring object message cause it isn't a command '" + object + "'"
                    + (object != null ? " (" + object.getClass().getName() + ")" : ""));
        }
    } else {
        log.warn("ignoring message '" + message + "' cause it isn't an ObjectMessage ("
                + message.getClass().getName() + ")");
    }
    return command;
}