Example usage for javax.jms Message getJMSCorrelationID

List of usage examples for javax.jms Message getJMSCorrelationID

Introduction

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

Prototype


String getJMSCorrelationID() throws JMSException;

Source Link

Document

Gets the correlation ID for the message.

Usage

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

protected String retrieveIdFromMessage(Message message, Map threadContext) throws ListenerException {
    String cid = "unset";
    String mode = "unknown";
    String id = "unset";
    Date tsSent = null;//from  w w  w. j a v  a 2s .  co m
    Destination replyTo = null;
    try {
        mode = deliveryModeToString(message.getJMSDeliveryMode());
    } catch (JMSException ignore) {
        log.debug("ignoring JMSException in getJMSDeliveryMode()", ignore);
    }
    // --------------------------
    // retrieve MessageID
    // --------------------------
    try {
        id = message.getJMSMessageID();
    } catch (JMSException ignore) {
        log.debug("ignoring JMSException in getJMSMessageID()", ignore);
    }
    // --------------------------
    // retrieve CorrelationID
    // --------------------------
    try {
        if (isForceMessageIdAsCorrelationId()) {
            if (log.isDebugEnabled())
                log.debug("forcing the messageID to be the correlationID");
            cid = id;
        } else {
            cid = message.getJMSCorrelationID();
            if (cid == null) {
                cid = id;
                log.debug("Setting correlation ID to MessageId");
            }
        }
    } catch (JMSException ignore) {
        log.debug("ignoring JMSException in getJMSCorrelationID()", ignore);
    }
    // --------------------------
    // retrieve TimeStamp
    // --------------------------
    try {
        long lTimeStamp = message.getJMSTimestamp();
        tsSent = new Date(lTimeStamp);

    } catch (JMSException ignore) {
        log.debug("ignoring JMSException in getJMSTimestamp()", ignore);
    }
    // --------------------------
    // retrieve ReplyTo address
    // --------------------------
    try {
        replyTo = message.getJMSReplyTo();

    } catch (JMSException ignore) {
        log.debug("ignoring JMSException in getJMSReplyTo()", ignore);
    }

    if (log.isDebugEnabled()) {
        log.debug(getLogPrefix() + "listener on [" + getDestinationName()
                + "] got message with JMSDeliveryMode=[" + mode + "] \n  JMSMessageID=[" + id
                + "] \n  JMSCorrelationID=[" + cid + "] \n  Timestamp Sent=[" + DateUtils.format(tsSent)
                + "] \n  ReplyTo=[" + ((replyTo == null) ? "none" : replyTo.toString()) + "] \n Message=["
                + message.toString() + "]");
    }
    PipeLineSessionBase.setListenerParameters(threadContext, id, cid, null, tsSent);
    threadContext.put("timestamp", tsSent);
    threadContext.put("replyTo", replyTo);
    try {
        if (getAckMode() == Session.CLIENT_ACKNOWLEDGE) {
            message.acknowledge();
            log.debug("Listener on [" + getDestinationName() + "] acknowledged message");
        }
    } catch (JMSException e) {
        log.error("Warning in ack", e);
    }
    return cid;
}

From source file:org.apache.servicemix.jms.jca.JcaConsumerProcessor.java

public void process(MessageExchange exchange) throws Exception {
    Context context = (Context) pendingMessages.remove(exchange.getExchangeId());
    Message message = (Message) context.getProperty(Message.class.getName());
    Message response = null;/*from ww  w.  ja v a 2  s  . c  o  m*/
    Connection connection = null;
    try {
        if (exchange.getStatus() == ExchangeStatus.DONE) {
            return;
        } else if (exchange.getStatus() == ExchangeStatus.ERROR) {
            if (endpoint.isRollbackOnError()) {
                TransactionManager tm = (TransactionManager) endpoint.getServiceUnit().getComponent()
                        .getComponentContext().getTransactionManager();
                tm.setRollbackOnly();
                return;
            } else if (exchange instanceof InOnly) {
                LOG.info("Exchange in error: " + exchange, exchange.getError());
                return;
            } else {
                connection = connectionFactory.createConnection();
                Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
                Exception error = exchange.getError();
                if (error == null) {
                    error = new Exception("Exchange in error");
                }
                response = session.createObjectMessage(error);
                MessageProducer producer = session.createProducer(message.getJMSReplyTo());
                if (endpoint.isUseMsgIdInResponse()) {
                    response.setJMSCorrelationID(message.getJMSMessageID());
                } else {
                    response.setJMSCorrelationID(message.getJMSCorrelationID());
                }
                producer.send(response);
            }
        } else {
            connection = connectionFactory.createConnection();
            Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
            response = fromNMSResponse(exchange, context, session);
            if (response != null) {
                MessageProducer producer = session.createProducer(message.getJMSReplyTo());
                if (endpoint.isUseMsgIdInResponse()) {
                    response.setJMSCorrelationID(message.getJMSMessageID());
                } else {
                    response.setJMSCorrelationID(message.getJMSCorrelationID());
                }
                producer.send(response);
            }
        }
    } finally {
        if (connection != null) {
            connection.close();
        }
        if (exchange.getStatus() == ExchangeStatus.ACTIVE) {
            exchange.setStatus(ExchangeStatus.DONE);
            channel.send(exchange);
        }
    }
}

