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:org.calrissian.mango.jms.stream.AbstractJmsFileTransferSupport.java

public InputStream receiveStream(final Request req) throws JmsFileTransferException {
    try {/*from ww  w.ja v  a2 s  .  c o m*/
        logger.info(
                "Broadcasting request for [" + req.getDownloadUri() + "] and id[" + req.getRequestId() + "]");
        Message returnMessage = sendWithResponse(new MessageCreator() {

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

        }, getStreamRequestDestination());

        // No one could fulfill the request
        if (returnMessage == null) {
            logger.info("No one can fullfil this request [" + req.getDownloadUri() + "]");
            return null;
        }

        // start the stream transfer at this destination
        final Destination receiveAckDestination = returnMessage.getJMSReplyTo();
        final String sendDataDestination = UUID.randomUUID().toString();

        logger.info("Receiver[" + req.getRequestId() + "]: File Transfer starting");

        return new JmsFileReceiverInputStream(this, sendDataDestination, receiveAckDestination);
    } catch (Exception e) {
        throw new JmsFileTransferException(e);
    }
}

From source file:ConsumerTool.java

public void onMessage(Message message) {

    messagesReceived++;/*from   w  w w.j a  v  a  2 s.  c  om*/

    try {

        if (message instanceof TextMessage) {
            TextMessage txtMsg = (TextMessage) message;
            if (verbose) {

                String msg = txtMsg.getText();
                int length = msg.length();
                if (length > 50) {
                    msg = msg.substring(0, 50) + "...";
                }
                System.out.println("[" + this.getName() + "] Received: '" + msg + "' (length " + length + ")");
            }
        } else {
            if (verbose) {
                System.out.println("[" + this.getName() + "] Received: '" + message + "'");
            }
        }

        if (message.getJMSReplyTo() != null) {
            replyProducer.send(message.getJMSReplyTo(),
                    session.createTextMessage("Reply: " + message.getJMSMessageID()));
        }

        if (transacted) {
            if ((messagesReceived % batch) == 0) {
                System.out.println("Commiting transaction for last " + batch + " messages; messages so far = "
                        + messagesReceived);
                session.commit();
            }
        } else if (ackMode == Session.CLIENT_ACKNOWLEDGE) {
            if ((messagesReceived % batch) == 0) {
                System.out.println(
                        "Acknowledging last " + batch + " messages; messages so far = " + messagesReceived);
                message.acknowledge();
            }
        }

    } catch (JMSException e) {
        System.out.println("[" + this.getName() + "] Caught: " + e);
        e.printStackTrace();
    } finally {
        if (sleepTime > 0) {
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
            }
        }
    }
}

From source file:org.openanzo.combus.endpoint.BaseServiceListener.java

