Example usage for javax.jms Session close

List of usage examples for javax.jms Session close

Introduction

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

Prototype


void close() throws JMSException;

Source Link

Document

Closes the session.

Usage

From source file:org.gss_project.gss.server.ejb.AdminAPIBean.java

public void indexFile(Long fileId, boolean delete) {
    Connection qConn = null;// w w  w . j ava2s. c om
    Session session = null;
    MessageProducer sender = null;
    try {
        Context jndiCtx = new InitialContext();
        ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA");
        Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue");
        qConn = factory.createConnection();
        session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        sender = session.createProducer(queue);

        MapMessage map = session.createMapMessage();
        map.setObject("id", fileId);
        map.setBoolean("delete", delete);
        sender.send(map);
    } catch (NamingException e) {
        logger.error("Index was not updated: ", e);
    } catch (JMSException e) {
        logger.error("Index was not updated: ", e);
    } finally {
        try {
            if (sender != null)
                sender.close();
            if (session != null)
                session.close();
            if (qConn != null)
                qConn.close();
        } catch (JMSException e) {
            logger.warn(e);
        }
    }
}

From source file:org.gss_project.gss.server.ejb.ExternalAPIBean.java

private void indexFile(Long fileId, boolean delete) {
     Connection qConn = null;//from w  ww  .ja v  a  2  s  .  co m
     Session session = null;
     MessageProducer sender = null;
     try {
         Context jndiCtx = new InitialContext();
         ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA");
         Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue");
         qConn = factory.createConnection();
         session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
         sender = session.createProducer(queue);

         MapMessage map = session.createMapMessage();
         map.setObject("id", fileId);
         map.setBoolean("delete", delete);
         sender.send(map);
     } catch (NamingException e) {
         logger.error("Index was not updated: ", e);
     } catch (JMSException e) {
         logger.error("Index was not updated: ", e);
     } finally {
         try {
             if (sender != null)
                 sender.close();
             if (session != null)
                 session.close();
             if (qConn != null)
                 qConn.close();
         } catch (JMSException e) {
             logger.warn(e);
         }
     }
 }

From source file:org.jboss.activemq.clients.JMSConsumer.java

public static void main(String args[]) {
    Connection connection = null;

    try {//from  w  w  w.  jav a 2s  .  c  om

        Options options = new Options();
        options.addOption("h", "help", false, "help:");
        options.addOption("url", true, "url for the broker to connect to");
        options.addOption("u", "username", true, "User name for connection");
        options.addOption("p", "password", true, "password for connection");
        options.addOption("d", "destination", true, "destination to send to");
        options.addOption("n", "number", true, "number of messages to send");
        options.addOption("delay", true, "delay between each send");

        CommandLineParser parser = new BasicParser();
        CommandLine commandLine = parser.parse(options, args);

        if (commandLine.hasOption("h")) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("OptionsTip", options);
            System.exit(0);
        }

        String url = commandLine.hasOption("host") ? commandLine.getOptionValue("host") : URL;

        String userName = commandLine.hasOption("u") ? commandLine.getOptionValue("u") : "admin";
        String password = commandLine.hasOption("p") ? commandLine.getOptionValue("p") : "admin";
        String destinationName = commandLine.hasOption("d") ? commandLine.getOptionValue("d")
                : DESTINATION_NAME;
        int numberOfMessages = commandLine.hasOption("n") ? Integer.parseInt(commandLine.getOptionValue("n"))
                : NUM_MESSAGES_TO_RECEIVE;
        ;

        ConnectionFactory factory = new ActiveMQConnectionFactory(userName, password, url);

        connection = factory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(destinationName);

        MessageConsumer consumer = session.createConsumer(topic);

        LOG.info("Start consuming " + numberOfMessages + " messages from " + topic.toString());

        for (int i = 0; i < numberOfMessages; i++) {
            Message message = consumer.receive();
            if (message != null) {
                if (message instanceof BytesMessage) {
                    BytesMessage bytesMessage = (BytesMessage) message;
                    int len = (int) bytesMessage.getBodyLength();
                    byte[] data = new byte[len];
                    bytesMessage.readBytes(data);
                    String value = new String(data);

                    LOG.info("Got " + value);
                } else {
                    LOG.info("Got a message " + message);
                }
            }
        }

        consumer.close();
        session.close();
    } catch (Throwable t) {
        LOG.error("Error receiving message", t);
    } finally {

        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOG.error("Error closing connection", e);
            }
        }
    }
}

From source file:org.jbpm.bpel.integration.jms.JmsIntegrationService.java

private void jmsReply(ReplyAction replyAction, Token token) throws JMSException {
    // extract the output parts
    Map parts = replyAction.writeMessage(token);

    // obtain the outstanding request for the partner link, operation and
    // message exchange of the replier
    IntegrationControl integrationControl = getIntegrationControl(token);
    OutstandingRequest request = integrationControl.removeOutstandingRequest(replyAction, token);

    Session jmsSession = integrationControl.createJmsSession();
    try {//w  w w  . j  a  v a2 s . com
        request.sendReply(parts, replyAction.getFaultName(), jmsSession);
    } finally {
        jmsSession.close();
    }
}

From source file:org.jbpm.bpel.integration.server.SoapHandler.java