From source file:com.cws.esolutions.agent.mq.MQMessageHandler.java

public void onMessage(final Message message) {
    final String methodName = MQMessageHandler.CNAME + "#onMessage(final Message message)";

    if (DEBUG) {//w  w  w. j av  a2  s. co m
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Message: {}", message);
    }

    final Session session = agentBean.getSession();
    final MessageProducer producer = agentBean.getProducer();
    final Destination destination = MQMessageHandler.agentBean.getResponseQueue();

    if (DEBUG) {
        DEBUGGER.debug("Session: {}", session);
        DEBUGGER.debug("MessageProducer: {}", producer);
        DEBUGGER.debug("Destination: {}", destination);
    }

    try {
        ObjectMessage mqMessage = (ObjectMessage) message;

        if (DEBUG) {
            DEBUGGER.debug("mqMessage: {}", mqMessage);
        }

        if ((StringUtils.equals(MQMessageHandler.serverConfig.getRequestQueue(),
                MQMessageHandler.serverConfig.getResponseQueue()))
                && (mqMessage.getObject() instanceof AgentResponse)) {
            return;
        }

        AgentRequest agentRequest = (AgentRequest) mqMessage.getObject();

        if (DEBUG) {
            DEBUGGER.debug("agentRequest: {}", agentRequest);
        }

        mqMessage.acknowledge();

        AgentResponse agentResponse = MQMessageHandler.processor.processRequest(agentRequest);

        if (DEBUG) {
            DEBUGGER.debug("AgentResponse: {}", agentResponse);
        }

        ObjectMessage oMessage = session.createObjectMessage(true);
        oMessage.setObject(agentResponse);
        oMessage.setJMSCorrelationID(message.getJMSCorrelationID());

        if (DEBUG) {
            DEBUGGER.debug("ObjectMessage: {}", oMessage);
        }

        producer.send(destination, oMessage);
    } catch (JMSException jx) {
        ERROR_RECORDER.error(jx.getMessage(), jx);
    } catch (AgentException ax) {
        ERROR_RECORDER.error(ax.getMessage(), ax);
    }
}

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

