Example usage for javax.jms Message getJMSReplyTo

List of usage examples for javax.jms Message getJMSReplyTo

Introduction

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

Prototype


Destination getJMSReplyTo() throws JMSException;

Source Link

Document

Gets the Destination object to which a reply to this message should be sent.

Usage

From source file:com.chinamobile.bcbsp.comm.ConsumerTool.java

/**
 * Put message into messageQueue with serialize method.
 *//*from  www. j ava2 s  .  c o m*/
public void onMessageOptimistic(Message message) throws IOException {
    messagesReceived++;
    try {
        if (message instanceof BytesMessage) {
            BytesMessage mapMsg = (BytesMessage) message;
            BSPMessage bspMsg;
            int packSize = mapMsg.readInt();
            int count = 0;
            int partitionID;
            String srcVertexID;
            String dstVertexID;
            byte[] tag;
            byte[] data;
            int tagLen;
            int dataLen;
            while (count < packSize) {
                partitionID = mapMsg.readInt();
                dstVertexID = mapMsg.readUTF();
                tagLen = mapMsg.readInt();
                tag = new byte[tagLen];
                mapMsg.readBytes(tag);
                dataLen = mapMsg.readInt();
                data = new byte[dataLen];
                mapMsg.readBytes(data);
                // bspMsg = new BSPMessage(partitionID, dstVertexID, tag, data);
                // dst is message if it is not null.
                bspMsg = new BSPMessage(partitionID, dstVertexID, tag, data);
                this.messageQueues.incomeAMessage(dstVertexID, bspMsg);
                this.messageCount++;
                this.messageBytesCount += bspMsg.size();
                count++;
            }
        } else {
            // Message received is not ObjectMessage.
            LOG.error("[ConsumerTool] Message received is not BytesMessage!");
        }
        if (message.getJMSReplyTo() != null) {
            replyProducer.send(message.getJMSReplyTo(),
                    session.createTextMessage("Reply: " + message.getJMSMessageID()));
        }
        if (transacted) {
            if ((messagesReceived % batch) == 0) {
                LOG.info("Commiting transaction for last " + batch + " messages; messages so far = "
                        + messagesReceived);
                session.commit();
            }
        } else if (ackMode == Session.CLIENT_ACKNOWLEDGE) {
            if ((messagesReceived % batch) == 0) {
                LOG.info("Acknowledging last " + batch + " messages; messages so far = " + messagesReceived);
                message.acknowledge();
            }
        }
    } catch (JMSException e) {
        LOG.error("[ConsumerTool] caught: ", e);
    } finally {
        if (sleepTime > 0) {
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                LOG.error("[ConsumerTool] caught: ", e);
            }
        }
    }
}

From source file:org.calrissian.mango.jms.stream.AbstractJmsFileTransferSupport.java

