Example usage for javax.jms MessageProducer close

List of usage examples for javax.jms MessageProducer close

Introduction

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

Prototype


void close() throws JMSException;

Source Link

Document

Closes the message producer.

Usage

From source file:net.timewalker.ffmq4.common.session.AbstractSession.java

/**
 * Close remaining consumers//from  www .  ja  v  a 2s . co  m
 */
private void closeRemainingProducers() {
    List<AbstractMessageProducer> producersToClose = new ArrayList<>(producersMap.size());
    synchronized (producersMap) {
        producersToClose.addAll(producersMap.values());
    }
    for (int n = 0; n < producersToClose.size(); n++) {
        MessageProducer producer = producersToClose.get(n);
        log.debug("Auto-closing unclosed producer : " + producer);
        try {
            producer.close();
        } catch (Exception e) {
            log.error("Could not close producer " + producer, e);
        }
    }
}

From source file:nl.nn.adapterframework.extensions.fxf.FxfSender.java

public String sendMessage(String correlationID, String message, ParameterResolutionContext prc)
        throws SenderException, TimeOutException {
    String action = "put";
    String transfername = getTransfername();
    String filename = message;//from  w  w w .  j  a  v  a 2s  .  c o m

    String command = getScript() + " " + action + " " + transfername + " " + filename;
    if (atLeastVersion2) {
        int timeout = getTimeout();
        command = command + " " + timeout;
    }
    String remoteFilename = null;
    if (remoteFilenameParam != null && prc != null) {
        try {
            remoteFilename = (String) prc.getValues(paramList).getParameterValue(0).getValue();
            command += " " + remoteFilename;
        } catch (ParameterException e) {
            throw new SenderException("Could not resolve remote filename", e);
        }
    }
    log.debug(getLogPrefix() + "sending local file [" + message + "] by executing command [" + command + "]");
    String transporthandle = ProcessUtil.executeCommand(command, getTimeout() * 2);
    log.debug(getLogPrefix() + "output of command [" + transporthandle + "]");
    if (transporthandle != null) {
        transporthandle = transporthandle.trim();
    }

    // delete file or move it to processed directory
    if (isDelete() || StringUtils.isNotEmpty(getProcessedDirectory())) {
        File f = new File(message);
        try {
            log.debug(getLogPrefix() + "moving or deleteing file [" + message + "]");
            FileUtils.moveFileAfterProcessing(f, getProcessedDirectory(), isDelete(), isOverwrite(),
                    getNumberOfBackups());
        } catch (Exception e) {
            throw new SenderException("Could not move file [" + message + "]", e);
        }
    }
    if (atLeastVersion2) {
        String commitMsg = FxfUtil.makeProcessedPutFileMessage(transporthandle);

        Session s = null;
        MessageProducer mp = null;

        try {
            s = createSession();
            mp = getMessageProducer(s, getDestination());

            // create message
            Message msg = createTextMessage(s, correlationID, commitMsg);
            mp.setDeliveryMode(DeliveryMode.PERSISTENT);

            // send message   
            send(mp, msg);
            if (log.isDebugEnabled()) {
                log.debug(getLogPrefix() + "sent message [" + message + "] to [" + getDestinationName() + "] "
                        + "msgID [" + msg.getJMSMessageID() + "]");
                ;
            } else {
                if (log.isInfoEnabled()) {
                    log.info(getLogPrefix() + "sent message to [" + getDestinationName() + "] " + "msgID ["
                            + msg.getJMSMessageID() + "]");
                    ;
                }
            }
        } catch (Throwable e) {
            throw new SenderException(e);
        } finally {
            if (mp != null) {
                try {
                    mp.close();
                } catch (JMSException e) {
                    log.warn(getLogPrefix() + "got exception closing message producer", e);
                }
            }
            closeSession(s);
        }

    }
    return transporthandle;
}

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

