Example usage for javax.jms MessageProducer send

List of usage examples for javax.jms MessageProducer send

Introduction

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

Prototype


void send(Message message) throws JMSException;

Source Link

Document

Sends a message using the MessageProducer 's default delivery mode, priority, and time to live.

Usage

From source file:org.eclipse.smila.connectivity.queue.worker.internal.task.impl.Send.java

/**
 * {@inheritDoc}//  w ww  .j  a  v  a 2s .  c o m
 * 
 */
@Override
public String[] executeInternal(final TaskExecutionEnv env, final SendType config,
        final Map<String, Properties> idPropertyMap)
        throws TaskExecutionException, BlackboardAccessException, RecordFilterNotFoundException {
    Connection connection = null;
    Session session = null;
    try {
        // get cached connection, if do not cache connections -> socket error when many records pushed
        connection = env.getServices().getBrokerConnections().getConnection(config, true);
        connection.start();
        session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        final Destination destination = session.createQueue(config.getQueue());
        final MessageProducer producer = session.createProducer(destination);
        if (config.isPersistentDelivery()) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }

        final Iterator<Entry<String, Properties>> entries = idPropertyMap.entrySet().iterator();
        while (entries.hasNext()) {
            final Entry<String, Properties> entry = entries.next();
            // get message record, optionally a filtered copy.
            final Record record = createMessageRecord(entry.getKey(), config, env);
            // prepare queue message. messages are actually sent on session.commit() below.
            producer.send(createMessage(config, record, entry.getValue(), session));
        }

        // we must commit here so that the message consumer find the correct record version in storages.
        env.getBlackboard().commit();
        env.setCommitRequired(false);
        // finally send the messages.
        session.commit();

        return idPropertyMap.keySet().toArray(new String[idPropertyMap.size()]);
    } catch (final Throwable e) {
        _log.error(msg("Error"), e);
        rollbackQuietly(session);
        throw new TaskExecutionException(e);
    } finally {
        closeQuietly(session);
        closeQuietly(connection);
    }
}

From source file:org.apache.activemq.bugs.AMQ7067Test.java

protected void doTestXACompletionWithAckCompactionDoesNotLooseOutcomeOnFullRecovery(boolean commit)
        throws Exception {

    ((KahaDBPersistenceAdapter) broker.getPersistenceAdapter()).setCompactAcksAfterNoGC(2);
    // investigate liner gc issue - store usage not getting released
    org.apache.log4j.Logger.getLogger(MessageDatabase.class).setLevel(Level.TRACE);

    setupXAConnection();/*  w ww .  j a  v a2 s .c om*/

    Queue holdKahaDb = xaSession.createQueue("holdKahaDb");

    MessageProducer holdKahaDbProducer = xaSession.createProducer(holdKahaDb);

    XATransactionId txid = createXATransaction();
    System.out.println("****** create new txid = " + txid);
    xaRes.start(txid, TMNOFLAGS);

    TextMessage helloMessage = xaSession.createTextMessage(StringUtils.repeat("a", 10));
    holdKahaDbProducer.send(helloMessage);
    xaRes.end(txid, TMSUCCESS);

    Queue queue = xaSession.createQueue("test");

    produce(xaRes, xaSession, queue, 100, 512 * 1024);
    ((org.apache.activemq.broker.region.Queue) broker.getRegionBroker().getDestinationMap().get(queue)).purge();

    xaRes.prepare(txid);

    // hold onto data file with prepare record
    produce(xaRes, xaSession, holdKahaDb, 1, 10);

    produce(xaRes, xaSession, queue, 50, 512 * 1024);
    ((org.apache.activemq.broker.region.Queue) broker.getRegionBroker().getDestinationMap().get(queue)).purge();

    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return 0 == getQueueSize(queue.getQueueName());
        }
    });

    if (commit) {
        xaRes.commit(txid, false);
    } else {
        xaRes.rollback(txid);
    }

    produce(xaRes, xaSession, queue, 50, 512 * 1024);
    ((org.apache.activemq.broker.region.Queue) broker.getRegionBroker().getDestinationMap().get(queue)).purge();

    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return 0 == getQueueSize(queue.getQueueName());
        }
    });

    int limit = ((KahaDBPersistenceAdapter) broker.getPersistenceAdapter()).getCompactAcksAfterNoGC() + 1;
    // force gc, n data files requires n cycles
    for (int dataFilesToMove = 0; dataFilesToMove < 4; dataFilesToMove++) {
        for (int i = 0; i < limit; i++) {
            broker.getPersistenceAdapter().checkpoint(true);
        }
        // ack compaction task operates in the background
        TimeUnit.SECONDS.sleep(2);
    }

    Xid[] xids = xaRes.recover(TMSTARTRSCAN);

    //Should be 0 since we have delivered the outcome
    assertEquals(0, xids.length);
    connection.close();

    // need full recovery to see lost commit record
    curruptIndexFile(getDataDirectory());

    broker.stop();
    broker.waitUntilStopped();
    createBroker();

    setupXAConnection();
    xids = xaRes.recover(TMSTARTRSCAN);

    System.out.println("****** recovered = " + xids);

    assertEquals(0, xids.length);
}