public String sendMessage(String correlationID, String message, ParameterResolutionContext prc,
        String soapHeader) throws SenderException, TimeOutException {
    Session s = null;/*from   w  w  w .j a v  a2s.  c  om*/
    MessageProducer mp = null;

    ParameterValueList pvl = null;
    if (prc != null && paramList != null) {
        try {
            pvl = prc.getValues(paramList);
        } catch (ParameterException e) {
            throw new SenderException(getLogPrefix() + "cannot extract parameters", e);
        }
    }

    if (isSoap()) {
        if (soapHeader == null) {
            if (pvl != null && StringUtils.isNotEmpty(getSoapHeaderParam())) {
                ParameterValue soapHeaderParamValue = pvl.getParameterValue(getSoapHeaderParam());
                if (soapHeaderParamValue == null) {
                    log.warn("no SoapHeader found using parameter [" + getSoapHeaderParam() + "]");
                } else {
                    soapHeader = soapHeaderParamValue.asStringValue("");
                }
            }
        }
        message = soapWrapper.putInEnvelope(message, getEncodingStyleURI(), getServiceNamespaceURI(),
                soapHeader);
        if (log.isDebugEnabled())
            log.debug(getLogPrefix() + "correlationId [" + correlationID + "] soap message [" + message + "]");
    }
    try {
        s = createSession();
        mp = getMessageProducer(s, getDestination(prc));
        Destination replyQueue = null;

        // create message
        Message msg = createTextMessage(s, correlationID, message);

        if (getMessageType() != null) {
            msg.setJMSType(getMessageType());
        }
        if (getDeliveryModeInt() > 0) {
            msg.setJMSDeliveryMode(getDeliveryModeInt());
            mp.setDeliveryMode(getDeliveryModeInt());
        }
        if (getPriority() >= 0) {
            msg.setJMSPriority(getPriority());
            mp.setPriority(getPriority());
        }

        // set properties
        if (pvl != null) {
            setProperties(msg, pvl);
        }
        if (replyToName != null) {
            replyQueue = getDestination(replyToName);
        } else {
            if (isSynchronous()) {
                replyQueue = getMessagingSource().getDynamicReplyQueue(s);
            }
        }
        if (replyQueue != null) {
            msg.setJMSReplyTo(replyQueue);
            if (log.isDebugEnabled())
                log.debug("replyTo set to queue [" + replyQueue.toString() + "]");
        }

        // send message   
        send(mp, msg);
        if (log.isDebugEnabled()) {
            log.debug("[" + getName() + "] " + "sent message [" + message + "] " + "to [" + mp.getDestination()
                    + "] " + "msgID [" + msg.getJMSMessageID() + "] " + "correlationID ["
                    + msg.getJMSCorrelationID() + "] " + "using deliveryMode [" + getDeliveryMode() + "] "
                    + ((replyToName != null) ? "replyTo [" + replyToName + "]" : ""));
        } else {
            if (log.isInfoEnabled()) {
                log.info("[" + getName() + "] " + "sent message to [" + mp.getDestination() + "] " + "msgID ["
                        + msg.getJMSMessageID() + "] " + "correlationID [" + msg.getJMSCorrelationID() + "] "
                        + "using deliveryMode [" + getDeliveryMode() + "] "
                        + ((replyToName != null) ? "replyTo [" + replyToName + "]" : ""));
            }
        }
        if (isSynchronous()) {
            String replyCorrelationId = null;
            if (replyToName != null) {
                if ("CORRELATIONID".equalsIgnoreCase(getLinkMethod())) {
                    replyCorrelationId = correlationID;
                } else if ("CORRELATIONID_FROM_MESSAGE".equalsIgnoreCase(getLinkMethod())) {
                    replyCorrelationId = msg.getJMSCorrelationID();
                } else {
                    replyCorrelationId = msg.getJMSMessageID();
                }
            }
            if (log.isDebugEnabled())
                log.debug("[" + getName() + "] start waiting for reply on [" + replyQueue + "] requestMsgId ["
                        + msg.getJMSMessageID() + "] replyCorrelationId [" + replyCorrelationId + "] for ["
                        + getReplyTimeout() + "] ms");
            MessageConsumer mc = getMessageConsumerForCorrelationId(s, replyQueue, replyCorrelationId);
            try {
                Message rawReplyMsg = mc.receive(getReplyTimeout());
                if (rawReplyMsg == null) {
                    throw new TimeOutException("did not receive reply on [" + replyQueue + "] requestMsgId ["
                            + msg.getJMSMessageID() + "] replyCorrelationId [" + replyCorrelationId
                            + "] within [" + getReplyTimeout() + "] ms");
                }
                return getStringFromRawMessage(rawReplyMsg, prc != null ? prc.getSession() : null, isSoap(),
                        getReplySoapHeaderSessionKey(), soapWrapper);
            } finally {
                if (mc != null) {
                    try {
                        mc.close();
                    } catch (JMSException e) {
                        log.warn("JmsSender [" + getName()
                                + "] got exception closing message consumer for reply", e);
                    }
                }
            }
        }
        return msg.getJMSMessageID();
    } catch (JMSException e) {
        throw new SenderException(e);
    } catch (IOException e) {
        throw new SenderException(e);
    } catch (NamingException e) {
        throw new SenderException(e);
    } catch (DomBuilderException e) {
        throw new SenderException(e);
    } catch (TransformerException e) {
        throw new SenderException(e);
    } catch (JmsException e) {
        throw new SenderException(e);
    } finally {
        if (mp != null) {
            try {
                mp.close();
            } catch (JMSException e) {
                log.warn("JmsSender [" + getName() + "] got exception closing message producer", e);
            }
        }
        closeSession(s);
    }
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.JMSInjectHandler.java

/**
 * Invoke the mediation logic for the passed message
 * *//*from   w  ww  . ja va2s  .c  o  m*/
public boolean invoke(Object object, String name) throws SynapseException {

    Message msg = (Message) object;
    try {
        org.apache.synapse.MessageContext msgCtx = createMessageContext();
        msgCtx.setProperty("inbound.endpoint.name", name);
        InboundEndpoint inboundEndpoint = msgCtx.getConfiguration().getInboundEndpoint(name);
        CustomLogSetter.getInstance().setLogAppender(inboundEndpoint.getArtifactContainerName());
        String contentType = msg.getJMSType();

        if (contentType == null || contentType.trim().equals("")) {
            String contentTypeProperty = jmsProperties.getProperty(JMSConstants.CONTENT_TYPE_PROPERTY);
            if (contentTypeProperty != null) {
                contentType = msg.getStringProperty(contentTypeProperty);
            }
        } else {
            msgCtx.setProperty(JMSConstants.JMS_MESSAGE_TYPE, contentType);
        }

        if (contentType == null || contentType.trim().equals("")) {
            contentType = jmsProperties.getProperty(JMSConstants.CONTENT_TYPE);
        }
        if (log.isDebugEnabled()) {
            log.debug("Processed JMS Message of Content-type : " + contentType);
        }
        MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx)
                .getAxis2MessageContext();
        //setting transport headers
        axis2MsgCtx.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS,
                JMSUtils.getTransportHeaders(msg, axis2MsgCtx));
        // set the JMS Message ID as the Message ID of the MessageContext
        try {
            msgCtx.setMessageID(msg.getJMSMessageID());
            String jmsCorrelationID = msg.getJMSCorrelationID();
            if (jmsCorrelationID != null && !jmsCorrelationID.isEmpty()) {
                msgCtx.setProperty(JMSConstants.JMS_COORELATION_ID, jmsCorrelationID);
            } else {
                msgCtx.setProperty(JMSConstants.JMS_COORELATION_ID, msg.getJMSMessageID());
            }
        } catch (JMSException ignore) {
            log.warn("Error getting the COORELATION ID from the message.");
        }

        // Handle dual channel
        Destination replyTo = msg.getJMSReplyTo();
        if (replyTo != null) {
            msgCtx.setProperty(SynapseConstants.IS_INBOUND, true);
            // Create the cachedJMSConnectionFactory with the existing
            // connection
            CachedJMSConnectionFactory cachedJMSConnectionFactory = new CachedJMSConnectionFactory(
                    jmsProperties, connection);
            String strUserName = jmsProperties.getProperty(JMSConstants.PARAM_JMS_USERNAME);
            String strPassword = jmsProperties.getProperty(JMSConstants.PARAM_JMS_PASSWORD);
            JMSReplySender jmsReplySender = new JMSReplySender(replyTo, cachedJMSConnectionFactory, strUserName,
                    strPassword);
            msgCtx.setProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, jmsReplySender);
        } else if (replyDestination != null) {
            msgCtx.setProperty(SynapseConstants.IS_INBOUND, true);
            // Create the cachedJMSConnectionFactory with the existing
            // connection
            CachedJMSConnectionFactory cachedJMSConnectionFactory = new CachedJMSConnectionFactory(
                    jmsProperties, connection);
            String strUserName = jmsProperties.getProperty(JMSConstants.PARAM_JMS_USERNAME);
            String strPassword = jmsProperties.getProperty(JMSConstants.PARAM_JMS_PASSWORD);
            JMSReplySender jmsReplySender = new JMSReplySender(replyDestination, cachedJMSConnectionFactory,
                    strUserName, strPassword);
            msgCtx.setProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, jmsReplySender);
        }

        // Determine the message builder to use
        Builder builder;
        if (contentType == null) {
            log.debug("No content type specified. Using SOAP builder.");
            builder = new SOAPBuilder();
        } else {
            int index = contentType.indexOf(';');
            String type = index > 0 ? contentType.substring(0, index) : contentType;
            builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx);
            if (builder == null) {
                if (log.isDebugEnabled()) {
                    log.debug("No message builder found for type '" + type + "'. Falling back to SOAP.");
                }
                builder = new SOAPBuilder();
            }
        }
        OMElement documentElement = null;
        // set the message payload to the message context
        try {
            if (msg instanceof TextMessage) {
                String message = ((TextMessage) msg).getText();
                InputStream in = new AutoCloseInputStream(new ByteArrayInputStream(message.getBytes()));
                documentElement = builder.processDocument(in, contentType, axis2MsgCtx);
            } else if (msg instanceof BytesMessage) {
                if (builder instanceof DataSourceMessageBuilder) {
                    documentElement = ((DataSourceMessageBuilder) builder).processDocument(
                            new BytesMessageDataSource((BytesMessage) msg), contentType, axis2MsgCtx);
                } else {
                    documentElement = builder.processDocument(new BytesMessageInputStream((BytesMessage) msg),
                            contentType, axis2MsgCtx);
                }
            } else if (msg instanceof MapMessage) {
                documentElement = convertJMSMapToXML((MapMessage) msg);
            }
        } catch (Exception ex) {
            // Handle message building error
            log.error("Error while building the message", ex);
            msgCtx.setProperty(SynapseConstants.ERROR_CODE, GenericConstants.INBOUND_BUILD_ERROR);
            msgCtx.setProperty(SynapseConstants.ERROR_MESSAGE, ex.getMessage());
            SequenceMediator faultSequence = getFaultSequence(msgCtx, inboundEndpoint);
            faultSequence.mediate(msgCtx);

            if (isRollback(msgCtx)) {
                return false;
            }
            return true;
        }

        // Setting JMSXDeliveryCount header on the message context
        try {
            int deliveryCount = msg.getIntProperty("JMSXDeliveryCount");
            msgCtx.setProperty(JMSConstants.DELIVERY_COUNT, deliveryCount);
        } catch (NumberFormatException nfe) {
            if (log.isDebugEnabled()) {
                log.debug("JMSXDeliveryCount is not set in the received message");
            }
        }

        // Inject the message to the sequence.
        msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));
        if (injectingSeq == null || injectingSeq.equals("")) {
            log.error("Sequence name not specified. Sequence : " + injectingSeq);
            return false;
        }
        SequenceMediator seq = (SequenceMediator) synapseEnvironment.getSynapseConfiguration()
                .getSequence(injectingSeq);
        if (seq != null) {
            if (log.isDebugEnabled()) {
                log.debug("injecting message to sequence : " + injectingSeq);
            }
            if (!seq.isInitialized()) {
                seq.init(synapseEnvironment);
            }
            SequenceMediator faultSequence = getFaultSequence(msgCtx, inboundEndpoint);
            MediatorFaultHandler mediatorFaultHandler = new MediatorFaultHandler(faultSequence);
            msgCtx.pushFaultHandler(mediatorFaultHandler);

            if (!synapseEnvironment.injectInbound(msgCtx, seq, sequential)) {
                return false;
            }
        } else {
            log.error("Sequence: " + injectingSeq + " not found");
        }

        if (isRollback(msgCtx)) {
            return false;
        }
    } catch (SynapseException se) {
        throw se;
    } catch (Exception e) {
        log.error("Error while processing the JMS Message", e);
        throw new SynapseException("Error while processing the JMS Message", e);
    }
    return true;
}

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

