Example usage for javax.jms Connection start

List of usage examples for javax.jms Connection start

Introduction

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

Prototype


void start() throws JMSException;

Source Link

Document

Starts (or restarts) a connection's delivery of incoming messages.

Usage

From source file:com.fusesource.forge.jmstest.tests.simple.SimpleConsumer.java

protected void run() {
    Connection con = null;
    Session session = null;//from w  ww .j  a  v  a2 s .  com
    final CountDownLatch latch = new CountDownLatch(Integer.MAX_VALUE);
    try {
        con = getConnection();
        session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination dest = getDestinationProvider().getDestination(session, "queue:TEST");
        MessageConsumer consumer = session.createConsumer(dest);
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message msg) {
                String grp = null;
                long nr = 0L;
                try {
                    grp = msg.getStringProperty("JMSXGroupID");
                    nr = msg.getLongProperty("MsgNr");
                } catch (JMSException jme) {
                }
                log().info("Received Message Group=(" + grp + ") MsgNr=" + nr);
                latch.countDown();
            }
        });
        con.start();
        latch.await();
        con.close();
    } catch (Exception e) {
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (Exception e) {
            }
        }
    }
}

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

@Override
public boolean connect() {
    connection = null;/*from  w w  w .j ava 2 s  .com*/
    ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();

    String ip = null;
    try {
        ip = Inet4Address.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        log.severe("Unable to get localhost IP address.");
    }
    Connection connectiontmp = null;
    try {
        connectiontmp = connectionFactory.createConnection();
        String url = "";
        if (Jenkins.getInstance() != null) {
            url = Jenkins.getInstance().getRootUrl();
        }
        connectiontmp.setClientID(provider.getName() + "_" + url + "_" + ip + "_" + jobname);
        connectiontmp.start();
    } catch (JMSException e) {
        log.severe("Unable to connect to " + provider.getBroker() + " " + e.getMessage());
        return false;
    }
    log.info("Connection started");
    connection = connectiontmp;
    return true;
}

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

@Override
public String waitForMessage(Run<?, ?> build, String selector, String variable, Integer timeout) {
    String ip = null;/*ww w  . j  a  v  a  2  s.  c o  m*/
    try {
        ip = Inet4Address.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        log.severe("Unable to get localhost IP address.");
    }

    String ltopic = getTopic();
    if (ip != null && provider.getAuthenticationMethod() != null && ltopic != null
            && provider.getBroker() != null) {
        log.info("Waiting for message with selector: " + selector);
        Connection connection = null;
        MessageConsumer consumer = null;
        try {
            ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();
            connection = connectionFactory.createConnection();
            connection.setClientID(ip + "_" + UUID.randomUUID().toString());
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Topic destination = session.createTopic(ltopic);

            consumer = session.createConsumer(destination, selector);

            Message message = consumer.receive(timeout * 60 * 1000);
            if (message != null) {
                String value = getMessageBody(message);
                if (build != null) {
                    if (StringUtils.isNotEmpty(variable)) {
                        EnvVars vars = new EnvVars();
                        vars.put(variable, value);
                        build.addAction(new CIEnvironmentContributingAction(vars));

                    }
                }
                log.info("Received message with selector: " + selector + "\n" + formatMessage(message));
                return value;
            }
            log.info("Timed out waiting for message!");
        } catch (Exception e) {
            log.log(Level.SEVERE, "Unhandled exception waiting for message.", e);
        } finally {
            if (consumer != null) {
                try {
                    consumer.close();
                } catch (Exception e) {
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception e) {
                }
            }
        }
    } else {
        log.severe("One or more of the following is invalid (null): ip, user, password, topic, broker.");
    }
    return null;
}

From source file:RequesterTool.java

