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.springframework.cloud.stream.binder.jms.solace.SolaceQueueProvisioner.java

@Override
public Destinations provisionTopicAndConsumerGroup(String name, String... groups) {
    Destinations.Factory destinationsFactory = new Destinations.Factory();

    try {/*  www .  j ava2  s.c o m*/
        Topic topic = JCSMPFactory.onlyInstance().createTopic(name);
        JCSMPSession session = sessionFactory.build();
        Connection connection = connectionFactory.createConnection();
        javax.jms.Session jmsSession = connection.createSession(false, 1);

        // Using Durable... because non-durable Solace TopicEndpoints don't have names
        TopicEndpoint topicEndpoint = new DurableTopicEndpointImpl(name);
        session.provision(topicEndpoint, null, JCSMPSession.FLAG_IGNORE_ALREADY_EXISTS);
        destinationsFactory.withTopic(jmsSession.createTopic(name));

        if (ArrayUtils.isEmpty(groups)) {
            return destinationsFactory.build();
        }

        for (String group : groups) {
            destinationsFactory.addGroup(jmsSession.createQueue(group));
            doProvision(session, topic, group);
        }

        JmsUtils.commitIfNecessary(jmsSession);
        JmsUtils.closeSession(jmsSession);
        JmsUtils.closeConnection(connection);
    } catch (JCSMPErrorResponseException e) {
        if (JCSMPErrorResponseSubcodeEx.SUBSCRIPTION_ALREADY_PRESENT != e.getSubcodeEx()) {
            throw new RuntimeException(e);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return destinationsFactory.build();
}

From source file:org.calrissian.mango.jms.stream.JmsFileTransferSupportTest.java

public void testFullCycle() throws Exception {
    try {/*from  ww w. j  a  v  a  2 s.co  m*/
        URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {

            @Override
            public URLStreamHandler createURLStreamHandler(String protocol) {
                if ("testprot".equals(protocol))
                    return new URLStreamHandler() {

                        @Override
                        protected URLConnection openConnection(URL u) throws IOException {
                            return new URLConnection(u) {

                                @Override
                                public void connect() throws IOException {

                                }

                                @Override
                                public InputStream getInputStream() throws IOException {
                                    return new ByteArrayInputStream(TEST_STR.getBytes());
                                }

                                @Override
                                public String getContentType() {
                                    return "content/notnull";
                                }
                            };
                        }
                    };
                return null;
            }
        });
    } catch (Error ignored) {
    }

    final ActiveMQTopic ft = new ActiveMQTopic("testFileTransfer");

    ThreadPoolTaskExecutor te = new ThreadPoolTaskExecutor();
    te.initialize();

    JmsFileSenderListener listener = new JmsFileSenderListener();
    final String hashAlgorithm = "MD5";
    listener.setHashAlgorithm(hashAlgorithm);
    listener.setStreamRequestDestination(ft);
    listener.setPieceSize(9);
    listener.setTaskExecutor(te);

    ConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
    cf = new SingleTopicConnectionFactory(cf, "test");
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cf);
    jmsTemplate.setReceiveTimeout(60000);
    listener.setJmsTemplate(jmsTemplate);

    Connection conn = cf.createConnection();
    conn.start();
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = sess.createConsumer(ft);
    consumer.setMessageListener(listener);

    JmsFileReceiver receiver = new JmsFileReceiver();
    receiver.setHashAlgorithm(hashAlgorithm);
    receiver.setStreamRequestDestination(ft);
    receiver.setJmsTemplate(jmsTemplate);
    receiver.setPieceSize(9);

    JmsFileReceiverInputStream stream = (JmsFileReceiverInputStream) receiver.receiveStream("testprot:test");
    StringBuilder buffer = new StringBuilder();
    int read;
    while ((read = stream.read()) >= 0) {
        buffer.append((char) read);
    }
    stream.close();

    assertEquals(TEST_STR, buffer.toString());

    conn.stop();

}

From source file:org.ahp.core.messaging.AhpJmsProducer.java

public void sendTextMessage(String pTextMessage, AhpJmsDestinationTypes pAhpJmsDestinationTypes,
        AhpJmsDestinationNames pAhpJmsDestinationNames) {
    Connection lConnection = null;
    Session lSession = null;/*from  w  w w  . jav a  2s. c  om*/
    try {
        lConnection = this.mJmsConnectionFactory.createConnection();
        lSession = lConnection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        Destination lDestination = null;
        if (pAhpJmsDestinationTypes.equals(AhpJmsDestinationTypes.Queue))
            lDestination = lSession.createQueue(pAhpJmsDestinationNames.toString());
        else
            lDestination = lSession.createTopic(pAhpJmsDestinationNames.toString());
        MessageProducer lMessageProducer = lSession.createProducer(lDestination);
        lMessageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
        //lMessageProducer.setTimeToLive( timeToLive );
        Message lTextMessage = lSession.createTextMessage(pTextMessage);
        LOGGER.debug("AhpJmsProducer sending message to Destination " + pAhpJmsDestinationNames.toString()
                + " TextMessage :: \n" + pTextMessage);
        lMessageProducer.send(lTextMessage);
        lSession.commit();
    } catch (JMSException exJms) {
        LOGGER.error("", exJms);
    } finally {
        try {
            lConnection.close();
        } catch (JMSException exJms) {
            LOGGER.error("", exJms);
        }
    }
}

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