From source file:org.apache.activemq.cli.test.ArtemisTest.java

public void testSimpleRun(String folderName) throws Exception {
    File instanceFolder = temporaryFolder.newFolder(folderName);

    setupAuth(instanceFolder);//from w  ww.j  a v  a 2s .c  om
    String queues = "q1,q2";
    String addresses = "a1,a2";

    // This is usually set when run from the command line via artemis.profile
    Run.setEmbedded(true);
    Artemis.main("create", instanceFolder.getAbsolutePath(), "--force", "--silent", "--no-web", "--queues",
            queues, "--addresses", addresses, "--no-autotune", "--require-login");
    System.setProperty("artemis.instance", instanceFolder.getAbsolutePath());

    // Some exceptions may happen on the initialization, but they should be ok on start the basic core protocol
    Artemis.internalExecute("run");

    try {
        try (ServerLocator locator = ServerLocatorImpl.newLocator("tcp://localhost:61616");
                ClientSessionFactory factory = locator.createSessionFactory();
                ClientSession coreSession = factory.createSession("admin", "admin", false, true, true, false,
                        0)) {
            for (String str : queues.split(",")) {
                ClientSession.QueueQuery queryResult = coreSession.queueQuery(SimpleString.toSimpleString(str));
                assertTrue("Couldn't find queue " + str, queryResult.isExists());
            }
            for (String str : addresses.split(",")) {
                ClientSession.AddressQuery queryResult = coreSession
                        .addressQuery(SimpleString.toSimpleString(str));
                assertTrue("Couldn't find address " + str, queryResult.isExists());
            }
        }

        try {
            Artemis.internalExecute("data", "print");
            Assert.fail("Exception expected");
        } catch (CLIException expected) {
        }
        Artemis.internalExecute("data", "print", "--f");

        assertEquals(Integer.valueOf(100), Artemis.internalExecute("producer", "--message-count", "100",
                "--verbose", "--user", "admin", "--password", "admin"));
        assertEquals(Integer.valueOf(100), Artemis.internalExecute("consumer", "--verbose", "--break-on-null",
                "--receive-timeout", "100", "--user", "admin", "--password", "admin"));

        ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection connection = cf.createConnection("admin", "admin");
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        MessageProducer producer = session.createProducer(
                ActiveMQDestination.createDestination("queue://TEST", ActiveMQDestination.QUEUE_TYPE));

        TextMessage message = session.createTextMessage("Banana");
        message.setStringProperty("fruit", "banana");
        producer.send(message);

        for (int i = 0; i < 100; i++) {
            message = session.createTextMessage("orange");
            message.setStringProperty("fruit", "orange");
            producer.send(message);
        }
        session.commit();

        connection.close();
        cf.close();

        assertEquals(Integer.valueOf(1), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--filter", "fruit='banana'", "--user", "admin", "--password", "admin"));

        assertEquals(Integer.valueOf(100), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--filter", "fruit='orange'", "--user", "admin", "--password", "admin"));

        assertEquals(Integer.valueOf(101), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--user", "admin", "--password", "admin"));

        // should only receive 10 messages on browse as I'm setting messageCount=10
        assertEquals(Integer.valueOf(10), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--message-count", "10", "--user", "admin", "--password", "admin"));

        // Nothing was consumed until here as it was only browsing, check it's receiving again
        assertEquals(Integer.valueOf(1),
                Artemis.internalExecute("consumer", "--txt-size", "50", "--verbose", "--break-on-null",
                        "--receive-timeout", "100", "--filter", "fruit='banana'", "--user", "admin",
                        "--password", "admin"));

        // Checking it was acked before
        assertEquals(Integer.valueOf(100), Artemis.internalExecute("consumer", "--txt-size", "50", "--verbose",
                "--break-on-null", "--receive-timeout", "100", "--user", "admin", "--password", "admin"));
    } finally {
        stopServer();
    }
}

From source file:org.jbpm.executor.impl.ExecutorImpl.java

protected void sendMessage(String messageBody, int priority) {
    if (connectionFactory == null && queue == null) {
        throw new IllegalStateException("ConnectionFactory and Queue cannot be null");
    }/*from w  ww .j  a  va 2s  . c o m*/
    Connection queueConnection = null;
    Session queueSession = null;
    MessageProducer producer = null;
    try {
        queueConnection = connectionFactory.createConnection();
        queueSession = queueConnection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);

        TextMessage message = queueSession.createTextMessage(messageBody);
        producer = queueSession.createProducer(queue);
        producer.setPriority(priority);

        queueConnection.start();

        producer.send(message);
    } catch (Exception e) {
        throw new RuntimeException("Error when sending JMS message with executor job request", e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException e) {
                logger.warn("Error when closing producer", e);
            }
        }

        if (queueSession != null) {
            try {
                queueSession.close();
            } catch (JMSException e) {
                logger.warn("Error when closing queue session", e);
            }
        }

        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
                logger.warn("Error when closing queue connection", e);
            }
        }
    }
}