private static String formatHeaders(Message message) {
    Destination dest = null;//from  w  w  w  .  j  a v a 2 s . c o  m
    int delMode = 0;
    long expiration = 0;
    Time expTime = null;
    int priority = 0;
    String msgID = null;
    long timestamp = 0;
    Time timestampTime = null;
    String correlID = null;
    Destination replyTo = null;
    boolean redelivered = false;
    String type = null;

    StringBuilder sb = new StringBuilder();
    try {

        try {
            dest = message.getJMSDestination();
            sb.append("  JMSDestination: ");
            sb.append(dest);
            sb.append("\n");
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSDestination header\n", e);
        }

        try {
            delMode = message.getJMSDeliveryMode();
            if (delMode == DeliveryMode.NON_PERSISTENT) {
                sb.append("  JMSDeliveryMode: non-persistent\n");
            } else if (delMode == DeliveryMode.PERSISTENT) {
                sb.append("  JMSDeliveryMode: persistent\n");
            } else {
                sb.append("  JMSDeliveryMode: neither persistent nor non-persistent; error\n");
            }
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSDeliveryMode header\n", e);
        }

        try {
            expiration = message.getJMSExpiration();
            if (expiration != 0) {
                expTime = new Time(expiration);
                sb.append("  JMSExpiration: ");
                sb.append(expTime);
                sb.append("\n");
            } else {
                sb.append("  JMSExpiration: 0\n");
            }
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSExpiration header\n", e);
        }

        try {
            priority = message.getJMSPriority();
            sb.append("  JMSPriority: ");
            sb.append(priority);
            sb.append("\n");
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSPriority header\n", e);
        }

        try {
            msgID = message.getJMSMessageID();
            sb.append("  JMSMessageID: ");
            sb.append(msgID);
            sb.append("\n");
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSMessageID header\n", e);
        }

        try {
            timestamp = message.getJMSTimestamp();
            if (timestamp != 0) {
                timestampTime = new Time(timestamp);
                sb.append("  JMSTimestamp: ");
                sb.append(timestampTime);
                sb.append("\n");
            } else {
                sb.append("  JMSTimestamp: 0\n");
            }
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSTimestamp header\n", e);
        }

        try {
            correlID = message.getJMSCorrelationID();
            sb.append("  JMSCorrelationID: ");
            sb.append(correlID);
            sb.append("\n");
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSCorrelationID header\n", e);
        }

        try {
            replyTo = message.getJMSReplyTo();
            sb.append("  JMSReplyTo: ");
            sb.append(replyTo);
            sb.append("\n");
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSReplyTo header\n", e);
        }

        try {
            redelivered = message.getJMSRedelivered();
            sb.append("  JMSRedelivered: ");
            sb.append(redelivered);
            sb.append("\n");
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSRedelivered header\n", e);
        }

        try {
            type = message.getJMSType();
            sb.append("  JMSType: ");
            sb.append(type);
            sb.append("\n");
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSType header\n", e);
        }

    } catch (Exception e) {
        log.log(Level.WARNING, "Unable to generate JMS headers\n", e);
    }
    return sb.toString();
}

