Example usage for javax.jms TextMessage setStringProperty

List of usage examples for javax.jms TextMessage setStringProperty

Introduction

In this page you can find the example usage for javax.jms TextMessage setStringProperty.

Prototype


void setStringProperty(String name, String value) throws JMSException;

Source Link

Document

Sets a String property value with the specified name into the message.

Usage

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

private TextMessage sendJMSErrorMessage(Destination replyTo, Message request, Throwable jmex, long errorCode,
        String... args) throws JMSException {
    try {// w  w w .  ja  v  a  2s  .  c o  m
        if (replyTo != null) {
            if (log.isWarnEnabled()) {
                log.warn(LogUtils.COMBUS_MARKER,
                        "Exception while ServiceListener [" + name + "] was precessing request.", jmex);

            }
            String message = null;
            if (jmex instanceof AnzoException) {
                message = ((AnzoException) jmex).getMessage(false);
            } else if (jmex instanceof AnzoRuntimeException) {
                message = ((AnzoRuntimeException) jmex).getMessage(false);
            } else {
                message = jmex.getMessage();
            }
            TextMessage response = session.createTextMessage(message);
            response.setJMSCorrelationID(request.getJMSCorrelationID());
            response.setBooleanProperty(SerializationConstants.operationFailed, true);
            response.setLongProperty(SerializationConstants.errorTags, 0);
            response.setLongProperty(SerializationConstants.errorCode, errorCode);
            response.setIntProperty(SerializationConstants.protocolVersion, Constants.VERSION);
            // send a single arg string for compat. with older readers
            response.setStringProperty(SerializationConstants.errorMessageArg, Arrays.toString(args));

            // send the individual error args for readers that can make use of them
            for (int i = 0; i < args.length; i++) {
                response.setStringProperty(SerializationConstants.errorMessageArg + i, args[i]);
            }

            // we log all JMS messages, even errors.
            if (log.isDebugEnabled()) {
                log.debug(LogUtils.COMBUS_MARKER,
                        MessageUtils.prettyPrint(response, "Sending Response to " + replyTo));
            }
            mp.send(replyTo, response);
            return response;
        }
    } catch (JMSException jmsex) {
        log.debug(LogUtils.COMBUS_MARKER, "Error sending error message to client", jmsex);
    }
    return null;
}

From source file:org.openanzo.combus.bayeux.BridgeConnectionManager.java

/**
 * Marks a temporary topic for deletion. Before deleting the topic, it will be unregistered via the notification registration service. The topic will be
 * deleted once that operation completes.
 * //from w ww  .  j ava2s.c  om
 * @param topicToClose
 *            the temporary topic to close.
 * @param username
 *            the username of the user to which the temporary topic belongs
 * @param clientId
 *            the clientId of the specific Bayeux connection to which the temporary topic applies.
 */
private void cleanupTemporaryTopic(TemporaryTopic topicToClose, MessageConsumer tempTopicConsumerToClose,
        String username, String clientId) {

    String correlationId = UUID.randomUUID().toString();
    mapLock.lock();
    try {
        topicsToDelete.put(correlationId, new ClientStateToClose(tempTopicConsumerToClose, topicToClose,
                System.currentTimeMillis(), username, clientId));
    } finally {
        mapLock.unlock();
    }

    log.debug(LogUtils.COMBUS_MARKER, "Sending unregister subscriber message for {}/{}", username, clientId);
    try {
        TextMessage tmsg = session.createTextMessage();
        tmsg.setJMSCorrelationID(correlationId);
        tmsg.setJMSReplyTo(topicToClose);
        tmsg.setStringProperty(SerializationConstants.operation,
                INotificationRegistrationService.UNREGISTER_SUBSCRIBER);
        tmsg.setStringProperty("runAsUser", username);
        mp.send(destinations.get(COMBUS.NOTIFICATION_SERVICE_QUEUE), tmsg);
    } catch (JMSException e) {
        MDC.put(LogUtils.USER, username);
        log.warn(LogUtils.COMBUS_MARKER, "Error while sending real-time update subscription remove request for "
                + username + "/" + clientId, e);
        MDC.clear();
    }

}

