Example usage for javax.jms Connection close

List of usage examples for javax.jms Connection close

Introduction

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

Prototype


void close() throws JMSException;

Source Link

Document

Closes the connection.

Usage

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

@Test
public void testCommit() throws Exception {
    final Connection connection = ACTIVE_MQ_NON_XA_CONNECTION_FACTORY.createConnection();
    connection.start();/*from   w ww  .j av a  2 s  .com*/

    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue holdKahaDb = session.createQueue("holdKahaDb");
    MessageProducer holdKahaDbProducer = session.createProducer(holdKahaDb);
    TextMessage helloMessage = session.createTextMessage(StringUtils.repeat("a", 10));
    holdKahaDbProducer.send(helloMessage);
    Queue queue = session.createQueue("test");
    produce(connection, queue, 100, 512 * 1024);
    session.commit();
    produce(connection, queue, 100, 512 * 1024);

    System.out.println(String.format("QueueSize %s: %d", holdKahaDb.getQueueName(),
            getQueueSize(holdKahaDb.getQueueName())));
    purgeQueue(queue.getQueueName());
    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return 0 == getQueueSize(queue.getQueueName());
        }
    });

    // force gc
    broker.getPersistenceAdapter().checkpoint(true);

    connection.close();
    curruptIndexFile(getDataDirectory());

    broker.stop();
    broker.waitUntilStopped();
    createBroker();
    broker.waitUntilStarted();

    while (true) {
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(String.format("QueueSize %s: %d", holdKahaDb.getQueueName(),
                    getQueueSize(holdKahaDb.getQueueName())));
            break;
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            break;
        }
    }

    // THIS SHOULD NOT FAIL AS THERE SHOULD BE ONLY 1 TRANSACTION!
    assertEquals(1, getQueueSize(holdKahaDb.getQueueName()));
}

From source file:ProducerTool.java

public void run() {
    Connection connection = null;
    try {/*from  w  ww  . ja va2 s.  co m*/
        // 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:org.apache.activemq.usecases.RequestReplyToTopicViaThreeNetworkHopsTest.java

/**
 * TEST TOPICS//from  w ww  .  j ava 2 s .c om
 */
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.jbpm.executor.impl.ExecutorImpl.java

protected void sendMessage(String messageBody, int priority) {
    if (connectionFactory == null && queue == null) {
        throw new IllegalStateException("ConnectionFactory and Queue cannot be null");
    }//from  ww  w. j a v a2s. co  m
    Connection queueConnection = null;
    Session queueSession = null;
    MessageProducer producer = null;
    try {
        queueConnection = connectionFactory.createConnection();
        queueSession = queueConnection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);

        TextMessage message = queueSession.createTextMessage(messageBody);
        producer = queueSession.createProducer(queue);
        producer.setPriority(priority);

        queueConnection.start();

        producer.send(message);
    } catch (Exception e) {
        throw new RuntimeException("Error when sending JMS message with executor job request", e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException e) {
                logger.warn("Error when closing producer", e);
            }
        }

        if (queueSession != null) {
            try {
                queueSession.close();
            } catch (JMSException e) {
                logger.warn("Error when closing queue session", e);
            }
        }

        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
                logger.warn("Error when closing queue connection", e);
            }
        }
    }
}

From source file:org.dawnsci.commandserver.core.consumer.RemoteSubmission.java

/**
 * Submits the bean onto the server. From there events about this
 * bean are tacked by monitoring the status queue.
 * //from   w  w  w.  j  av a 2s  .  co  m
 * @param uri
 * @param bean
 */
