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:ConsumerTool.java

public void run() {
    try {/*from  w ww  . ja va2s  . c o m*/
        running = true;

        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
        Connection connection = connectionFactory.createConnection();
        if (durable && clientId != null && clientId.length() > 0 && !"null".equals(clientId)) {
            connection.setClientID(clientId);
        }
        connection.setExceptionListener(this);
        connection.start();

        session = connection.createSession(transacted, ackMode);
        if (topic) {
            destination = session.createTopic(subject);
        } else {
            destination = session.createQueue(subject);
        }

        replyProducer = session.createProducer(null);
        replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        MessageConsumer consumer = null;
        if (durable && topic) {
            consumer = session.createDurableSubscriber((Topic) destination, consumerName);
        } else {
            consumer = session.createConsumer(destination);
        }

        if (maxiumMessages > 0) {
            consumeMessagesAndClose(connection, session, consumer);
        } else {
            if (receiveTimeOut == 0) {
                consumer.setMessageListener(this);
            } else {
                consumeMessagesAndClose(connection, session, consumer, receiveTimeOut);
            }
        }

    } catch (Exception e) {
        System.out.println("[" + this.getName() + "] Caught: " + e);
        e.printStackTrace();
    }
}

From source file:com.datatorrent.lib.io.jms.JMSStringInputOperatorTest.java

private void produceMsg(int numMessages) throws Exception {
    // Create a ConnectionFactory
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

    // Create a Connection
    Connection connection = connectionFactory.createConnection();
    connection.start();/*from   w w  w .  j a  v a 2 s .  c o m*/

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

    // Create the destination (Topic or Queue)
    Destination destination = session.createQueue("TEST.FOO");

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

    // Create a messages
    String text = "Hello world! From tester producer";
    TextMessage message = session.createTextMessage(text);
    for (int i = 0; i < numMessages; i++) {
        producer.send(message);
    }

    // Clean up
    session.close();
    connection.close();

}

From source file:org.nuxeo.ecm.core.jms.CoreEventPublisher.java