From source file:org.openanzo.combus.bayeux.BridgeConnectionManager.java

/**
 * Send a JMS message on behalf of the given client to a specific destination. The destination is a string that names an abstract queue such as that in
 * Constants.NOTIFICATION_SERVICE_QUEUE, etc.
 * /*from   ww w. j  a v a 2 s .  c o  m*/
 * @param clientId
 * @param destination
 * @param messageProperties
 * @param msgBody
 * @return returns whether or not this message was published to a topic
 * @throws JMSException
 * @throws AnzoException
 */
protected boolean sendClientMessage(String clientId, AnzoPrincipal principal, String destination,
        Map<?, ?> messageProperties, String msgBody, IOperationContext opContext)
        throws JMSException, AnzoException {
    //long destinationProfiler = profiler.start("Resolving destination.");
    Destination dest = destinations.get(destination);
    //profiler.stop(destinationProfiler);
    if (dest == null && destination.startsWith("services/")) {
        dest = session.createQueue(destination);
        destinations.put(destination, dest);
    }
    if (dest == null) { // we probably have a statement channel
        //long nullDestProfiler = profiler.start("Sending client message with null destination.");
        if (destination == null || !destination.startsWith(NAMESPACES.STREAM_TOPIC_PREFIX)) {
            //profiler.stop(nullDestProfiler);
            throw new AnzoException(ExceptionConstants.COMBUS.INVALID_TOPIC, destination);
        }
        // first we have to get the named graph uri out of the statement channel topic.
        String uri = UriGenerator.stripEncapsulatedString(NAMESPACES.STREAM_TOPIC_PREFIX, destination);
        URI graphUri = Constants.valueFactory.createURI(uri);
        if (!userHasGraphAddAccess(graphUri, principal, opContext)) {
            //profiler.stop(nullDestProfiler);
            throw new AnzoException(ExceptionConstants.COMBUS.NOT_AUTHORIZED_FOR_TOPIC,
                    opContext.getOperationPrincipal().getUserURI().toString(), destination);
        }
        Topic topic = session.createTopic(destination);

        TextMessage tmsg = session.createTextMessage();
        for (Map.Entry<?, ?> prop : messageProperties.entrySet()) {
            tmsg.setStringProperty(prop.getKey().toString(), prop.getValue().toString());
        }
        tmsg.setText(msgBody);
        mp.send(topic, tmsg);
        //profiler.stop(nullDestProfiler);
        return true;
    } else {
        TemporaryTopic tempTopicForReply;
        //long = clientStateProfiler = profiler.start("Obtaining Bayeux client state.");
        mapLock.lock();
        try {
            ClientState state = clientIdToClientState.get(clientId);
            if (state == null) {
                throw new AnzoException(ExceptionConstants.CLIENT.CLIENT_NOT_CONNECTED);
            }
            tempTopicForReply = state.topic;
        } finally {
            mapLock.unlock();
            //profiler.stop(clientStateProfiler);
        }

        //long prepareJmsProfiler = profiler.start("Preparing JMS Message.");
        TextMessage tmsg = session.createTextMessage();
        int priority = 4;
        for (Map.Entry<?, ?> prop : messageProperties.entrySet()) {
            if (JMS_MSG_PROPERTY_CORRELATION_ID.equals(prop.getKey())) {
                tmsg.setJMSCorrelationID(prop.getValue().toString());
            }
            if (JMS_MSG_PROPERTY_PRIORITY.equals(prop.getKey())) {
                priority = Integer.parseInt(prop.getValue().toString());
            } else {
                tmsg.setStringProperty(prop.getKey().toString(), prop.getValue().toString());
            }
        }
        tmsg.setJMSPriority(priority);
        tmsg.setJMSReplyTo(tempTopicForReply);
        tmsg.setText(msgBody);
        String username = principal.getName();
        tmsg.setStringProperty("runAsUser", username);
        //profiler.stop(prepareJmsProfiler);
        long sendJmsProfiler = profiler.start("Sending JMS Message");
        mp.setPriority(priority);
        mp.send(dest, tmsg);
        profiler.stop(sendJmsProfiler);
        return false;
    }

}

