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.rhq.enterprise.server.drift.DriftManagerBean.java

@Override
@TransactionAttribute(REQUIRES_NEW)//from w w  w.ja v a2  s .  c  o m
public void addFiles(Subject subject, int resourceId, String driftDefName, String token, long zipSize,
        InputStream zipStream) throws Exception {

    Connection connection = factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(fileQueue);
    ObjectMessage msg = session
            .createObjectMessage(new DriftUploadRequest(resourceId, driftDefName, token, zipSize, zipStream));
    producer.send(msg);
    connection.close();
}

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

public void indexFile(Long fileId, boolean delete) {
    Connection qConn = null;/*from  ww w  . j  ava2  s.  c o  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);
        }
    }
}

From source file:org.apache.servicemix.jms.endpoints.AbstractConsumerEndpoint.java

protected void send(Message msg, Session session, Destination dest) throws JMSException {
    MessageProducer producer;/*ww w  . j  a v a 2s  .  com*/
    if (isJms102()) {
        if (isPubSubDomain()) {
            producer = ((TopicSession) session).createPublisher((Topic) dest);
        } else {
            producer = ((QueueSession) session).createSender((Queue) dest);
        }
    } else {
        producer = session.createProducer(dest);
    }
    try {
        if (replyProperties != null) {
            for (Map.Entry<String, Object> e : replyProperties.entrySet()) {
                msg.setObjectProperty(e.getKey(), e.getValue());
            }
        }
        if (isJms102()) {
            if (isPubSubDomain()) {
                if (replyExplicitQosEnabled) {
                    ((TopicPublisher) producer).publish(msg, replyDeliveryMode, replyPriority, replyTimeToLive);
                } else {
                    ((TopicPublisher) producer).publish(msg);
                }
            } else {
                if (replyExplicitQosEnabled) {
                    ((QueueSender) producer).send(msg, replyDeliveryMode, replyPriority, replyTimeToLive);
                } else {
                    ((QueueSender) producer).send(msg);
                }
            }
        } else {
            if (replyExplicitQosEnabled) {
                producer.send(msg, replyDeliveryMode, replyPriority, replyTimeToLive);
            } else {
                producer.send(msg);
            }
        }
    } finally {
        JmsUtils.closeMessageProducer(producer);
    }
}

From source file:com.aol.advertising.qiao.emitter.AMQEmitter.java

/**
 * Create JMS connectins, sessions, producers, destination objects. (one
 * producer per connection)//w w  w.j  ava  2  s. c  om
 *
 * @throws Exception
 */
protected void createJmsResources() throws Exception {

    Connection conn;
    Session session;
    MessageProducer producer;

    // create connections
    logger.info("creating producers...");
    for (int i = 0; i < numProducer; i++) {
        conn = connectionFactory.createConnection();
        connList.add(conn);

        // create sessions for a connection
        session = conn.createSession(transacted, ackMode);

        if (destination == null) {
            if (isQueue) {
                destination = session.createQueue(destinationName);
            } else {
                destination = session.createTopic(destinationName);
            }
        }

        producer = session.createProducer(destination);
        producer.setDeliveryMode(deliveryMode);

        Producer p = new Producer(session, producer);
        producersPool.add(p);
        producersStack.add(p);
    }

    logger.info("AMQ producer(s) created, count=" + producersStack.size());
}