public boolean handleRequest(MessageContext messageContext) throws JAXRPCException, SOAPFaultException {
    /*//from w  ww .j  a  v  a 2 s  .c  om
     * WSEE 1.1 section 6.2.2.1: If Handler instances are pooled, they must be pooled by Port
     * component. This is because Handlers may retain non-client specific state across method calls
     * that are specific to the Port component.
     */
    if (integrationControl == null) {
        /*
         * COMPLIANCE NOTE: the state initialized in this call is port-component specific, but
         * non-client specific
         */
        lookupEndpointMetadata(messageContext);
    }

    JbpmContext jbpmContext = integrationControl.getIntegrationServiceFactory().getJbpmConfiguration()
            .createJbpmContext();
    try {
        Session jmsSession = integrationControl.createJmsSession();
        try {
            SOAPMessage soapMessage = ((SOAPMessageContext) messageContext).getMessage();
            ObjectMessage jmsRequest = sendRequest(soapMessage, jmsSession, jbpmContext);

            Destination replyTo = jmsRequest.getJMSReplyTo();
            if (replyTo != null) {
                ObjectMessage jmsResponse = receiveResponse(jmsSession, replyTo, jmsRequest.getJMSMessageID(),
                        jbpmContext);

                // remember operation name and message parts for handling response
                messageContext.setProperty(OPERATION_NAME_PROP,
                        jmsRequest.getStringProperty(IntegrationConstants.OPERATION_NAME_PROP));
                messageContext.setProperty(MESSAGE_PARTS_PROP, jmsResponse.getObject());

                // is response a fault?
                String faultName = jmsResponse.getStringProperty(IntegrationConstants.FAULT_NAME_PROP);
                if (faultName != null) {
                    // remember fault name for handling fault
                    messageContext.setProperty(FAULT_NAME_PROP, faultName);
                    throw new SOAPFaultException(SoapBindConstants.CLIENT_FAULTCODE,
                            SoapBindConstants.BUSINESS_FAULTSTRING, null, null);
                }
            }
        } finally {
            jmsSession.close();
        }
    }
    /*
     * NO need to set jbpm context as rollback only for any exception, since operations in try-block
     * only read definitions from database
     */
    catch (SOAPFaultException e) {
        log.debug("request caused a fault", e);
        messageContext.setProperty(FAULT_EXCEPTION_PROP, e);
    } catch (SOAPException e) {
        /*
         * BP 1.2 R2724: If an INSTANCE receives an envelope that is inconsistent with its WSDL
         * description, it SHOULD generate a soap:Fault with a faultcode of "Client", unless a
         * "MustUnderstand" or "VersionMismatch" fault is generated.
         */
        log.debug("incoming soap message carries invalid content", e);
        messageContext.setProperty(FAULT_EXCEPTION_PROP,
                new SOAPFaultException(SoapBindConstants.CLIENT_FAULTCODE, e.getMessage(), null, null));
    } catch (JMSException e) {
        throw new JAXRPCException("message delivery failed", e);
    } finally {
        jbpmContext.close();
    }
    return true;
}

From source file:org.jbpm.bpel.tutorial.invoice.ComputePricePT_Impl.java

protected void sendInvoiceMessage(float shippingPrice) throws JMSException {
    ServletContext servletContext = endpointContext.getServletContext();
    Integer orderId = (Integer) servletContext.getAttribute(ORDER_ID_ATTR);
    Float linePrice = (Float) servletContext.getAttribute(LINE_PRICE_ATTR);
    float amount = linePrice.floatValue() + shippingPrice;

    // create a session
    Session jmsSession = jmsConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    try {/*from   ww w  .  j a  v a  2  s . c o  m*/
        // create the message
        MapMessage invoiceMessage = jmsSession.createMapMessage();
        invoiceMessage.setInt("orderId", orderId.intValue());
        invoiceMessage.setFloat("amount", amount);

        // send it!
        MessageProducer producer = jmsSession.createProducer(invoiceDestination);
        producer.send(invoiceMessage);

        log.debug("Sent invoice message: orderId=" + orderId + ", amount=" + amount);
    } finally {
        jmsSession.close();
    }
}

From source file:org.jbpm.bpel.tutorial.shipping.ShippingPT_Impl.java

protected void sendShippingMessage(String customerId) throws JMSException {
    // create a session
    Session jmsSession = jmsConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    try {//  w w  w .  ja  va 2s  .  com
        // create the message
        MapMessage message = jmsSession.createMapMessage();
        message.setString("customerId", customerId);

        // send it!
        MessageProducer producer = jmsSession.createProducer(shippingDestination);
        producer.send(message);

        log.debug("Sent shipping message: customerId=" + customerId);
    } finally {
        jmsSession.close();
    }
}

From source file:org.jbpm.ejb.impl.CommandListenerBean.java

private void discard(Message message) throws JMSException {
    if (deadLetterQueue == null) {
        // lookup dead letter queue
        try {//www  .j  a v  a  2s  .c o m
            Context initial = new InitialContext();
            deadLetterQueue = (Destination) initial.lookup("java:comp/env/jms/DeadLetterQueue");
        } catch (NamingException e) {
            log.debug("failed to retrieve dead letter queue, rejecting message: " + message);
            messageDrivenContext.setRollbackOnly();
            return;
        }
    }
    // send message to dead letter queue
    Session jmsSession = createSession();
    try {
        jmsSession.createProducer(deadLetterQueue).send(message);
    } finally {
        jmsSession.close();
    }
}

From source file:org.jbpm.ejb.impl.CommandListenerBean.java

private void sendResult(Serializable result, Destination destination, String correlationId)
        throws JMSException {
    log.debug("sending result " + result + " to " + destination);
    Session jmsSession = createSession();
    try {/*from   w  w w  .  j  av  a  2 s . c om*/
        Message resultMessage = jmsSession.createObjectMessage(result);
        resultMessage.setJMSCorrelationID(correlationId);
        jmsSession.createProducer(destination).send(resultMessage);
    } finally {
        jmsSession.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");
    }//ww  w.  j av a  2 s . c  om
    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);
            }
        }
    }
}