Example usage for javax.jms Connection createSession

List of usage examples for javax.jms Connection createSession

Introduction

In this page you can find the example usage for javax.jms Connection createSession.

Prototype


Session createSession(boolean transacted, int acknowledgeMode) throws JMSException;

Source Link

Document

Creates a Session object, specifying transacted and acknowledgeMode .

Usage

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

private void sendMessages() throws Exception {
    Connection connection = createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination queue = session.createQueue(QUEUE_NAME);
    Destination retainQueue = session.createQueue(QUEUE_NAME + "-retain");
    MessageProducer producer = session.createProducer(null);

    final byte[] payload = new byte[1000];
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    BytesMessage message = session.createBytesMessage();
    message.writeBytes(payload);//from  w w w.  j  a v a2  s  . c  o m

    // Build up a set of messages that will be redelivered and updated later.
    while (getLogFileCount() < 3) {
        producer.send(queue, message);
    }

    // Now create some space for files that are retained during the test.
    while (getLogFileCount() < 6) {
        producer.send(retainQueue, message);
    }

    connection.close();
}

From source file:org.wso2.andes.systest.TestingBaseCase.java

/**
 * Create and start an asynchrounous publisher that will send MAX_QUEUE_MESSAGE_COUNT
 * messages to the provided destination. Messages are sent in a new connection
 * on a transaction. Any error is captured and the test is signalled to exit.
 *
 * @param destination/*from   w ww .  j a va  2s.  co  m*/
 */
private void startPublisher(final Destination destination) {
    _publisher = new Thread(new Runnable() {

        public void run() {
            try {
                Connection connection = getConnection();
                Session session = connection.createSession(true, Session.SESSION_TRANSACTED);

                MessageProducer publisher = session.createProducer(destination);

                for (int count = 0; count < MAX_QUEUE_MESSAGE_COUNT; count++) {
                    publisher.send(createNextMessage(session, count));
                    session.commit();
                }
            } catch (Exception e) {
                _publisherError = e;
                _disconnectionLatch.countDown();
            }
        }
    });

    _publisher.start();
}

From source file:de.elomagic.carafile.server.bl.SeedBean.java

public MetaData seedFile(final InputStream inputStream, final String filename)
        throws IOException, GeneralSecurityException, JMSException {
    LOG.debug("Seeding file " + filename);
    MetaData md;//  w w  w. j av a  2  s.c o m
    md = new MetaData();
    md.setFilename(filename);
    md.setCreationDate(new Date());
    md.setChunkSize(DEFAULT_PIECE_SIZE);
    md.setRegistryURI(UriBuilder.fromUri(registryURI).build());

    MessageDigest messageDigest = DigestUtils.getSha1Digest();
    long totalBytes = 0;

    try (DigestInputStream dis = new DigestInputStream(inputStream, messageDigest)) {
        byte[] buffer = new byte[md.getChunkSize()];
        int bytesRead;
        while ((bytesRead = readBlock(dis, buffer)) > 0) {
            totalBytes += bytesRead;
            String chunkId = Hex
                    .encodeHexString(DigestUtils.sha1(new ByteArrayInputStream(buffer, 0, bytesRead)));

            repositoryBean.writeChunk(chunkId, buffer, bytesRead);

            URI uri = UriBuilder.fromUri(ownURI).build();

            ChunkData chunkData = new ChunkData(chunkId, uri);
            md.addChunk(chunkData);
        }
    }

    md.setSize(totalBytes);
    md.setId(Hex.encodeHexString(messageDigest.digest()));

    LOG.debug("File id of seed file is " + md.getId() + "; Size=" + md.getSize() + "; Chunks="
            + md.getChunks().size());

    // Initiate to register at tracker
    LOG.debug("Queue up new file for registration.");
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer messageProducer = session.createProducer(fileQueue);

    ObjectMessage message = session.createObjectMessage(md);

    messageProducer.send(message);

    connection.close();

    return md;
}

From source file:org.apache.falcon.regression.core.supportClasses.JmsMessageConsumer.java

