Example usage for javax.jms QueueSender send

List of usage examples for javax.jms QueueSender send

Introduction

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

Prototype


void send(Message message) throws JMSException;

Source Link

Document

Sends a message to the queue.

Usage

From source file:io.datalayer.activemq.producer.SimpleQueueSender.java

/**
 * Main method./* w w  w.  j  a  v a2s  . c  o m*/
 * 
 * @param args the queue used by the example and, optionally, the number of
 *                messages to send
 */
public static void main(String... args) {
    String queueName = null;
    Context jndiContext = null;
    QueueConnectionFactory queueConnectionFactory = null;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    Queue queue = null;
    QueueSender queueSender = null;
    TextMessage message = null;
    final int numMsgs;

    if ((args.length < 1) || (args.length > 2)) {
        LOG.info("Usage: java SimpleQueueSender " + "<queue-name> [<number-of-messages>]");
        System.exit(1);
    }
    queueName = args[0];
    LOG.info("Queue name is " + queueName);
    if (args.length == 2) {
        numMsgs = (new Integer(args[1])).intValue();
    } else {
        numMsgs = 1;
    }

    /*
     * Create a JNDI API InitialContext object if none exists yet.
     */
    try {
        jndiContext = new InitialContext();
    } catch (NamingException e) {
        LOG.info("Could not create JNDI API context: " + e.toString());
        System.exit(1);
    }

    /*
     * Look up connection factory and queue. If either does not exist, exit.
     */
    try {
        queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory");
        queue = (Queue) jndiContext.lookup(queueName);
    } catch (NamingException e) {
        LOG.info("JNDI API lookup failed: " + e);
        System.exit(1);
    }

    /*
     * Create connection. Create session from connection; false means
     * session is not transacted. Create sender and text message. Send
     * messages, varying text slightly. Send end-of-messages message.
     * Finally, close connection.
     */
    try {
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        message = queueSession.createTextMessage();
        for (int i = 0; i < numMsgs; i++) {
            message.setText("This is message " + (i + 1));
            LOG.info("Sending message: " + message.getText());
            queueSender.send(message);
        }

        /*
         * Send a non-text control message indicating end of messages.
         */
        queueSender.send(queueSession.createMessage());
    } catch (JMSException e) {
        LOG.info("Exception occurred: " + e.toString());
    } finally {
        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
            }
        }
    }
}

From source file:org.apache.servicemix.jms.JmsMarshalerTest.java

public void testMarshalTextMessage() throws Exception {
    JmsComponent jms = new JmsComponent();
    jms.getConfiguration().setConnectionFactory(connectionFactory);
    JmsEndpoint ep = new JmsEndpoint();
    ep.setService(ReceiverComponent.SERVICE);
    ep.setEndpoint("jms");
    ep.setTargetService(ReceiverComponent.SERVICE);
    ep.setTargetEndpoint(ReceiverComponent.ENDPOINT);
    ep.setRole(MessageExchange.Role.CONSUMER);
    ep.setDestinationStyle(AbstractJmsProcessor.STYLE_QUEUE);
    ep.setDestination(queue);/*from   w  w  w  . j  a  v  a2 s  . c  o m*/
    ep.setDefaultMep(JbiConstants.IN_ONLY);
    ep.setMarshaler(new DefaultJmsMarshaler(ep));
    jms.setEndpoints(new JmsEndpoint[] { ep });
    container.activateComponent(jms, "servicemix-jms");

    ReceiverComponent receiver = new ReceiverComponent();
    container.activateComponent(receiver, "receiver");

    QueueConnection qConn = connectionFactory.createQueueConnection();
    QueueSession qSess = qConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    QueueSender qSender = qSess.createSender(queue);
    TextMessage message = qSess
            .createTextMessage("<?xml version=\"1.0\" encoding=\"UTF-8\"?><hello>world</hello>");
    qSender.send(message);

    receiver.getMessageList().assertMessagesReceived(1);
    List msgs = receiver.getMessageList().flushMessages();
    NormalizedMessage msg = (NormalizedMessage) msgs.get(0);
    assertEquals("Messages match", message.getText(), new SourceTransformer().contentToString(msg));

    // Wait for DONE status
    Thread.sleep(50);
}

From source file:org.panksdmz.jms.tibco.MessageSenderBean.java