@SuppressWarnings("unchecked")
public void sendStream(Request req, final Destination replyTo) throws IOException {

    DigestInputStream is;/*from   w w w.  ja v  a 2 s .  c o  m*/
    Assert.notNull(req, "Request cannot be null");
    final URI downloadUrl;
    try {
        downloadUrl = new URI(req.getDownloadUri());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    try {

        is = new DigestInputStream(new BufferedInputStream(streamOpener.openStream(downloadUrl)),
                MessageDigest.getInstance(getHashAlgorithm()));

    } catch (NoSuchAlgorithmException e) {
        throw new JmsFileTransferException(e);
    } catch (Throwable e) {

        logger.info("Error occurred opening stream: " + e);
        return;
    }

    MessageQueueListener queueListener = null;
    try {

        @SuppressWarnings("rawtypes")
        Message returnMessage = (Message) jmsTemplate.execute(new SessionCallback() {

            @Override
            public Object doInJms(Session session) throws JMSException {
                DestinationRequestor requestor = null;
                try {
                    Message responseMessage = DomainMessageUtils.toResponseMessage(session,
                            new Response(ResponseStatusEnum.ACCEPT));

                    // Actual file transfer should be done on a queue.
                    // Topics will not work
                    Destination streamTransferDestination = factoryDestination(session,
                            UUID.randomUUID().toString());
                    requestor = new DestinationRequestor(session, replyTo, streamTransferDestination,
                            jmsTemplate.getReceiveTimeout());
                    Message returnMessage = requestor.request(responseMessage);
                    requestor.close();
                    return returnMessage;
                } finally {
                    if (requestor != null)
                        requestor.close();
                }
            }

        }, true);

        // timeout
        if (returnMessage == null)
            return;
        Response response = DomainMessageUtils.fromResponseMessage(returnMessage);

        // cancel transfer
        if (!ResponseStatusEnum.STARTSEND.equals(response.getStatus()))
            return;

        final Destination receiveAckDestination = returnMessage.getJMSDestination();
        final Destination sendDataDestination = returnMessage.getJMSReplyTo();

        queueListener = new MessageQueueListener(this, receiveAckDestination);

        logger.info("Sender[" + req.getRequestId() + "]: Starting send to: " + sendDataDestination);

        byte[] buffer = new byte[getPieceSize()];
        int read = is.read(buffer);
        long placeInFile = 0;
        while (read >= 0) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            stream.write(buffer, 0, read);
            stream.close();
            final byte[] pieceData = stream.toByteArray();
            final Piece piece = new Piece(placeInFile, pieceData, getHashAlgorithm());
            logger.info("Sender[" + req.getRequestId() + "]: Sending piece with position: "
                    + piece.getPosition() + " Size of piece: " + pieceData.length);
            jmsTemplate.send(sendDataDestination, new MessageCreator() {

                @Override
                public Message createMessage(Session session) throws JMSException {
                    return DomainMessageUtils.toPieceMessage(session, piece);
                }

            });
            //                Message ret = jmsTemplate.receive(receiveAckDestination);
            Message ret = queueListener.getMessageInQueue();
            logger.info("Sender[" + req.getRequestId() + "]: Sent piece and got ack");

            // no one on the other end any longer, timeout
            if (ret == null)
                return;

            Response res = DomainMessageUtils.fromResponseMessage(ret);
            // stop transfer
            if (ResponseStatusEnum.RESEND.equals(res.getStatus())) {
                // resend piece
                logger.info("Sender[" + req.getRequestId() + "]: Resending piece");
            } else if (ResponseStatusEnum.DENY.equals(res.getStatus())) {
                return;
            } else {
                buffer = new byte[getPieceSize()];
                placeInFile += read;
                read = is.read(buffer);
            }
        }

        logger.info("Sender[" + req.getRequestId() + "]: Sending stop send");

        final DigestInputStream fiIs = is;

        jmsTemplate.send(sendDataDestination, new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                Response stopSendResponse = new Response(ResponseStatusEnum.STOPSEND);
                stopSendResponse.setHash(new String(fiIs.getMessageDigest().digest()));
                return DomainMessageUtils.toResponseMessage(session, stopSendResponse);
            }

        });

        Message ackMessage = queueListener.getMessageInQueue();

        Object fromMessage = DomainMessageUtils.fromMessage(ackMessage);
        if (fromMessage instanceof Response) {
            Response ackResponse = (Response) fromMessage;
            if (ResponseStatusEnum.RESEND.equals(ackResponse.getStatus())) {
                // TODO: resend the whole file
            }
        }

    } catch (Exception e) {
        throw new JmsFileTransferException(e);
    } finally {
        try {
            is.close();
        } catch (IOException ignored) {
        }
        if (queueListener != null)
            queueListener.close();
    }
}

From source file:org.springframework.jms.support.converter.SimpleJmsHeaderMapper.java

