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

public void run() {

    Connection connection = null;
    try {/*from   w ww  .ja  va  2  s .c  o  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:org.apache.juddi.subscription.notify.AMQPNotifier.java

@Override
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body)
        throws DispositionReportFaultMessage, RemoteException {
    Connection connection = null;
    Context context = null;//from   ww w. j  a v  a  2s  . c  o m
    boolean success = false;
    String err = null;
    try {
        if (destination != null && exchangeType != null && exchangeName != null) {
            log.info("Sending notification AMQP to " + destination);
            Properties properties = new Properties();

            properties.put("java.naming.factory.initial",
                    "org.apache.qpid.jndi.PropertiesFileInitialContextFactory");
            properties.put("connectionfactory.qpidConnectionfactory", destination);
            properties.put("destination." + exchangeName, exchangeType);

            context = new InitialContext(properties);

            ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("qpidConnectionfactory");
            connection = connectionFactory.createConnection();
            connection.start();

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destinationLocal = (Destination) context.lookup(exchangeName);

            MessageProducer messageProducer = session.createProducer(destinationLocal);

            String subscriptionResultXML = JAXBMarshaller.marshallToString(body,
                    JAXBMarshaller.PACKAGE_SUBSCR_RES);
            TextMessage message = session.createTextMessage(subscriptionResultXML);
            messageProducer.send(message);
            success = true;

        }
    } catch (Exception e) {
        e.printStackTrace();
        log.error("Error deliverying AMQP subscription " + e.getMessage());
        log.debug("Error deliverying AMQP subscription " + e.getMessage(), e);
        err = e.getMessage();

    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (JMSException ex) {
            log.error(null, ex);
        }
        try {
            if (context != null) {
                context.close();
            }
        } catch (NamingException ex) {
            log.error(null, ex);
        }
    }
    if (!success) {
        throw new DispositionReportFaultMessage(err, null);
    }
    DispositionReport dr = new DispositionReport();
    Result res = new Result();
    dr.getResult().add(res);

    return dr;
}

From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

@Override
public boolean sendMessage(Run<?, ?> build, TaskListener listener, MessageUtils.MESSAGE_TYPE type, String props,
        String content) {/*from  w w  w.  j  av a 2s.  co  m*/
    Connection connection = null;
    Session session = null;
    MessageProducer publisher = null;

    try {
        String ltopic = getTopic();
        if (provider.getAuthenticationMethod() != null && ltopic != null && provider.getBroker() != null) {
            ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();
            connection = connectionFactory.createConnection();
            connection.start();

            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createTopic(ltopic);
            publisher = session.createProducer(destination);

            TextMessage message;
            message = session.createTextMessage("");
            message.setJMSType(JSON_TYPE);

            message.setStringProperty("CI_NAME", build.getParent().getName());
            message.setStringProperty("CI_TYPE", type.getMessage());
            if (!build.isBuilding()) {
                message.setStringProperty("CI_STATUS",
                        (build.getResult() == Result.SUCCESS ? "passed" : "failed"));
            }

            StrSubstitutor sub = new StrSubstitutor(build.getEnvironment(listener));

            if (props != null && !props.trim().equals("")) {
                Properties p = new Properties();
                p.load(new StringReader(props));
                @SuppressWarnings("unchecked")
                Enumeration<String> e = (Enumeration<String>) p.propertyNames();
                while (e.hasMoreElements()) {
                    String key = e.nextElement();
                    message.setStringProperty(key, sub.replace(p.getProperty(key)));
                }
            }

            message.setText(sub.replace(content));

            publisher.send(message);
            log.info("Sent " + type.toString() + " message for job '" + build.getParent().getName()
                    + "' to topic '" + ltopic + "':\n" + formatMessage(message));
        } else {
            log.severe("One or more of the following is invalid (null): user, password, topic, broker.");
            return false;
        }

    } catch (Exception e) {
        log.log(Level.SEVERE, "Unhandled exception in perform.", e);
    } finally {
        if (publisher != null) {
            try {
                publisher.close();
            } catch (JMSException e) {
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
    return true;
}

From source file:nl.nn.adapterframework.jms.MessagingSource.java

public Session createSession(boolean transacted, int acknowledgeMode) throws IbisException {
    Connection connection = null;
    ;/*  w  w w .  j  a v  a2 s  .com*/
    Session session;
    try {
        connection = getConnection();
    } catch (JMSException e) {
        throw new JmsException("could not obtain Connection", e);
    }
    try {
        // do not log, as this may happen very often
        //         if (log.isDebugEnabled()) log.debug(getLogPrefix()+"creating Session, openSessionCount before ["+openSessionCount.getValue()+"]");
        if (useJms102()) {
            if (connection instanceof QueueConnection) {
                session = ((QueueConnection) connection).createQueueSession(transacted, acknowledgeMode);
            } else {
                session = ((TopicConnection) connection).createTopicSession(transacted, acknowledgeMode);
            }
        } else {
            session = connection.createSession(transacted, acknowledgeMode);
        }
        openSessionCount.increase();
        if (connectionsArePooled()) {
            connectionTable.put(session, connection);
        }
        return session;
    } catch (JMSException e) {
        releaseConnection(connection);
        throw new JmsException("could not create Session", e);
    }
}

From source file:org.apache.activemq.usecases.RequestReplyToTopicViaThreeNetworkHopsTest.java

/**
 * TEST QUEUES//from  w  w  w .  j  av a 2 s .  com
 */
public void testQueue(String prod_broker_url, String cons_broker_url) throws Exception {
    int num_msg;

    Connection conn;
    Session sess;
    String queue_name;

    Destination cons_dest;

    num_msg = 5;

    LOG.info("TESTING QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)");

    conn = createConnection(cons_broker_url);
    conn.start();
    sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    //
    // Create the destination on which messages are being tested.
    //
    queue_name = "topotest2.perm.queue";
    LOG.trace("Removing existing Queue");
    removeQueue(conn, queue_name);
    LOG.trace("Creating Queue, " + queue_name);
    cons_dest = sess.createQueue(queue_name);

    testOneDest(conn, sess, cons_dest, num_msg);

    removeQueue(conn, queue_name);
    sess.close();
    conn.close();
}

From source file:org.apache.activemq.usecases.RequestReplyToTopicViaThreeNetworkHopsTest.java

/**
 * TEST TOPICS/*from  w w w .ja v a2 s  . com*/
 */
public void testTopic(String prod_broker_url, String cons_broker_url) throws Exception {
    int num_msg;

    Connection conn;
    Session sess;
    String topic_name;

    Destination cons_dest;

    num_msg = 5;

    LOG.info("TESTING TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)");

    conn = createConnection(cons_broker_url);
    conn.start();
    sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    //
    // Create the destination on which messages are being tested.
    //
    topic_name = "topotest2.perm.topic";
    LOG.trace("Removing existing Topic");
    removeTopic(conn, topic_name);
    LOG.trace("Creating Topic, " + topic_name);
    cons_dest = sess.createTopic(topic_name);

    testOneDest(conn, sess, cons_dest, num_msg);

    //
    // Cleanup
    //
    removeTopic(conn, topic_name);
    sess.close();
    conn.close();
}

From source file:org.springframework.jms.connection.SingleConnectionFactory.java

/**
 * Create a default Session for this ConnectionFactory,
 * adapting to JMS 1.0.2 style queue/topic mode if necessary.
 * @param con the JMS Connection to operate on
 * @param mode the Session acknowledgement mode
 * ({@code Session.TRANSACTED} or one of the common modes)
 * @return the newly created Session//w  ww .  ja v a  2 s .  c o m
 * @throws JMSException if thrown by the JMS API
 */
protected Session createSession(Connection con, Integer mode) throws JMSException {
    // Determine JMS API arguments...
    boolean transacted = (mode == Session.SESSION_TRANSACTED);
    int ackMode = (transacted ? Session.AUTO_ACKNOWLEDGE : mode);
    // Now actually call the appropriate JMS factory method...
    if (Boolean.FALSE.equals(this.pubSubMode) && con instanceof QueueConnection) {
        return ((QueueConnection) con).createQueueSession(transacted, ackMode);
    } else if (Boolean.TRUE.equals(this.pubSubMode) && con instanceof TopicConnection) {
        return ((TopicConnection) con).createTopicSession(transacted, ackMode);
    } else {
        return con.createSession(transacted, ackMode);
    }
}

From source file:org.apache.activemq.usecases.RequestReplyToTopicViaThreeNetworkHopsTest.java

/**
 * TEST TEMPORARY QUEUES//  w  w  w . j  a v  a  2 s  .c om
 */
public void testTempQueue(String prod_broker_url, String cons_broker_url) throws Exception {
    int num_msg;

    Connection conn;
    Session sess;

    Destination cons_dest;

    num_msg = 5;

    LOG.info("TESTING TEMP QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg
            + " messages)");

    //
    // Connect to the bus.
    //
    conn = createConnection(cons_broker_url);
    conn.start();
    sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    //
    // Create the destination on which messages are being tested.
    //
    LOG.trace("Creating destination");
    cons_dest = sess.createTemporaryQueue();

    testOneDest(conn, sess, cons_dest, num_msg);

    //
    // Cleanup
    //
    sess.close();
    conn.close();
}

From source file:org.apache.activemq.usecases.RequestReplyToTopicViaThreeNetworkHopsTest.java

/**
 * TEST TEMPORARY TOPICS// w w w .j a  va 2s.  c  o  m
 */
public void testTempTopic(String prod_broker_url, String cons_broker_url) throws Exception {
    Connection conn;
    Session sess;
    Destination cons_dest;
    int num_msg;

    num_msg = 5;

    LOG.debug("TESTING TEMP TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg
            + " messages)");

    //
    // Connect to the bus.
    //
    conn = createConnection(cons_broker_url);
    conn.start();
    sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    //
    // Create the destination on which messages are being tested.
    //
    LOG.trace("Creating destination");
    cons_dest = sess.createTemporaryTopic();

    testOneDest(conn, sess, cons_dest, num_msg);

    //
    // Cleanup
    //
    sess.close();
    conn.close();
}

From source file:com.web.server.EJBDeployer.java

@Override
public void fileChanged(FileChangeEvent arg0) throws Exception {
    try {//from  w ww. j a  v a 2s .co m
        FileObject baseFile = arg0.getFile();
        EJBContext ejbContext;
        if (baseFile.getName().getURI().endsWith(".jar")) {
            fileDeleted(arg0);
            URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(baseFile.getName().getURI()) },
                    Thread.currentThread().getContextClassLoader());
            ConfigurationBuilder config = new ConfigurationBuilder();
            config.addUrls(ClasspathHelper.forClassLoader(classLoader));
            config.addClassLoader(classLoader);
            org.reflections.Reflections reflections = new org.reflections.Reflections(config);
            EJBContainer container = EJBContainer.getInstance(baseFile.getName().getURI(), config);
            container.inject();
            Set<Class<?>> cls = reflections.getTypesAnnotatedWith(Stateless.class);
            Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class);
            Object obj;
            System.gc();
            if (cls.size() > 0) {
                ejbContext = new EJBContext();
                ejbContext.setJarPath(baseFile.getName().getURI());
                ejbContext.setJarDeployed(baseFile.getName().getBaseName());
                for (Class<?> ejbInterface : cls) {
                    //BeanPool.getInstance().create(ejbInterface);
                    obj = BeanPool.getInstance().get(ejbInterface);
                    System.out.println(obj);
                    ProxyFactory factory = new ProxyFactory();
                    obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj),
                            servicesRegistryPort);
                    String remoteBinding = container.getRemoteBinding(ejbInterface);
                    System.out.println(remoteBinding + " for EJB" + obj);
                    if (remoteBinding != null) {
                        //registry.unbind(remoteBinding);
                        registry.rebind(remoteBinding, (Remote) obj);
                        ejbContext.put(remoteBinding, obj.getClass());
                    }
                    //registry.rebind("name", (Remote) obj);
                }
                jarEJBMap.put(baseFile.getName().getURI(), ejbContext);
            }
            System.out.println("Class Message Driven" + clsMessageDriven);
            System.out.println("Class Message Driven" + clsMessageDriven);
            if (clsMessageDriven.size() > 0) {
                System.out.println("Class Message Driven");
                MDBContext mdbContext;
                ConcurrentHashMap<String, MDBContext> mdbContexts;
                if (jarMDBMap.get(baseFile.getName().getURI()) != null) {
                    mdbContexts = jarMDBMap.get(baseFile.getName().getURI());
                } else {
                    mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                }
                jarMDBMap.put(baseFile.getName().getURI(), mdbContexts);
                MDBContext mdbContextOld;
                for (Class<?> mdbBean : clsMessageDriven) {
                    String classwithpackage = mdbBean.getName();
                    System.out.println("class package" + classwithpackage);
                    classwithpackage = classwithpackage.replace("/", ".");
                    System.out.println("classList:" + classwithpackage.replace("/", "."));
                    try {
                        if (!classwithpackage.contains("$")) {
                            //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                            //System.out.println();
                            if (!mdbBean.isInterface()) {
                                Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations();
                                if (classServicesAnnot != null) {
                                    for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                        if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                            MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                            ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot
                                                    .activationConfig();
                                            mdbContext = new MDBContext();
                                            mdbContext.setMdbName(messageDrivenAnnot.name());
                                            for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) {
                                                if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.DESTINATIONTYPE)) {
                                                    mdbContext.setDestinationType(
                                                            activationConfigProperty.propertyValue());
                                                } else if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.DESTINATION)) {
                                                    mdbContext.setDestination(
                                                            activationConfigProperty.propertyValue());
                                                } else if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.ACKNOWLEDGEMODE)) {
                                                    mdbContext.setAcknowledgeMode(
                                                            activationConfigProperty.propertyValue());
                                                }
                                            }
                                            if (mdbContext.getDestinationType().equals(Queue.class.getName())) {
                                                mdbContextOld = null;
                                                if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                    mdbContextOld = mdbContexts.get(mdbContext.getMdbName());
                                                    if (mdbContextOld != null && mdbContext.getDestination()
                                                            .equals(mdbContextOld.getDestination())) {
                                                        throw new Exception(
                                                                "Only one MDB can listen to destination:"
                                                                        + mdbContextOld.getDestination());
                                                    }
                                                }
                                                mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                Queue queue = (Queue) jms.lookup(mdbContext.getDestination());
                                                Connection connection = connectionFactory
                                                        .createConnection("guest", "guest");
                                                connection.start();
                                                Session session;
                                                if (mdbContext.getAcknowledgeMode() != null && mdbContext
                                                        .getAcknowledgeMode().equals("Auto-Acknowledge")) {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                } else {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                }
                                                MessageConsumer consumer = session.createConsumer(queue);
                                                consumer.setMessageListener(
                                                        (MessageListener) mdbBean.newInstance());
                                                mdbContext.setConnection(connection);
                                                mdbContext.setSession(session);
                                                mdbContext.setConsumer(consumer);
                                                System.out.println("Queue=" + queue);
                                            } else if (mdbContext.getDestinationType()
                                                    .equals(Topic.class.getName())) {
                                                if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                    mdbContextOld = mdbContexts.get(mdbContext.getMdbName());
                                                    if (mdbContextOld.getConsumer() != null)
                                                        mdbContextOld.getConsumer().setMessageListener(null);
                                                    if (mdbContextOld.getSession() != null)
                                                        mdbContextOld.getSession().close();
                                                    if (mdbContextOld.getConnection() != null)
                                                        mdbContextOld.getConnection().close();
                                                }
                                                mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                Topic topic = (Topic) jms.lookup(mdbContext.getDestination());
                                                Connection connection = connectionFactory
                                                        .createConnection("guest", "guest");
                                                connection.start();
                                                Session session;
                                                if (mdbContext.getAcknowledgeMode() != null && mdbContext
                                                        .getAcknowledgeMode().equals("Auto-Acknowledge")) {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                } else {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                }
                                                MessageConsumer consumer = session.createConsumer(topic);
                                                consumer.setMessageListener(
                                                        (MessageListener) mdbBean.newInstance());
                                                mdbContext.setConnection(connection);
                                                mdbContext.setSession(session);
                                                mdbContext.setConsumer(consumer);
                                                System.out.println("Topic=" + topic);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            classLoader.close();
            System.out.println(baseFile.getName().getURI() + " Deployed");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}