public void run() {

    Connection connection = null;
    try {/*from   w ww  . ja v a  2s  . co 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:com.web.server.EJBDeployer.java

@Override
public void run() {
    EJBJarFileListener jarFileListener = new EJBJarFileListener(registry, this.servicesRegistryPort, jarEJBMap,
            jarMDBMap, jms, connectionFactory);
    DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener);
    FileObject listendir = null;/*from w w w .  j  a  v a2 s .  com*/
    StandardFileSystemManager fsManager = new StandardFileSystemManager();
    String[] dirsToScan = scanDirectory.split(";");
    EJBContext ejbContext;
    try {
        File scanDirFile = new File(dirsToScan[0]);
        File[] scanJarFiles = scanDirFile.listFiles();
        System.out.println("SCANDIRECTORY=" + scanDirectory);
        if (scanJarFiles != null) {
            for (File scanJarFile : scanJarFiles) {
                if (scanJarFile.isFile() && scanJarFile.getAbsolutePath().endsWith(".jar")) {
                    URLClassLoader classLoader = new URLClassLoader(
                            new URL[] { new URL("file:///" + scanJarFile.getAbsolutePath()) },
                            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("file:///" + scanJarFile.getAbsolutePath(), 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(scanJarFile.getAbsolutePath());
                        ejbContext.setJarDeployed(scanJarFile.getName());
                        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("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"),
                                ejbContext);
                    }
                    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(scanJarFile.getAbsolutePath()) != null) {
                            mdbContexts = jarMDBMap.get(scanJarFile.getAbsolutePath());
                        } else {
                            mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                        }
                        jarMDBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"),
                                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(scanJarFile.getAbsolutePath() + " Deployed");
                }
            }
        }
        FileSystemOptions opts = new FileSystemOptions();
        FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
        fsManager.init();
        for (String dir : dirsToScan) {
            if (dir.startsWith("ftp://")) {
                listendir = fsManager.resolveFile(dir, opts);
            } else {
                listendir = fsManager.resolveFile(dir);
            }
            fm.addFile(listendir);
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    fm.setRecursive(true);
    fm.setDelay(1000);
    fm.start();
}

From source file:com.microsoft.azure.servicebus.samples.jmsqueuequickstart.JmsQueueQuickstart.java

public void run(String connectionString) throws Exception {

    // The connection string builder is the only part of the azure-servicebus SDK library
    // we use in this JMS sample and for the purpose of robustly parsing the Service Bus 
    // connection string. 
    ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString);

    // set up JNDI context
    Hashtable<String, String> hashtable = new Hashtable<>();
    hashtable.put("connectionfactory.SBCF",
            "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true");
    hashtable.put("queue.QUEUE", "BasicQueue");
    hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
    Context context = new InitialContext(hashtable);
    ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");

    // Look up queue
    Destination queue = (Destination) context.lookup("QUEUE");

    // we create a scope here so we can use the same set of local variables cleanly 
    // again to show the receive side separately with minimal clutter
    {//from ww w. ja va 2s.com
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

        // Create producer
        MessageProducer producer = session.createProducer(queue);

        // Send messages
        for (int i = 0; i < totalSend; i++) {
            BytesMessage message = session.createBytesMessage();
            message.writeBytes(String.valueOf(i).getBytes());
            producer.send(message);
            System.out.printf("Sent message %d.\n", i + 1);
        }

        producer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    {
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        connection.start();
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        // Create consumer
        MessageConsumer consumer = session.createConsumer(queue);
        // create a listener callback to receive the messages
        consumer.setMessageListener(message -> {
            try {
                // receives message is passed to callback
                System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the tracking counter
                        message.getJMSMessageID());
                message.acknowledge();
            } catch (Exception e) {
                logger.error(e);
            }
        });

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

    System.out.printf("Received all messages, exiting the sample.\n");
    System.out.printf("Closing queue client.\n");
}

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 w ww  .j ava2 s.  c o 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.apache.juddi.subscription.notify.AMQPNotifier.java

@Override
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body)
        throws DispositionReportFaultMessage, RemoteException {
    Connection connection = null;
    Context context = null;//w  w w.  ja v  a  2s . co  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.springframework.jms.core.JmsTemplate.java

/**
 * Execute the action specified by the given action object within a
 * JMS Session. Generalized version of execute(SessionCallback),
 * allowing to start the JMS Connection on the fly.
 * <p>Use execute(SessionCallback) for the general case. Starting
 * the JMS Connection is just necessary for receiving messages,
 * which is preferably achieve through the <code>receive</code> methods.
 * @param action callback object that exposes the session
 * @return the result object from working with the session
 * @throws JmsException if there is any problem
 * @see #execute(SessionCallback)/*  w ww.j a  v a 2  s . com*/
 * @see #receive
 */
public Object execute(SessionCallback action, boolean startConnection) throws JmsException {
    Connection con = null;
    Session session = null;
    try {
        Connection conToUse = null;
        Session sessionToUse = null;
        ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager
                .getResource(getConnectionFactory());
        if (conHolder != null) {
            conToUse = conHolder.getConnection();
            if (startConnection) {
                conToUse.start();
            }
            sessionToUse = conHolder.getSession();
        } else {
            //connection
            con = createConnection();
            if (startConnection) {
                con.start();
            }
            //session
            session = createSession(con);
            conToUse = con;
            sessionToUse = session;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Executing callback on JMS session [" + sessionToUse + "] from connection [" + conToUse
                    + "]");
        }
        //
        return action.doInJms(sessionToUse);
    } catch (JMSException ex) {
        throw convertJmsAccessException(ex);
    } finally {
        JmsUtils.closeSession(session);
        JmsUtils.closeConnection(con);
    }
}

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

/**
 * Clear the specified topic//w ww. ja  v  a  2s. 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);
}