Example usage for javax.jms Session createProducer

List of usage examples for javax.jms Session createProducer

Introduction

In this page you can find the example usage for javax.jms Session createProducer.

Prototype


MessageProducer createProducer(Destination destination) throws JMSException;

Source Link

Document

Creates a MessageProducer to send messages to the specified destination.

Usage

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

private Object doSendAndReceiveAsync(Destination requestDestination, javax.jms.Message jmsRequest,
        Session session, int priority) throws JMSException {
    String correlationId = null;//from   w w  w .j  a va  2s  .co m
    MessageProducer messageProducer = null;
    try {
        messageProducer = session.createProducer(requestDestination);
        correlationId = this.gatewayCorrelation + "_" + Long.toString(this.correlationId.incrementAndGet());
        if (this.correlationKey.equals("JMSCorrelationID")) {
            jmsRequest.setJMSCorrelationID(correlationId);
        } else {
            jmsRequest.setStringProperty(this.correlationKey, correlationId);
            /*
             * Remove any existing correlation id that was mapped from the inbound message
             * (it will be restored in the reply by normal ARPMH header processing).
             */
            jmsRequest.setJMSCorrelationID(null);
        }
        LinkedBlockingQueue<javax.jms.Message> replyQueue = null;
        if (logger.isDebugEnabled()) {
            logger.debug(this.getComponentName() + " Sending message with correlationId " + correlationId);
        }
        SettableListenableFuture<AbstractIntegrationMessageBuilder<?>> future = null;
        boolean async = isAsync();
        if (!async) {
            replyQueue = new LinkedBlockingQueue<javax.jms.Message>(1);
            this.replies.put(correlationId, replyQueue);
        } else {
            future = createFuture(correlationId);
        }

        this.sendRequestMessage(jmsRequest, messageProducer, priority);

        if (async) {
            return future;
        } else {
            return obtainReplyFromContainer(correlationId, replyQueue);
        }
    } finally {
        JmsUtils.closeMessageProducer(messageProducer);
        if (correlationId != null && !isAsync()) {
            this.replies.remove(correlationId);
        }
    }
}

From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java

