Java Code Examples for org.springframework.jms.support.JmsUtils#closeMessageConsumer()

The following examples show how to use org.springframework.jms.support.JmsUtils#closeMessageConsumer() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SimpleMessageListenerContainer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Destroy the registered JMS Sessions and associated MessageConsumers.
 */
@Override
protected void doShutdown() throws JMSException {
	synchronized (this.consumersMonitor) {
		if (this.consumers != null) {
			logger.debug("Closing JMS MessageConsumers");
			for (MessageConsumer consumer : this.consumers) {
				JmsUtils.closeMessageConsumer(consumer);
			}
			if (this.sessions != null) {
				logger.debug("Closing JMS Sessions");
				for (Session session : this.sessions) {
					JmsUtils.closeSession(session);
				}
			}
		}
	}
}
 
Example 2
Source File: JmsInvokerClientInterceptor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Actually execute the given request, sending the invoker request message
 * to the specified target queue and waiting for a corresponding response.
 * <p>The default implementation is based on standard JMS send/receive,
 * using a {@link javax.jms.TemporaryQueue} for receiving the response.
 * @param session the JMS Session to use
 * @param queue the resolved target Queue to send to
 * @param requestMessage the JMS Message to send
 * @return the RemoteInvocationResult object
 * @throws JMSException in case of JMS failure
 */
protected Message doExecuteRequest(Session session, Queue queue, Message requestMessage) throws JMSException {
	TemporaryQueue responseQueue = null;
	MessageProducer producer = null;
	MessageConsumer consumer = null;
	try {
		responseQueue = session.createTemporaryQueue();
		producer = session.createProducer(queue);
		consumer = session.createConsumer(responseQueue);
		requestMessage.setJMSReplyTo(responseQueue);
		producer.send(requestMessage);
		long timeout = getReceiveTimeout();
		return (timeout > 0 ? consumer.receive(timeout) : consumer.receive());
	}
	finally {
		JmsUtils.closeMessageConsumer(consumer);
		JmsUtils.closeMessageProducer(producer);
		if (responseQueue != null) {
			responseQueue.delete();
		}
	}
}
 
Example 3
Source File: SimpleMessageListenerContainer.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Destroy the registered JMS Sessions and associated MessageConsumers.
 */
@Override
protected void doShutdown() throws JMSException {
	synchronized (this.consumersMonitor) {
		if (this.consumers != null) {
			logger.debug("Closing JMS MessageConsumers");
			for (MessageConsumer consumer : this.consumers) {
				JmsUtils.closeMessageConsumer(consumer);
			}
			logger.debug("Closing JMS Sessions");
			for (Session session : this.sessions) {
				JmsUtils.closeSession(session);
			}
		}
	}
}
 
Example 4
Source File: DefaultMessageListenerContainer.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private void clearResources() {
	if (sharedConnectionEnabled()) {
		synchronized (sharedConnectionMonitor) {
			JmsUtils.closeMessageConsumer(this.consumer);
			JmsUtils.closeSession(this.session);
		}
	}
	else {
		JmsUtils.closeMessageConsumer(this.consumer);
		JmsUtils.closeSession(this.session);
	}
	if (this.consumer != null) {
		synchronized (lifecycleMonitor) {
			registeredWithDestination--;
		}
	}
	this.consumer = null;
	this.session = null;
}
 
Example 5
Source File: JmsInvokerClientInterceptor.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Actually execute the given request, sending the invoker request message
 * to the specified target queue and waiting for a corresponding response.
 * <p>The default implementation is based on standard JMS send/receive,
 * using a {@link javax.jms.TemporaryQueue} for receiving the response.
 * @param session the JMS Session to use
 * @param queue the resolved target Queue to send to
 * @param requestMessage the JMS Message to send
 * @return the RemoteInvocationResult object
 * @throws JMSException in case of JMS failure
 */
@Nullable
protected Message doExecuteRequest(Session session, Queue queue, Message requestMessage) throws JMSException {
	TemporaryQueue responseQueue = null;
	MessageProducer producer = null;
	MessageConsumer consumer = null;
	try {
		responseQueue = session.createTemporaryQueue();
		producer = session.createProducer(queue);
		consumer = session.createConsumer(responseQueue);
		requestMessage.setJMSReplyTo(responseQueue);
		producer.send(requestMessage);
		long timeout = getReceiveTimeout();
		return (timeout > 0 ? consumer.receive(timeout) : consumer.receive());
	}
	finally {
		JmsUtils.closeMessageConsumer(consumer);
		JmsUtils.closeMessageProducer(producer);
		if (responseQueue != null) {
			responseQueue.delete();
		}
	}
}
 