From source file:nl.nn.adapterframework.extensions.tibco.SendTibcoMessage.java

public String doPipeWithTimeoutGuarded(Object input, IPipeLineSession session) throws PipeRunException {
    Connection connection = null;
    Session jSession = null;/*  w  w  w.  j  av  a 2 s  .co  m*/
    MessageProducer msgProducer = null;
    Destination destination = null;

    String url_work;
    String authAlias_work;
    String userName_work;
    String password_work;
    String queueName_work;
    String messageProtocol_work;
    int replyTimeout_work;
    String soapAction_work;

    String result = null;

    ParameterValueList pvl = null;
    if (getParameterList() != null) {
        ParameterResolutionContext prc = new ParameterResolutionContext((String) input, session);
        try {
            pvl = prc.getValues(getParameterList());
        } catch (ParameterException e) {
            throw new PipeRunException(this, getLogPrefix(session) + "exception on extracting parameters", e);
        }
    }

    url_work = getParameterValue(pvl, "url");
    if (url_work == null) {
        url_work = getUrl();
    }
    authAlias_work = getParameterValue(pvl, "authAlias");
    if (authAlias_work == null) {
        authAlias_work = getAuthAlias();
    }
    userName_work = getParameterValue(pvl, "userName");
    if (userName_work == null) {
        userName_work = getUserName();
    }
    password_work = getParameterValue(pvl, "password");
    if (password_work == null) {
        password_work = getPassword();
    }
    queueName_work = getParameterValue(pvl, "queueName");
    if (queueName_work == null) {
        queueName_work = getQueueName();
    }
    messageProtocol_work = getParameterValue(pvl, "messageProtocol");
    if (messageProtocol_work == null) {
        messageProtocol_work = getMessageProtocol();
    }
    String replyTimeout_work_str = getParameterValue(pvl, "replyTimeout");
    if (replyTimeout_work_str == null) {
        replyTimeout_work = getReplyTimeout();
    } else {
        replyTimeout_work = Integer.parseInt(replyTimeout_work_str);
    }
    soapAction_work = getParameterValue(pvl, "soapAction");
    if (soapAction_work == null)
        soapAction_work = getSoapAction();

    if (StringUtils.isEmpty(soapAction_work) && !StringUtils.isEmpty(queueName_work)) {
        String[] q = queueName_work.split("\\.");
        if (q.length > 0) {
            if (q[0].equalsIgnoreCase("P2P") && q.length >= 4) {
                soapAction_work = q[3];
            } else if (q[0].equalsIgnoreCase("ESB") && q.length == 8) {
                soapAction_work = q[5] + "_" + q[6];
            } else if (q[0].equalsIgnoreCase("ESB") && q.length > 8) {
                soapAction_work = q[6] + "_" + q[7];
            }
        }
    }

    if (StringUtils.isEmpty(soapAction_work)) {
        log.debug(getLogPrefix(session) + "deriving default soapAction");
        try {
            URL resource = ClassUtils.getResourceURL(this, "/xml/xsl/esb/soapAction.xsl");
            TransformerPool tp = new TransformerPool(resource, true);
            soapAction_work = tp.transform(input.toString(), null);
        } catch (Exception e) {
            log.error(getLogPrefix(session) + "failed to execute soapAction.xsl");
        }
    }

    if (messageProtocol_work == null) {
        throw new PipeRunException(this, getLogPrefix(session) + "messageProtocol must be set");
    }
    if (!messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY)
            && !messageProtocol_work.equalsIgnoreCase(FIRE_AND_FORGET)) {
        throw new PipeRunException(this, getLogPrefix(session) + "illegal value for messageProtocol ["
                + messageProtocol_work + "], must be '" + REQUEST_REPLY + "' or '" + FIRE_AND_FORGET + "'");
    }

    CredentialFactory cf = new CredentialFactory(authAlias_work, userName_work, password_work);
    try {
        TibjmsAdmin admin;
        try {
            admin = TibcoUtils.getActiveServerAdmin(url_work, cf);
        } catch (TibjmsAdminException e) {
            log.debug(getLogPrefix(session) + "caught exception", e);
            admin = null;
        }
        if (admin != null) {
            QueueInfo queueInfo;
            try {
                queueInfo = admin.getQueue(queueName_work);
            } catch (Exception e) {
                throw new PipeRunException(this, getLogPrefix(session) + " exception on getting queue info", e);
            }
            if (queueInfo == null) {
                throw new PipeRunException(this,
                        getLogPrefix(session) + " queue [" + queueName_work + "] does not exist");
            }

            try {
                admin.close();
            } catch (TibjmsAdminException e) {
                log.warn(getLogPrefix(session) + "exception on closing Tibjms Admin", e);
            }
        }

        ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(url_work);
        connection = factory.createConnection(cf.getUsername(), cf.getPassword());
        jSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        destination = jSession.createQueue(queueName_work);

        msgProducer = jSession.createProducer(destination);
        TextMessage msg = jSession.createTextMessage();
        msg.setText(input.toString());
        Destination replyQueue = null;
        if (messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY)) {
            replyQueue = jSession.createTemporaryQueue();
            msg.setJMSReplyTo(replyQueue);
            msg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
            msgProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            msgProducer.setTimeToLive(replyTimeout_work);
        } else {
            msg.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
            msgProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
        }
        if (StringUtils.isNotEmpty(soapAction_work)) {
            log.debug(
                    getLogPrefix(session) + "setting [SoapAction] property to value [" + soapAction_work + "]");
            msg.setStringProperty("SoapAction", soapAction_work);
        }
        msgProducer.send(msg);
        if (log.isDebugEnabled()) {
            log.debug(getLogPrefix(session) + "sent message [" + msg.getText() + "] " + "to ["
                    + msgProducer.getDestination() + "] " + "msgID [" + msg.getJMSMessageID() + "] "
                    + "correlationID [" + msg.getJMSCorrelationID() + "] " + "replyTo [" + msg.getJMSReplyTo()
                    + "]");
        } else {
            if (log.isInfoEnabled()) {
                log.info(getLogPrefix(session) + "sent message to [" + msgProducer.getDestination() + "] "
                        + "msgID [" + msg.getJMSMessageID() + "] " + "correlationID ["
                        + msg.getJMSCorrelationID() + "] " + "replyTo [" + msg.getJMSReplyTo() + "]");
            }
        }
        if (messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY)) {
            String replyCorrelationId = msg.getJMSMessageID();
            MessageConsumer msgConsumer = jSession.createConsumer(replyQueue,
                    "JMSCorrelationID='" + replyCorrelationId + "'");
            log.debug(getLogPrefix(session) + "] start waiting for reply on [" + replyQueue + "] selector ["
                    + replyCorrelationId + "] for [" + replyTimeout_work + "] ms");
            try {
                connection.start();
                Message rawReplyMsg = msgConsumer.receive(replyTimeout_work);
                if (rawReplyMsg == null) {
                    throw new PipeRunException(this,
                            getLogPrefix(session) + "did not receive reply on [" + replyQueue
                                    + "] replyCorrelationId [" + replyCorrelationId + "] within ["
                                    + replyTimeout_work + "] ms");
                }
                TextMessage replyMsg = (TextMessage) rawReplyMsg;
                result = replyMsg.getText();
            } finally {
            }

        } else {
            result = msg.getJMSMessageID();
        }
    } catch (JMSException e) {
        throw new PipeRunException(this, getLogPrefix(session) + " exception on sending message to Tibco queue",
                e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                log.warn(getLogPrefix(session) + "exception on closing connection", e);
            }
        }
    }
    return result;
}

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