public void testCommonsEmailOneWaySeparateSessions() {

    Queue emailQueue = null;/*www.  j  a va2  s  . co m*/
    MessageConsumer consumer = null;
    MessageProducer producer = null;
    Session clientSession = null;
    Session listenerSession = null;
    // it is not necessary to use the Email interface here
    // Email is used here just to allow for multiple types of emails to
    // occupy
    // the same varaible. SimpleEmail etc can each be used directly.
    List<Email> emails = new ArrayList<Email>();
    EmailMessagingService messagingService = new EmailMessagingService(vmURL, emailQueueName, emailType, null,
            null, null, null);
    emails.add(new SimpleEmail(messagingService));
    emails.add(new MultiPartEmail(messagingService));
    emails.add(new HtmlEmail(messagingService));
    try {

        listenerSession = listenerConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = listenerSession.createQueue(emailQueueName);

        consumer = listenerSession.createConsumer(emailQueue);

        consumer.setMessageListener(new EmailListener());

        listenerConn.start();

        listenerSession.run();

    } catch (JMSException e2) {
        e2.printStackTrace();
        Assert.assertTrue(false);
    }

    Wiser smtpServer = new Wiser();
    smtpServer.setPort(smtpTestPort);
    smtpServer.start();

    try {
        clientSession = clientConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = clientSession.createQueue(emailQueueName);
        producer = clientSession.createProducer(emailQueue);

        clientConn.start();
        clientSession.run();

    } catch (JMSException e) {
        e.printStackTrace();
        Assert.assertTrue(false);
    }

    for (Email em : emails) {

        try {
            em.addTo(TEST_EMAIL_TO);
            em.setFrom(TEST_EMAIL_FROM_ADDRESS, TEST_EMAIL_FROM_LABEL);
            // host and port will be ignored since the email session is
            // established
            // by
            // the listener
            em.setHostName("localhost");
            em.setSmtpPort(smtpTestPort);
            em.setSubject(TEST_EMAIL_SUBJECT);
            if (em instanceof HtmlEmail) {
                em.setMsg(TEST_EMAIL_BODY_HTMLEMAIL);
            } else if (em instanceof MultiPartEmail) {
                em.setMsg(TEST_EMAIL_BODY_MULTIPARTEMAIL);
            } else if (em instanceof SimpleEmail) {
                em.setMsg(TEST_EMAIL_BODY_SIMPLEEMAIL);
            }

        } catch (EmailException e1) {
            Assert.assertTrue(false);
            e1.printStackTrace();
        }

        try {
            em.buildMimeMessage();
        } catch (EmailException e1) {
            e1.printStackTrace();
            Assert.assertTrue(false);
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {

            em.getMimeMessage().writeTo(os);
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        } catch (IOException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

        String content = os.toString();

        ObjectMessage om;
        try {
            om = clientSession.createObjectMessage(content);

            om.setJMSType(emailType);

            LOG.info("Client: Sending test message....");
            producer.send(om);
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

    }

    long start = System.currentTimeMillis();
    while (listenerMessagesProcessed < 3 && System.currentTimeMillis() - start < 10000L) {
        // wait for transport
    }
    Assert.assertTrue(listenerMessagesProcessed == 3);

    List<WiserMessage> messages = smtpServer.getMessages();
    Assert.assertTrue(messages.size() + " != expected value of 3", messages.size() == 3);

    for (WiserMessage wisermsg : messages) {
        String body = null;
        String subject = null;
        MimeMessage testmail = null;

        try {
            testmail = wisermsg.getMimeMessage();
        } catch (MessagingException e) {
            Assert.assertTrue(false);
            e.printStackTrace();
        }

        if (testmail != null) {
            LOG.info("SMTP server: test email received: ");
            try {
                LOG.info("To: " + testmail.getHeader("To", ","));

                LOG.info("Subject: " + testmail.getHeader("Subject", ","));
                body = getBodyAsString(testmail.getContent());
                subject = testmail.getHeader("Subject", ",");
            } catch (MessagingException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            } catch (IOException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            }
            LOG.info("Body: " + body);
            Assert.assertTrue(subject.contains(TEST_EMAIL_SUBJECT));
            Assert.assertTrue(body.contains("This is a Commons"));
        } else {
            Assert.assertTrue(false);
        }
    }

    if (clientSession != null) {
        try {
            clientSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        clientSession = null;
    }

    if (listenerSession != null) {
        try {
            listenerSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        listenerSession = null;
    }

    smtpServer.stop();

}

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

public String send(Session session, Destination dest, String correlationId, String message, String messageType,
        long timeToLive, int deliveryMode, int priority, boolean ignoreInvalidDestinationException,
        Map properties) throws NamingException, JMSException, SenderException {
    TextMessage msg = createTextMessage(session, correlationId, message);
    MessageProducer mp;//from w  w  w.j ava2 s . co  m
    try {
        if (useJms102()) {
            if ((session instanceof TopicSession) && (dest instanceof Topic)) {
                mp = getTopicPublisher((TopicSession) session, (Topic) dest);
            } else {
                if ((session instanceof QueueSession) && (dest instanceof Queue)) {
                    mp = getQueueSender((QueueSession) session, (Queue) dest);
                } else {
                    throw new SenderException(
                            "classes of Session [" + session.getClass().getName() + "] and Destination ["
                                    + dest.getClass().getName() + "] do not match (Queue vs Topic)");
                }
            }
        } else {
            mp = session.createProducer(dest);
        }
    } catch (InvalidDestinationException e) {
        if (ignoreInvalidDestinationException) {
            log.warn("queue [" + dest + "] doesn't exist");
            return null;
        } else {
            throw e;
        }
    }
    if (messageType != null) {
        msg.setJMSType(messageType);
    }
    if (deliveryMode > 0) {
        msg.setJMSDeliveryMode(deliveryMode);
        mp.setDeliveryMode(deliveryMode);
    }
    if (priority >= 0) {
        msg.setJMSPriority(priority);
        mp.setPriority(priority);
    }
    if (timeToLive > 0) {
        mp.setTimeToLive(timeToLive);
    }
    if (properties != null) {
        for (Iterator it = properties.keySet().iterator(); it.hasNext();) {
            String key = (String) it.next();
            Object value = properties.get(key);
            log.debug("setting property [" + name + "] to value [" + value + "]");
            msg.setObjectProperty(key, value);
        }
    }
    String result = send(mp, msg, ignoreInvalidDestinationException);
    mp.close();
    return result;
}

From source file:org.jbpm.bpel.integration.server.SoapHandler.java

protected ObjectMessage sendRequest(SOAPMessage soapMessage, Session jmsSession, JbpmContext jbpmContext)
        throws SOAPException, JMSException {
    // create a jms message to deliver the incoming content
    ObjectMessage jmsRequest = jmsSession.createObjectMessage();

    // put the partner link identified by handle in a jms property
    PartnerLinkEntry partnerLinkEntry = integrationControl.getPartnerLinkEntry(portTypeName, serviceName,
            portName);//from  ww  w. j  a va  2  s.com
    long partnerLinkId = partnerLinkEntry.getId();
    jmsRequest.setLongProperty(IntegrationConstants.PARTNER_LINK_ID_PROP, partnerLinkId);

    Operation operation = determineOperation(soapMessage);
    if (operation == null)
        throw new SOAPException("could not determine operation to perform");

    // put the operation name in a jms property
    String operationName = operation.getName();
    jmsRequest.setStringProperty(IntegrationConstants.OPERATION_NAME_PROP, operationName);

    log.debug("received request: partnerLink=" + partnerLinkId + ", operation=" + operationName);

    // extract message content
    HashMap requestParts = new HashMap();
    formatter.readMessage(operationName, soapMessage, requestParts, MessageDirection.INPUT);
    jmsRequest.setObject(requestParts);

    // fill message properties
    BpelProcessDefinition process = integrationControl.getDeploymentDescriptor()
            .findProcessDefinition(jbpmContext);
    MessageType requestType = process.getImportDefinition()
            .getMessageType(operation.getInput().getMessage().getQName());
    fillCorrelationProperties(requestParts, jmsRequest, requestType.getPropertyAliases());

    // set up producer
    MessageProducer producer = jmsSession.createProducer(partnerLinkEntry.getDestination());
    try {
        // is the exchange pattern request/response?
        if (operation.getOutput() != null) {
            Destination replyTo = integrationControl.getIntegrationServiceFactory().getResponseDestination();
            jmsRequest.setJMSReplyTo(replyTo);

            // have jms discard request message if response timeout expires
            Number responseTimeout = getResponseTimeout(jbpmContext);
            if (responseTimeout != null)
                producer.setTimeToLive(responseTimeout.longValue());
        } else {
            // have jms discard message if one-way timeout expires
            Number oneWayTimeout = getOneWayTimeout(jbpmContext);
            if (oneWayTimeout != null)
                producer.setTimeToLive(oneWayTimeout.longValue());
        }

        // send request message
        producer.send(jmsRequest);
        log.debug("sent request: " + RequestListener.messageToString(jmsRequest));

        return jmsRequest;
    } finally {
        // release producer resources
        producer.close();
    }
}

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

/**
 * Creates the MessageConsumer after sending the request Message since we need
 * the MessageID for correlation with a MessageSelector.
 *//*from w ww .j  a  v  a2s  . c o m*/
private javax.jms.Message doSendAndReceiveWithMessageIdCorrelation(Destination requestDestination,
        javax.jms.Message jmsRequest, Destination replyTo, Session session, int priority) throws JMSException {
    if (replyTo instanceof Topic && logger.isWarnEnabled()) {
        logger.warn(
                "Relying on the MessageID for correlation is not recommended when using a Topic as the replyTo Destination "
                        + "because that ID can only be provided to a MessageSelector after the request Message has been sent thereby "
                        + "creating a race condition where a fast response might be sent before the MessageConsumer has been created. "
                        + "Consider providing a value to the 'correlationKey' property of this gateway instead. Then the MessageConsumer "
                        + "will be created before the request Message is sent.");
    }
    MessageProducer messageProducer = null;
    try {
        messageProducer = session.createProducer(requestDestination);
        this.sendRequestMessage(jmsRequest, messageProducer, priority);
        String messageId = jmsRequest.getJMSMessageID().replaceAll("'", "''");
        String messageSelector = "JMSCorrelationID = '" + messageId + "'";
        return retryableReceiveReply(session, replyTo, messageSelector);
    } finally {
        JmsUtils.closeMessageProducer(messageProducer);
    }
}

From source file:org.wso2.extension.siddhi.io.jms.source.client.JMSClient.java

public void sendJMSEvents(String filePath, String topicName, String queueName, String format, String broker,
        String providerURL) {//from  w  ww . j a  v  a  2 s .  c o m
    if (format == null || "map".equals(format)) {
        format = "csv";
    }
    if ("".equalsIgnoreCase(broker)) {
        broker = "activemq";
    }
    Session session = null;
    Properties properties = new Properties();
    if (!"activemq".equalsIgnoreCase(broker) && !"mb".equalsIgnoreCase(broker)
            && !"qpid".equalsIgnoreCase(broker)) {
        log.error("Please enter a valid JMS message broker. (ex: activemq, mb, qpid");
        return;
    }
    try {
        if (topicName != null && !"".equalsIgnoreCase(topicName)) {
            TopicConnection topicConnection;
            TopicConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                // to provide custom provider urls
                if (providerURL != null) {
                    properties.put(Context.PROVIDER_URL, providerURL);
                }
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                topicConnection = connFactory.createTopicConnection();
                topicConnection.start();
                session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Topic topic = session.createTopic(topicName);
                    MessageProducer producer = session.createProducer(topic);
                    List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + topicName + "' topic");
                            JMSClientUtil.publishMapMessage(producer, session, messagesList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + topicName + "' topic");
                            JMSClientUtil.publishTextMessage(producer, session, messagesList);
                        }
                        log.info("All Order Messages sent");
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        topicConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else if (queueName != null && !queueName.equalsIgnoreCase("")) {
            QueueConnection queueConnection;
            QueueConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                queueConnection = connFactory.createQueueConnection();
                queueConnection.start();
                session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Queue queue = session.createQueue(queueName);
                    MessageProducer producer = session.createProducer(queue);
                    List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + queueName + "' queue");
                            JMSClientUtil.publishMapMessage(producer, session, messagesList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + queueName + "' queue");
                            JMSClientUtil.publishTextMessage(producer, session, messagesList);
                        }
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        queueConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else {
            log.error("Enter queue name or topic name to be published!");
        }
    } catch (Exception e) {
        log.error("Error when publishing" + e.getMessage(), e);
    }
}

From source file:org.wso2.extension.siddhi.io.jms.source.client.JMSClient.java

public void sendJMSEvents(List<String> messageList, String topicName, String queueName, String format,
        String broker, String providerURL) {
    if (format == null || "map".equals(format)) {
        format = "csv";
    }//from   w w w . j ava  2s  .  com
    if ("".equalsIgnoreCase(broker)) {
        broker = "activemq";
    }
    Session session = null;
    Properties properties = new Properties();
    if (!"activemq".equalsIgnoreCase(broker) && !"mb".equalsIgnoreCase(broker)
            && !"qpid".equalsIgnoreCase(broker)) {
        log.error("Please enter a valid JMS message broker. (ex: activemq, mb, qpid");
        return;
    }
    try {
        if (topicName != null && !"".equalsIgnoreCase(topicName)) {
            TopicConnection topicConnection;
            TopicConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                // to provide custom provider urls
                if (providerURL != null) {
                    properties.put(Context.PROVIDER_URL, providerURL);
                }
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                topicConnection = connFactory.createTopicConnection();
                topicConnection.start();
                session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Topic topic = session.createTopic(topicName);
                    MessageProducer producer = session.createProducer(topic);
                    //List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + topicName + "' topic");
                            JMSClientUtil.publishMapMessage(producer, session, messageList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + topicName + "' topic");
                            JMSClientUtil.publishTextMessage(producer, session, messageList);
                        }
                        log.info("All Order Messages sent");
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        topicConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else if (queueName != null && !queueName.equalsIgnoreCase("")) {
            QueueConnection queueConnection;
            QueueConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                // to provide custom provider urls
                if (providerURL != null) {
                    properties.put(Context.PROVIDER_URL, providerURL);
                }
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                queueConnection = connFactory.createQueueConnection();
                queueConnection.start();
                session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Queue queue = session.createQueue(queueName);
                    MessageProducer producer = session.createProducer(queue);
                    //List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + queueName + "' queue");
                            JMSClientUtil.publishMapMessage(producer, session, messageList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + queueName + "' queue");
                            JMSClientUtil.publishTextMessage(producer, session, messageList);
                        }
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        queueConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else {
            log.error("Enter queue name or topic name to be published!");
        }
    } catch (Exception e) {
        log.error("Error when publishing" + e.getMessage(), e);
    }
}

From source file:gov.medicaid.services.impl.ProviderEnrollmentServiceBean.java

/**
 * Sends the given provider for export to the message queue.
 * @param ticketId the ticket id//from  w w  w .  j av a 2 s. c om
 */
@Override
public void sendSyncronizationRequest(long ticketId) {
    Session session = null;
    Connection connection = null;

    try {
        connection = mqConnectionFactory.createConnection();
        session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        MessageProducer sender = session.createProducer(dataSyncQueue);
        BytesMessage message = session.createBytesMessage();
        byte[] content = exportAsFlatFile(ticketId);
        getLog().log(Level.INFO, "Sending data sync request:" + new String(content));
        message.writeBytes(content);
        sender.send(message);
    } catch (PortalServiceException e) {
        getLog().log(Level.ERROR, e);
        throw new PortalServiceRuntimeException("While attempting to synchronize data", e);
    } catch (JMSException e) {
        getLog().log(Level.ERROR, e);
        throw new PortalServiceRuntimeException("While attempting to synchronize data", e);
    }
}

From source file:org.apache.james.queue.activemq.ActiveMQMailQueue.java

/**
 * Produce the mail to the JMS Queue/*  w w w .  j  a  v  a  2s . c  o m*/
 */
protected void produceMail(Session session, Map<String, Object> props, int msgPrio, Mail mail)
        throws JMSException, MessagingException, IOException {
    MessageProducer producer = null;
    BlobMessage blobMessage = null;
    boolean reuse = false;

    try {

        // check if we should use a blob message here
        if (useBlob) {
            MimeMessage mm = mail.getMessage();
            MimeMessage wrapper = mm;

            ActiveMQSession amqSession = getAMQSession(session);

            /*
             * Remove this optimization as it could lead to problems when the same blob content
             * is shared across different messages. 
             * 
             * I still think it would be a good idea to somehow do this but at the moment it's just 
             * safer to disable it.
             * 
             * TODO: Re-Enable it again once it works!
             * 
             * See JAMES-1240
            if (wrapper instanceof MimeMessageCopyOnWriteProxy) {
            wrapper = ((MimeMessageCopyOnWriteProxy) mm).getWrappedMessage();
            }
                    
            if (wrapper instanceof MimeMessageWrapper) {
            URL blobUrl = (URL) mail.getAttribute(JAMES_BLOB_URL);
            String fromQueue = (String) mail.getAttribute(JAMES_QUEUE_NAME);
            MimeMessageWrapper mwrapper = (MimeMessageWrapper) wrapper;
                    
            if (blobUrl != null && fromQueue != null && mwrapper.isModified() == false) {
                // the message content was not changed so don't need to
                // upload it again and can just point to the url
                blobMessage = amqSession.createBlobMessage(blobUrl);
                reuse = true;
            }
                    
            }*/
            if (blobMessage == null) {
                // just use the MimeMessageInputStream which can read every
                // MimeMessage implementation
                blobMessage = amqSession.createBlobMessage(new MimeMessageInputStream(wrapper));
            }

            // store the queue name in the props
            props.put(JAMES_QUEUE_NAME, queuename);

            Queue queue = session.createQueue(queuename);

            producer = session.createProducer(queue);
            for (Map.Entry<String, Object> entry : props.entrySet()) {
                blobMessage.setObjectProperty(entry.getKey(), entry.getValue());
            }
            producer.send(blobMessage, Message.DEFAULT_DELIVERY_MODE, msgPrio, Message.DEFAULT_TIME_TO_LIVE);

        } else {
            super.produceMail(session, props, msgPrio, mail);
        }
    } catch (JMSException e) {
        if (!reuse && blobMessage != null && blobMessage instanceof ActiveMQBlobMessage) {
            ((ActiveMQBlobMessage) blobMessage).deleteFile();
        }
        throw e;
    } finally {

        try {
            if (producer != null)
                producer.close();
        } catch (JMSException e) {
            // ignore here
        }
    }

}

From source file:org.gss_project.gss.server.ejb.ExternalAPIBean.java

private void indexFile(Long fileId, boolean delete) {
     Connection qConn = null;/*  w ww . j  av  a  2  s  .  co  m*/
     Session session = null;
     MessageProducer sender = null;
     try {
         Context jndiCtx = new InitialContext();
         ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA");
         Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue");
         qConn = factory.createConnection();
         session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
         sender = session.createProducer(queue);

         MapMessage map = session.createMapMessage();
         map.setObject("id", fileId);
         map.setBoolean("delete", delete);
         sender.send(map);
     } catch (NamingException e) {
         logger.error("Index was not updated: ", e);
     } catch (JMSException e) {
         logger.error("Index was not updated: ", e);
     } finally {
         try {
             if (sender != null)
                 sender.close();
             if (session != null)
                 session.close();
             if (qConn != null)
                 qConn.close();
         } catch (JMSException e) {
             logger.warn(e);
         }
     }
 }