private void processMessage(Message request) {
    try {/*from  w w w.ja  va  2s .  c  o  m*/
        IOperationContext context = null;
        TextMessage response = null;
        String operation = request.getStringProperty(SerializationConstants.operation);
        try {
            Destination replyTo = null;
            try {
                if (mp == null) {
                    mp = session.createProducer(null);
                    mp.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                }
                replyTo = request.getJMSReplyTo();

                String resultFormat = request.getStringProperty(SerializationConstants.resultFormat);
                context = new BaseOperationContext(operation, request.getJMSCorrelationID(), null);
                if (request.propertyExists(SerializationConstants.userDescription)) {
                    context.setAttribute(SerializationConstants.userDescription,
                            request.getStringProperty(SerializationConstants.userDescription));
                }
                if (request.propertyExists(OPTIONS.SKIPCACHE)) {
                    context.setAttribute(OPTIONS.SKIPCACHE, request.getBooleanProperty(OPTIONS.SKIPCACHE));
                }
                if (request.propertyExists(OPTIONS.INCLUDEMETADATAGRAPHS)) {
                    context.setAttribute(OPTIONS.INCLUDEMETADATAGRAPHS,
                            request.getBooleanProperty(OPTIONS.INCLUDEMETADATAGRAPHS));
                }

                AnzoPrincipal callerPrincipal = getContextPrincipal(context, request);
                context.setOperationPrincipal(callerPrincipal);

                if (log.isTraceEnabled()) {
                    log.trace(LogUtils.COMBUS_MARKER,
                            MessageUtils.prettyPrint(request,
                                    "Message Recieved from [" + callerPrincipal.getName() + "]"
                                            + ((replyTo != null) ? (" with replyto [" + replyTo + "]") : "")));
                } else if (log.isDebugEnabled()) {
                    log.debug(LogUtils.COMBUS_MARKER, "Message Recieved from [" + callerPrincipal.getName()
                            + "]" + ((replyTo != null) ? (" with replyto [" + replyTo + "]") : ""));
                }
                context.setMDC();
                Boolean analyzeRequest = request
                        .getBooleanProperty(RequestAnalysis.CONTEXT_PROP_REQUEST_ENABLED);
                if (analyzeRequest || recorder != null) {
                    RequestAnalysis.setCurrentContext(context.getAttributes());
                    RequestAnalysis.setRequestAnalysisEnabled(true);
                }

                if (recorder != null) {
                    recorder.recordRequest((TextMessage) request, request.getStringProperty("JMSXUserID"),
                            request.getStringProperty(SerializationConstants.runAsUser));
                }

                long start = 0, end = 0;
                if (RequestAnalysis.isAnalysisEnabled(context.getAttributes())) {
                    start = System.currentTimeMillis();
                }

                response = handleMessage(context, replyTo, resultFormat, operation, (TextMessage) request, mp);
                if (RequestAnalysis.isAnalysisEnabled(context.getAttributes())) {
                    end = System.currentTimeMillis();
                    RequestAnalysis.addAnalysisProperty(RequestAnalysis.ANS_PROP_OPERATION_TIME,
                            String.valueOf(end - start));
                }

                if (response != null) {
                    response.setIntProperty(SerializationConstants.protocolVersion, Constants.VERSION);
                    if (operation != null) {
                        response.setStringProperty(SerializationConstants.operation, operation);
                    }
                    Integer totalSolutions = context.getAttribute(SerializationConstants.totalSolutions,
                            Integer.class);
                    if (totalSolutions != null) {
                        response.setIntProperty(SerializationConstants.totalSolutions,
                                totalSolutions.intValue());
                    }
                    if (analyzeRequest) {
                        for (String name : RequestAnalysis.getAnalysisPropertyNames()) {
                            response.setStringProperty(name, context.getAttribute(name).toString());
                        }
                    }
                }

                if (response != null && replyTo != null) {
                    response.setJMSCorrelationID(request.getJMSCorrelationID());
                    if (log.isTraceEnabled()) {
                        log.trace(LogUtils.COMBUS_MARKER,
                                MessageUtils.prettyPrint(response, "Sending Response to [" + replyTo + "]"));
                    } else if (log.isDebugEnabled()) {
                        log.debug(LogUtils.COMBUS_MARKER, "Sending Response to [" + replyTo + "]");
                    }
                    mp.send(replyTo, response);
                }

            } catch (JMSException jmex) {
                response = sendJMSErrorMessage(replyTo, request, jmex,
                        ExceptionConstants.COMBUS.JMS_SERVICE_EXCEPTION, jmex.toString());
            } catch (AnzoException jmex) {
                response = sendJMSErrorMessage(replyTo, request, jmex, jmex.getErrorCode(), jmex.getArgs());
            } catch (AnzoRuntimeException jmex) {
                response = sendJMSErrorMessage(replyTo, request, jmex, jmex.getErrorCode(), jmex.getArgs());
            } catch (RuntimeException jmex) {
                response = sendJMSErrorMessage(replyTo, request, jmex,
                        ExceptionConstants.COMBUS.JMS_SERVICE_EXCEPTION, jmex.toString());
            } catch (Throwable jmex) {
                response = sendJMSErrorMessage(replyTo, request, jmex,
                        ExceptionConstants.COMBUS.JMS_SERVICE_EXCEPTION, jmex.toString());
            }

            if (recorder != null) {
                if (response != null) {
                    recorder.recordResponse(response);
                } else {
                    recorder.recordResponse(request.getJMSCorrelationID(), operation);
                }
            }
        } finally {
            if (context != null) {
                context.clearMDC();
            }
        }
    } catch (JMSException jmsex) {
        if (jmsex.getCause() instanceof InterruptedException) {
            log.debug(LogUtils.COMBUS_MARKER, "Thread interrupted in order to stop.", jmsex);
        } else {
            log.error(LogUtils.COMBUS_MARKER, "Error in BaseService Listener's process thread loop", jmsex);
        }
    } catch (Throwable jmex) {
        log.error(LogUtils.COMBUS_MARKER, "Error in BaseService Listener's process thread loop", jmex);
    }
}

From source file:com.jmstoolkit.beans.MessageTableModel.java

/**
 *
 * @param message/* ww w. j a v a  2 s.com*/
 */