public synchronized TextMessage submit(StatusBean bean, boolean prepareBean) throws Exception {

    if (getQueueName() == null || "".equals(getQueueName()))
        throw new Exception("Please specify a queue name!");

    Connection send = null;
    Session session = null;
    MessageProducer producer = null;

    try {
        QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
        send = connectionFactory.createConnection();

        session = send.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(queueName);

        producer = session.createProducer(queue);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        ObjectMapper mapper = new ObjectMapper();

        if (getTimestamp() < 1)
            setTimestamp(System.currentTimeMillis());
        if (getPriority() < 1)
            setPriority(1);
        if (getLifeTime() < 1)
            setLifeTime(7 * 24 * 60 * 60 * 1000); // 7 days in ms

        if (prepareBean) {
            if (bean.getUserName() == null)
                bean.setUserName(System.getProperty("user.name"));
            bean.setUniqueId(uniqueId);
            bean.setSubmissionTime(getTimestamp());
        }
        String jsonString = mapper.writeValueAsString(bean);

        TextMessage message = session.createTextMessage(jsonString);

        message.setJMSMessageID(uniqueId);
        message.setJMSExpiration(getLifeTime());
        message.setJMSTimestamp(getTimestamp());
        message.setJMSPriority(getPriority());

        producer.send(message);

        return message;

    } finally {
        if (send != null)
            send.close();
        if (session != null)
            session.close();
        if (producer != null)
            producer.close();
    }

}

From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