From source file:org.nuclos.client.main.MainController.java

private void handleMessage(final Message msg) {
    try {/*from ww w .j a  v a  2  s.c  o m*/
        if ((msg.getJMSCorrelationID() == null
                || msg.getJMSCorrelationID().equals(MainController.this.getUserName()))
                && msg instanceof ObjectMessage) {
            final Object objMessage = ((ObjectMessage) msg).getObject();

            if (objMessage.getClass().equals(ApiMessageImpl.class)) {
                final ApiMessageImpl apiMsg = (ApiMessageImpl) ((ObjectMessage) msg).getObject();
                LOG.info("Handle " + apiMsg);
                Component parent = null;
                if (apiMsg.getReceiverId() != null) {
                    MainFrameTab target = MainFrameTab.getMainFrameTab(apiMsg.getReceiverId());
                    parent = target;
                    if (target != null) {
                        if (apiMsg.getMessage().isOverlay()) {
                            OverlayOptionPane.showMessageDialog(target, apiMsg.getMessage().getMessage(),
                                    apiMsg.getMessage().getTitle(), new OvOpAdapter() {
                                    });
                            return;
                        }
                    } else {
                        LOG.warn(String.format("Receiver with id %s not found!", apiMsg.getReceiverId()));
                    }
                }

                if (parent == null) {
                    parent = Main.getInstance().getMainFrame();
                }
                JOptionPane.showMessageDialog(parent, apiMsg.getMessage().getMessage(),
                        apiMsg.getMessage().getTitle(), JOptionPane.INFORMATION_MESSAGE);
            } else if (objMessage.getClass().equals(RuleNotification.class)) {
                final RuleNotification notification = (RuleNotification) ((ObjectMessage) msg).getObject();
                getNotificationDialog().addMessage(notification);
                switch (notification.getPriority()) {
                case LOW:
                    // just add the message, nothing else.
                    break;
                case NORMAL:
                    getMainFrame().getMessagePanel().startFlashing();
                    break;
                case HIGH:
                    getNotificationDialog().setVisible(true);
                    break;
                default:
                    LOG.warn("Undefined message priority: " + notification.getPriority());
                }
                LOG.info("Handled RuleNotification " + notification.toDescription());
            } else if (objMessage.getClass().equals(CommandMessage.class)) {
                final CommandMessage command = (CommandMessage) ((ObjectMessage) msg).getObject();
                switch (command.getCommand()) {
                case CommandMessage.CMD_SHUTDOWN:
                    getNotificationDialog().addMessage(new RuleNotification(Priority.HIGH,
                            getSpringLocaleDelegate().getMessage("MainController.19",
                                    "Der Client wird auf Anweisung des Administrators in 10 Sekunden beendet."),
                            "Administrator"));
                    getNotificationDialog().setVisible(true);

                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(10000);
                            } catch (InterruptedException e) {
                                // do nothing
                            } finally {
                                MainController.this.cmdExit();
                            }
                        }
                    });
                    break;
                }
                LOG.info("Handled CommandMessage " + command);
            } else if (objMessage.getClass().equals(CommandInformationMessage.class)) {
                final CommandInformationMessage command = (CommandInformationMessage) ((ObjectMessage) msg)
                        .getObject();
                switch (command.getCommand()) {
                case CommandInformationMessage.CMD_INFO_SHUTDOWN:
                    Object[] options = { "OK" };
                    int decision = JOptionPane.showOptionDialog(getMainFrame(), command.getInfo(),
                            getSpringLocaleDelegate().getMessage("MainController.17",
                                    "Administrator - Passwort\u00e4nderung"),
                            JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options,
                            options[0]);
                    if (decision == 0 || decision == JOptionPane.CLOSED_OPTION
                            || decision == JOptionPane.NO_OPTION) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(10000);
                                } catch (InterruptedException e) {
                                    // do nothing
                                } finally {
                                    MainController.this.cmdExit();
                                }
                            }
                        }, "MainController.handleMessage.cmdExit").run();
                    }
                    break;
                }
                LOG.info("Handled CommandInformationMessage " + command);
            }
        } else {
            LOG.warn(getSpringLocaleDelegate().getMessage("MainController.14",
                    "Message of type {0} received, while an ObjectMessage was expected.",
                    msg.getClass().getName()));
        }
    } catch (JMSException ex) {
        LOG.warn("Exception thrown in JMS message listener.", ex);
    }
}

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