@Override
public void onMessage(Message message) {
    LOGGER.log(Level.FINE, "Message Received");
    messagesReceived++;
    try {
        MessageTableRecord qRecord = new MessageTableRecord();
        qRecord.setJMSCorrelationID(message.getJMSCorrelationID());
        qRecord.setJMSDeliveryMode(message.getJMSDeliveryMode());
        qRecord.setJMSExpiration(message.getJMSExpiration());
        qRecord.setJMSMessageID(message.getJMSMessageID());
        qRecord.setJMSTimestamp(message.getJMSTimestamp());
        qRecord.setJMSType(message.getJMSType());
        qRecord.setJMSDestination(message.getJMSDestination());
        qRecord.setJMSCorrelationIDAsBytes(message.getJMSCorrelationIDAsBytes());
        qRecord.setJMSPriority(message.getJMSPriority());
        qRecord.setJMSType(message.getJMSType());
        qRecord.setJMSReplyTo(message.getJMSReplyTo());
        qRecord.setJMSRedelivered(message.getJMSRedelivered());
        Enumeration pEnumerator = message.getPropertyNames();
        Properties props = new Properties();
        while (pEnumerator.hasMoreElements()) {
            String pElement = (String) pEnumerator.nextElement();
            props.put(pElement, message.getStringProperty(pElement));
        }
        qRecord.setProperties(props);

        if (message instanceof TextMessage) {
            qRecord.setText(((TextMessage) message).getText());
        }
        if (message instanceof ObjectMessage) {
            qRecord.setObject(((ObjectMessage) message).getObject());
        }

        List newData = data;
        newData.add(qRecord);
        this.setData(newData);
    } catch (JMSException e) {
        LOGGER.log(Level.WARNING, "JMS problem", e);
    }
}

From source file:org.codehaus.stomp.jms.StompSession.java

protected void copyStandardHeadersFromMessageToFrame(Message message, StompFrame command) throws JMSException {
    final Map headers = command.getHeaders();
    headers.put(Stomp.Headers.Message.DESTINATION, convertDestination(message.getJMSDestination()));
    headers.put(Stomp.Headers.Message.MESSAGE_ID, message.getJMSMessageID());

    if (message.getJMSCorrelationID() != null) {
        headers.put(Stomp.Headers.Message.CORRELATION_ID, message.getJMSCorrelationID());
    }/* w w w.j  a  va 2s  .c om*/
    headers.put(Stomp.Headers.Message.EXPIRATION_TIME, "" + message.getJMSExpiration());

    if (message.getJMSRedelivered()) {
        headers.put(Stomp.Headers.Message.REDELIVERED, "true");
    }
    headers.put(Stomp.Headers.Message.PRORITY, "" + message.getJMSPriority());

    if (message.getJMSReplyTo() != null) {
        headers.put(Stomp.Headers.Message.REPLY_TO, convertDestination(message.getJMSReplyTo()));
    }
    headers.put(Stomp.Headers.Message.TIMESTAMP, "" + message.getJMSTimestamp());

    if (message.getJMSType() != null) {
        headers.put(Stomp.Headers.Message.TYPE, message.getJMSType());
    }

    // now lets add all the message headers
    Enumeration names = message.getPropertyNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Object value = message.getObjectProperty(name);
        headers.put(name, value);
    }
}

From source file:org.springframework.integration.jms.DefaultJmsHeaderMapper.java