public void send(Scenario scenario) throws Exception {
    Connection connection = null;
    try {/*from w w w .  j  a v a  2s .  com*/
        connection = getConnection(false, false);
        connection.start();
        Session session = null;
        try {
            session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge());
            Destination destination = createInputDestination(session, scenario);
            MessageProducer producer = null;
            try {
                producer = session.createProducer(destination);
                if (scenario.isPersistent()) {
                    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
                }
                scenario.send(session, producer);
            } finally {
                if (producer != null) {
                    producer.close();
                }
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:Supplier.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;//  w  ww.  j  a  va 2  s  .  c o m
    Destination orderQueue;
    try {
        Connection connection = connectionFactory.createConnection();

        session = connection.createSession(true, Session.SESSION_TRANSACTED);
        orderQueue = session.createQueue(QUEUE);
        MessageConsumer consumer = session.createConsumer(orderQueue);

        connection.start();

        while (true) {
            Message message = consumer.receive();
            MessageProducer producer = session.createProducer(message.getJMSReplyTo());
            MapMessage orderMessage;
            if (message instanceof MapMessage) {
                orderMessage = (MapMessage) message;
            } else {
                // End of Stream
                producer.send(session.createMessage());
                session.commit();
                producer.close();
                break;
            }

            int quantity = orderMessage.getInt("Quantity");
            System.out.println(
                    ITEM + " Supplier: Vendor ordered " + quantity + " " + orderMessage.getString("Item"));

            MapMessage outMessage = session.createMapMessage();
            outMessage.setInt("VendorOrderNumber", orderMessage.getInt("VendorOrderNumber"));
            outMessage.setString("Item", ITEM);

            quantity = Math.min(orderMessage.getInt("Quantity"),
                    new Random().nextInt(orderMessage.getInt("Quantity") * 10));
            outMessage.setInt("Quantity", quantity);

            producer.send(outMessage);
            System.out.println(ITEM + " Supplier: Sent " + quantity + " " + ITEM + "(s)");
            session.commit();
            System.out.println(ITEM + " Supplier: committed transaction");
            producer.close();
        }
        connection.close();
    } catch (JMSException e) {
        e.printStackTrace();
    }
}

From source file:org.miloss.fgsms.bueller.Bueller.java

/**
 * Performs the work of status bueller by sending an http get message to
 * attempt to pull the wsdl Loads all service urls that are of PolicyType
 * transactional/*  w  w w  . j a  v a 2s.  c  o m*/
 *
 * @param pooled
 * @throws SQLException
 * @throws Exception
 */
public void Fire(boolean pooled) throws SQLException, Exception {
    Init(pooled);
    java.sql.Connection con = null;
    java.sql.Connection perf = null;
    if (pooled) {
        con = Utility.getConfigurationDBConnection();
        perf = Utility.getPerformanceDBConnection();
    } else {
        con = Utility.getConfigurationDB_NONPOOLED_Connection();
        perf = Utility.getPerformanceDB_NONPOOLED_Connection();
    }
    PreparedStatement com = null;
    ResultSet rs = null;
    List<String> urls = new ArrayList<String>();
    try {
        boolean run = true;
        KeyNameValueEnc GetPropertiesFromDB = DBSettingsLoader.GetPropertiesFromDB(pooled, "Bueller", "Enabled");
        if (GetPropertiesFromDB != null && GetPropertiesFromDB.getKeyNameValue() != null) {
            try {
                run = Boolean.parseBoolean(GetPropertiesFromDB.getKeyNameValue().getPropertyValue());
            } catch (Exception ex) {
            }
        }
        if (!run) {
            log.log(Level.INFO, "Bueller is disabled by General Settings, key=Bueller, name=Enabled, exiting...");
            con.close();
            perf.close();
            return;
        }

        //snip, there used to be code here to tie into a jboss workmanager was it was removed due to licensing concerns.
        com = con.prepareStatement("select uri from servicepolicies where buellerenabled=true and policytype=?; ");
        com.setInt(1, PolicyType.TRANSACTIONAL.ordinal());
        rs = com.executeQuery();

        while (rs.next()) {
            urls.add(rs.getString(1));
        }
        rs.close();
        com.close();
    } catch (Exception ex) {
        log.log(Level.ERROR, "unexpected error running bueller ", ex);

    } finally {
        DBUtils.safeClose(rs);
        DBUtils.safeClose(com);
    }

    try {
        log.log(Level.INFO, urls.size() + " urls to process");

        {
            for (int i = 0; i < urls.size(); i++) {
                if (!running) {
                    log.log(Level.INFO, "Interupt detected on url " + (i + 1) + " of " + urls.size());
                    break;
                }
                try {
                    String s = sendGetRequest(pooled, urls.get(i), 0);
                    Boolean currenstatus = s.equalsIgnoreCase("ok");
                    log.log(Level.INFO, (i + 1) + "/" + urls.size() + " " + urls.get(i) + " status is " + s);
                    if (!currenstatus) {
                        List<String> alts = GetAlternateUrls(urls.get(i), perf);
                        for (int k = 0; k < alts.size(); k++) {
                            if (currenstatus) {
                                break;
                            }
                            s = sendGetRequest(pooled, alts.get(k), 0);
                            currenstatus = s.equalsIgnoreCase("ok");
                            log.log(Level.INFO, urls.get(i) + " via alternate URL " + alts.get(k) + " status is " + s);
                        }
                    }

                    AuxHelper.TryUpdateStatus(currenstatus, urls.get(i), s, pooled, AuxHelper.UNSPECIFIED, SLACommon.GetHostName(), AuxHelper.FLAGS.NO_AUTO_CREATE);

                } catch (Exception ex) {
                    log.log(Level.ERROR, "error setting status in config db for uri " + urls.get(i), ex);
                }
            }

            cleanUpOldStuff(urls, con);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, "unexpected error running bueller ", ex);

    } finally {
        DBUtils.safeClose(con);
        DBUtils.safeClose(perf);
    }
}

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  w w w .j ava  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:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

/**
 * Clear the specified topic//from  w w w .  j ava 2 s  .  c o  m
 */
protected void purgeTopic(String destination, String topic) throws Exception {
    Connection c = null;
    Session s = null;

    try {
        logger.debug("purging topic : " + topic);
        c = getConnection(true, false);
        if (c == null) {
            logger.debug("could not create a connection to topic : " + destination);
        }

        c.start();
        s = ((TopicConnection) c).createTopicSession(true, Session.SESSION_TRANSACTED);

        logger.debug("created topic session");
        Topic dest = s.createTopic(destination);
        logger.debug("created topic destination");

        if (client != null) {
            client.dispose();
        }

        MessageConsumer consumer = null;

        try {
            consumer = s.createDurableSubscriber(dest, topic);
            logger.debug("created consumer");
            while (consumer.receiveNoWait() != null) {
                logger.debug("Topic " + topic + " isn't empty, draining it");
            }
            logger.debug("topic should be empty");
            consumer.close();
            s.unsubscribe(topic);
        } catch (JMSException e) {
            logger.debug("could not unsubscribe : " + topic);
        }
    }

    finally {
        if (c != null) {
            c.stop();
            if (s != null) {
                s.close();
            }
            try {
                c.close();
            } catch (JMSException e) {
                logger.warn("Failed to close jms connection: " + e.getMessage());
            }
        }
    }
    logger.debug("completed draining topic :" + topic);
}