private void consumer() throws JMSException {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
    Connection connection = connectionFactory.createConnection();
    connection.start();/*from  w  w  w  .  j  a v a 2s . co  m*/

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

    latch.countDown();

    for (int index = 0; index < outputFeedNames.length; ++index) {
        MapMessage m = (MapMessage) consumer.receive();
        System.out.println("Consumed: " + m.toString());
        assertMessage(m);
        Assert.assertEquals(m.getString(WorkflowExecutionArgs.OUTPUT_FEED_NAMES.getName()),
                outputFeedNames[index]);
        Assert.assertEquals(m.getString(WorkflowExecutionArgs.OUTPUT_FEED_PATHS.getName()),
                outputFeedPaths[index]);
    }
    connection.close();
}

From source file:org.apache.activemq.camel.JmsJdbcXARollbackTest.java

private boolean consumedFrom(String qName) throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://testXA");
    factory.setWatchTopicAdvisories(false);
    Connection connection = factory.createConnection();
    connection.start();//from www.  java2 s .  co  m
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(new ActiveMQQueue(qName));
    Message message = consumer.receive(500);
    LOG.info("Got from queue:{} {}", qName, message);
    connection.close();
    return message != null;
}

From source file:org.apache.activemq.camel.JmsJdbcXARollbackTest.java

private void sendJMSMessageToKickOffRoute() throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://testXA");
    factory.setWatchTopicAdvisories(false);
    Connection connection = factory.createConnection();
    connection.start();// ww  w  .ja  v  a 2  s.com
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(new ActiveMQQueue("scp_transacted"));
    TextMessage message = session.createTextMessage("Some Text, messageCount:" + messageCount++);
    message.setJMSCorrelationID("pleaseCorrelate");
    producer.send(message);
    connection.close();
}

From source file:org.logicblaze.lingo.jmx.remote.jms.MBeanJmsServerConnectionClient.java

/**
 * Construct this thing//  w w w .  ja  v a2  s .  c o  m
 * 
 * @param connection
 * @throws JMSException
 */
public MBeanJmsServerConnectionClient(MBeanJmsServerConnection connection, Connection jmsConnection)
        throws JMSException {
    super(connection);
    this.serverConnection = connection;
    Session jmsSession = jmsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    replyToDestination = jmsSession.createTemporaryTopic();
    MessageConsumer consumer = jmsSession.createConsumer(replyToDestination);
    consumer.setMessageListener(this);
}

From source file:fr.xebia.sample.springframework.jms.requestreply.RequestReplyClientInvoker.java

/**
 * Request/Reply SpringFramework sample.
 * /*from ww  w . ja va 2  s  . com*/
 * @param request
 *            sent to the remote service
 * @return reply returned by the remote service
 * @throws JMSException
 */
public String requestReply(String request) throws JMSException {

    Connection connection = connectionFactory.createConnection();
    try {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        try {
            MessageProducer messageProducer = session.createProducer(this.requestDestination);
            try {
                Message requestMessage = session.createTextMessage(request);
                requestMessage.setJMSReplyTo(this.replyToDestination);
                // requestMessage.setJMSCorrelationID(String.valueOf(random.nextLong()));

                messageProducer.send(requestMessage);
                String messageSelector = "JMSCorrelationID  LIKE '" + requestMessage.getJMSMessageID() + "'";

                MessageConsumer messageConsumer = session.createConsumer(this.replyToDestination,
                        messageSelector);
                TextMessage replyMessage = (TextMessage) messageConsumer.receive(timeoutInMillis);
                Assert.notNull(replyMessage, "Timeout waiting for jms response");
                logger.debug(
                        "requestReply " + "\r\nrequest : " + requestMessage + "\r\nreply : " + replyMessage);
                String result = replyMessage.getText();
                logger.debug("requestReply('" + request + "'): '" + result + "'");
                return result;
            } finally {
                JmsUtils.closeMessageProducer(messageProducer);
            }
        } finally {
            JmsUtils.closeSession(session);
        }
    } finally {
        JmsUtils.closeConnection(connection);
    }
}

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

private void consumerAndRollback(int iteration) throws Exception {
    Connection connection = createConnection();
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    Queue queue = session.createQueue(QUEUE_NAME);
    MessageConsumer consumer = session.createConsumer(queue);

    long msgCount = getProxyToQueue(queue.getQueueName()).getQueueSize();

    for (int i = 0; i < msgCount; ++i) {
        Message message = consumer.receive(50000);
        assertNotNull(message);/* w w w  . j ava  2  s  .  com*/
        if (iteration > 0) {
            assertTrue(message.getJMSRedelivered());
        }
    }

    connection.close();
}

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

public void seedChunk(final InputStream inputStream, final String chunkId)
        throws IOException, GeneralSecurityException, JMSException {
    LOG.debug("Seeding chunk " + chunkId);
    Chunk chunk = chunkDAO.findByIdentifier(chunkId);

    if (chunk == null) {
        throw new FileNotFoundException(
                "Chunk id " + chunkId + " not found. File already registered at registry?");
    }/*w  w  w. ja va2s .c  o m*/

    byte[] buf = new byte[chunk.getFileMeta().getChunkSize()];
    int bufferSize;
    try (InputStream in = inputStream) {
        bufferSize = readBlock(in, buf);
    } catch (IOException ex) {
        throw ex;
    }

    // Check SHA-1
    String sha1 = Hex.encodeHexString(DigestUtils.sha1(Arrays.copyOf(buf, bufferSize)));
    if (!chunk.getHash().equalsIgnoreCase(sha1)) {
        throw new GeneralSecurityException(
                "Chunk SHA-1 validation failed (Expected " + chunk.getHash() + ", but is " + sha1 + ")");
    }

    repositoryBean.writeChunk(chunkId, buf, bufferSize);

    LOG.debug("Chunk id " + chunkId + " seed");

    // 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(chunkQueue);

    TextMessage message = session.createTextMessage(chunkId);
    messageProducer.send(message);
    connection.close();
}