public void send() {
    try {/*from  w w w  .j a  v  a2  s  .  com*/
        QueueConnection connection = connectionFactory.createQueueConnection();
        QueueSession session = connection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(sendQueueName);
        QueueSender sender = session.createSender(queue);
        TextMessage message = session
                .createTextMessage("Message @ " + CaliHDateTime.now().getTimeInMillis() + " from thread "
                        + Thread.currentThread().getId() + " from session [" + session.toString() + "]");

        sender.send(message);
        session.close();

    } catch (JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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   ww w . ja  v a 2  s.co 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 w  w w  .j a  v  a2  s.  c om
    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  ww.j  a va  2 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;/*w  ww  .j a  v a 2s. 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

/**
 * Sends a message,and if transacted, the queueSession is committed.
 * <p>This method is intended for <b>clients</b>, as <b>server</b>s
 * will use the <code>sendReply</code>.
 * @return the correlationID of the sent message
 *///from  ww w  . ja  v  a2  s  .  c  o m
public TextMessage sendMessage(QueueSession session, QueueSender sender, String message, Map udzMap,
        String bifName, byte btcData[]) throws IfsaException {

    try {
        if (!isRequestor()) {
            throw new IfsaException(getLogPrefix() + "Provider cannot use sendMessage, should use sendReply");
        }
        IFSATextMessage msg = (IFSATextMessage) session.createTextMessage();
        msg.setText(message);
        if (udzMap != null && msg instanceof IFSAMessage) {
            // Handle UDZs
            log.debug(getLogPrefix() + "add UDZ map to IFSAMessage");
            // process the udzMap
            Map udzObject = (Map) ((IFSAMessage) msg).getOutgoingUDZObject();
            udzObject.putAll(udzMap);
        }
        String replyToQueueName = "-";
        //Client side
        if (messageProtocol.equals(IfsaMessageProtocolEnum.REQUEST_REPLY)) {
            // set reply-to address
            Queue replyTo = getMessagingSource().getClientReplyQueue(session);
            msg.setJMSReplyTo(replyTo);
            replyToQueueName = replyTo.getQueueName();
        }
        if (messageProtocol.equals(IfsaMessageProtocolEnum.FIRE_AND_FORGET)) {
            // not applicable
        }
        if (StringUtils.isNotEmpty(bifName)) {
            msg.setBifName(bifName);
        }
        if (btcData != null && btcData.length > 0) {
            msg.setBtcData(btcData);
        }

        if (log.isDebugEnabled()) {
            log.debug(getLogPrefix() + " messageProtocol [" + messageProtocol + "] replyToQueueName ["
                    + replyToQueueName + "] sending message [" + message + "]");
        } else {
            if (log.isInfoEnabled()) {
                log.info(getLogPrefix() + " messageProtocol [" + messageProtocol + "] replyToQueueName ["
                        + replyToQueueName + "] sending message");
            }
        }

        // send the message
        sender.send(msg);

        // perform commit
        if (isJmsTransacted() && !(messagingSource.isXaEnabledForSure() && JtaUtil.inTransaction())) {
            session.commit();
            log.debug(getLogPrefix() + "committing (send) transaction");
        }

        return msg;

    } catch (Exception e) {
        throw new IfsaException(e);
    }
}

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);
    tqs.close();/*from  w  ww.  j a v a  2  s  . c  om*/
    return message.getJMSMessageID();
}

From source file:org.apache.activemq.demo.SimpleQueueSender.java

/**
 * Main method.//from   ww  w .ja  va  2  s  .c  om
 *
 * @param args the queue used by the example and, optionally, the number of
 *                messages to send
 */
public static void main(String[] args) {
    String queueName = null;
    Context jndiContext = null;
    QueueConnectionFactory queueConnectionFactory = null;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    Queue queue = null;
    QueueSender queueSender = null;
    TextMessage message = null;
    final int numMsgs;

    if ((args.length < 1) || (args.length > 2)) {
        LOG.info("Usage: java SimpleQueueSender " + "<queue-name> [<number-of-messages>]");
        System.exit(1);
    }
    queueName = args[0];
    LOG.info("Queue name is " + queueName);
    if (args.length == 2) {
        numMsgs = (new Integer(args[1])).intValue();
    } else {
        numMsgs = 1;
    }

    /*
     * Create a JNDI API InitialContext object if none exists yet.
     */
    try {
        jndiContext = new InitialContext();
    } catch (NamingException e) {
        LOG.info("Could not create JNDI API context: " + e.toString());
        System.exit(1);
    }

    /*
     * Look up connection factory and queue. If either does not exist, exit.
     */
    try {
        queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory");
        queue = (Queue) jndiContext.lookup(queueName);
    } catch (NamingException e) {
        LOG.info("JNDI API lookup failed: " + e);
        System.exit(1);
    }

    /*
     * Create connection. Create session from connection; false means
     * session is not transacted. Create sender and text message. Send
     * messages, varying text slightly. Send end-of-messages message.
     * Finally, close connection.
     */
    try {
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        message = queueSession.createTextMessage();
        for (int i = 0; i < numMsgs; i++) {
            message.setText("This is message " + (i + 1));
            LOG.info("Sending message: " + message.getText());
            queueSender.send(message);
        }

        /*
         * Send a non-text control message indicating end of messages.
         */
        queueSender.send(queueSession.createMessage());
    } catch (JMSException e) {
        LOG.info("Exception occurred: " + e.toString());
    } finally {
        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
            }
        }
    }
}