public Map<String, Object> toHeaders(javax.jms.Message jmsMessage) {
    Map<String, Object> headers = new HashMap<String, Object>();
    try {/*from  ww  w  .j  a  v a 2s .c  o  m*/
        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 {
            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 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:biz.fstechnology.micro.server.jms.AbstractJmsService.java

/**
 * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
 *///from   w  w w .  j ava2  s. c o  m
@Override
public void onMessage(Message message) {
    try {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        if (((ObjectMessage) message).getObject() instanceof Result) {
            // no op
            return;
        }
        Request<?> request = (Request<?>) ((ObjectMessage) message).getObject(); // cast hell...
        Future<Request<?>> preProcessFuture = executor.submit(() -> onPreProcessRequest(request));

        Future<Result<?>> resultFuture = executor.submit(() -> processRequest(preProcessFuture.get()));

        Future<Result<?>> postProcessFuture = executor
                .submit(() -> onPostProcessRequest(request, resultFuture.get()));
        executor.shutdown();

        Result<?> result = postProcessFuture.get();

        ResponseMessageCreator messageCreator = new ResponseMessageCreator();
        messageCreator.setContents(result);
        messageCreator.setRequestId(message.getJMSCorrelationID());

        replyProducer.send(message.getJMSReplyTo(), messageCreator.createMessage(session));

    } catch (JMSException | InterruptedException | ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Result<Object> result = new Result<>(e);
        try {
            ResponseMessageCreator messageCreator = new ResponseMessageCreator();
            messageCreator.setContents(result);
            messageCreator.setRequestId(message.getJMSCorrelationID());

            replyProducer.send(message.getJMSReplyTo(), messageCreator.createMessage(session));
        } catch (JmsException | JMSException e1) {
            e1.printStackTrace();
        }
    }
}

From source file:net.blogracy.services.SeedService.java

@Override
public void onMessage(Message request) {
    try {//from w ww  .j  a  va2s .com
        String text = ((TextMessage) request).getText();
        Logger.info("seed service:" + text + ";");
        JSONObject entry = new JSONObject(text);
        try {
            File file = new File(entry.getString("file"));

            Torrent torrent = plugin.getTorrentManager().createFromDataFile(file,
                    new URL("udp://tracker.openbittorrent.com:80"));
            torrent.setComplete(file.getParentFile());

            String name = Base32.encode(torrent.getHash());
            int index = file.getName().lastIndexOf('.');
            if (0 < index && index <= file.getName().length() - 2) {
                name = name + file.getName().substring(index);
            }

            Download download = plugin.getDownloadManager().addDownload(torrent, null, // torrentFile,
                    file.getParentFile());
            if (download != null)
                download.renameDownload(name);
            entry.put("uri", torrent.getMagnetURI().toExternalForm());

            if (request.getJMSReplyTo() != null) {
                TextMessage response = session.createTextMessage();
                response.setText(entry.toString());
                response.setJMSCorrelationID(request.getJMSCorrelationID());
                producer.send(request.getJMSReplyTo(), response);
            }
        } catch (MalformedURLException e) {
            Logger.error("Malformed URL error: seed service " + text);
        } catch (TorrentException e) {
            Logger.error("Torrent error: seed service: " + text);
            e.printStackTrace();
        } catch (DownloadException e) {
            Logger.error("Download error: seed service: " + text);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (JMSException e) {
        Logger.error("JMS error: seed service");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java

private void addMatchScanListener() throws JMSException {
    addMessageListener("matchRequest", new MessageListener() {
        @Override//from w  ww .j a v a2 s  .  co  m
        public void onMessage(Message msg) {
            BytesMessage o = (BytesMessage) msg;
            byte[] body;
            try {
                body = new byte[(int) o.getBodyLength()];
                o.readBytes(body);
                BCSAPIMessage.ExactMatchRequest request = BCSAPIMessage.ExactMatchRequest.parseFrom(body);
                final List<byte[]> match = new ArrayList<byte[]>();
                for (ByteString bs : request.getMatchList()) {
                    match.add(bs.toByteArray());
                }
                final UpdateMode mode = UpdateMode.values()[request.getMode()];
                final MessageProducer producer = session.createProducer(msg.getJMSReplyTo());
                final long after = request.hasAfter() ? request.getAfter() : 0;
                requestProcessor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            store.filterTransactions(match, mode, after, new TransactionProcessor() {
                                @Override
                                public void process(Tx tx) {
                                    if (tx != null) {
                                        Transaction transaction = toBCSAPITransaction(tx);
                                        BytesMessage m;
                                        try {
                                            m = session.createBytesMessage();
                                            m.writeBytes(transaction.toProtobuf().toByteArray());
                                            producer.send(m);
                                        } catch (JMSException e) {
                                        }
                                    } else {
                                        try {
                                            BytesMessage m = session.createBytesMessage();
                                            producer.send(m); // indicate EOF
                                            producer.close();
                                        } catch (JMSException e) {
                                        }
                                    }
                                }
                            });
                        } catch (ValidationException e) {
                            log.error("Error while scanning", e);
                        }
                    }
                });
            } catch (JMSException e) {
                log.error("invalid filter request", e);
            } catch (InvalidProtocolBufferException e) {
                log.error("invalid filter request", e);
            }
        }
    });
}

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

/**
 * Put message into messageQueue and update information.
 *//*from   w ww .j av  a  2s  .  c om*/
public void onMessage(Message message) {
    messagesReceived++;
    try {
        if (message instanceof ObjectMessage) {
            ObjectMessage objMsg = (ObjectMessage) message;
            BSPMessagesPack msgPack = (BSPMessagesPack) objMsg.getObject();
            IMessage bspMsg;
            Iterator<IMessage> iter = msgPack.getPack().iterator();
            while (iter.hasNext()) {
                bspMsg = iter.next();
                String vertexID = bspMsg.getDstVertexID();
                this.messageQueues.incomeAMessage(vertexID, bspMsg);
                this.messageCount++;
                this.messageBytesCount += bspMsg.size();
            }
        } else {
            // Message received is not ObjectMessage.
            LOG.error("[ConsumerTool] Message received is not ObjectMessage!");
        }
        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) {
        throw new RuntimeException("[ConsumerTool] caught: ", e);
    } finally {
        if (sleepTime > 0) {
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                LOG.error("[ConsumerTool] Message received not ObjectMessage!", e);
                throw new RuntimeException("[ConsumerTool] Message received not ObjectMessage! s", e);
            }
        }
    }
}