/**
 * Perform actual sending of the JMS message
 *//*  w w w .j a  v a  2s  . c  o m*/
private void sendOverJMS(MessageContext msgCtx, JMSMessageSender messageSender, String contentTypeProperty,
        JMSConnectionFactory jmsConnectionFactory, JMSOutTransportInfo jmsOut) throws AxisFault {

    // convert the axis message context into a JMS Message that we can send over JMS
    Message message = null;
    String correlationId = null;
    try {
        message = createJMSMessage(msgCtx, messageSender.getSession(), contentTypeProperty);
    } catch (JMSException e) {
        handleException("Error creating a JMS message from the message context", e);
    }

    // should we wait for a synchronous response on this same thread?
    boolean waitForResponse = waitForSynchronousResponse(msgCtx);
    Destination replyDestination = jmsOut.getReplyDestination();

    // if this is a synchronous out-in, prepare to listen on the response destination
    if (waitForResponse) {

        String replyDestName = (String) msgCtx.getProperty(JMSConstants.JMS_REPLY_TO);
        if (replyDestName == null && jmsConnectionFactory != null) {
            replyDestName = jmsConnectionFactory.getReplyToDestination();
        }

        String replyDestType = (String) msgCtx.getProperty(JMSConstants.JMS_REPLY_TO_TYPE);
        if (replyDestType == null && jmsConnectionFactory != null) {
            replyDestType = jmsConnectionFactory.getReplyDestinationType();
        }

        if (replyDestName != null) {
            if (jmsConnectionFactory != null) {
                replyDestination = jmsConnectionFactory.getDestination(replyDestName, replyDestType);
            } else {
                replyDestination = jmsOut.getReplyDestination(replyDestName);
            }
        }
        replyDestination = JMSUtils.setReplyDestination(replyDestination, messageSender.getSession(), message);
    }

    try {
        messageSender.send(message, msgCtx);
        metrics.incrementMessagesSent(msgCtx);

    } catch (AxisJMSException e) {
        metrics.incrementFaultsSending();
        handleException("Error sending JMS message", e);
    }

    try {
        metrics.incrementBytesSent(msgCtx, JMSUtils.getMessageSize(message));
    } catch (JMSException e) {
        log.warn("Error reading JMS message size to update transport metrics", e);
    }

    // if we are expecting a synchronous response back for the message sent out
    if (waitForResponse) {
        // TODO ********************************************************************************
        // TODO **** replace with asynchronous polling via a poller task to process this *******
        // information would be given. Then it should poll (until timeout) the
        // requested destination for the response message and inject it from a
        // asynchronous worker thread
        try {
            messageSender.getConnection().start(); // multiple calls are safely ignored
        } catch (JMSException ignore) {
        }

        try {
            String jmsCorrelationID = message.getJMSCorrelationID();
            if (jmsCorrelationID != null && jmsCorrelationID.length() > 0) {
                correlationId = jmsCorrelationID;
            } else {
                correlationId = message.getJMSMessageID();
            }
        } catch (JMSException ignore) {
        }

        // We assume here that the response uses the same message property to
        // specify the content type of the message.
        waitForResponseAndProcess(messageSender.getSession(), replyDestination, msgCtx, correlationId,
                contentTypeProperty);
        // TODO ********************************************************************************
    }
}

