Example usage for javax.jms DeliveryMode NON_PERSISTENT

List of usage examples for javax.jms DeliveryMode NON_PERSISTENT

Introduction

In this page you can find the example usage for javax.jms DeliveryMode NON_PERSISTENT.

Prototype

int NON_PERSISTENT

To view the source code for javax.jms DeliveryMode NON_PERSISTENT.

Click Source Link

Document

This is the lowest-overhead delivery mode because it does not require that the message be logged to stable storage.

Usage

From source file:org.wso2.carbon.esb.scenario.test.common.jms.ActiveMQJMSClient.java

/**
 * Function to produce message to ActiveMQ Queue
 *
 * @param queueName name of the target queue
 * @param messageStr message to place//from  w w  w  .j a v  a 2  s . c o  m
 * @throws JMSException
 */
public void produceMessageToQueue(String queueName, String messageStr) throws JMSException {

    Connection connection = null;
    Session session = null;

    try {
        // Create a ConnectionFactory
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);

        // Create a Connection
        connection = connectionFactory.createConnection();
        connection.start();
        connection.setExceptionListener(this);

        // Create a Session
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // Create the destination (Topic or Queue)
        Destination destination = session.createQueue(queueName);

        // Create a MessageProducer from the Session to the Topic or Queue
        MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        // Create a messages
        TextMessage message = session.createTextMessage(messageStr);

        // Tell the producer to send the message
        producer.send(message);

    } finally {
        // Clean up
        if (session != null) {
            session.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.activemq.broker.region.cursors.KahaDBPendingMessageCursorTest.java

/**
 * Test that the the counter restores size and works after restart and more
 * messages are published/*from   w  w  w  .ja v  a2 s.co m*/
 *
 * @throws Exception
 */
@Test(timeout = 60000)
public void testNonPersistentDurableMessageSize() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = new ActiveMQConnectionFactory(brokerConnectURI).createConnection();
    connection.setClientID("clientId");
    connection.start();
    Topic topic = publishTestMessagesDurable(connection, new String[] { "sub1" }, 200, publishedMessageSize,
            DeliveryMode.NON_PERSISTENT);

    SubscriptionKey subKey = new SubscriptionKey("clientId", "sub1");

    // verify the count and size
    verifyPendingStats(topic, subKey, 200, publishedMessageSize.get());
    verifyStoreStats(topic, 0, 0);
}

From source file:net.timewalker.ffmq4.admin.RemoteAdministrationThread.java

@Override
public void run() {
    log.info("Starting remote administration thread ...");

    try {//from ww  w . ja  va 2  s  .  c o  m
        LocalQueue inputQueue = engine.getLocalQueue(FFMQConstants.ADM_REQUEST_QUEUE);
        LocalQueue outputQueue = engine.getLocalQueue(FFMQConstants.ADM_REPLY_QUEUE);

        conn = new LocalQueueConnection(engine, null, null);
        session = conn.createQueueSession(true, Session.SESSION_TRANSACTED);
        receiver = session.createReceiver(inputQueue);
        sender = session.createSender(outputQueue);

        conn.start();

        // Flush input queue on startup
        inputQueue.purge(null);
        outputQueue.purge(null);

        // Enter listening loop
        notifyStartup();
        while (!stopRequired) {
            Message message = receiver.receive();
            if (message == null)
                break; // Interrupted
            log.debug("Received message " + message);

            try {
                // Process the command
                String errorMsg = process(message);

                // Build response message
                Message response = session.createMessage();
                response.setJMSCorrelationID(message.getJMSMessageID());
                if (errorMsg != null)
                    response.setStringProperty(FFMQAdminConstants.ADM_HEADER_ERRMSG, errorMsg);

                sender.send(response, DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY,
                        Message.DEFAULT_TIME_TO_LIVE);
            } catch (JMSException e) {
                log.error("Cannot process admin command", e);
            } finally {
                session.commit();
            }
        }

        log.debug("Remote administration thread has stopped");
    } catch (Throwable e) {
        log.fatal("Administration thread failed", e);
        notifyStartup();
    } finally {
        try {
            if (sender != null)
                sender.close();
        } catch (JMSException e) {
            ErrorTools.log(e, log);
        }

        try {
            if (receiver != null)
                receiver.close();
        } catch (JMSException e) {
            ErrorTools.log(e, log);
        }

        try {
            if (session != null)
                session.close();
        } catch (JMSException e) {
            ErrorTools.log(e, log);
        }

        try {
            if (conn != null)
                conn.close();
        } catch (JMSException e) {
            ErrorTools.log(e, log);
        }
    }
}

From source file:org.wso2.esb.integration.common.utils.clients.jmsclient.JMSQueueMessageProducer.java

/**
 * Method to establish the connection with the given Queue, with message persistance as specified.
 * This must be called before calling pushMessage() to send messages.
 *
 * @param persistMessage whether or not messages need to be persisted
 * @param queueName name of the queue/*from  www.  j  a  va 2 s. com*/
 * @throws JMSException if connection to the queue fails
 */
public void connect(String queueName, boolean persistMessage) throws JMSException {
    connection = connectionFactory.createConnection();
    connection.start();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue(queueName);
    producer = session.createProducer(destination);
    if (persistMessage) {
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    } else {
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    }
}

From source file:net.blogracy.controller.FileSharing.java

public FileSharing() {
    try {//  ww  w  .  j  a v  a  2s  . c  o  m
        connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
        connection = connectionFactory.createConnection();
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(null);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        seedQueue = session.createQueue("seed");
        downloadQueue = session.createQueue("download");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:RequesterTool.java

public void run() {

    Connection connection = null;
    try {/*from  w  w  w .  j  a  va  2s  .co m*/

        System.out.println("Connecting to URL: " + url);
        System.out.println("Publishing a Message with size " + messageSize + " to "
                + (topic ? "topic" : "queue") + ": " + subject);
        System.out.println("Using " + (persistent ? "persistent" : "non-persistent") + " messages");
        System.out.println("Sleeping between publish " + sleepTime + " ms");

        // Create the connection
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
        connection = connectionFactory.createConnection();
        if (persistent && clientId != null && clientId.length() > 0 && !"null".equals(clientId)) {
            connection.setClientID(clientId);
        }
        connection.start();

        // Create the Session
        session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);

        // And the Destinations..
        if (topic) {
            destination = session.createTopic(subject);
            if (replySubject == null || replySubject.equals("")) {
                replyDest = session.createTemporaryTopic();
            } else {
                replyDest = session.createTopic(replySubject);
            }
        } else {
            destination = session.createQueue(subject);
            if (replySubject == null || replySubject.equals("")) {
                replyDest = session.createTemporaryQueue();
            } else {
                replyDest = session.createQueue(replySubject);
            }
        }
        System.out.println("Reply Destination: " + replyDest);

        // Create the producer
        producer = session.createProducer(destination);
        if (persistent) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }
        if (timeToLive != 0) {
            System.out.println("Messages time to live " + timeToLive + " ms");
            producer.setTimeToLive(timeToLive);
        }

        // Create the reply consumer
        consumer = session.createConsumer(replyDest);

        // Start sending reqests.
        requestLoop();

        System.out.println("Done.");

        // Use the ActiveMQConnection interface to dump the connection
        // stats.
        ActiveMQConnection c = (ActiveMQConnection) connection;
        c.getConnectionStats().dump(new IndentPrinter());

    } catch (Exception e) {
        System.out.println("Caught: " + e);
        e.printStackTrace();
    } finally {
        try {
            connection.close();
        } catch (Throwable ignore) {
        }
    }
}

From source file:tools.ProducerTool.java

@Override
public void run() {
    Connection connection = null;
    Session session = null;/* ww  w. j  a v  a  2s.  c  om*/
    try {
        connection = connectionFactory.createConnection();
        if (clientId != null) {
            connection.setClientID(clientId);
        }
        session = connection.createSession(transacted, acknowledgeMode);
        Destination destination = null;
        if (jndiLookupDestinations) {
            destination = (Destination) context.lookup(destinationName);
        } else {
            if (useQueueDestinations) {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryQueue();
                } else {
                    destination = session.createQueue(destinationName);
                }
            } else {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryTopic();
                } else {
                    destination = session.createTopic(destinationName);
                }
            }
        }

        MessageProducer producer = session.createProducer(destination);
        if (durable) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }

        int numMessagesToSend = useFinalControlMessage ? numMessages - 1 : numMessages;

        for (int i = 0; i < numMessagesToSend; i++) {
            String messageText = "Message " + i + " at " + new Date();
            if (bytesLength > -1) {
                byte[] messageTextBytes = messageText.getBytes(StandardCharsets.UTF_8);
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(messageTextBytes);
                if (messageTextBytes.length < bytesLength) {
                    byte[] paddingBytes = new byte[bytesLength - messageTextBytes.length];
                    bytesMessage.writeBytes(paddingBytes);
                }
                if (messageGroupId != null) {
                    bytesMessage.setStringProperty("JMSXGroupID", messageGroupId);
                }
                LOGGER.info("Sending bytes message");
                producer.send(bytesMessage);
            } else {
                TextMessage textMessage = session.createTextMessage(messageText);
                if (messageGroupId != null) {
                    textMessage.setStringProperty("JMSXGroupID", messageGroupId);
                }
                LOGGER.info("Sending text message: " + messageText);
                producer.send(textMessage);
            }

            if (perMessageSleepMS > 0) {
                Thread.sleep(perMessageSleepMS);
            }
            if (transacted) {
                if ((i + 1) % batchSize == 0) {
                    session.commit();
                }
            }
        }
        if (useFinalControlMessage) {
            Message message = session.createMessage();
            if (messageGroupId != null) {
                message.setStringProperty("JMSXGroupID", messageGroupId);
            }
            LOGGER.info("Sending message");
            producer.send(message);
            if (transacted) {
                session.commit();
            }
        }
        producer.close();
    } catch (Exception ex) {
        LOGGER.error("ProducerTool hit exception: " + ex.getMessage(), ex);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
    }
}