Example 6
Source File: SimpleMessageListenerContainer.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Destroy the registered JMS Sessions and associated MessageConsumers.
 */
@Override
protected void doShutdown() throws JMSException {
	synchronized (this.consumersMonitor) {
		if (this.consumers != null) {
			logger.debug("Closing JMS MessageConsumers");
			for (MessageConsumer consumer : this.consumers) {
				JmsUtils.closeMessageConsumer(consumer);
			}
			if (this.sessions != null) {
				logger.debug("Closing JMS Sessions");
				for (Session session : this.sessions) {
					JmsUtils.closeSession(session);
				}
			}
		}
	}
}
 
Example 7
Source File: DefaultMessageListenerContainer.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void clearResources() {
	if (sharedConnectionEnabled()) {
		synchronized (sharedConnectionMonitor) {
			JmsUtils.closeMessageConsumer(this.consumer);
			JmsUtils.closeSession(this.session);
		}
	}
	else {
		JmsUtils.closeMessageConsumer(this.consumer);
		JmsUtils.closeSession(this.session);
	}
	if (this.consumer != null) {
		synchronized (lifecycleMonitor) {
			registeredWithDestination--;
		}
	}
	this.consumer = null;
	this.session = null;
}
 
Example 8
Source File: JmsInvokerClientInterceptor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Actually execute the given request, sending the invoker request message
 * to the specified target queue and waiting for a corresponding response.
 * <p>The default implementation is based on standard JMS send/receive,
 * using a {@link javax.jms.TemporaryQueue} for receiving the response.
 * @param session the JMS Session to use
 * @param queue the resolved target Queue to send to
 * @param requestMessage the JMS Message to send
 * @return the RemoteInvocationResult object
 * @throws JMSException in case of JMS failure
 */
@Nullable
protected Message doExecuteRequest(Session session, Queue queue, Message requestMessage) throws JMSException {
	TemporaryQueue responseQueue = null;
	MessageProducer producer = null;
	MessageConsumer consumer = null;
	try {
		responseQueue = session.createTemporaryQueue();
		producer = session.createProducer(queue);
		consumer = session.createConsumer(responseQueue);
		requestMessage.setJMSReplyTo(responseQueue);
		producer.send(requestMessage);
		long timeout = getReceiveTimeout();
		return (timeout > 0 ? consumer.receive(timeout) : consumer.receive());
	}
	finally {
		JmsUtils.closeMessageConsumer(consumer);
		JmsUtils.closeMessageProducer(producer);
		if (responseQueue != null) {
			responseQueue.delete();
		}
	}
}
 
Example 9
Source File: DefaultMessageListenerContainer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void clearResources() {
	if (sharedConnectionEnabled()) {
		synchronized (sharedConnectionMonitor) {
			JmsUtils.closeMessageConsumer(this.consumer);
			JmsUtils.closeSession(this.session);
		}
	}
	else {
		JmsUtils.closeMessageConsumer(this.consumer);
		JmsUtils.closeSession(this.session);
	}
	if (this.consumer != null) {
		synchronized (lifecycleMonitor) {
			registeredWithDestination--;
		}
	}
	this.consumer = null;
	this.session = null;
}
 
Example 10
Source File: JmsTemplate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Send a request message to the given {@link Destination} and block until
 * a reply has been received on a temporary queue created on-the-fly.
 * <p>Return the response message or {@code null} if no message has
 * @throws JMSException if thrown by JMS API methods
 */
@Nullable
protected Message doSendAndReceive(Session session, Destination destination, MessageCreator messageCreator)
		throws JMSException {

	Assert.notNull(messageCreator, "MessageCreator must not be null");
	TemporaryQueue responseQueue = null;
	MessageProducer producer = null;
	MessageConsumer consumer = null;
	try {
		Message requestMessage = messageCreator.createMessage(session);
		responseQueue = session.createTemporaryQueue();
		producer = session.createProducer(destination);
		consumer = session.createConsumer(responseQueue);
		requestMessage.setJMSReplyTo(responseQueue);
		if (logger.isDebugEnabled()) {
			logger.debug("Sending created message: " + requestMessage);
		}
		doSend(producer, requestMessage);
		return receiveFromConsumer(consumer, getReceiveTimeout());
	}
	finally {
		JmsUtils.closeMessageConsumer(consumer);
		JmsUtils.closeMessageProducer(producer);
		if (responseQueue != null) {
			responseQueue.delete();
		}
	}
}
 