public void publish(Object content, Topic topic, MessageFactory factory, String eventId) throws JMSException {
    TopicConnection connection = null;/*  w w w.j a  v  a  2s .  co m*/
    TopicSession session = null;
    TopicPublisher publisher = null;
    try {
        // get a connection from topic connection pool
        connection = getTopicConnection();

        // create a not transacted session
        session = connection.createTopicSession(transacted, TopicSession.AUTO_ACKNOWLEDGE);

        // create the publisher
        publisher = session.createPublisher(topic);
        publisher.setDeliveryMode(isDeliveryPersistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
        publisher.setDisableMessageID(isDisableMessageID);
        publisher.setDisableMessageTimestamp(isDisableMessageTimestamp);
        // create the message using the given factory
        Message msg = factory.createMessage(session, content);
        if (eventId != null) {
            msg.setStringProperty("NuxeoEventId", eventId);
        }
        // publish the message
        publisher.publish(topic, msg);
    } finally {
        if (publisher != null) {
            publisher.close();
        }
        if (session != null) {
            session.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:com.cws.esolutions.core.utils.MQUtils.java

/**
 * Puts an MQ message on a specified queue and returns the associated
 * correlation ID for retrieval upon request.
 *
 * @param connName - The connection name to utilize
 * @param authData - The authentication data to utilize, if required
 * @param requestQueue - The request queue name to put the message on
 * @param targetHost - The target host for the message
 * @param value - The data to place on the request. MUST be <code>Serialiable</code>
 * @return <code>String</code> - the JMS correlation ID associated with the message
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 *///from ww  w  . jav a2s .  c o m
public static final synchronized String sendMqMessage(final String connName, final List<String> authData,
        final String requestQueue, final String targetHost, final Serializable value) throws UtilityException {
    final String methodName = MQUtils.CNAME
            + "sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", connName);
        DEBUGGER.debug("Value: {}", requestQueue);
        DEBUGGER.debug("Value: {}", targetHost);
        DEBUGGER.debug("Value: {}", value);
    }

    Connection conn = null;
    Session session = null;
    Context envContext = null;
    InitialContext initCtx = null;
    MessageProducer producer = null;
    ConnectionFactory connFactory = null;

    final String correlationId = RandomStringUtils.randomAlphanumeric(64);

    if (DEBUG) {
        DEBUGGER.debug("correlationId: {}", correlationId);
    }

    try {
        try {
            initCtx = new InitialContext();
            envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT);

            connFactory = (ConnectionFactory) envContext.lookup(connName);
        } catch (NamingException nx) {
            // we're probably not in a container
            connFactory = new ActiveMQConnectionFactory(connName);
        }

        if (DEBUG) {
            DEBUGGER.debug("ConnectionFactory: {}", connFactory);
        }

        if (connFactory == null) {
            throw new UtilityException("Unable to create connection factory for provided name");
        }

        // Create a Connection
        conn = connFactory.createConnection(authData.get(0),
                PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3),
                        Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6),
                        authData.get(7), authData.get(8)));
        conn.start();

        if (DEBUG) {
            DEBUGGER.debug("Connection: {}", conn);
        }

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

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", session);
        }

        // Create a MessageProducer from the Session to the Topic or Queue
        if (envContext != null) {
            try {
                producer = session.createProducer((Destination) envContext.lookup(requestQueue));
            } catch (NamingException nx) {
                throw new UtilityException(nx.getMessage(), nx);
            }
        } else {
            Destination destination = session.createTopic(requestQueue);

            if (DEBUG) {
                DEBUGGER.debug("Destination: {}", destination);
            }

            producer = session.createProducer(destination);
        }

        if (producer == null) {
            throw new JMSException("Failed to create a producer object");
        }

        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        if (DEBUG) {
            DEBUGGER.debug("MessageProducer: {}", producer);
        }

        ObjectMessage message = session.createObjectMessage(true);
        message.setJMSCorrelationID(correlationId);
        message.setStringProperty("targetHost", targetHost);

        if (DEBUG) {
            DEBUGGER.debug("correlationId: {}", correlationId);
        }

        message.setObject(value);

        if (DEBUG) {
            DEBUGGER.debug("ObjectMessage: {}", message);
        }

        producer.send(message);
    } catch (JMSException jx) {
        throw new UtilityException(jx.getMessage(), jx);
    } finally {
        try {
            // Clean up
            if (!(session == null)) {
                session.close();
            }

            if (!(conn == null)) {
                conn.close();
                conn.stop();
            }
        } catch (JMSException jx) {
            ERROR_RECORDER.error(jx.getMessage(), jx);
        }
    }

    return correlationId;
}

From source file:net.timewalker.ffmq4.remote.session.RemoteSession.java

protected final void dispatch(Message message) throws JMSException {
    if (debugEnabled)
        log.debug("#" + id + " Sending message " + message.getJMSMessageID());

    boolean asyncDispatch = transacted || message.getJMSDeliveryMode() == DeliveryMode.NON_PERSISTENT;

    PutQuery query = new PutQuery();
    query.setSessionId(id);//from   www . j  a  va2s  .  co  m

    if (asyncDispatch) {
        // Create a message copy to make sure the message is not modified concurrently
        Message msgCopy = MessageTools.makeInternalCopy(message);
        query.setMessage((AbstractMessage) msgCopy);
    } else
        query.setMessage((AbstractMessage) message);

    if (asyncDispatch)
        transportEndpoint.nonBlockingRequest(query);
    else {
        if (retryOnQueueFull)
            retriableBlockingQuery(query, retryTimeout);
        else
            transportEndpoint.blockingRequest(query);
    }
}

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

