Example usage for javax.jms QueueSender close

List of usage examples for javax.jms QueueSender close

Introduction

In this page you can find the example usage for javax.jms QueueSender close.

Prototype


void close() throws JMSException;

Source Link

Document

Closes the message producer.

Usage

From source file:eu.planets_project.tb.impl.system.batch.backends.ifwee.TestbedWEEBatchProcessor.java

public void submitTicketForPollingToQueue(String ticket, String queueName, String batchProcessorSystemID)
        throws Exception {
    Context ctx = null;/*from   w w w  . ja  v a  2  s  .  c  o  m*/
    QueueConnection cnn = null;
    QueueSession sess = null;
    Queue queue = null;
    QueueSender sender = null;
    try {
        ctx = new InitialContext();
        QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup(QueueConnectionFactoryName);
        queue = (Queue) ctx.lookup(queueName);
        cnn = factory.createQueueConnection();
        sess = cnn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

        //create the message to send to the MDB e.g. a TextMessage
        TextMessage message = sess.createTextMessage(ticket);
        message.setStringProperty(BatchProcessor.QUEUE_PROPERTY_NAME_FOR_SENDING, batchProcessorSystemID);

        //and finally send the message to the queue.
        sender = sess.createSender(queue);
        sender.send(message);
        log.debug("TestbedWEEBatchProcessor: sent message to queue, ID:" + message.getJMSMessageID());
    } finally {
        try {
            if (null != sender)
                sender.close();
        } catch (Exception ex) {
        }
        try {
            if (null != sess)
                sess.close();
        } catch (Exception ex) {
        }
        try {
            if (null != cnn)
                cnn.close();
        } catch (Exception ex) {
        }
        try {
            if (null != ctx)
                ctx.close();
        } catch (Exception ex) {
        }
    }
}

From source file:edu.harvard.iq.dvn.core.index.IndexServiceBean.java