Example 11
Source File: JmsTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Send a request message to the given {@link Destination} and block until
 * a reply has been received on a temporary queue created on-the-fly.
 * <p>Return the response message or {@code null} if no message has
 * @throws JMSException if thrown by JMS API methods
 */
@Nullable
protected Message doSendAndReceive(Session session, Destination destination, MessageCreator messageCreator)
		throws JMSException {

	Assert.notNull(messageCreator, "MessageCreator must not be null");
	TemporaryQueue responseQueue = null;
	MessageProducer producer = null;
	MessageConsumer consumer = null;
	try {
		Message requestMessage = messageCreator.createMessage(session);
		responseQueue = session.createTemporaryQueue();
		producer = session.createProducer(destination);
		consumer = session.createConsumer(responseQueue);
		requestMessage.setJMSReplyTo(responseQueue);
		if (logger.isDebugEnabled()) {
			logger.debug("Sending created message: " + requestMessage);
		}
		doSend(producer, requestMessage);
		return receiveFromConsumer(consumer, getReceiveTimeout());
	}
	finally {
		JmsUtils.closeMessageConsumer(consumer);
		JmsUtils.closeMessageProducer(producer);
		if (responseQueue != null) {
			responseQueue.delete();
		}
	}
}
 
Example 12
Source File: JmsTemplate.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Actually receive a JMS message.
 * @param session the JMS Session to operate on
 * @param consumer the JMS MessageConsumer to receive with
 * @return the JMS Message received, or {@code null} if none
 * @throws JMSException if thrown by JMS API methods
 */
protected Message doReceive(Session session, MessageConsumer consumer) throws JMSException {
	try {
		// Use transaction timeout (if available).
		long timeout = getReceiveTimeout();
		JmsResourceHolder resourceHolder =
				(JmsResourceHolder) TransactionSynchronizationManager.getResource(getConnectionFactory());
		if (resourceHolder != null && resourceHolder.hasTimeout()) {
			timeout = Math.min(timeout, resourceHolder.getTimeToLiveInMillis());
		}
		Message message = doReceive(consumer, timeout);
		if (session.getTransacted()) {
			// Commit necessary - but avoid commit call within a JTA transaction.
			if (isSessionLocallyTransacted(session)) {
				// Transacted session created by this template -> commit.
				JmsUtils.commitIfNecessary(session);
			}
		}
		else if (isClientAcknowledge(session)) {
			// Manually acknowledge message, if any.
			if (message != null) {
				message.acknowledge();
			}
		}
		return message;
	}
	finally {
		JmsUtils.closeMessageConsumer(consumer);
	}
}
 
Example 13
Source File: JmsTemplate.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Send a request message to the given {@link Destination} and block until
 * a reply has been received on a temporary queue created on-the-fly.
 * <p>Return the response message or {@code null} if no message has
 * @throws JMSException if thrown by JMS API methods
 */
protected Message doSendAndReceive(Session session, Destination destination, MessageCreator messageCreator)
		throws JMSException {

	Assert.notNull(messageCreator, "MessageCreator must not be null");
	TemporaryQueue responseQueue = null;
	MessageProducer producer = null;
	MessageConsumer consumer = null;
	try {
		Message requestMessage = messageCreator.createMessage(session);
		responseQueue = session.createTemporaryQueue();
		producer = session.createProducer(destination);
		consumer = session.createConsumer(responseQueue);
		requestMessage.setJMSReplyTo(responseQueue);
		if (logger.isDebugEnabled()) {
			logger.debug("Sending created message: " + requestMessage);
		}
		doSend(producer, requestMessage);
		return doReceive(consumer, getReceiveTimeout());
	}
	finally {
		JmsUtils.closeMessageConsumer(consumer);
		JmsUtils.closeMessageProducer(producer);
		if (responseQueue != null) {
			responseQueue.delete();
		}
	}
}
 
Example 14
Source File: BatchedJmsTemplate.java    From jadira with Apache License 2.0 5 votes vote down vote up
protected List<Message> doBatchReceive(Session session, MessageConsumer consumer, int batchSize)
        throws JMSException {

    try {
        final List<Message> result;
        long timeout = determineTimeout();

        Message message = doReceive(consumer, timeout);

        if (message == null) {
            result = new ArrayList<Message>(0);
        } else {
            result = new ArrayList<Message>(batchSize);
            result.add(message);
            for (int i = 1; i < batchSize; i++) {
                message = doReceive(consumer, RECEIVE_TIMEOUT_NO_WAIT);
                if (message == null) {
                    break;
                }
                result.add(message);
            }
        }

        if (session.getTransacted()) {
            if (isSessionLocallyTransacted(session)) {
                JmsUtils.commitIfNecessary(session);
            }
        } else if (isClientAcknowledge(session)) {
            if (message != null) {
                message.acknowledge();
            }
        }
        return result;
    } finally {
        JmsUtils.closeMessageConsumer(consumer);
    }
}
 