public void testMessages(Session sess, MessageProducer req_prod, Destination resp_dest, int num_msg)
        throws Exception {
    MessageConsumer resp_cons;/*  ww  w  . j  a  v  a2s  . c om*/
    TextMessage msg;
    MessageClient cons_client;
    int cur;
    int tot_expected;

    resp_cons = sess.createConsumer(resp_dest);

    cons_client = new MessageClient(resp_cons, num_msg);
    cons_client.start();

    cur = 0;
    while ((cur < num_msg) && (!fatalTestError)) {
        msg = sess.createTextMessage("MSG AAAA " + cur);
        msg.setIntProperty("SEQ", 100 + cur);
        msg.setStringProperty("TEST", "TOPO");
        msg.setJMSReplyTo(resp_dest);

        if (cur == (num_msg - 1))
            msg.setBooleanProperty("end-of-response", true);

        sendWithRetryOnDeletedDest(req_prod, msg);
        LOG.debug("Sent:" + msg);

        cur++;
    }

    //
    // Give the consumer some time to receive the response.
    //
    cons_client.waitShutdown(5000);

    //
    // Now shutdown the consumer if it's still running.
    //
    if (cons_client.shutdown())
        LOG.debug("Consumer client shutdown complete");
    else
        LOG.debug("Consumer client shutdown incomplete!!!");

    //
    // Check that the correct number of messages was received.
    //
    tot_expected = num_msg * (echoResponseFill + 1);

    if (cons_client.getNumMsgReceived() == tot_expected) {
        LOG.debug("Have " + tot_expected + " messages, as-expected");
    } else {
        testError = true;

        if (cons_client.getNumMsgReceived() == 0)
            fatalTestError = true;

        LOG.error("Have " + cons_client.getNumMsgReceived() + " messages; expected " + tot_expected
                + " on destination " + resp_dest);
    }

    resp_cons.close();
}