public String send(Session session, Destination dest, String correlationId, String message, String messageType,
        long timeToLive, int deliveryMode, int priority, boolean ignoreInvalidDestinationException,
        Map properties) throws NamingException, JMSException, SenderException {
    TextMessage msg = createTextMessage(session, correlationId, message);
    MessageProducer mp;
    try {/*www . j av a  2  s. c  o m*/
        if (useJms102()) {
            if ((session instanceof TopicSession) && (dest instanceof Topic)) {
                mp = getTopicPublisher((TopicSession) session, (Topic) dest);
            } else {
                if ((session instanceof QueueSession) && (dest instanceof Queue)) {
                    mp = getQueueSender((QueueSession) session, (Queue) dest);
                } else {
                    throw new SenderException(
                            "classes of Session [" + session.getClass().getName() + "] and Destination ["
                                    + dest.getClass().getName() + "] do not match (Queue vs Topic)");
                }
            }
        } else {
            mp = session.createProducer(dest);
        }
    } catch (InvalidDestinationException e) {
        if (ignoreInvalidDestinationException) {
            log.warn("queue [" + dest + "] doesn't exist");
            return null;
        } else {
            throw e;
        }
    }
    if (messageType != null) {
        msg.setJMSType(messageType);
    }
    if (deliveryMode > 0) {
        msg.setJMSDeliveryMode(deliveryMode);
        mp.setDeliveryMode(deliveryMode);
    }
    if (priority >= 0) {
        msg.setJMSPriority(priority);
        mp.setPriority(priority);
    }
    if (timeToLive > 0) {
        mp.setTimeToLive(timeToLive);
    }
    if (properties != null) {
        for (Iterator it = properties.keySet().iterator(); it.hasNext();) {
            String key = (String) it.next();
            Object value = properties.get(key);
            log.debug("setting property [" + name + "] to value [" + value + "]");
            msg.setObjectProperty(key, value);
        }
    }
    String result = send(mp, msg, ignoreInvalidDestinationException);
    mp.close();
    return result;
}

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

public String send(Session session, Destination dest, Message message,
        boolean ignoreInvalidDestinationException) throws NamingException, JMSException {
    try {// w  w  w .  j a v a  2  s  . co m
        if (useJms102()) {
            if (dest instanceof Topic) {
                return sendByTopic((TopicSession) session, (Topic) dest, message);
            } else {
                return sendByQueue((QueueSession) session, (Queue) dest, message);
            }
        } else {
            MessageProducer mp = session.createProducer(dest);
            mp.send(message);
            mp.close();
            return message.getJMSMessageID();
        }
    } catch (InvalidDestinationException e) {
        if (ignoreInvalidDestinationException) {
            log.warn("queue [" + dest + "] doesn't exist");
            return null;
        } else {
            throw e;
        }
    }
}

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