@Override
public Map<String, Object> toHeaders(javax.jms.Message jmsMessage) {
    Map<String, Object> headers = new HashMap<String, Object>();
    try {/*from  w ww.ja  v a 2s  . c om*/
        try {
            String correlationId = jmsMessage.getJMSCorrelationID();
            if (correlationId != null) {
                headers.put(JmsHeaders.CORRELATION_ID, correlationId);
            }
        } catch (Exception e) {
            logger.info("failed to read JMSCorrelationID property, skipping", e);
        }
        try {
            Destination destination = jmsMessage.getJMSDestination();
            if (destination != null) {
                headers.put(JmsHeaders.DESTINATION, destination);
            }
        } catch (Exception e) {
            logger.info("failed to read JMSDestination property, skipping", e);
        }
        try {
            int deliveryMode = jmsMessage.getJMSDeliveryMode();
            headers.put(JmsHeaders.DELIVERY_MODE, deliveryMode);
        } catch (Exception e) {
            logger.info("failed to read JMSDeliveryMode property, skipping", e);
        }
        try {
            long expiration = jmsMessage.getJMSExpiration();
            headers.put(JmsHeaders.EXPIRATION, expiration);
        } catch (Exception e) {
            logger.info("failed to read JMSExpiration property, skipping", e);
        }
        try {
            String messageId = jmsMessage.getJMSMessageID();
            if (messageId != null) {
                headers.put(JmsHeaders.MESSAGE_ID, messageId);
            }
        } catch (Exception e) {
            logger.info("failed to read JMSMessageID property, skipping", e);
        }
        try {
            headers.put(JmsHeaders.PRIORITY, jmsMessage.getJMSPriority());
        } catch (Exception e) {
            logger.info("failed to read JMSPriority property, skipping", e);
        }
        try {
            Destination replyTo = jmsMessage.getJMSReplyTo();
            if (replyTo != null) {
                headers.put(JmsHeaders.REPLY_TO, replyTo);
            }
        } catch (Exception e) {
            logger.info("failed to read JMSReplyTo property, skipping", e);
        }
        try {
            headers.put(JmsHeaders.REDELIVERED, jmsMessage.getJMSRedelivered());
        } catch (Exception e) {
            logger.info("failed to read JMSRedelivered property, skipping", e);
        }
        try {
            String type = jmsMessage.getJMSType();
            if (type != null) {
                headers.put(JmsHeaders.TYPE, type);
            }
        } catch (Exception e) {
            logger.info("failed to read JMSType property, skipping", e);
        }
        try {
            headers.put(JmsHeaders.TIMESTAMP, jmsMessage.getJMSTimestamp());
        } catch (Exception e) {
            logger.info("failed to read JMSTimestamp property, skipping", e);
        }

        Enumeration<?> jmsPropertyNames = jmsMessage.getPropertyNames();
        if (jmsPropertyNames != null) {
            while (jmsPropertyNames.hasMoreElements()) {
                String propertyName = jmsPropertyNames.nextElement().toString();
                try {
                    String headerName = this.toHeaderName(propertyName);
                    headers.put(headerName, jmsMessage.getObjectProperty(propertyName));
                } catch (Exception e) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("error occurred while mapping JMS property '" + propertyName
                                + "' to Message header", e);
                    }
                }
            }
        }
    } catch (JMSException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("error occurred while mapping from JMS properties to MessageHeaders", e);
        }
    }
    return headers;
}

From source file:org.springframework.jms.support.SimpleJmsHeaderMapper.java