From source file:org.wso2.mb.integration.common.clients.operations.topic.TopicMessagePublisher.java

public void run() {
    try {/*from w w w. j  a v a 2  s .c  om*/
        TextMessage textMessage = null;
        String everything = "";
        if (readFromFile) {
            BufferedReader br = new BufferedReader(new FileReader(filePath));
            try {
                StringBuilder sb = new StringBuilder();
                String line = br.readLine();

                while (line != null) {
                    sb.append(line);
                    sb.append('\n');
                    line = br.readLine();
                }
                everything = sb.toString();
            } finally {

                br.close();

            }
        }
        long threadID = Thread.currentThread().getId();
        int localMessageCount = 0;
        while (messageCounter.get() < numOfMessagesToSend) {
            if (!readFromFile) {
                textMessage = topicSession.createTextMessage(
                        "sending Message:-" + messageCounter.get() + "- " + "ThreadID:" + threadID);
            } else {
                textMessage = topicSession.createTextMessage("sending Message:-" + messageCounter.get() + "- "
                        + "ThreadID:" + threadID + "  " + everything);
            }
            textMessage.setStringProperty("msgID", Integer.toString(messageCounter.get()));

            // Check the message count again before publishing since, messages count might have increased from
            // other threads after the last check,
            // Double checking has been done to reduce the synchronized block size
            synchronized (messageCounter.getClass()) {
                if (messageCounter.get() >= numOfMessagesToSend) {
                    break;
                }
                topicPublisher.send(textMessage, DeliveryMode.PERSISTENT, 0, jmsExpiration);

                messageCounter.incrementAndGet();
            }

            localMessageCount++;
            if (messageCounter.get() % printNumberOfMessagesPer == 0) {

                log.info((readFromFile ? "(FROM FILE)" : "(SIMPLE MESSAGE) ") + "[TOPIC SEND] ThreadID:"
                        + threadID + " topicName:" + topicName + " localMessageCount:" + localMessageCount
                        + " totalMessageCount:" + messageCounter.get() + " count to send:"
                        + numOfMessagesToSend);
            }
            if (isToPrintEachMessage) {
                log.info("(count:" + messageCounter.get() + "/threadID:" + threadID + ") " + textMessage);
            }
            if (delay != 0) {
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException e) {
                    //silently ignore
                }
            }
        }
        stopPublishing();

    } catch (JMSException e) {
        log.error("Error while publishing messages", e);
    } catch (IOException e) {
        log.error("Error while reading from file", e);
    }
}