public String sendMessage(String correlationID, String message, ParameterResolutionContext prc,
        String soapHeader) throws SenderException, TimeOutException {
    Session s = null;//w  w w.  j  a v  a 2s  .c om
    MessageProducer mp = null;

    ParameterValueList pvl = null;
    if (prc != null && paramList != null) {
        try {
            pvl = prc.getValues(paramList);
        } catch (ParameterException e) {
            throw new SenderException(getLogPrefix() + "cannot extract parameters", e);
        }
    }

    if (isSoap()) {
        if (soapHeader == null) {
            if (pvl != null && StringUtils.isNotEmpty(getSoapHeaderParam())) {
                ParameterValue soapHeaderParamValue = pvl.getParameterValue(getSoapHeaderParam());
                if (soapHeaderParamValue == null) {
                    log.warn("no SoapHeader found using parameter [" + getSoapHeaderParam() + "]");
                } else {
                    soapHeader = soapHeaderParamValue.asStringValue("");
                }
            }
        }
        message = soapWrapper.putInEnvelope(message, getEncodingStyleURI(), getServiceNamespaceURI(),
                soapHeader);
        if (log.isDebugEnabled())
            log.debug(getLogPrefix() + "correlationId [" + correlationID + "] soap message [" + message + "]");
    }
    try {
        s = createSession();
        mp = getMessageProducer(s, getDestination(prc));
        Destination replyQueue = null;

        // create message
        Message msg = createTextMessage(s, correlationID, message);

        if (getMessageType() != null) {
            msg.setJMSType(getMessageType());
        }
        if (getDeliveryModeInt() > 0) {
            msg.setJMSDeliveryMode(getDeliveryModeInt());
            mp.setDeliveryMode(getDeliveryModeInt());
        }
        if (getPriority() >= 0) {
            msg.setJMSPriority(getPriority());
            mp.setPriority(getPriority());
        }

        // set properties
        if (pvl != null) {
            setProperties(msg, pvl);
        }
        if (replyToName != null) {
            replyQueue = getDestination(replyToName);
        } else {
            if (isSynchronous()) {
                replyQueue = getMessagingSource().getDynamicReplyQueue(s);
            }
        }
        if (replyQueue != null) {
            msg.setJMSReplyTo(replyQueue);
            if (log.isDebugEnabled())
                log.debug("replyTo set to queue [" + replyQueue.toString() + "]");
        }

        // send message   
        send(mp, msg);
        if (log.isDebugEnabled()) {
            log.debug("[" + getName() + "] " + "sent message [" + message + "] " + "to [" + mp.getDestination()
                    + "] " + "msgID [" + msg.getJMSMessageID() + "] " + "correlationID ["
                    + msg.getJMSCorrelationID() + "] " + "using deliveryMode [" + getDeliveryMode() + "] "
                    + ((replyToName != null) ? "replyTo [" + replyToName + "]" : ""));
        } else {
            if (log.isInfoEnabled()) {
                log.info("[" + getName() + "] " + "sent message to [" + mp.getDestination() + "] " + "msgID ["
                        + msg.getJMSMessageID() + "] " + "correlationID [" + msg.getJMSCorrelationID() + "] "
                        + "using deliveryMode [" + getDeliveryMode() + "] "
                        + ((replyToName != null) ? "replyTo [" + replyToName + "]" : ""));
            }
        }
        if (isSynchronous()) {
            String replyCorrelationId = null;
            if (replyToName != null) {
                if ("CORRELATIONID".equalsIgnoreCase(getLinkMethod())) {
                    replyCorrelationId = correlationID;
                } else if ("CORRELATIONID_FROM_MESSAGE".equalsIgnoreCase(getLinkMethod())) {
                    replyCorrelationId = msg.getJMSCorrelationID();
                } else {
                    replyCorrelationId = msg.getJMSMessageID();
                }
            }
            if (log.isDebugEnabled())
                log.debug("[" + getName() + "] start waiting for reply on [" + replyQueue + "] requestMsgId ["
                        + msg.getJMSMessageID() + "] replyCorrelationId [" + replyCorrelationId + "] for ["
                        + getReplyTimeout() + "] ms");
            MessageConsumer mc = getMessageConsumerForCorrelationId(s, replyQueue, replyCorrelationId);
            try {
                Message rawReplyMsg = mc.receive(getReplyTimeout());
                if (rawReplyMsg == null) {
                    throw new TimeOutException("did not receive reply on [" + replyQueue + "] requestMsgId ["
                            + msg.getJMSMessageID() + "] replyCorrelationId [" + replyCorrelationId
                            + "] within [" + getReplyTimeout() + "] ms");
                }
                return getStringFromRawMessage(rawReplyMsg, prc != null ? prc.getSession() : null, isSoap(),
                        getReplySoapHeaderSessionKey(), soapWrapper);
            } finally {
                if (mc != null) {
                    try {
                        mc.close();
                    } catch (JMSException e) {
                        log.warn("JmsSender [" + getName()
                                + "] got exception closing message consumer for reply", e);
                    }
                }
            }
        }
        return msg.getJMSMessageID();
    } catch (JMSException e) {
        throw new SenderException(e);
    } catch (IOException e) {
        throw new SenderException(e);
    } catch (NamingException e) {
        throw new SenderException(e);
    } catch (DomBuilderException e) {
        throw new SenderException(e);
    } catch (TransformerException e) {
        throw new SenderException(e);
    } catch (JmsException e) {
        throw new SenderException(e);
    } finally {
        if (mp != null) {
            try {
                mp.close();
            } catch (JMSException e) {
                log.warn("JmsSender [" + getName() + "] got exception closing message producer", e);
            }
        }
        closeSession(s);
    }
}

From source file:org.aludratest.service.jms.impl.JmsActionImpl.java

@Override
public void sendMessage(Message message, String destinationName) {
    MessageProducer producer = null;
    try {//from ww w .j a v  a 2s .c  o m
        LOGGER.debug("Sending message to destination " + destinationName);
        Destination dest = (Destination) context.lookup(destinationName);
        producer = getSession().createProducer(dest);
        this.startConnection();
        producer.send(message);
        this.stopConnection();
    } catch (NamingException e) {
        throw new AutomationException("Could not lookup destination " + destinationName, e);
    } catch (ClassCastException e) {
        throw new AutomationException("JNDI object with name " + destinationName + " is no destination", e);
    } catch (JMSException e) {
        throw new AccessFailure("Could not send JMS message", e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException e) {
            }
        }
    }
}

From source file:org.apache.activemq.apollo.JmsQueueBrowserTest.java

public void testBrowseReceive() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");

    connection.start();/* w  w  w.j  a  v a 2 s.  c  o  m*/

    Message[] outbound = new Message[] { session.createTextMessage("First Message"),
            session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };

    MessageProducer producer = session.createProducer(destination);
    producer.send(outbound[0]);

    // create browser first
    QueueBrowser browser = session.createBrowser((Queue) destination);
    Enumeration enumeration = browser.getEnumeration();

    // create consumer
    MessageConsumer consumer = session.createConsumer(destination);

    // browse the first message
    assertTrue("should have received the first message", enumeration.hasMoreElements());
    assertEquals(outbound[0], (Message) enumeration.nextElement());

    // Receive the first message.
    assertEquals(outbound[0], consumer.receive(1000));
    consumer.close();
    browser.close();
    producer.close();

}

