Java Code Examples for org.springframework.jms.connection.ConnectionFactoryUtils#releaseConnection()

The following examples show how to use org.springframework.jms.connection.ConnectionFactoryUtils#releaseConnection() . 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: AbstractJmsListeningContainer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Initialize this container.
 * <p>Creates a JMS Connection, starts the {@link javax.jms.Connection}
 * (if {@link #setAutoStartup(boolean) "autoStartup"} hasn't been turned off),
 * and calls {@link #doInitialize()}.
 * @throws org.springframework.jms.JmsException if startup failed
 */
public void initialize() throws JmsException {
	try {
		synchronized (this.lifecycleMonitor) {
			this.active = true;
			this.lifecycleMonitor.notifyAll();
		}
		doInitialize();
	}
	catch (JMSException ex) {
		synchronized (this.sharedConnectionMonitor) {
			ConnectionFactoryUtils.releaseConnection(this.sharedConnection, getConnectionFactory(), this.autoStartup);
			this.sharedConnection = null;
		}
		throw convertJmsAccessException(ex);
	}
}
 
Example 2
Source File: JmsTemplate.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * A variant of {@link #execute(SessionCallback, boolean)} that explicitly
 * creates a non-transactional {@link Session}. The given {@link SessionCallback}
 * does not participate in an existing transaction.
 */
private <T> T executeLocal(SessionCallback<T> action, boolean startConnection) throws JmsException {
	Assert.notNull(action, "Callback object must not be null");
	Connection con = null;
	Session session = null;
	try {
		con = getConnectionFactory().createConnection();
		session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
		if (startConnection) {
			con.start();
		}
		if (logger.isDebugEnabled()) {
			logger.debug("Executing callback on JMS Session: " + session);
		}
		return action.doInJms(session);
	}
	catch (JMSException ex) {
		throw convertJmsAccessException(ex);
	}
	finally {
		JmsUtils.closeSession(session);
		ConnectionFactoryUtils.releaseConnection(con, getConnectionFactory(), startConnection);
	}
}
 
Example 3
Source File: JmsInvokerClientInterceptor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Execute the given remote invocation, sending an invoker request message
 * to this accessor's target queue and waiting for a corresponding response.
 * @param invocation the RemoteInvocation to execute
 * @return the RemoteInvocationResult object
 * @throws JMSException in case of JMS failure
 * @see #doExecuteRequest
 */
protected RemoteInvocationResult executeRequest(RemoteInvocation invocation) throws JMSException {
	Connection con = createConnection();
	Session session = null;
	try {
		session = createSession(con);
		Queue queueToUse = resolveQueue(session);
		Message requestMessage = createRequestMessage(session, invocation);
		con.start();
		Message responseMessage = doExecuteRequest(session, queueToUse, requestMessage);
		if (responseMessage != null) {
			return extractInvocationResult(responseMessage);
		}
		else {
			return onReceiveTimeout(invocation);
		}
	}
	finally {
		JmsUtils.closeSession(session);
		ConnectionFactoryUtils.releaseConnection(con, getConnectionFactory(), true);
	}
}
 
Example 4
Source File: JmsTemplate.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * A variant of {@link #execute(SessionCallback, boolean)} that explicitly
 * creates a non-transactional {@link Session}. The given {@link SessionCallback}
 * does not participate in an existing transaction.
 */
@Nullable
private <T> T executeLocal(SessionCallback<T> action, boolean startConnection) throws JmsException {
	Assert.notNull(action, "Callback object must not be null");
	Connection con = null;
	Session session = null;
	try {
		con = createConnection();
		session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
		if (startConnection) {
			con.start();
		}
		if (logger.isDebugEnabled()) {
			logger.debug("Executing callback on JMS Session: " + session);
		}
		return action.doInJms(session);
	}
	catch (JMSException ex) {
		throw convertJmsAccessException(ex);
	}
	finally {
		JmsUtils.closeSession(session);
		ConnectionFactoryUtils.releaseConnection(con, getConnectionFactory(), startConnection);
	}
}
 
Example 5
Source File: AbstractJmsListeningContainer.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Initialize this container.
 * <p>Creates a JMS Connection, starts the {@link javax.jms.Connection}
 * (if {@link #setAutoStartup(boolean) "autoStartup"} hasn't been turned off),
 * and calls {@link #doInitialize()}.
 * @throws org.springframework.jms.JmsException if startup failed
 */
public void initialize() throws JmsException {
	try {
		synchronized (this.lifecycleMonitor) {
			this.active = true;
			this.lifecycleMonitor.notifyAll();
		}
		doInitialize();
	}
	catch (JMSException ex) {
		synchronized (this.sharedConnectionMonitor) {
			ConnectionFactoryUtils.releaseConnection(this.sharedConnection, getConnectionFactory(), this.autoStartup);
			this.sharedConnection = null;
		}
		throw convertJmsAccessException(ex);
	}
}
 
Example 6
Source File: JmsInvokerClientInterceptor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Execute the given remote invocation, sending an invoker request message
 * to this accessor's target queue and waiting for a corresponding response.
 * @param invocation the RemoteInvocation to execute
 * @return the RemoteInvocationResult object
 * @throws JMSException in case of JMS failure
 * @see #doExecuteRequest
 */
protected RemoteInvocationResult executeRequest(RemoteInvocation invocation) throws JMSException {
	Connection con = createConnection();
	Session session = null;
	try {
		session = createSession(con);
		Queue queueToUse = resolveQueue(session);
		Message requestMessage = createRequestMessage(session, invocation);
		con.start();
		Message responseMessage = doExecuteRequest(session, queueToUse, requestMessage);
		if (responseMessage != null) {
			return extractInvocationResult(responseMessage);
		}
		else {
			return onReceiveTimeout(invocation);
		}
	}
	finally {
		JmsUtils.closeSession(session);
		ConnectionFactoryUtils.releaseConnection(con, getConnectionFactory(), true);
	}
}
 
Example 7
Source File: JmsInvokerClientInterceptor.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Execute the given remote invocation, sending an invoker request message
 * to this accessor's target queue and waiting for a corresponding response.
 * @param invocation the RemoteInvocation to execute
 * @return the RemoteInvocationResult object
 * @throws JMSException in case of JMS failure
 * @see #doExecuteRequest
 */
protected RemoteInvocationResult executeRequest(RemoteInvocation invocation) throws JMSException {
	Connection con = createConnection();
	Session session = null;
	try {
		session = createSession(con);
		Queue queueToUse = resolveQueue(session);
		Message requestMessage = createRequestMessage(session, invocation);
		con.start();
		Message responseMessage = doExecuteRequest(session, queueToUse, requestMessage);
		if (responseMessage != null) {
			return extractInvocationResult(responseMessage);
		}
		else {
			return onReceiveTimeout(invocation);
		}
	}
	finally {
		JmsUtils.closeSession(session);
		ConnectionFactoryUtils.releaseConnection(con, getConnectionFactory(), true);
	}
}
 
Example 8
Source File: AbstractJmsListeningContainer.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize this container.
 * <p>Creates a JMS Connection, starts the {@link javax.jms.Connection}
 * (if {@link #setAutoStartup(boolean) "autoStartup"} hasn't been turned off),
 * and calls {@link #doInitialize()}.
 * @throws org.springframework.jms.JmsException if startup failed
 */
public void initialize() throws JmsException {
	try {
		synchronized (this.lifecycleMonitor) {
			this.active = true;
			this.lifecycleMonitor.notifyAll();
		}
		doInitialize();
	}
	catch (JMSException ex) {
		synchronized (this.sharedConnectionMonitor) {
			ConnectionFactoryUtils.releaseConnection(this.sharedConnection, getConnectionFactory(), this.autoStartup);
			this.sharedConnection = null;
		}
		throw convertJmsAccessException(ex);
	}
}
 
Example 9
Source File: JmsTemplate.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * A variant of {@link #execute(SessionCallback, boolean)} that explicitly
 * creates a non-transactional {@link Session}. The given {@link SessionCallback}
 * does not participate in an existing transaction.
 */
@Nullable
private <T> T executeLocal(SessionCallback<T> action, boolean startConnection) throws JmsException {
	Assert.notNull(action, "Callback object must not be null");
	Connection con = null;
	Session session = null;
	try {
		con = createConnection();
		session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
		if (startConnection) {
			con.start();
		}
		if (logger.isDebugEnabled()) {
			logger.debug("Executing callback on JMS Session: " + session);
		}
		return action.doInJms(session);
	}
	catch (JMSException ex) {
		throw convertJmsAccessException(ex);
	}
	finally {
		JmsUtils.closeSession(session);
		ConnectionFactoryUtils.releaseConnection(con, getConnectionFactory(), startConnection);
	}
}
 
Example 10
Source File: AbstractJmsListeningContainer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Refresh the shared Connection that this container holds.
 * <p>Called on startup and also after an infrastructure exception
 * that occurred during invoker setup and/or execution.
 * @throws JMSException if thrown by JMS API methods
 */
protected final void refreshSharedConnection() throws JMSException {
	synchronized (this.sharedConnectionMonitor) {
		ConnectionFactoryUtils.releaseConnection(
				this.sharedConnection, getConnectionFactory(), this.sharedConnectionStarted);
		this.sharedConnection = null;
		this.sharedConnection = createSharedConnection();
		if (this.sharedConnectionStarted) {
			this.sharedConnection.start();
		}
	}
}
 
Example 11
Source File: JmsTemplate.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Execute the action specified by the given action object within a
 * JMS Session. Generalized version of {@code execute(SessionCallback)},
 * allowing the JMS Connection to be started on the fly.
 * <p>Use {@code execute(SessionCallback)} for the general case.
 * Starting the JMS Connection is just necessary for receiving messages,
 * which is preferably achieved through the {@code receive} methods.
 * @param action callback object that exposes the Session
 * @param startConnection whether to start the Connection
 * @return the result object from working with the Session
 * @throws JmsException if there is any problem
 * @see #execute(SessionCallback)
 * @see #receive
 */
public <T> T execute(SessionCallback<T> action, boolean startConnection) throws JmsException {
	Assert.notNull(action, "Callback object must not be null");
	Connection conToClose = null;
	Session sessionToClose = null;
	try {
		Session sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(
				getConnectionFactory(), this.transactionalResourceFactory, startConnection);
		if (sessionToUse == null) {
			conToClose = createConnection();
			sessionToClose = createSession(conToClose);
			if (startConnection) {
				conToClose.start();
			}
			sessionToUse = sessionToClose;
		}
		if (logger.isDebugEnabled()) {
			logger.debug("Executing callback on JMS Session: " + sessionToUse);
		}
		return action.doInJms(sessionToUse);
	}
	catch (JMSException ex) {
		throw convertJmsAccessException(ex);
	}
	finally {
		JmsUtils.closeSession(sessionToClose);
		ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), startConnection);
	}
}
 
Example 12
Source File: AbstractJmsListeningContainer.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Refresh the shared Connection that this container holds.
 * <p>Called on startup and also after an infrastructure exception
 * that occurred during invoker setup and/or execution.
 * @throws JMSException if thrown by JMS API methods
 */
protected final void refreshSharedConnection() throws JMSException {
	synchronized (this.sharedConnectionMonitor) {
		ConnectionFactoryUtils.releaseConnection(
				this.sharedConnection, getConnectionFactory(), this.sharedConnectionStarted);
		this.sharedConnection = null;
		this.sharedConnection = createSharedConnection();
		if (this.sharedConnectionStarted) {
			this.sharedConnection.start();
		}
	}
}
 
Example 13
Source File: JmsTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Execute the action specified by the given action object within a
 * JMS Session. Generalized version of {@code execute(SessionCallback)},
 * allowing the JMS Connection to be started on the fly.
 * <p>Use {@code execute(SessionCallback)} for the general case.
 * Starting the JMS Connection is just necessary for receiving messages,
 * which is preferably achieved through the {@code receive} methods.
 * @param action callback object that exposes the Session
 * @param startConnection whether to start the Connection
 * @return the result object from working with the Session
 * @throws JmsException if there is any problem
 * @see #execute(SessionCallback)
 * @see #receive
 */
@Nullable
public <T> T execute(SessionCallback<T> action, boolean startConnection) throws JmsException {
	Assert.notNull(action, "Callback object must not be null");
	Connection conToClose = null;
	Session sessionToClose = null;
	try {
		Session sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(
				obtainConnectionFactory(), this.transactionalResourceFactory, startConnection);
		if (sessionToUse == null) {
			conToClose = createConnection();
			sessionToClose = createSession(conToClose);
			if (startConnection) {
				conToClose.start();
			}
			sessionToUse = sessionToClose;
		}
		if (logger.isDebugEnabled()) {
			logger.debug("Executing callback on JMS Session: " + sessionToUse);
		}
		return action.doInJms(sessionToUse);
	}
	catch (JMSException ex) {
		throw convertJmsAccessException(ex);
	}
	finally {
		JmsUtils.closeSession(sessionToClose);
		ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), startConnection);
	}
}
 
Example 14
Source File: AbstractJmsListeningContainer.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Refresh the shared Connection that this container holds.
 * <p>Called on startup and also after an infrastructure exception
 * that occurred during invoker setup and/or execution.
 * @throws JMSException if thrown by JMS API methods
 */
protected final void refreshSharedConnection() throws JMSException {
	synchronized (this.sharedConnectionMonitor) {
		ConnectionFactoryUtils.releaseConnection(
				this.sharedConnection, getConnectionFactory(), this.sharedConnectionStarted);
		this.sharedConnection = null;
		this.sharedConnection = createSharedConnection();
		if (this.sharedConnectionStarted) {
			this.sharedConnection.start();
		}
	}
}
 
Example 15
Source File: JmsTemplate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Execute the action specified by the given action object within a
 * JMS Session. Generalized version of {@code execute(SessionCallback)},
 * allowing the JMS Connection to be started on the fly.
 * <p>Use {@code execute(SessionCallback)} for the general case.
 * Starting the JMS Connection is just necessary for receiving messages,
 * which is preferably achieved through the {@code receive} methods.
 * @param action callback object that exposes the Session
 * @param startConnection whether to start the Connection
 * @return the result object from working with the Session
 * @throws JmsException if there is any problem
 * @see #execute(SessionCallback)
 * @see #receive
 */
@Nullable
public <T> T execute(SessionCallback<T> action, boolean startConnection) throws JmsException {
	Assert.notNull(action, "Callback object must not be null");
	Connection conToClose = null;
	Session sessionToClose = null;
	try {
		Session sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(
				obtainConnectionFactory(), this.transactionalResourceFactory, startConnection);
		if (sessionToUse == null) {
			conToClose = createConnection();
			sessionToClose = createSession(conToClose);
			if (startConnection) {
				conToClose.start();
			}
			sessionToUse = sessionToClose;
		}
		if (logger.isDebugEnabled()) {
			logger.debug("Executing callback on JMS Session: " + sessionToUse);
		}
		return action.doInJms(sessionToUse);
	}
	catch (JMSException ex) {
		throw convertJmsAccessException(ex);
	}
	finally {
		JmsUtils.closeSession(sessionToClose);
		ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), startConnection);
	}
}
 
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);
	}
}