Example 15
Source File: BatchedJmsTemplate.java    From jadira with Apache License 2.0 5 votes vote down vote up
protected Message doSingleReceive(Session session, MessageConsumer consumer) throws JMSException {

        if (!session.getTransacted() || isSessionLocallyTransacted(session)) {
            // If we are not using JTA we should use standard JmsTemplate behaviour
            return super.doReceive(session, consumer);
        }

        // Otherwise batching - the batch can span multiple receive() calls, until you commit the
        // batch
        try {
            final Message message;
            if (Boolean.TRUE.equals(IS_START_OF_BATCH.get())) {
                // Register Synchronization
                TransactionSynchronizationManager.registerSynchronization(BATCH_SYNCHRONIZATION);

                // Use transaction timeout (if available).
                long timeout = determineTimeout();

                message = doReceive(consumer, timeout);
                IS_START_OF_BATCH.set(Boolean.FALSE);
            } else {
                message = doReceive(consumer, RECEIVE_TIMEOUT_NO_WAIT);
            }

            if (isClientAcknowledge(session)) {
                // Manually acknowledge message, if any.
                if (message != null) {
                    message.acknowledge();
                }
            }
            return message;
        } finally {
            JmsUtils.closeMessageConsumer(consumer);
        }
    }
 
Example 16
Source File: AbstractPollingMessageListenerContainer.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Actually execute the listener for a message received from the given consumer,
 * fetching all requires resources and invoking the listener.
 * @param session the JMS Session to work on
 * @param consumer the MessageConsumer to work on
 * @param status the TransactionStatus (may be {@code null})
 * @return whether a message has been received
 * @throws JMSException if thrown by JMS methods
 * @see #doExecuteListener(javax.jms.Session, javax.jms.Message)
 */
protected boolean doReceiveAndExecute(Object invoker, @Nullable Session session,
		@Nullable MessageConsumer consumer, @Nullable TransactionStatus status) throws JMSException {

	Connection conToClose = null;
	Session sessionToClose = null;
	MessageConsumer consumerToClose = null;
	try {
		Session sessionToUse = session;
		boolean transactional = false;
		if (sessionToUse == null) {
			sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(
					obtainConnectionFactory(), this.transactionalResourceFactory, true);
			transactional = (sessionToUse != null);
		}
		if (sessionToUse == null) {
			Connection conToUse;
			if (sharedConnectionEnabled()) {
				conToUse = getSharedConnection();
			}
			else {
				conToUse = createConnection();
				conToClose = conToUse;
				conToUse.start();
			}
			sessionToUse = createSession(conToUse);
			sessionToClose = sessionToUse;
		}
		MessageConsumer consumerToUse = consumer;
		if (consumerToUse == null) {
			consumerToUse = createListenerConsumer(sessionToUse);
			consumerToClose = consumerToUse;
		}
		Message message = receiveMessage(consumerToUse);
		if (message != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("Received message of type [" + message.getClass() + "] from consumer [" +
						consumerToUse + "] of " + (transactional ? "transactional " : "") + "session [" +
						sessionToUse + "]");
			}
			messageReceived(invoker, sessionToUse);
			boolean exposeResource = (!transactional && isExposeListenerSession() &&
					!TransactionSynchronizationManager.hasResource(obtainConnectionFactory()));
			if (exposeResource) {
				TransactionSynchronizationManager.bindResource(
						obtainConnectionFactory(), new LocallyExposedJmsResourceHolder(sessionToUse));
			}
			try {
				doExecuteListener(sessionToUse, message);
			}
			catch (Throwable ex) {
				if (status != null) {
					if (logger.isDebugEnabled()) {
						logger.debug("Rolling back transaction because of listener exception thrown: " + ex);
					}
					status.setRollbackOnly();
				}
				handleListenerException(ex);
				// Rethrow JMSException to indicate an infrastructure problem
				// that may have to trigger recovery...
				if (ex instanceof JMSException) {
					throw (JMSException) ex;
				}
			}
			finally {
				if (exposeResource) {
					TransactionSynchronizationManager.unbindResource(obtainConnectionFactory());
				}
			}
			// Indicate that a message has been received.
			return true;
		}
		else {
			if (logger.isTraceEnabled()) {
				logger.trace("Consumer [" + consumerToUse + "] of " + (transactional ? "transactional " : "") +
						"session [" + sessionToUse + "] did not receive a message");
			}
			noMessageReceived(invoker, sessionToUse);
			// Nevertheless call commit, in order to reset the transaction timeout (if any).
			if (shouldCommitAfterNoMessageReceived(sessionToUse)) {
				commitIfNecessary(sessionToUse, null);
			}
			// Indicate that no message has been received.
			return false;
		}
	}
	finally {
		JmsUtils.closeMessageConsumer(consumerToClose);
		JmsUtils.closeSession(sessionToClose);
		ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), true);
	}
}
 