/** Run of Thread. */
public void run() {
    try {/* w ww .j  a va  2 s .c o m*/
        running = true;
        this.url = "failover://vm://" + this.brokerName;
        BSPActiveMQConnFactory connectionFactory = new BSPActiveMQConnFactoryImpl();
        connectionFactory.activeMQConnFactoryMethod(url);
        connectionFactory.setOptimizeAcknowledge(true);
        Connection connection = connectionFactory.createConnection();
        if (durable && clientId != null && clientId.length() > 0 && !"null".equals(clientId)) {
            connection.setClientID(clientId);
        }
        connection.setExceptionListener(this);
        connection.start();
        session = connection.createSession(transacted, ackMode);
        if (topic) {
            destination = session.createTopic(subject);
        } else {
            destination = session.createQueue(subject);
        }
        replyProducer = session.createProducer(null);
        replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        if (durable && topic) {
            consumer = session.createDurableSubscriber((Topic) destination, consumerName);
        } else {
            consumer = session.createConsumer(destination);
        }
        consumeMessages(connection, session, consumer, receiveTimeOut);
        LOG.info("[ConsumerTool] has received " + this.messagesReceived + " object messages from <"
                + this.subject + ">.");
        LOG.info("[ConsumerTool] has received " + this.messageCount + " BSP messages from <" + this.subject
                + ">.");
        this.receiver.addMessageCount(this.messageCount);
        this.receiver.addMessageBytesCount(messageBytesCount);
    } catch (Exception e) {
        throw new RuntimeException("[ConsumerTool] caught: ", e);
    }
}

From source file:eu.domibus.submission.jms.BackendJMSImpl.java

/**
 * This method is called when a message was received at the incoming queue
 *
 * @param message The incoming JMS Message
 *//*from  w w  w .  jav a 2s.c  o  m*/
@Override
public void onMessage(final Message message) {
    final MapMessage map = (MapMessage) message;
    try {
        final Connection con = this.cf.createConnection();
        final Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final MapMessage res = session.createMapMessage();
        try {
            final String messageID = this.submit(map);
            res.setStringProperty("messageId", messageID);
        } catch (final TransformationException | ValidationException e) {
            BackendJMSImpl.LOG.error("Exception occurred: ", e);
            res.setString("ErrorMessage", e.getMessage());
        }

        res.setJMSCorrelationID(map.getJMSCorrelationID());
        final MessageProducer sender = session.createProducer(this.outQueue);
        sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        sender.send(res);
        sender.close();
        session.close();
        con.close();

    } catch (final JMSException ex) {
        BackendJMSImpl.LOG.error("Error while sending response to queue", ex);

    }
}

From source file:com.datatorrent.lib.io.jms.JMSObjectInputOperatorTest.java