From source file:Vendor.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;
    Destination orderQueue;//  www.  j  a  v a2s  . c  o m
    Destination monitorOrderQueue;
    Destination storageOrderQueue;
    TemporaryQueue vendorConfirmQueue;
    MessageConsumer orderConsumer = null;
    MessageProducer monitorProducer = null;
    MessageProducer storageProducer = null;

    try {
        Connection connection = connectionFactory.createConnection();

        session = connection.createSession(true, Session.SESSION_TRANSACTED);
        orderQueue = session.createQueue("VendorOrderQueue");
        monitorOrderQueue = session.createQueue("MonitorOrderQueue");
        storageOrderQueue = session.createQueue("StorageOrderQueue");

        orderConsumer = session.createConsumer(orderQueue);
        monitorProducer = session.createProducer(monitorOrderQueue);
        storageProducer = session.createProducer(storageOrderQueue);

        Connection asyncconnection = connectionFactory.createConnection();
        asyncSession = asyncconnection.createSession(true, Session.SESSION_TRANSACTED);

        vendorConfirmQueue = asyncSession.createTemporaryQueue();
        MessageConsumer confirmConsumer = asyncSession.createConsumer(vendorConfirmQueue);
        confirmConsumer.setMessageListener(this);

        asyncconnection.start();

        connection.start();

        while (true) {
            Order order = null;
            try {
                Message inMessage = orderConsumer.receive();
                MapMessage message;
                if (inMessage instanceof MapMessage) {
                    message = (MapMessage) inMessage;

                } else {
                    // end of stream
                    Message outMessage = session.createMessage();
                    outMessage.setJMSReplyTo(vendorConfirmQueue);
                    monitorProducer.send(outMessage);
                    storageProducer.send(outMessage);
                    session.commit();
                    break;
                }

                // Randomly throw an exception in here to simulate a Database error
                // and trigger a rollback of the transaction
                if (new Random().nextInt(3) == 0) {
                    throw new JMSException("Simulated Database Error.");
                }

                order = new Order(message);

                MapMessage orderMessage = session.createMapMessage();
                orderMessage.setJMSReplyTo(vendorConfirmQueue);
                orderMessage.setInt("VendorOrderNumber", order.getOrderNumber());
                int quantity = message.getInt("Quantity");
                System.out.println("Vendor: Retailer ordered " + quantity + " " + message.getString("Item"));

                orderMessage.setInt("Quantity", quantity);
                orderMessage.setString("Item", "Monitor");
                monitorProducer.send(orderMessage);
                System.out.println("Vendor: ordered " + quantity + " Monitor(s)");

                orderMessage.setString("Item", "HardDrive");
                storageProducer.send(orderMessage);
                System.out.println("Vendor: ordered " + quantity + " Hard Drive(s)");

                session.commit();
                System.out.println("Vendor: Comitted Transaction 1");

            } catch (JMSException e) {
                System.out.println("Vendor: JMSException Occured: " + e.getMessage());
                e.printStackTrace();
                session.rollback();
                System.out.println("Vendor: Rolled Back Transaction.");
            }
        }

        synchronized (supplierLock) {
            while (numSuppliers > 0) {
                try {
                    supplierLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        connection.close();
        asyncconnection.close();

    } catch (JMSException e) {
        e.printStackTrace();
    }

}

From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

public void send(Scenario scenario) throws Exception {
    Connection connection = null;
    try {//w w w.  j  av  a  2s  .c om
        connection = getConnection(false, false);
        connection.start();
        Session session = null;
        try {
            session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge());
            Destination destination = createInputDestination(session, scenario);
            MessageProducer producer = null;
            try {
                producer = session.createProducer(destination);
                if (scenario.isPersistent()) {
                    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
                }
                scenario.send(session, producer);
            } finally {
                if (producer != null) {
                    producer.close();
                }
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public void createProducer(final CreateProducerCommand command) {
    try {//from w w w  . j a v  a2  s. c o m
        final Session session = _testSessions.get(command.getSessionName());
        if (session == null) {
            throw new DistributedTestException("No test session found called: " + command.getSessionName(),
                    command);
        }

        synchronized (session) {
            final Destination destination;
            if (command.isTopic()) {
                destination = session.createTopic(command.getDestinationName());
            } else {
                destination = session.createQueue(command.getDestinationName());
            }

            final MessageProducer jmsProducer = session.createProducer(destination);

            if (command.getPriority() != -1) {
                jmsProducer.setPriority(command.getPriority());
            }
            if (command.getTimeToLive() > 0) {
                jmsProducer.setTimeToLive(command.getTimeToLive());
            }

            if (command.getDeliveryMode() == DeliveryMode.NON_PERSISTENT
                    || command.getDeliveryMode() == DeliveryMode.PERSISTENT) {
                jmsProducer.setDeliveryMode(command.getDeliveryMode());
            }

            addProducer(command.getParticipantName(), jmsProducer);
        }
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to create new producer: " + command, jmse);
    }
}

From source file:org.apache.synapse.message.store.impl.jms.JmsStore.java

/**
 * Creates a new JMS Message Producer./*from  ww w . ja v a2  s. c o m*/
 *
 * @param session  A JMS Session.
 * @return A JMS Message Producer.
 * @throws JMSException
 */
public javax.jms.MessageProducer newProducer(Session session) throws JMSException {
    if (session == null) {
        logger.error(nameString() + " cannot create JMS Producer. Invalid session.");
        return null;
    }
    if (!createDestIfAbsent(session)) {
        logger.error(nameString() + " cannot create JMS Producer. " + "Destination queue is invalid.");
        return null;
    }
    javax.jms.MessageProducer producer;
    if (isVersion11) {
        producer = session.createProducer(queue);
    } else {
        producer = ((QueueSession) session).createSender((javax.jms.Queue) queue);
    }
    if (logger.isDebugEnabled()) {
        logger.debug(nameString() + " created JMS Message Producer to destination [" + queue.toString() + "].");
    }
    return producer;
}

From source file:org.wso2.carbon.sample.jmsclient.JMSClient.java

public static void publishMessages(String topicName, String broker) {
    try {/*from w ww .  j a v  a 2s.  c  o m*/

        //            filePath = JMSClientUtil.getEventFilePath(sampleNumber, format, topicName, filePath);

        TopicConnection topicConnection = null;
        Session session = null;

        Properties properties = new Properties();
        if (broker.equalsIgnoreCase("activemq")) {
            properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
            Context context = new InitialContext(properties);
            TopicConnectionFactory connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
            topicConnection = connFactory.createTopicConnection();
            topicConnection.start();
            session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        } else if (broker.equalsIgnoreCase("mb")) {
            properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
            Context context = new InitialContext(properties);
            TopicConnectionFactory connFactory = (TopicConnectionFactory) context
                    .lookup("qpidConnectionFactory");
            topicConnection = connFactory.createTopicConnection();
            topicConnection.start();
            session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        } else if (broker.equalsIgnoreCase("qpid")) {
            properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
            Context context = new InitialContext(properties);
            TopicConnectionFactory connFactory = (TopicConnectionFactory) context
                    .lookup("qpidConnectionFactory");
            topicConnection = connFactory.createTopicConnection();
            topicConnection.start();
            session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        } else {
            log.info("Please enter a valid JMS message broker. (ex: activemq, mb, qpid");
        }

        if (session != null) {
            Topic topic = session.createTopic(topicName);
            MessageProducer producer = session.createProducer(topic);

            try {

                List<Map<String, Object>> messageList = new ArrayList<Map<String, Object>>();

                Random random = new Random();
                for (int j = 0; j < sessionsPerThread; j++) {
                    for (int i = 0; i < msgsPerSession; i++) {
                        HashMap<String, Object> map = new HashMap<String, Object>();

                        map.put("id", random.nextInt() + "");
                        map.put("value", random.nextInt());
                        map.put("content", "sample content");
                        map.put("client", "jmsQueueClient");
                        // setting the timestamp later
                        messageList.add(map);
                    }

                    publishMapMessage(producer, session, messageList);

                }
            } catch (JMSException e) {
                log.error("Can not 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();
            }
        }
    } catch (Exception e) {
        log.error("Error when publishing message" + e.getMessage(), e);
    }
}

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

public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception {
    bridgeBrokers(SPOKE, HUB);//from   www.  j  a v  a2  s . c om

    startAllBrokers();

    // Setup connection
    URI hubURI = brokers.get(HUB).broker.getVmConnectorURI();
    URI spokeURI = brokers.get(SPOKE).broker.getVmConnectorURI();
    ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI);
    ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI);
    Connection conHub = facHub.createConnection();
    Connection conSpoke = facSpoke.createConnection();
    conHub.setClientID("clientHUB");
    conSpoke.setClientID("clientSPOKE");
    conHub.start();
    conSpoke.start();
    Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE);

    ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO");
    String consumerName = "consumerName";

    // Setup consumers
    MessageConsumer remoteConsumer = sesSpoke.createDurableSubscriber(topic, consumerName);
    remoteConsumer.setMessageListener(new MessageListener() {
        public void onMessage(Message msg) {
            try {
                TextMessage textMsg = (TextMessage) msg;
                receivedMsgs++;
                LOG.info("Received messages (" + receivedMsgs + "): " + textMsg.getText());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    });

    // allow subscription information to flow back to Spoke
    sleep(1000);

    // Setup producer
    MessageProducer localProducer = sesHub.createProducer(topic);
    localProducer.setDeliveryMode(DeliveryMode.PERSISTENT);

    // Send messages
    for (int i = 0; i < MESSAGE_COUNT; i++) {
        sleep(50);
        if (i == 50 || i == 150) {
            if (simulateStalledNetwork) {
                socketProxy.pause();
            } else {
                socketProxy.close();
            }
            networkDownTimeStart = System.currentTimeMillis();
        } else if (networkDownTimeStart > 0) {
            // restart after NETWORK_DOWN_TIME seconds
            sleep(NETWORK_DOWN_TIME);
            networkDownTimeStart = 0;
            if (simulateStalledNetwork) {
                socketProxy.goOn();
            } else {
                socketProxy.reopen();
            }
        } else {
            // slow message production to allow bridge to recover and limit message duplication
            sleep(500);
        }
        Message test = sesHub.createTextMessage("test-" + i);
        localProducer.send(test);
    }

    LOG.info("waiting for messages to flow");
    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return receivedMsgs >= MESSAGE_COUNT;
        }
    });

    assertTrue("At least message " + MESSAGE_COUNT + " must be received, count=" + receivedMsgs,
            MESSAGE_COUNT <= receivedMsgs);
    brokers.get(HUB).broker.deleteAllMessages();
    brokers.get(SPOKE).broker.deleteAllMessages();
    conHub.close();
    conSpoke.close();
}