Example 17
Source File: AbstractPollingMessageListenerContainer.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Actually execute the listener for a message received from the given consumer,
 * fetching all requires resources and invoking the listener.
 * @param session the JMS Session to work on
 * @param consumer the MessageConsumer to work on
 * @param status the TransactionStatus (may be {@code null})
 * @return whether a message has been received
 * @throws JMSException if thrown by JMS methods
 * @see #doExecuteListener(javax.jms.Session, javax.jms.Message)
 */
protected boolean doReceiveAndExecute(Object invoker, @Nullable Session session,
		@Nullable MessageConsumer consumer, @Nullable TransactionStatus status) throws JMSException {

	Connection conToClose = null;
	Session sessionToClose = null;
	MessageConsumer consumerToClose = null;
	try {
		Session sessionToUse = session;
		boolean transactional = false;
		if (sessionToUse == null) {
			sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(
					obtainConnectionFactory(), this.transactionalResourceFactory, true);
			transactional = (sessionToUse != null);
		}
		if (sessionToUse == null) {
			Connection conToUse;
			if (sharedConnectionEnabled()) {
				conToUse = getSharedConnection();
			}
			else {
				conToUse = createConnection();
				conToClose = conToUse;
				conToUse.start();
			}
			sessionToUse = createSession(conToUse);
			sessionToClose = sessionToUse;
		}
		MessageConsumer consumerToUse = consumer;
		if (consumerToUse == null) {
			consumerToUse = createListenerConsumer(sessionToUse);
			consumerToClose = consumerToUse;
		}
		Message message = receiveMessage(consumerToUse);
		if (message != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("Received message of type [" + message.getClass() + "] from consumer [" +
						consumerToUse + "] of " + (transactional ? "transactional " : "") + "session [" +
						sessionToUse + "]");
			}
			messageReceived(invoker, sessionToUse);
			boolean exposeResource = (!transactional && isExposeListenerSession() &&
					!TransactionSynchronizationManager.hasResource(obtainConnectionFactory()));
			if (exposeResource) {
				TransactionSynchronizationManager.bindResource(
						obtainConnectionFactory(), new LocallyExposedJmsResourceHolder(sessionToUse));
			}
			try {
				doExecuteListener(sessionToUse, message);
			}
			catch (Throwable ex) {
				if (status != null) {
					if (logger.isDebugEnabled()) {
						logger.debug("Rolling back transaction because of listener exception thrown: " + ex);
					}
					status.setRollbackOnly();
				}
				handleListenerException(ex);
				// Rethrow JMSException to indicate an infrastructure problem
				// that may have to trigger recovery...
				if (ex instanceof JMSException) {
					throw (JMSException) ex;
				}
			}
			finally {
				if (exposeResource) {
					TransactionSynchronizationManager.unbindResource(obtainConnectionFactory());
				}
			}
			// Indicate that a message has been received.
			return true;
		}
		else {
			if (logger.isTraceEnabled()) {
				logger.trace("Consumer [" + consumerToUse + "] of " + (transactional ? "transactional " : "") +
						"session [" + sessionToUse + "] did not receive a message");
			}
			noMessageReceived(invoker, sessionToUse);
			// Nevertheless call commit, in order to reset the transaction timeout (if any).
			if (shouldCommitAfterNoMessageReceived(sessionToUse)) {
				commitIfNecessary(sessionToUse, null);
			}
			// Indicate that no message has been received.
			return false;
		}
	}
	finally {
		JmsUtils.closeMessageConsumer(consumerToClose);
		JmsUtils.closeSession(sessionToClose);
		ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), true);
	}
}