@Override
public void run() {
    try {/*from  w  w w  . j a v a 2 s . c o m*/
        // Getting JMS connection from the server
        Connection connection = new ActiveMQConnectionFactory(brokerURL).createConnection();
        connection.start();

        // Creating session for sending messages
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(destination);

        try {
            LOGGER.info("Starting to receive messages.");
            int count = 0;
            for (; count < MAX_MESSAGE_COUNT; ++count) {
                Message message = consumer.receive(); //blocking call
                if (message == null) {
                    LOGGER.info("Received empty message, count = " + count);
                } else {
                    LOGGER.info("Received message, id = " + message.getJMSMessageID());
                    receivedMessages.add((MapMessage) message);
                }
            }
            if (count >= MAX_MESSAGE_COUNT) {
                LOGGER.warn("Not reading more messages, already read " + count + " messages.");
            }
        } finally {
            LOGGER.info("Stopping to receive messages.");
            connection.close();
        }
    } catch (Exception e) {
        LOGGER.info("caught exception: " + ExceptionUtils.getStackTrace(e));
    }
}

From source file:org.apache.falcon.messaging.FeedProducerTest.java

private void consumer() throws JMSException {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
    Connection connection = connectionFactory.createConnection();
    connection.start();//  w  w  w  .jav a2  s.c  om

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(TOPIC_NAME);
    MessageConsumer consumer = session.createConsumer(destination);

    latch.countDown();
    verifyMesssage(consumer);

    connection.close();
}

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 ww. j av  a  2s .co  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:com.microsoft.azure.servicebus.samples.jmstopicquickstart.JmsTopicQuickstart.java

private void receiveFromSubscription(ConnectionStringBuilder csb, Context context, ConnectionFactory cf,
        String name) throws NamingException, JMSException, InterruptedException {
    AtomicInteger totalReceived = new AtomicInteger(0);
    System.out.printf("Subscription %s: \n", name);

    Destination subscription = (Destination) context.lookup(name);
    // Create Connection
    Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
    connection.start();//from w  w  w.  ja v  a  2  s .  co  m
    // Create Session, no transaction, client ack
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    // Create consumer
    MessageConsumer consumer = session.createConsumer(subscription);
    // Set callback listener. Gets called for each received message.
    consumer.setMessageListener(message -> {
        try {
            System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the counter
                    message.getJMSMessageID());
            message.acknowledge();
        } catch (Exception e) {
            System.out.printf("%s", e.toString());
        }
    });

    // wait on the main thread until all sent messages have been received
    while (totalReceived.get() < totalSend) {
        Thread.sleep(1000);
    }
    consumer.close();
    session.close();
    connection.stop();
    connection.close();
}

From source file:org.apache.flume.source.jms.TestIntegrationActiveMQ.java

private void putQueue(List<String> events) throws Exception {
    ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_BIND_URL);
    Connection connection = factory.createConnection();
    connection.start();// www. ja  va 2 s  .c om

    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(destination);

    for (String event : events) {
        TextMessage message = session.createTextMessage();
        message.setText(event);
        producer.send(message);
    }
    session.commit();
    session.close();
    connection.close();
}

From source file:org.apache.flume.source.jms.TestIntegrationActiveMQ.java

private void putTopic(List<String> events) throws Exception {
    ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_BIND_URL);
    Connection connection = factory.createConnection();
    connection.start();//from w  ww  .jav a  2s.  co  m

    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(destination);

    for (String event : events) {
        TextMessage message = session.createTextMessage();
        message.setText(event);
        producer.send(message);
    }
    session.commit();
    session.close();
    connection.close();
}

From source file:org.sakaiproject.kernel.messaging.email.EmailMessagingService.java

public String send(Email email) throws MessagingException, JMSException {
    try {//  www.ja va 2s.  c o  m
        email.buildMimeMessage();
    } catch (Exception e) {
        // this is a lossy cast. This would be a commons EmailException
        // this up cast is to keep commons-email out of our direct bindings
        throw new MessagingException(e);
    }

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        email.getMimeMessage().writeTo(os);
    } catch (javax.mail.MessagingException e) {
        throw new MessagingException(e);

    } catch (IOException e) {
        throw new MessagingException(e);
    }

    String content = os.toString();
    Connection conn = connectionFactory.createTopicConnection();
    conn.setClientID(getNextId());
    Session clientSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination emailTopic = clientSession.createTopic(emailQueueName);
    MessageProducer client = clientSession.createProducer(emailTopic);
    ObjectMessage mesg = clientSession.createObjectMessage(content);
    mesg.setJMSType(emailJmsType);
    client.send(mesg);
    // TODO finish this
    return null;

}