private void sendMessage(final IndexEdit op) {
    QueueConnection conn = null;//from  www.  j  ava2s .  c  o  m
    QueueSession session = null;
    QueueSender sender = null;
    try {
        conn = factory.createQueueConnection();
        session = conn.createQueueSession(false, 0);
        sender = session.createSender(queue);

        Message message = session.createObjectMessage(op);
        sender.send(message);

    } catch (JMSException ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (sender != null) {
                sender.close();
            }
            if (session != null) {
                session.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (JMSException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:edu.harvard.iq.dvn.core.study.StudyFileServiceBean.java

private void addFiles(StudyVersion studyVersion, List<StudyFileEditBean> newFiles, VDCUser user,
        String ingestEmail, int messageLevel) {

    Study study = studyVersion.getStudy();
    MD5Checksum md5Checksum = new MD5Checksum();

    // step 1: divide the files, based on subsettable or not
    List subsettableFiles = new ArrayList();
    List otherFiles = new ArrayList();

    Iterator iter = newFiles.iterator();
    while (iter.hasNext()) {
        StudyFileEditBean fileBean = (StudyFileEditBean) iter.next();
        // Note that for the "special" OtherFiles we want to utilize the 
        // same ingest scheme as for subsettables: they will be queued and 
        // processed asynchronously, and the user will be notified by email.
        // - L.A.
        if (fileBean.getStudyFile().isSubsettable() || fileBean.getStudyFile() instanceof SpecialOtherFile) {
            subsettableFiles.add(fileBean);
        } else {/*from   w  w  w.ja  v  a2  s. co m*/
            otherFiles.add(fileBean);
            // also add to study, so that it will be flushed for the ids
            fileBean.getStudyFile().setStudy(study);
            study.getStudyFiles().add(fileBean.getStudyFile());

        }
    }

    if (otherFiles.size() > 0) {
        // Only persist the studyVersion we are adding a file that doesn't need to be ingested (non-subsettable)
        if (studyVersion.getId() == null) {
            em.persist(studyVersion);
            em.flush(); // populates studyVersion_id
        } else {
            // There is a problem merging the existing studyVersion,
            // so since all we need from the exisiting version is the versionNote,
            // we get a fresh copy of the object from the database, and update it with the versionNote.
            String versionNote = studyVersion.getVersionNote();
            studyVersion = em.find(StudyVersion.class, studyVersion.getId());
            studyVersion.setVersionNote(versionNote);
        }

    }

    // step 2: iterate through nonsubsettable files, moving from temp to new location
    File newDir = FileUtil.getStudyFileDir(study);
    iter = otherFiles.iterator();
    while (iter.hasNext()) {
        StudyFileEditBean fileBean = (StudyFileEditBean) iter.next();
        StudyFile f = fileBean.getStudyFile();
        File tempFile = new File(fileBean.getTempSystemFileLocation());
        File newLocationFile = new File(newDir, f.getFileSystemName());
        try {
            FileUtil.copyFile(tempFile, newLocationFile);
            tempFile.delete();
            f.setFileSystemLocation(newLocationFile.getAbsolutePath());

            fileBean.getFileMetadata().setStudyVersion(studyVersion);

            em.persist(fileBean.getStudyFile());
            em.persist(fileBean.getFileMetadata());

        } catch (IOException ex) {
            throw new EJBException(ex);
        }
        f.setMd5(md5Checksum.CalculateMD5(f.getFileSystemLocation()));
    }

    // step 3: iterate through subsettable files, sending a message via JMS
    if (subsettableFiles.size() > 0) {
        QueueConnection conn = null;
        QueueSession session = null;
        QueueSender sender = null;
        try {
            conn = factory.createQueueConnection();
            session = conn.createQueueSession(false, 0);
            sender = session.createSender(queue);

            DSBIngestMessage ingestMessage = new DSBIngestMessage(messageLevel);
            ingestMessage.setFileBeans(subsettableFiles);
            ingestMessage.setIngestEmail(ingestEmail);
            ingestMessage.setIngestUserId(user.getId());
            ingestMessage.setStudyId(study.getId());
            ingestMessage.setStudyVersionId(studyVersion.getId());
            ingestMessage.setVersionNote(studyVersion.getVersionNote());

            ingestMessage.setStudyTitle(studyVersion.getMetadata().getTitle());
            ingestMessage.setStudyGlobalId(studyVersion.getStudy().getGlobalId());
            ingestMessage.setStudyVersionNumber(studyVersion.getVersionNumber().toString());
            ingestMessage.setDataverseName(studyVersion.getStudy().getOwner().getName());

            Message message = session.createObjectMessage(ingestMessage);

            String detail = "Ingest processing for " + subsettableFiles.size() + " file(s).";
            studyService.addStudyLock(study.getId(), user.getId(), detail);
            try {
                sender.send(message);
            } catch (Exception ex) {
                // If anything goes wrong, remove the study lock.
                studyService.removeStudyLock(study.getId());
                ex.printStackTrace();
            }

            // send an e-mail
            if (ingestMessage.sendInfoMessage()) {
                mailService.sendIngestRequestedNotification(ingestMessage, subsettableFiles);
            }

        } catch (JMSException ex) {
            ex.printStackTrace();
        } finally {
            try {

                if (sender != null) {
                    sender.close();
                }
                if (session != null) {
                    session.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (JMSException ex) {
                ex.printStackTrace();
            }
        }
    }

    if (!otherFiles.isEmpty()) {
        studyService.saveStudyVersion(studyVersion, user.getId());

    }

}

From source file:edu.harvard.iq.dataverse.ingest.IngestServiceBean.java

public void startIngestJobs(Dataset dataset, AuthenticatedUser user) {
    int count = 0;
    List<DataFile> scheduledFiles = new ArrayList<>();

    IngestMessage ingestMessage = null;/*from w ww .j  a v  a2  s  .c  om*/

    for (DataFile dataFile : dataset.getFiles()) {
        if (dataFile.isIngestScheduled()) {
            // todo: investigate why when calling save with the file object
            // gotten from the loop, the roles assignment added at create is removed
            // (switching to refinding via id resolves that)                
            dataFile = fileService.find(dataFile.getId());

            long ingestSizeLimit = -1;
            try {
                ingestSizeLimit = systemConfig.getTabularIngestSizeLimit(
                        getTabDataReaderByMimeType(dataFile.getContentType()).getFormatName());
            } catch (IOException ioex) {
                logger.warning(
                        "IO Exception trying to retrieve the ingestable format identifier from the plugin for type "
                                + dataFile.getContentType() + " (non-fatal);");
            }

            if (ingestSizeLimit == -1 || dataFile.getFilesize() < ingestSizeLimit) {
                dataFile.SetIngestInProgress();
                dataFile = fileService.save(dataFile);

                scheduledFiles.add(dataFile);

                logger.fine("Attempting to queue the file " + dataFile.getFileMetadata().getLabel()
                        + " for ingest, for dataset: " + dataset.getGlobalId());
                count++;
            } else {
                dataFile.setIngestDone();
                dataFile = fileService.save(dataFile);

                logger.info("Skipping tabular ingest of the file " + dataFile.getFileMetadata().getLabel()
                        + ", because of the size limit (set to " + ingestSizeLimit + " bytes).");
                // TODO: (urgent!)
                // send notification to the user!
            }
        }
    }

    if (count > 0) {
        String info = "Attempting to ingest " + count + " tabular data file(s).";
        logger.info(info);
        if (user != null) {
            datasetService.addDatasetLock(dataset.getId(), user.getId(), info);
        } else {
            datasetService.addDatasetLock(dataset.getId(), null, info);
        }

        DataFile[] scheduledFilesArray = (DataFile[]) scheduledFiles.toArray(new DataFile[count]);
        scheduledFiles = null;

        // Sort ingest jobs by file size: 
        Arrays.sort(scheduledFilesArray, new Comparator<DataFile>() {
            @Override
            public int compare(DataFile d1, DataFile d2) {
                long a = d1.getFilesize();
                long b = d2.getFilesize();
                return Long.valueOf(a).compareTo(b);
            }
        });

        ingestMessage = new IngestMessage(IngestMessage.INGEST_MESAGE_LEVEL_INFO);

        for (int i = 0; i < count; i++) {
            ingestMessage.addFileId(scheduledFilesArray[i].getId());
            logger.fine("Sorted order: " + i + " (size=" + scheduledFilesArray[i].getFilesize() + ")");
        }

        QueueConnection conn = null;
        QueueSession session = null;
        QueueSender sender = null;
        try {
            conn = factory.createQueueConnection();
            session = conn.createQueueSession(false, 0);
            sender = session.createSender(queue);

            //ingestMessage.addFile(new File(tempFileLocation));
            Message message = session.createObjectMessage(ingestMessage);

            //try {
            sender.send(message);
            //} catch (JMSException ex) {
            //    ex.printStackTrace();
            //}

        } catch (JMSException ex) {
            ex.printStackTrace();
            //throw new IOException(ex.getMessage());
        } finally {
            try {

                if (sender != null) {
                    sender.close();
                }
                if (session != null) {
                    session.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (JMSException ex) {
                ex.printStackTrace();
            }
        }
    }
}

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

/**
 * Intended for server-side reponse sending and implies that the received
 * message *always* contains a reply-to address.
 *///from   w w  w.j av a  2 s  . co m
public void sendReply(QueueSession session, Message received_message, String response) throws IfsaException {
    QueueSender tqs = null;
    try {
        TextMessage answer = session.createTextMessage();
        answer.setText(response);
        Queue replyQueue = (Queue) received_message.getJMSReplyTo();
        tqs = session.createSender(replyQueue);
        if (log.isDebugEnabled())
            log.debug(getLogPrefix() + "sending reply to [" + received_message.getJMSReplyTo() + "]");
        ((IFSAServerQueueSender) tqs).sendReply(received_message, answer);
    } catch (Throwable t) {
        throw new IfsaException(t);
    } finally {
        if (tqs != null) {
            try {
                tqs.close();
            } catch (JMSException e) {
                log.warn(getLogPrefix() + "exception closing reply queue sender", e);
            }
        }
    }
}

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

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

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

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

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

        if (isSynchronous()) {

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

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

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

protected String sendByQueue(QueueSession session, Queue destination, Message message)
        throws NamingException, JMSException {
    QueueSender tqs = session.createSender(destination);
    tqs.send(message);/*from w w  w .ja v a  2  s  .c  om*/
    tqs.close();
    return message.getJMSMessageID();
}

From source file:org.apache.stratos.status.monitor.agent.clients.service.CEPServerClient.java

private static void executeService() throws SQLException {
    int serviceID = MySQLConnectionInitializer.getServiceID(StatusMonitorConstants.CEP);
    AuthConfigBean authConfigBean = StatusMonitorConfigurationBuilder.getAuthConfigBean();

    String userName = authConfigBean.getUserName();
    tcpUserName = userName.replace('@', '!');

    //check whether login success
    if (ServiceLoginClient.loginChecker(StatusMonitorConstants.CEP_HOST, serviceID)) {

        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, StatusMonitorAgentConstants.QPID_ICF);
        properties.put(StatusMonitorAgentConstants.CF_NAME_PREFIX + StatusMonitorAgentConstants.CF_NAME,
                getTCPConnectionURL(tcpUserName, authConfigBean.getPassword()));

        InitialContext ctx;//ww  w . ja  v  a 2s  .  com
        try {
            ctx = new InitialContext(properties);

            // Lookup connection factory
            QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx
                    .lookup(StatusMonitorAgentConstants.CF_NAME);
            QueueConnection queueConnection = connFactory.createQueueConnection();
            queueConnection.start();
            QueueSession queueSession = queueConnection.createQueueSession(false,
                    QueueSession.AUTO_ACKNOWLEDGE);

            // Send message
            Queue queue = queueSession.createQueue(
                    StatusMonitorAgentConstants.QUEUE_NAME_CEP + ";{create:always, node:{durable: True}}");

            // create the message to send
            TextMessage textMessage = queueSession.createTextMessage("Test Message Hello");
            javax.jms.QueueSender queueSender = queueSession.createSender(queue);
            queueSender.setTimeToLive(100000000);

            QueueReceiver queueReceiver = queueSession.createReceiver(queue);
            queueSender.send(textMessage);

            TextMessage message = (TextMessage) queueReceiver.receiveNoWait();
            if (log.isDebugEnabled()) {
                log.debug("Message in the execute() of CEPServer Client: " + message.getText());
            }
            if (message.getText().equals("Test Message Hello")) {
                MySQLConnector.insertStats(serviceID, true);
                MySQLConnector.insertState(serviceID, true, "");
            } else {
                MySQLConnector.insertStats(serviceID, false);
                MySQLConnector.insertState(serviceID, false, "Send or retrieve messages failed");
            }
            queueSender.close();
            queueSession.close();
            queueConnection.close();

        } catch (JMSException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "JMS Exception in inserting stats into the DB for the CEPServerClient";
            log.warn(msg, e);
        } catch (NamingException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "Naming Exception in inserting stats into the DB for the CEPServerClient";
            log.warn(msg, e);
        }
    }
}

From source file:org.apache.stratos.status.monitor.agent.clients.service.MessageBrokerServiceClient.java

private static void executeService() throws SQLException {
    int serviceID = MySQLConnectionInitializer.getServiceID(StatusMonitorConstants.MESSAGING);
    AuthConfigBean authConfigBean = StatusMonitorConfigurationBuilder.getAuthConfigBean();

    String userName = authConfigBean.getUserName();
    tcpUserName = userName.replace('@', '!');

    //check whether login success
    if (ServiceLoginClient.loginChecker(StatusMonitorConstants.MESSAGING_HOST, serviceID)) {

        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, StatusMonitorAgentConstants.QPID_ICF);
        properties.put(StatusMonitorAgentConstants.CF_NAME_PREFIX + StatusMonitorAgentConstants.CF_NAME,
                getTCPConnectionURL(tcpUserName, authConfigBean.getPassword()));

        if (log.isDebugEnabled()) {
            log.debug("getTCPConnectionURL(username,password) = "
                    + getTCPConnectionURL(tcpUserName, authConfigBean.getPassword()));
        }// w w w .  j  a v a  2 s.c  om
        try {
            InitialContext ctx = new InitialContext(properties);
            // Lookup connection factory
            QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx
                    .lookup(StatusMonitorAgentConstants.CF_NAME);
            QueueConnection queueConnection = connFactory.createQueueConnection();
            queueConnection.start();
            QueueSession queueSession = queueConnection.createQueueSession(false,
                    QueueSession.AUTO_ACKNOWLEDGE);

            // Send message
            Queue queue = queueSession.createQueue(
                    StatusMonitorAgentConstants.QUEUE_NAME_MB + ";{create:always, node:{durable: True}}");

            // create the message to send
            TextMessage textMessage = queueSession.createTextMessage("Test Message Hello");
            javax.jms.QueueSender queueSender = queueSession.createSender(queue);
            queueSender.setTimeToLive(100000000);

            QueueReceiver queueReceiver = queueSession.createReceiver(queue);
            queueSender.send(textMessage);

            TextMessage message = (TextMessage) queueReceiver.receiveNoWait();

            if (message.getText().equals("Test Message Hello")) {
                MySQLConnector.insertStats(serviceID, true);
                MySQLConnector.insertState(serviceID, true, "");
            } else {
                MySQLConnector.insertStats(serviceID, false);
                MySQLConnector.insertState(serviceID, false, "Send and retrieve messages failed");
            }
            queueSender.close();
            queueSession.close();
            queueConnection.close();

        } catch (JMSException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "Exception in executing the client - "
                    + "Status Monitor Agent for MessageBrokerServiceClient";
            log.warn(msg, e);

        } catch (NamingException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "Naming exception in executing the client - "
                    + "Status Monitor agent for MessageBrokerServiceClient";
            log.warn(msg, e);
        }
    }
}

From source file:org.grouter.common.jms.QueueListenerDestination.java

/**
 * <br>// ww  w  . j a v  a 2  s  .  c o m
 */
public void sendReplyToTemporaryDestination(Message request) {
    TemporaryQueue replyQueue = null;
    QueueSender tempsender = null;
    String temporaryDestinationName = null;
    try {
        if (request.getJMSReplyTo() == null) {
            throw new IllegalStateException("The sender of this message has not entered a JMSReplyTo field - "
                    + "impossible to send reply on temporary destination!!");
        }
        temporaryDestinationName = request.getJMSReplyTo().toString();
        request.setJMSCorrelationID(temporaryDestinationName);
        replyQueue = (TemporaryQueue) request.getJMSReplyTo();
        tempsender = queueSession.createSender(replyQueue);
        tempsender.send(request);
        logger.debug("Created a tempsender and sent reply to " + replyQueue);
    } catch (JMSException ex) {
        //ignore
        logger.warn("Failed sending reply on temporary destination : " + temporaryDestinationName);
    } finally {
        try {
            if (tempsender != null) {
                tempsender.close();
            }
            if (replyQueue != null) {
                replyQueue.delete();
            }
        } catch (JMSException ex1) {
            //ignore
        }
    }
}