@Override
public MessageHeaders toHeaders(javax.jms.Message jmsMessage) {
    Map<String, Object> headers = new HashMap<String, Object>();
    try {//from w  w w .j a  va2s  .c o  m
        try {
            String correlationId = jmsMessage.getJMSCorrelationID();
            if (correlationId != null) {
                headers.put(JmsHeaders.CORRELATION_ID, correlationId);
            }
        } catch (Exception ex) {
            logger.info("failed to read JMSCorrelationID property, skipping", ex);
        }
        try {
            Destination destination = jmsMessage.getJMSDestination();
            if (destination != null) {
                headers.put(JmsHeaders.DESTINATION, destination);
            }
        } catch (Exception ex) {
            logger.info("failed to read JMSDestination property, skipping", ex);
        }
        try {
            int deliveryMode = jmsMessage.getJMSDeliveryMode();
            headers.put(JmsHeaders.DELIVERY_MODE, deliveryMode);
        } catch (Exception ex) {
            logger.info("failed to read JMSDeliveryMode property, skipping", ex);
        }
        try {
            long expiration = jmsMessage.getJMSExpiration();
            headers.put(JmsHeaders.EXPIRATION, expiration);
        } catch (Exception ex) {
            logger.info("failed to read JMSExpiration property, skipping", ex);
        }
        try {
            String messageId = jmsMessage.getJMSMessageID();
            if (messageId != null) {
                headers.put(JmsHeaders.MESSAGE_ID, messageId);
            }
        } catch (Exception ex) {
            logger.info("failed to read JMSMessageID property, skipping", ex);
        }
        try {
            headers.put(JmsHeaders.PRIORITY, jmsMessage.getJMSPriority());
        } catch (Exception ex) {
            logger.info("failed to read JMSPriority property, skipping", ex);
        }
        try {
            Destination replyTo = jmsMessage.getJMSReplyTo();
            if (replyTo != null) {
                headers.put(JmsHeaders.REPLY_TO, replyTo);
            }
        } catch (Exception ex) {
            logger.info("failed to read JMSReplyTo property, skipping", ex);
        }
        try {
            headers.put(JmsHeaders.REDELIVERED, jmsMessage.getJMSRedelivered());
        } catch (Exception ex) {
            logger.info("failed to read JMSRedelivered property, skipping", ex);
        }
        try {
            String type = jmsMessage.getJMSType();
            if (type != null) {
                headers.put(JmsHeaders.TYPE, type);
            }
        } catch (Exception ex) {
            logger.info("failed to read JMSType property, skipping", ex);
        }
        try {
            headers.put(JmsHeaders.TIMESTAMP, jmsMessage.getJMSTimestamp());
        } catch (Exception ex) {
            logger.info("failed to read JMSTimestamp property, skipping", ex);
        }

        Enumeration<?> jmsPropertyNames = jmsMessage.getPropertyNames();
        if (jmsPropertyNames != null) {
            while (jmsPropertyNames.hasMoreElements()) {
                String propertyName = jmsPropertyNames.nextElement().toString();
                try {
                    String headerName = this.toHeaderName(propertyName);
                    headers.put(headerName, jmsMessage.getObjectProperty(propertyName));
                } catch (Exception ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Error occurred while mapping JMS property '" + propertyName
                                + "' to Message header", ex);
                    }
                }
            }
        }
    } catch (JMSException ex) {
        if (logger.isWarnEnabled()) {
            logger.warn("Error occurred while mapping from JMS properties to MessageHeaders", ex);
        }
    }
    return new MessageHeaders(headers);
}

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  ava 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.wso2.carbon.inbound.endpoint.protocol.jms.JMSInjectHandler.java

/**
 * Invoke the mediation logic for the passed message
 * *///from   w w  w . ja  va 2  s . 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.oxymores.chronix.engine.RunnerAgent.java

@Override
public void onMessage(Message msg) {
    log.info("Run request received");
    ObjectMessage omsg = (ObjectMessage) msg;
    RunDescription rd;//from  w w w. j av  a2  s  . 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 {//w  w  w. ja va  2 s  .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);
    }
}

From source file:org.mitre.mpf.markup.MarkupRequestConsumer.java