From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java

public void enqEmail(SmtpMessage msg) throws IOException, JMSException {

    TextMessage bm = session.createTextMessage();
    Gson gson = new Gson();
    bm.setText(gson.toJson(msg));/*from   w w  w. j  a v a2 s .co m*/
    bm.setStringProperty("OriginalQueue", this.smtpQueue);
    bm.setStringProperty("nonce", UUID.randomUUID().toString());
    bm.setStringProperty("JMSXGroupID", "unison-email");
    mp.send(bm);
    //session.commit();

}

From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java

public void enqueue(WorkflowHolder wfHolder) throws ProvisioningException {

    TextMessage bm;
    try {/* w  ww. j av a 2s. co  m*/

        MessageProducer mp;
        MessageProducerHolder mph = null;

        if (this.isInternalQueue()) {
            mp = this.taskMP;
            bm = taskSession.createTextMessage();
            bm.setStringProperty("OriginalQueue", this.taskQueue.getQueueName());
        } else {
            mph = this.getTaskMessageProducer();
            mp = mph.getProducer();
            bm = mph.getSession().createTextMessage();
            bm.setStringProperty("OriginalQueue",
                    ((javax.jms.Queue) mph.getProducer().getDestination()).getQueueName());
        }

        bm.setStringProperty("WorkflowName", wfHolder.getWorkflow().getName());
        bm.setStringProperty("WorkflowSubject", wfHolder.getUser().getUserID());
        bm.setStringProperty("JMSXGroupID", "unison");
        bm.setStringProperty("nonce", UUID.randomUUID().toString());

        TaskHolder holder = wfHolder.getWfStack().peek();
        WorkflowTask task = holder.getParent().get(holder.getPosition());

        bm.setStringProperty("WorkflowCurrentTask", task.getLabel());

        EncryptedMessage encMsg = this.encryptObject(wfHolder);

        String json = JsonWriter.objectToJson(encMsg);
        bm.setText(json);

        try {
            mp.send(bm);
        } finally {
            if (!this.isInternalQueue()) {
                this.returnMessageProducer(mph);
            }
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not enqueue message", e);
    }

}

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

private void processMessage(Message request) {
    try {/*from  w  w w.j  a va  2s  .  c  om*/
        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:edu.ucsd.library.dams.api.DAMSAPIServlet.java

/**
 * Send object to solrizer indexing queue.
 * @param objid Object id//from  w  ww  .j  a va2s. c o  m
 * @param type 'purgeObject' for deletes, 'modifyObject' for other operations.
  * @param priority Value from 0 (lowest) to 9 (highest) -- any other value is treated
 *   as the default priority (4).
 * @return Error message if there was a problem queueing a record for indexing, or null if
 *   the record was queued successfully.
**/
private String indexQueue(String objid, String type, int priority) {
    String error = null;
    if (queueEnabled && queueSession != null) {
        try {
            TextMessage msg = queueSession
                    .createTextMessage("DAMS Queue Message: " + objid + " (" + type + ")");
            msg.setStringProperty("pid", objid);
            msg.setStringProperty("methodName", type);

            if (priority < 1 || priority > 9) {
                priority = DEFAULT_PRIORITY;
            }
            queueProducer.send(msg, queueProducer.getDeliveryMode(), priority, queueProducer.getTimeToLive());
        } catch (Exception ex) {
            log.error("Error sending event to queue", ex);
            error = "Error sending object to queue: " + ex.toString();
        }
    }
    return error;
}