From source file:org.wso2.carbon.identity.agent.outbound.server.UserStoreServerEndpoint.java

/**
 * Process response message and send to response queue.
 * @param message Message/*from ww  w.  j a v  a 2  s.  c  o m*/
 */
private void processResponse(String message) {

    JMSConnectionFactory connectionFactory = new JMSConnectionFactory();
    Connection connection = null;
    MessageProducer producer;
    try {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Start processing response message: " + message);
        }
        MessageBrokerConfig conf = ServerConfigurationBuilder.build().getMessagebroker();
        connectionFactory.createActiveMQConnectionFactory(conf.getUrl());
        connection = connectionFactory.createConnection();
        connectionFactory.start(connection);
        javax.jms.Session session = connectionFactory.createSession(connection);
        Destination responseQueue = connectionFactory.createQueueDestination(session,
                UserStoreConstants.QUEUE_NAME_RESPONSE);
        producer = connectionFactory.createMessageProducer(session, responseQueue, DeliveryMode.NON_PERSISTENT);
        producer.setTimeToLive(UserStoreConstants.QUEUE_SERVER_MESSAGE_LIFETIME);

        JSONObject resultObj = new JSONObject(message);
        String responseData = resultObj.get(UserStoreConstants.UM_JSON_ELEMENT_RESPONSE_DATA).toString();
        String correlationId = (String) resultObj
                .get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID);

        UserOperation responseOperation = new UserOperation();
        responseOperation.setCorrelationId(correlationId);
        responseOperation.setResponseData(responseData.toString());

        ObjectMessage responseMessage = session.createObjectMessage();
        responseMessage.setObject(responseOperation);
        responseMessage.setJMSCorrelationID(correlationId);
        producer.send(responseMessage);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Finished processing response message: " + message);
        }
    } catch (JMSException e) {
        LOGGER.error("Error occurred while sending message: " + message, e);
    } catch (JSONException e) {
        LOGGER.error("Error occurred while reading json payload of message: " + message, e);
    } catch (JMSConnectionException e) {
        LOGGER.error("Error occurred while creating JMS connection to send message: " + message, e);
    } finally {
        try {
            connectionFactory.closeConnection(connection);
        } catch (JMSConnectionException e) {
            LOGGER.error("Error occurred while closing JMS connection", e);
        }
    }
}