public void onMessage(Message message) {
    Stopwatch stopwatch = Stopwatch.createStarted();

    if (message == null) {
        log.warn("Received a null JMS message. No action will be taken.");
        return;//from  w w  w  .  java 2s. c om
    }

    if (!(message instanceof BytesMessage)) {
        log.warn("Received a JMS message, but it was not of the correct type. No action will be taken.");
        return;
    }

    try {
        log.info("Received JMS message. Type = {}. JMS Message ID = {}. JMS Correlation ID = {}.",
                message.getClass().getName(), message.getJMSMessageID(), message.getJMSCorrelationID());

        final Map<String, Object> requestHeaders = new HashMap<String, Object>();
        Enumeration<String> properties = message.getPropertyNames();

        String propertyName = null;
        while (properties.hasMoreElements()) {
            propertyName = properties.nextElement();
            requestHeaders.put(propertyName, message.getObjectProperty(propertyName));
        }

        byte[] messageBytes = new byte[(int) (((BytesMessage) message).getBodyLength())];
        ((BytesMessage) message).readBytes(messageBytes);
        Markup.MarkupRequest markupRequest = Markup.MarkupRequest.parseFrom(messageBytes);
        Markup.MarkupResponse.Builder markupResponseBuilder = initializeResponse(markupRequest);
        markupResponseBuilder.setRequestTimestamp(message.getJMSTimestamp());

        log.debug("Processing markup request. Media Index = {}. Media ID = {} (type = {}). Request ID = {}.",
                markupRequest.getMediaIndex(), markupRequest.getMediaId(), markupRequest.getMediaType(),
                markupRequest.getRequestId());

        try {
            if (!new File(URI.create(markupRequest.getDestinationUri())).canWrite()) {
                throw new Exception();
            }
        } catch (Exception exception) {
            markupResponseBuilder.setHasError(true);
            markupResponseBuilder.setErrorMessage(
                    String.format("The target URI '%s' is not writable.", markupRequest.getDestinationUri()));
        }

        try {
            if (!new File(URI.create(markupRequest.getSourceUri())).canRead()) {
                throw new Exception();
            }
        } catch (Exception exception) {
            markupResponseBuilder.setHasError(true);
            markupResponseBuilder.setErrorMessage(
                    String.format("The source URI '%s' is not readable.", markupRequest.getSourceUri()));
        }

        if (!markupResponseBuilder.getHasError()) {
            if (markupRequest.getMapEntriesCount() == 0) {
                try {
                    FileUtils.copyFile(new File(URI.create(markupRequest.getSourceUri())),
                            new File(URI.create(markupRequest.getDestinationUri())));
                    markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri());
                } catch (Exception exception) {
                    log.error("Failed to mark up the file '{}' because of an exception.",
                            markupRequest.getSourceUri(), exception);
                    finishWithError(markupResponseBuilder, exception);
                }
            } else if (markupRequest.getMediaType() == Markup.MediaType.IMAGE) {
                try {
                    if (markupImage(markupRequest)) {
                        markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri());
                    } else {
                        markupResponseBuilder.setOutputFileUri(markupRequest.getSourceUri());
                    }
                } catch (Exception exception) {
                    log.error("Failed to mark up the image '{}' because of an exception.",
                            markupRequest.getSourceUri(), exception);
                    finishWithError(markupResponseBuilder, exception);
                }
            } else {
                try {
                    if (markupVideo(markupRequest)) {
                        markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri());
                    } else {
                        markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri());
                    }
                } catch (Exception exception) {
                    log.error("Failed to mark up the video '{}' because of an exception.",
                            markupRequest.getSourceUri(), exception);
                    finishWithError(markupResponseBuilder, exception);
                }
            }
        }

        stopwatch.stop();
        markupResponseBuilder.setTimeProcessing(stopwatch.elapsed(TimeUnit.MILLISECONDS));
        final Markup.MarkupResponse markupResponse = markupResponseBuilder.build();

        log.info("Returning response for Media {}. Error: {}.", markupResponse.getMediaId(),
                markupResponse.getHasError());
        markupResponseTemplate.setSessionTransacted(true);
        markupResponseTemplate.setDefaultDestination(message.getJMSReplyTo());
        markupResponseTemplate.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(markupResponse.toByteArray());
                for (Map.Entry<String, Object> entry : requestHeaders.entrySet()) {
                    bytesMessage.setObjectProperty(entry.getKey(), entry.getValue());
                }
                return bytesMessage;
            }
        });

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}