private void produceMsg() throws Exception {
    // Create a ConnectionFactory
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

    // Create a Connection
    testMeta.connection = connectionFactory.createConnection();
    testMeta.connection.start();//from ww  w. j  a va  2  s .  c o m

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

    // Create the destination (Topic or Queue)
    Destination destination = testMeta.session.createQueue("TEST.FOO");

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

From source file:net.timewalker.ffmq4.local.destination.LocalTopic.java

@Override
public boolean putLocked(AbstractMessage srcMessage, LocalSession session, MessageLockSet locks)
        throws JMSException {
    checkNotClosed();/*from   w  w  w.  java 2s . c o  m*/
    checkTransactionLock();

    // Check delivery mode
    if (!topicDef.supportDeliveryMode(srcMessage.getJMSDeliveryMode()))
        throw new FFMQException("Topic does not support this delivery mode : "
                + (srcMessage.getJMSDeliveryMode() == DeliveryMode.NON_PERSISTENT
                        ? "DeliveryMode.NON_PERSISTENT"
                        : "DeliveryMode.PERSISTENT"),
                "INVALID_DELIVERY_MODE");

    sentToTopicCount.incrementAndGet();

    String connectionID = session.getConnection().getId();
    CopyOnWriteList<LocalTopicSubscription> subscriptionsSnapshot;
    synchronized (subscriptionMap) {
        if (subscriptions.isEmpty())
            return false;

        subscriptionsSnapshot = subscriptions.fastCopy();
    }

    boolean commitRequired = false;
    for (int i = 0; i < subscriptionsSnapshot.size(); i++) {
        LocalTopicSubscription subscription = subscriptionsSnapshot.get(i);

        // No-local filtering
        if (subscription.getNoLocal() && subscription.getConnectionID().equals(connectionID))
            continue;

        try {
            // Message selector filtering
            MessageSelector selector = subscription.getMessageSelector();
            if (selector != null) {
                srcMessage.ensureDeserializationLevel(MessageSerializationLevel.ALL_HEADERS);
                if (!selector.matches(srcMessage))
                    continue;
            }

            LocalQueue subscriberQueue = subscription.getLocalQueue();

            // Only use transactional mode for fail-safe durable subscriptions
            if (subscriberQueue.requiresTransactionalUpdate() && subscription.isDurable()) {
                if (committables.add(subscriberQueue))
                    subscriberQueue.openTransaction();

                if (!subscriberQueue.putLocked(srcMessage, session, locks))
                    if (srcMessage.getJMSDeliveryMode() == DeliveryMode.PERSISTENT)
                        throw new IllegalStateException("Should require a commit");

                pendingChanges = true;
                commitRequired = true;
            } else {
                if (subscriberQueue.putLocked(srcMessage, session, locks))
                    throw new IllegalStateException("Should not require a commit");
            }

            dispatchedFromTopicCount.incrementAndGet();
        } catch (DataStoreFullException e) {
            processPutError(subscription.getSubscriberId(), e, getDefinition().getSubscriberOverflowPolicy());
        } catch (JMSException e) {
            processPutError(subscription.getSubscriberId(), e, getDefinition().getSubscriberFailurePolicy());
        }
    }

    return commitRequired;
}

From source file:org.apache.jmeter.protocol.jms.sampler.PublisherSampler.java

/**
 * The implementation will publish n messages within a for loop. Once n
 * messages are published, it sets the attributes of SampleResult.
 *
 * @return the populated sample result/*from w  w w. ja  v  a2  s  .co m*/
 */
@Override
public SampleResult sample() {
    SampleResult result = new SampleResult();
    result.setSampleLabel(getName());
    result.setSuccessful(false); // Assume it will fail
    result.setResponseCode("000"); // ditto $NON-NLS-1$
    if (publisher == null) {
        try {
            initClient();
        } catch (JMSException e) {
            result.setResponseMessage(e.toString());
            return result;
        } catch (NamingException e) {
            result.setResponseMessage(e.toString());
            return result;
        }
    }
    StringBuilder buffer = new StringBuilder();
    StringBuilder propBuffer = new StringBuilder();
    int loop = getIterationCount();
    result.sampleStart();
    String type = getMessageChoice();

    try {
        Map<String, Object> msgProperties = getJMSProperties().getJmsPropertysAsMap();
        int deliveryMode = getUseNonPersistentDelivery() ? DeliveryMode.NON_PERSISTENT
                : DeliveryMode.PERSISTENT;
        int priority = Integer.parseInt(getPriority());
        long expiration = Long.parseLong(getExpiration());

        for (int idx = 0; idx < loop; idx++) {
            if (JMSPublisherGui.TEXT_MSG_RSC.equals(type)) {
                String tmsg = getMessageContent();
                Message msg = publisher.publish(tmsg, getDestination(), msgProperties, deliveryMode, priority,
                        expiration);
                buffer.append(tmsg);
                Utils.messageProperties(propBuffer, msg);
            } else if (JMSPublisherGui.MAP_MSG_RSC.equals(type)) {
                Map<String, Object> m = getMapContent();
                Message msg = publisher.publish(m, getDestination(), msgProperties, deliveryMode, priority,
                        expiration);
                Utils.messageProperties(propBuffer, msg);
            } else if (JMSPublisherGui.OBJECT_MSG_RSC.equals(type)) {
                Serializable omsg = getObjectContent();
                Message msg = publisher.publish(omsg, getDestination(), msgProperties, deliveryMode, priority,
                        expiration);
                Utils.messageProperties(propBuffer, msg);
            } else if (JMSPublisherGui.BYTES_MSG_RSC.equals(type)) {
                byte[] bmsg = getBytesContent();
                Message msg = publisher.publish(bmsg, getDestination(), msgProperties, deliveryMode, priority,
                        expiration);
                Utils.messageProperties(propBuffer, msg);
            } else {
                throw new JMSException(type + " is not recognised");
            }
        }
        result.setResponseCodeOK();
        result.setResponseMessage(loop + " messages published");
        result.setSuccessful(true);
        result.setSamplerData(buffer.toString());
        result.setSampleCount(loop);
        result.setRequestHeaders(propBuffer.toString());
    } catch (Exception e) {
        result.setResponseMessage(e.toString());
    } finally {
        result.sampleEnd();
    }
    return result;
}