From source file:ProducerTool.java

public void run() {
    Connection connection = null;
    try {/*from   w  w  w  .  j  av a 2s. c om*/
        // Create the connection.
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
        connection = connectionFactory.createConnection();
        connection.start();

        // Create the session
        Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
        if (topic) {
            destination = session.createTopic(subject);
        } else {
            destination = session.createQueue(subject);
        }

        // Create the producer.
        MessageProducer producer = session.createProducer(destination);
        if (persistent) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }
        if (timeToLive != 0) {
            producer.setTimeToLive(timeToLive);
        }

        // Start sending messages
        sendLoop(session, producer);

        System.out.println("[" + this.getName() + "] Done.");

        synchronized (lockResults) {
            ActiveMQConnection c = (ActiveMQConnection) connection;
            System.out.println("[" + this.getName() + "] Results:\n");
            c.getConnectionStats().dump(new IndentPrinter());
        }

    } catch (Exception e) {
        System.out.println("[" + this.getName() + "] Caught: " + e);
        e.printStackTrace();
    } finally {
        try {
            connection.close();
        } catch (Throwable ignore) {
        }
    }
}

From source file:com.espertech.esper.example.servershellclient.ServerShellClientMain.java

public ServerShellClientMain() throws Exception {
    log.info("Loading properties");
    Properties properties = new Properties();
    InputStream propertiesIS = ServerShellClientMain.class.getClassLoader()
            .getResourceAsStream(ServerShellConstants.CONFIG_FILENAME);
    if (propertiesIS == null) {
        throw new RuntimeException(
                "Properties file '" + ServerShellConstants.CONFIG_FILENAME + "' not found in classpath");
    }/*from  w w w.ja v a  2  s .c  o m*/
    properties.load(propertiesIS);

    // Attached via JMX to running server
    log.info("Attach to server via JMX");
    JMXServiceURL url = new JMXServiceURL(properties.getProperty(ServerShellConstants.MGMT_SERVICE_URL));
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    ObjectName mBeanName = new ObjectName(ServerShellConstants.MGMT_MBEAN_NAME);
    EPServiceProviderJMXMBean proxy = (EPServiceProviderJMXMBean) MBeanServerInvocationHandler
            .newProxyInstance(mbsc, mBeanName, EPServiceProviderJMXMBean.class, true);

    // Connect to JMS
    log.info("Connecting to JMS server");
    String factory = properties.getProperty(ServerShellConstants.JMS_CONTEXT_FACTORY);
    String jmsurl = properties.getProperty(ServerShellConstants.JMS_PROVIDER_URL);
    String connFactoryName = properties.getProperty(ServerShellConstants.JMS_CONNECTION_FACTORY_NAME);
    String user = properties.getProperty(ServerShellConstants.JMS_USERNAME);
    String password = properties.getProperty(ServerShellConstants.JMS_PASSWORD);
    String destination = properties.getProperty(ServerShellConstants.JMS_INCOMING_DESTINATION);
    boolean isTopic = Boolean.parseBoolean(properties.getProperty(ServerShellConstants.JMS_IS_TOPIC));
    JMSContext jmsCtx = JMSContextFactory.createContext(factory, jmsurl, connFactoryName, user, password,
            destination, isTopic);

    // Create statement via JMX
    log.info("Creating a statement via Java Management Extensions (JMX) MBean Proxy");
    proxy.createEPL("select * from SampleEvent where duration > 9.9", "filterStatement",
            new ClientSideUpdateListener());

    // Get producer
    jmsCtx.getConnection().start();
    MessageProducer producer = jmsCtx.getSession().createProducer(jmsCtx.getDestination());

    Random random = new Random();
    String[] ipAddresses = { "127.0.1.0", "127.0.2.0", "127.0.3.0", "127.0.4.0" };
    NumberFormat format = NumberFormat.getInstance();

    // Send messages
    for (int i = 0; i < 1000; i++) {
        String ipAddress = ipAddresses[random.nextInt(ipAddresses.length)];
        double duration = 10 * random.nextDouble();
        String durationStr = format.format(duration);
        String payload = ipAddress + "," + durationStr;

        BytesMessage bytesMessage = jmsCtx.getSession().createBytesMessage();
        bytesMessage.writeBytes(payload.getBytes());
        bytesMessage.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
        producer.send(bytesMessage);

        if (i % 100 == 0) {
            log.info("Sent " + i + " messages");
        }
    }

    // Create statement via JMX
    log.info("Destroing statement via Java Management Extensions (JMX) MBean Proxy");
    proxy.destroy("filterStatement");

    log.info("Shutting down JMS client connection");
    jmsCtx.destroy();

    log.info("Exiting");
    System.exit(-1);
}