From source file:eu.eubrazilcc.lvl.storage.activemq.ActiveMQConnector.java

public void sendMessage(final String topicName, final String message) {
    checkArgument(isNotBlank(topicName), "Uninitialized or invalid topic");
    checkArgument(isNotBlank(message), "Uninitialized or invalid message");
    TopicConnection conn = null;/* w  w w  .ja va 2s.co m*/
    TopicSession session = null;
    MessageProducer producer = null;
    try {
        conn = (TopicConnection) broker().getProducersConnFactory().createConnection();
        /* conn = broker().getConnFactory().createTopicConnection();
        conn.start(); */
        session = conn.createTopicSession(false, AUTO_ACKNOWLEDGE);
        final Topic topic = session.createTopic(topicName);
        producer = session.createProducer(topic);
        producer.setDeliveryMode(NON_PERSISTENT);
        final TextMessage textMessage = session.createTextMessage(message);
        producer.send(textMessage);
    } catch (JMSException e) {
        LOGGER.error("Failed to send message to topic: " + topicName, e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException ignore) {
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException ignore) {
            }
        }
        /* if (conn != null) {
           try {
              conn.close();
           } catch (JMSException ignore) { }
        } */
    }
}

From source file:com.mdmserver.managers.ControllerFacade.java

public void uninstallApp(int accountId, String appPackageName) {
    Account account = databaseManager.getAccountByAccountId(accountId);
    Context ctx;/*  www  .j  a va  2 s .  c o  m*/
    try {
        ctx = new InitialContext();
        ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("jms/mdmConnectionFactory");
        Queue queue = (Queue) ctx.lookup("jms/mdmQueue");
        MessageProducer messageProducer;
        System.out.println("Naming success");
        try {

            javax.jms.Connection connection = connectionFactory.createConnection();
            javax.jms.Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            messageProducer = session.createProducer(queue);
            TextMessage message = session.createTextMessage();
            message.setStringProperty(Account.FIELD_NAME_CLOUD_ID, account.getCloudId());
            ControlClient cClient = new ControlClient();
            cClient.setCommandType(ControlClient.UNINSTALL_APP_CONTROL);
            cClient.setJsonCommandDetails(appPackageName);
            Gson gson = new Gson();
            message.setStringProperty(ControlClient.CONTROL_CLIENT_KEY, gson.toJson(cClient));
            System.out.println("It come from Servlet:" + message.getText());
            messageProducer.send(message);
            System.out.println("JMS success");
        } catch (JMSException ex) {
            //                  Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("JMS exception");
        }

    } catch (NamingException ex) {
        //                Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Naming exception");
    }
}