From source file:org.oxymores.chronix.engine.RunnerAgent.java

@Override
public void onMessage(Message msg) {
    log.info("Run request received");
    ObjectMessage omsg = (ObjectMessage) msg;
    RunDescription rd;/*w  w w  .  j  a  v  a2s.c o m*/
    RunResult res = null;

    try {
        Object o = omsg.getObject();
        if (!(o instanceof RunDescription)) {
            log.warn("An object was received on the runner queue but was not a RunDescription! Ignored.");
            jmsCommit();
            return;
        }
        rd = (RunDescription) o;
    } catch (JMSException e) {
        log.error(
                "An error occurred during RunDescription reception. Message will stay in queue and will be analysed later",
                e);
        jmsRollback();
        return;
    }

    if (!rd.getHelperExecRequest()) {
        log.info(String.format("Running command %s", rd.getCommand()));
    } else {
        log.debug(String.format("Running helper internal command %s", rd.getCommand()));
    }

    // Log file (only if true run)
    String logFilePath = null;
    String logFileName = null;
    Date start = new Date();
    if (!rd.getHelperExecRequest()) {
        SimpleDateFormat myFormatDir = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat myFormatFile = new SimpleDateFormat("yyyyMMddhhmmssSSS");
        String dd = myFormatDir.format(start);
        String logFileDateDir = FilenameUtils.concat(this.logDbPath, dd);
        if (!(new File(logFileDateDir)).exists() && !(new File(logFileDateDir)).mkdir()) {
            log.fatal("Could not create log directory, failing engine");
            this.broker.stop();
            jmsRollback();
            return;
        }
        logFileName = String.format("%s_%s_%s_%s.log", myFormatFile.format(start),
                rd.getPlaceName().replace(" ", "-"), rd.getActiveSourceName().replace(" ", "-"), rd.getId1());
        logFilePath = FilenameUtils.concat(logFileDateDir, logFileName);
    }

    // Run the command according to its method
    if (rd.getMethod().equals(Constants.JD_METHOD_SHELL)) {
        res = RunnerShell.run(rd, logFilePath, !rd.getHelperExecRequest(), rd.getShouldSendLogFile());
    } else {
        res = new RunResult();
        res.returnCode = -1;
        res.logStart = String.format("An unimplemented exec method (%s) was called!", rd.getMethod());
        log.error(String.format("An unimplemented exec method (%s) was called! Job will be failed.",
                rd.getMethod()));
    }
    res.start = start;
    res.end = new Date();
    res.logFileName = logFileName;
    res.logPath = logFilePath;

    // Copy the engine ids - that way it will be able to identify the launch
    // Part of the ids are in the JMS correlation id too
    res.id1 = rd.getId1();
    res.id2 = rd.getId2();
    res.outOfPlan = rd.getOutOfPlan();

    // Send the result!
    Message response;
    if (!rd.getHelperExecRequest()) {
        InputStream is = null;
        try {
            response = jmsSession.createObjectMessage(res);
            response.setJMSCorrelationID(msg.getJMSCorrelationID());
            jmsProducer.send(msg.getJMSReplyTo(), response);

            if (res.logSizeBytes <= 500000) {
                response = jmsSession.createBytesMessage();
                byte[] bytes = new byte[(int) res.logSizeBytes];
                is = new FileInputStream(res.logPath);
                is.read(bytes);
                IOUtils.closeQuietly(is);

                ((BytesMessage) response).writeBytes(bytes);
                response.setJMSCorrelationID(msg.getJMSCorrelationID());
                response.setStringProperty("FileName", logFileName);
                jmsProducer.send(msg.getJMSReplyTo(), response);
            } else {
                log.warn(
                        "A log file was too big and will not be sent. Only the full log file will be missing - the launch will still appear in the console.");
            }
        } catch (Exception e1) {
            log.error(
                    "The runner was not able to send the result of an execution to the engine. This may corrupt plan execution!",
                    e1);
            IOUtils.closeQuietly(is);
        }
    } else {
        try {
            response = jmsSession.createTextMessage(res.logStart);
            response.setJMSCorrelationID(msg.getJMSCorrelationID());
            jmsProducer.send(msg.getJMSReplyTo(), response);
        } catch (JMSException e1) {
            log.error(
                    "The runner was not able to send the result of a parameter resolution to the engine. This may corrupt plan execution!",
                    e1);
        }
    }

    jmsCommit();
}

From source file:hermes.impl.DefaultXMLHelper.java

public XMLMessage createXMLMessage(ObjectFactory factory, Message message)
        throws JMSException, IOException, EncoderException {
    try {//  ww w.j a v  a2s  .  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);
    }
}