From source file:org.apache.activemq.apollo.JmsQueueBrowserTest.java

public void testBrowseClose() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");

    connection.start();/*w  w  w .java2s .  c o  m*/

    TextMessage[] outbound = new TextMessage[] { session.createTextMessage("First Message"),
            session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };

    MessageProducer producer = session.createProducer(destination);
    producer.send(outbound[0]);
    producer.send(outbound[1]);
    producer.send(outbound[2]);

    // create browser first
    QueueBrowser browser = session.createBrowser((Queue) destination);
    Enumeration enumeration = browser.getEnumeration();

    // browse some messages
    assertEquals(outbound[0], (Message) enumeration.nextElement());
    assertEquals(outbound[1], (Message) enumeration.nextElement());
    //assertEquals(outbound[2], (Message) enumeration.nextElement());

    browser.close();

    // create consumer
    MessageConsumer consumer = session.createConsumer(destination);

    // Receive the first message.
    TextMessage msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[0].getText() + " but received " + msg.getText(), outbound[0], msg);
    msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[1].getText() + " but received " + msg.getText(), outbound[1], msg);
    msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[2].getText() + " but received " + msg.getText(), outbound[2], msg);

    consumer.close();
    producer.close();

}

From source file:org.apache.activemq.broker.jmx.ConcurrentMoveTest.java

public void testConcurrentMove() throws Exception {

    // Send some messages
    connection = connectionFactory.createConnection();
    connection.start();/*from w w w.jav  a2  s .  c  o m*/
    Session session = connection.createSession(transacted, authMode);
    destination = createDestination();
    MessageProducer producer = session.createProducer(destination);
    for (int i = 0; i < messageCount; i++) {
        Message message = session.createTextMessage("Message: " + i);
        producer.send(message);
    }

    long usageBeforMove = broker.getPersistenceAdapter().size();
    LOG.info("Store usage:" + usageBeforMove);

    // Now get the QueueViewMBean and purge
    String objectNameStr = broker.getBrokerObjectName().toString();
    objectNameStr += ",destinationType=Queue,destinationName=" + getDestinationString();
    ObjectName queueViewMBeanName = assertRegisteredObjectName(objectNameStr);
    final QueueViewMBean proxy = (QueueViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer,
            queueViewMBeanName, QueueViewMBean.class, true);

    final ActiveMQQueue to = new ActiveMQQueue("TO");
    ((RegionBroker) broker.getRegionBroker()).addDestination(broker.getAdminConnectionContext(), to, false);

    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int i = 0; i < 50; i++) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    proxy.moveMatchingMessagesTo(null, to.getPhysicalName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    executorService.shutdown();
    executorService.awaitTermination(5, TimeUnit.MINUTES);

    long count = proxy.getQueueSize();
    assertEquals("Queue size", count, 0);
    assertEquals("Browse size", proxy.browseMessages().size(), 0);

    objectNameStr = broker.getBrokerObjectName().toString();
    objectNameStr += ",destinationType=Queue,destinationName=" + to.getQueueName();
    queueViewMBeanName = assertRegisteredObjectName(objectNameStr);
    QueueViewMBean toProxy = (QueueViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer,
            queueViewMBeanName, QueueViewMBean.class, true);

    count = toProxy.getQueueSize();
    assertEquals("Queue size", count, messageCount);

    long usageAfterMove = broker.getPersistenceAdapter().size();
    LOG.info("Store usage, before: " + usageBeforMove + ", after:" + usageAfterMove);
    LOG.info("Store size increase:" + FileUtils.byteCountToDisplaySize(usageAfterMove - usageBeforMove));

    assertTrue("Usage not more than doubled", usageAfterMove < (usageBeforMove * 3));

    producer.close();
}

From source file:org.apache.activemq.store.jdbc.JmsTransactionCommitFailureTest.java

private void sendMessage(String queueName, int count, boolean transacted) throws JMSException {
    Connection con = connectionFactory.createConnection();
    try {//from www  .ja va  2 s .c  o  m
        Session session = con.createSession(transacted,
                transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE);
        try {
            Queue destination = session.createQueue(queueName);
            MessageProducer producer = session.createProducer(destination);
            try {
                for (int i = 0; i < count; i++) {
                    TextMessage message = session.createTextMessage();
                    message.setIntProperty("MessageId", messageCounter);
                    message.setText("Message-" + messageCounter++);
                    producer.send(message);
                }
                if (transacted) {
                    session.commit();
                }
            } finally {
                producer.close();
            }
        } finally {
            session.close();
        }
    } finally {
        con.close();
    }
}