From source file:com.chinamobile.bcbsp.comm.ProducerTool.java

/**
 * Send message into messageQueue and update information.
 * @param session/*from   w ww.  ja  va  2 s . c  o  m*/
 * @param producer
 * @throws Exception
 *         e
 */
private void sendLoop(final Session session, final MessageProducer producer) throws Exception {
    IMessage msg;
    int count = 0;
    BSPMessagesPack pack = new BSPMessagesPack();
    ArrayList<IMessage> content = new ArrayList<IMessage>();
    while ((msg = messageQueue.poll()) != null) {
        content.add(msg);
        count++;
        this.messageCount++;
        // enough for a pack.
        if (count == this.packSize) {
            pack.setPack(content);
            long start = System.currentTimeMillis();
            /** Clock */
            ObjectMessage message = session.createObjectMessage(pack);
            producer.send(message);
            this.sendTime += (System.currentTimeMillis() - start);
            /** Clock */
            content.clear();
            count = 0;
        }
    }
    // remaining messages into a pack.
    if (content.size() > 0) {
        pack.setPack(content);
        long start = System.currentTimeMillis();
        /* Clock */
        ObjectMessage message = session.createObjectMessage(pack);
        producer.send(message);
        this.sendTime += (System.currentTimeMillis() - start);
        /* Clock */
        content.clear();
    }
}

From source file:org.rhq.enterprise.server.drift.DriftManagerBean.java

@Override
@TransactionAttribute(REQUIRES_NEW)/*from   w ww. j  a v a 2 s  . com*/
public void addChangeSet(Subject subject, int resourceId, long zipSize, InputStream zipStream)
        throws Exception {

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

From source file:com.legstar.mq.client.AbstractCicsMQ.java

/**
 * Creates and send a JMS message to the mainframe.
 * <p/>/*from  w  w  w  .  j a va 2 s .  c  o m*/
 * Reply to queue name is where we expect the reply. We expect it to be
 * managed by the same mq manager as the request queue.
 * <p/>
 * Save the unique message ID that was generated by JMS. It will be needed
 * to retrieve the correlated reply.
 * 
 * @param request the request to be sent
 * @throws RequestException if send fails
 */
public void sendRequest(final LegStarRequest request) throws RequestException {

    MessageProducer producer = null;
    try {
        if (_log.isDebugEnabled()) {
            _log.debug("Sending Request:" + request.getID() + " on Connection:" + _connectionID + " "
                    + request.getRequestMessage().getHeaderPart().getJsonString() + '.');
        }

        Message jmsMessage = createRequestMessage(request);
        jmsMessage.setJMSReplyTo(getJmsReplyQueue());
        producer = getJmsQueueSession().createProducer(getJmsRequestQueue());
        producer.send(jmsMessage);

        request.setAttachment(jmsMessage.getJMSMessageID().getBytes());

        _lastUsedTime = System.currentTimeMillis();
        if (_log.isDebugEnabled()) {
            _log.debug("Sent Request:" + request.getID() + " on Connection:" + _connectionID + ". Message ID:"
                    + jmsMessage.getJMSMessageID());
        }
    } catch (HeaderPartException e) {
        throw new RequestException(e);
    } catch (JMSException e) {
        throw new RequestException(e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException e) {
                _log.error(e);
            }
        }
    }
}

From source file:org.rhq.enterprise.server.drift.DriftManagerBean.java

@Override
@TransactionAttribute(REQUIRES_NEW)//from   ww  w .  j  av  a 2s . 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();
}