PageRenderTime 48ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/projects/springframework-3.0.5/projects/org.springframework.jms/src/main/java/org/springframework/jms/listener/AbstractJmsListeningContainer.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 637 lines | 300 code | 70 blank | 267 comment | 27 complexity | 0d3a858a130c8ea579ce2f606a32568d MD5 | raw file
  1. /*
  2. * Copyright 2002-2010 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.jms.listener;
  17. import java.util.Iterator;
  18. import java.util.LinkedList;
  19. import java.util.List;
  20. import javax.jms.Connection;
  21. import javax.jms.JMSException;
  22. import org.springframework.beans.factory.BeanNameAware;
  23. import org.springframework.beans.factory.DisposableBean;
  24. import org.springframework.context.SmartLifecycle;
  25. import org.springframework.jms.JmsException;
  26. import org.springframework.jms.connection.ConnectionFactoryUtils;
  27. import org.springframework.jms.support.JmsUtils;
  28. import org.springframework.jms.support.destination.JmsDestinationAccessor;
  29. import org.springframework.util.ClassUtils;
  30. /**
  31. * Common base class for all containers which need to implement listening
  32. * based on a JMS Connection (either shared or freshly obtained for each attempt).
  33. * Inherits basic Connection and Session configuration handling from the
  34. * {@link org.springframework.jms.support.JmsAccessor} base class.
  35. *
  36. * <p>This class provides basic lifecycle management, in particular management
  37. * of a shared JMS Connection. Subclasses are supposed to plug into this
  38. * lifecycle, implementing the {@link #sharedConnectionEnabled()} as well
  39. * as the {@link #doInitialize()} and {@link #doShutdown()} template methods.
  40. *
  41. * <p>This base class does not assume any specific listener programming model
  42. * or listener invoker mechanism. It just provides the general runtime
  43. * lifecycle management needed for any kind of JMS-based listening mechanism
  44. * that operates on a JMS Connection/Session.
  45. *
  46. * <p>For a concrete listener programming model, check out the
  47. * {@link AbstractMessageListenerContainer} subclass. For a concrete listener
  48. * invoker mechanism, check out the {@link DefaultMessageListenerContainer} class.
  49. *
  50. * @author Juergen Hoeller
  51. * @since 2.0.3
  52. * @see #sharedConnectionEnabled()
  53. * @see #doInitialize()
  54. * @see #doShutdown()
  55. */
  56. public abstract class AbstractJmsListeningContainer extends JmsDestinationAccessor
  57. implements SmartLifecycle, BeanNameAware, DisposableBean {
  58. private String clientId;
  59. private boolean autoStartup = true;
  60. private int phase = Integer.MAX_VALUE;
  61. private String beanName;
  62. private Connection sharedConnection;
  63. private boolean sharedConnectionStarted = false;
  64. protected final Object sharedConnectionMonitor = new Object();
  65. private boolean active = false;
  66. private boolean running = false;
  67. private final List<Object> pausedTasks = new LinkedList<Object>();
  68. protected final Object lifecycleMonitor = new Object();
  69. /**
  70. * Specify the JMS client id for a shared Connection created and used
  71. * by this container.
  72. * <p>Note that client ids need to be unique among all active Connections
  73. * of the underlying JMS provider. Furthermore, a client id can only be
  74. * assigned if the original ConnectionFactory hasn't already assigned one.
  75. * @see javax.jms.Connection#setClientID
  76. * @see #setConnectionFactory
  77. */
  78. public void setClientId(String clientId) {
  79. this.clientId = clientId;
  80. }
  81. /**
  82. * Return the JMS client ID for the shared Connection created and used
  83. * by this container, if any.
  84. */
  85. public String getClientId() {
  86. return this.clientId;
  87. }
  88. /**
  89. * Set whether to automatically start the container after initialization.
  90. * <p>Default is "true"; set this to "false" to allow for manual startup
  91. * through the {@link #start()} method.
  92. */
  93. public void setAutoStartup(boolean autoStartup) {
  94. this.autoStartup = autoStartup;
  95. }
  96. public boolean isAutoStartup() {
  97. return this.autoStartup;
  98. }
  99. /**
  100. * Specify the phase in which this container should be started and
  101. * stopped. The startup order proceeds from lowest to highest, and
  102. * the shutdown order is the reverse of that. By default this value
  103. * is Integer.MAX_VALUE meaning that this container starts as late
  104. * as possible and stops as soon as possible.
  105. */
  106. public void setPhase(int phase) {
  107. this.phase = phase;
  108. }
  109. /**
  110. * Return the phase in which this container will be started and stopped.
  111. */
  112. public int getPhase() {
  113. return this.phase;
  114. }
  115. public void setBeanName(String beanName) {
  116. this.beanName = beanName;
  117. }
  118. /**
  119. * Return the bean name that this listener container has been assigned
  120. * in its containing bean factory, if any.
  121. */
  122. protected final String getBeanName() {
  123. return this.beanName;
  124. }
  125. /**
  126. * Delegates to {@link #validateConfiguration()} and {@link #initialize()}.
  127. */
  128. public void afterPropertiesSet() {
  129. super.afterPropertiesSet();
  130. validateConfiguration();
  131. initialize();
  132. }
  133. /**
  134. * Validate the configuration of this container.
  135. * <p>The default implementation is empty. To be overridden in subclasses.
  136. */
  137. protected void validateConfiguration() {
  138. }
  139. /**
  140. * Calls {@link #shutdown()} when the BeanFactory destroys the container instance.
  141. * @see #shutdown()
  142. */
  143. public void destroy() {
  144. shutdown();
  145. }
  146. //-------------------------------------------------------------------------
  147. // Lifecycle methods for starting and stopping the container
  148. //-------------------------------------------------------------------------
  149. /**
  150. * Initialize this container.
  151. * <p>Creates a JMS Connection, starts the {@link javax.jms.Connection}
  152. * (if {@link #setAutoStartup(boolean) "autoStartup"} hasn't been turned off),
  153. * and calls {@link #doInitialize()}.
  154. * @throws org.springframework.jms.JmsException if startup failed
  155. */
  156. public void initialize() throws JmsException {
  157. try {
  158. synchronized (this.lifecycleMonitor) {
  159. this.active = true;
  160. this.lifecycleMonitor.notifyAll();
  161. }
  162. doInitialize();
  163. }
  164. catch (JMSException ex) {
  165. synchronized (this.sharedConnectionMonitor) {
  166. ConnectionFactoryUtils.releaseConnection(this.sharedConnection, getConnectionFactory(), this.autoStartup);
  167. this.sharedConnection = null;
  168. }
  169. throw convertJmsAccessException(ex);
  170. }
  171. }
  172. /**
  173. * Stop the shared Connection, call {@link #doShutdown()},
  174. * and close this container.
  175. * @throws JmsException if shutdown failed
  176. */
  177. public void shutdown() throws JmsException {
  178. logger.debug("Shutting down JMS listener container");
  179. boolean wasRunning;
  180. synchronized (this.lifecycleMonitor) {
  181. wasRunning = this.running;
  182. this.running = false;
  183. this.active = false;
  184. this.lifecycleMonitor.notifyAll();
  185. }
  186. // Stop shared Connection early, if necessary.
  187. if (wasRunning && sharedConnectionEnabled()) {
  188. try {
  189. stopSharedConnection();
  190. }
  191. catch (Throwable ex) {
  192. logger.debug("Could not stop JMS Connection on shutdown", ex);
  193. }
  194. }
  195. // Shut down the invokers.
  196. try {
  197. doShutdown();
  198. }
  199. catch (JMSException ex) {
  200. throw convertJmsAccessException(ex);
  201. }
  202. finally {
  203. if (sharedConnectionEnabled()) {
  204. synchronized (this.sharedConnectionMonitor) {
  205. ConnectionFactoryUtils.releaseConnection(this.sharedConnection, getConnectionFactory(), false);
  206. this.sharedConnection = null;
  207. }
  208. }
  209. }
  210. }
  211. /**
  212. * Return whether this container is currently active,
  213. * that is, whether it has been set up but not shut down yet.
  214. */
  215. public final boolean isActive() {
  216. synchronized (this.lifecycleMonitor) {
  217. return this.active;
  218. }
  219. }
  220. /**
  221. * Start this container.
  222. * @throws JmsException if starting failed
  223. * @see #doStart
  224. */
  225. public void start() throws JmsException {
  226. try {
  227. doStart();
  228. }
  229. catch (JMSException ex) {
  230. throw convertJmsAccessException(ex);
  231. }
  232. }
  233. /**
  234. * Start the shared Connection, if any, and notify all invoker tasks.
  235. * @throws JMSException if thrown by JMS API methods
  236. * @see #startSharedConnection
  237. */
  238. protected void doStart() throws JMSException {
  239. // Lazily establish a shared Connection, if necessary.
  240. if (sharedConnectionEnabled()) {
  241. establishSharedConnection();
  242. }
  243. // Reschedule paused tasks, if any.
  244. synchronized (this.lifecycleMonitor) {
  245. this.running = true;
  246. this.lifecycleMonitor.notifyAll();
  247. resumePausedTasks();
  248. }
  249. // Start the shared Connection, if any.
  250. if (sharedConnectionEnabled()) {
  251. startSharedConnection();
  252. }
  253. }
  254. /**
  255. * Stop this container.
  256. * @throws JmsException if stopping failed
  257. * @see #doStop
  258. */
  259. public void stop() throws JmsException {
  260. try {
  261. doStop();
  262. }
  263. catch (JMSException ex) {
  264. throw convertJmsAccessException(ex);
  265. }
  266. }
  267. public void stop(Runnable callback) {
  268. this.stop();
  269. callback.run();
  270. }
  271. /**
  272. * Notify all invoker tasks and stop the shared Connection, if any.
  273. * @throws JMSException if thrown by JMS API methods
  274. * @see #stopSharedConnection
  275. */
  276. protected void doStop() throws JMSException {
  277. synchronized (this.lifecycleMonitor) {
  278. this.running = false;
  279. this.lifecycleMonitor.notifyAll();
  280. }
  281. if (sharedConnectionEnabled()) {
  282. stopSharedConnection();
  283. }
  284. }
  285. /**
  286. * Determine whether this container is currently running,
  287. * that is, whether it has been started and not stopped yet.
  288. * @see #start()
  289. * @see #stop()
  290. * @see #runningAllowed()
  291. */
  292. public final boolean isRunning() {
  293. synchronized (this.lifecycleMonitor) {
  294. return (this.running && runningAllowed());
  295. }
  296. }
  297. /**
  298. * Check whether this container's listeners are generally allowed to run.
  299. * <p>This implementation always returns <code>true</code>; the default 'running'
  300. * state is purely determined by {@link #start()} / {@link #stop()}.
  301. * <p>Subclasses may override this method to check against temporary
  302. * conditions that prevent listeners from actually running. In other words,
  303. * they may apply further restrictions to the 'running' state, returning
  304. * <code>false</code> if such a restriction prevents listeners from running.
  305. */
  306. protected boolean runningAllowed() {
  307. return true;
  308. }
  309. //-------------------------------------------------------------------------
  310. // Management of a shared JMS Connection
  311. //-------------------------------------------------------------------------
  312. /**
  313. * Establish a shared Connection for this container.
  314. * <p>The default implementation delegates to {@link #createSharedConnection()},
  315. * which does one immediate attempt and throws an exception if it fails.
  316. * Can be overridden to have a recovery process in place, retrying
  317. * until a Connection can be successfully established.
  318. * @throws JMSException if thrown by JMS API methods
  319. */
  320. protected void establishSharedConnection() throws JMSException {
  321. synchronized (this.sharedConnectionMonitor) {
  322. if (this.sharedConnection == null) {
  323. this.sharedConnection = createSharedConnection();
  324. logger.debug("Established shared JMS Connection");
  325. }
  326. }
  327. }
  328. /**
  329. * Refresh the shared Connection that this container holds.
  330. * <p>Called on startup and also after an infrastructure exception
  331. * that occurred during invoker setup and/or execution.
  332. * @throws JMSException if thrown by JMS API methods
  333. */
  334. protected final void refreshSharedConnection() throws JMSException {
  335. synchronized (this.sharedConnectionMonitor) {
  336. ConnectionFactoryUtils.releaseConnection(
  337. this.sharedConnection, getConnectionFactory(), this.sharedConnectionStarted);
  338. this.sharedConnection = null;
  339. this.sharedConnection = createSharedConnection();
  340. if (this.sharedConnectionStarted) {
  341. this.sharedConnection.start();
  342. }
  343. }
  344. }
  345. /**
  346. * Create a shared Connection for this container.
  347. * <p>The default implementation creates a standard Connection
  348. * and prepares it through {@link #prepareSharedConnection}.
  349. * @return the prepared Connection
  350. * @throws JMSException if the creation failed
  351. */
  352. protected Connection createSharedConnection() throws JMSException {
  353. Connection con = createConnection();
  354. try {
  355. prepareSharedConnection(con);
  356. return con;
  357. }
  358. catch (JMSException ex) {
  359. JmsUtils.closeConnection(con);
  360. throw ex;
  361. }
  362. }
  363. /**
  364. * Prepare the given Connection, which is about to be registered
  365. * as shared Connection for this container.
  366. * <p>The default implementation sets the specified client id, if any.
  367. * Subclasses can override this to apply further settings.
  368. * @param connection the Connection to prepare
  369. * @throws JMSException if the preparation efforts failed
  370. * @see #getClientId()
  371. */
  372. protected void prepareSharedConnection(Connection connection) throws JMSException {
  373. String clientId = getClientId();
  374. if (clientId != null) {
  375. connection.setClientID(clientId);
  376. }
  377. }
  378. /**
  379. * Start the shared Connection.
  380. * @throws JMSException if thrown by JMS API methods
  381. * @see javax.jms.Connection#start()
  382. */
  383. protected void startSharedConnection() throws JMSException {
  384. synchronized (this.sharedConnectionMonitor) {
  385. this.sharedConnectionStarted = true;
  386. if (this.sharedConnection != null) {
  387. try {
  388. this.sharedConnection.start();
  389. }
  390. catch (javax.jms.IllegalStateException ex) {
  391. logger.debug("Ignoring Connection start exception - assuming already started: " + ex);
  392. }
  393. }
  394. }
  395. }
  396. /**
  397. * Stop the shared Connection.
  398. * @throws JMSException if thrown by JMS API methods
  399. * @see javax.jms.Connection#start()
  400. */
  401. protected void stopSharedConnection() throws JMSException {
  402. synchronized (this.sharedConnectionMonitor) {
  403. this.sharedConnectionStarted = false;
  404. if (this.sharedConnection != null) {
  405. try {
  406. this.sharedConnection.stop();
  407. }
  408. catch (javax.jms.IllegalStateException ex) {
  409. logger.debug("Ignoring Connection stop exception - assuming already stopped: " + ex);
  410. }
  411. }
  412. }
  413. }
  414. /**
  415. * Return the shared JMS Connection maintained by this container.
  416. * Available after initialization.
  417. * @return the shared Connection (never <code>null</code>)
  418. * @throws IllegalStateException if this container does not maintain a
  419. * shared Connection, or if the Connection hasn't been initialized yet
  420. * @see #sharedConnectionEnabled()
  421. */
  422. protected final Connection getSharedConnection() {
  423. if (!sharedConnectionEnabled()) {
  424. throw new IllegalStateException(
  425. "This listener container does not maintain a shared Connection");
  426. }
  427. synchronized (this.sharedConnectionMonitor) {
  428. if (this.sharedConnection == null) {
  429. throw new SharedConnectionNotInitializedException(
  430. "This listener container's shared Connection has not been initialized yet");
  431. }
  432. return this.sharedConnection;
  433. }
  434. }
  435. //-------------------------------------------------------------------------
  436. // Management of paused tasks
  437. //-------------------------------------------------------------------------
  438. /**
  439. * Take the given task object and reschedule it, either immediately if
  440. * this container is currently running, or later once this container
  441. * has been restarted.
  442. * <p>If this container has already been shut down, the task will not
  443. * get rescheduled at all.
  444. * @param task the task object to reschedule
  445. * @return whether the task has been rescheduled
  446. * (either immediately or for a restart of this container)
  447. * @see #doRescheduleTask
  448. */
  449. protected final boolean rescheduleTaskIfNecessary(Object task) {
  450. if (this.running) {
  451. try {
  452. doRescheduleTask(task);
  453. }
  454. catch (RuntimeException ex) {
  455. logRejectedTask(task, ex);
  456. this.pausedTasks.add(task);
  457. }
  458. return true;
  459. }
  460. else if (this.active) {
  461. this.pausedTasks.add(task);
  462. return true;
  463. }
  464. else {
  465. return false;
  466. }
  467. }
  468. /**
  469. * Try to resume all paused tasks.
  470. * Tasks for which rescheduling failed simply remain in paused mode.
  471. */
  472. protected void resumePausedTasks() {
  473. synchronized (this.lifecycleMonitor) {
  474. if (!this.pausedTasks.isEmpty()) {
  475. for (Iterator it = this.pausedTasks.iterator(); it.hasNext();) {
  476. Object task = it.next();
  477. try {
  478. doRescheduleTask(task);
  479. it.remove();
  480. if (logger.isDebugEnabled()) {
  481. logger.debug("Resumed paused task: " + task);
  482. }
  483. }
  484. catch (RuntimeException ex) {
  485. logRejectedTask(task, ex);
  486. // Keep the task in paused mode...
  487. }
  488. }
  489. }
  490. }
  491. }
  492. /**
  493. * Determine the number of currently paused tasks, if any.
  494. */
  495. public int getPausedTaskCount() {
  496. synchronized (this.lifecycleMonitor) {
  497. return this.pausedTasks.size();
  498. }
  499. }
  500. /**
  501. * Reschedule the given task object immediately.
  502. * <p>To be implemented by subclasses if they ever call
  503. * <code>rescheduleTaskIfNecessary</code>.
  504. * This implementation throws an UnsupportedOperationException.
  505. * @param task the task object to reschedule
  506. * @see #rescheduleTaskIfNecessary
  507. */
  508. protected void doRescheduleTask(Object task) {
  509. throw new UnsupportedOperationException(
  510. ClassUtils.getShortName(getClass()) + " does not support rescheduling of tasks");
  511. }
  512. /**
  513. * Log a task that has been rejected by {@link #doRescheduleTask}.
  514. * <p>The default implementation simply logs a corresponding message
  515. * at debug level.
  516. * @param task the rejected task object
  517. * @param ex the exception thrown from {@link #doRescheduleTask}
  518. */
  519. protected void logRejectedTask(Object task, RuntimeException ex) {
  520. if (logger.isDebugEnabled()) {
  521. logger.debug("Listener container task [" + task + "] has been rejected and paused: " + ex);
  522. }
  523. }
  524. //-------------------------------------------------------------------------
  525. // Template methods to be implemented by subclasses
  526. //-------------------------------------------------------------------------
  527. /**
  528. * Return whether a shared JMS Connection should be maintained
  529. * by this container base class.
  530. * @see #getSharedConnection()
  531. */
  532. protected abstract boolean sharedConnectionEnabled();
  533. /**
  534. * Register any invokers within this container.
  535. * <p>Subclasses need to implement this method for their specific
  536. * invoker management process.
  537. * <p>A shared JMS Connection, if any, will already have been
  538. * started at this point.
  539. * @throws JMSException if registration failed
  540. * @see #getSharedConnection()
  541. */
  542. protected abstract void doInitialize() throws JMSException;
  543. /**
  544. * Close the registered invokers.
  545. * <p>Subclasses need to implement this method for their specific
  546. * invoker management process.
  547. * <p>A shared JMS Connection, if any, will automatically be closed
  548. * <i>afterwards</i>.
  549. * @throws JMSException if shutdown failed
  550. * @see #shutdown()
  551. */
  552. protected abstract void doShutdown() throws JMSException;
  553. /**
  554. * Exception that indicates that the initial setup of this container's
  555. * shared JMS Connection failed. This is indicating to invokers that they need
  556. * to establish the shared Connection themselves on first access.
  557. */
  558. public static class SharedConnectionNotInitializedException extends RuntimeException {
  559. /**
  560. * Create a new SharedConnectionNotInitializedException.
  561. * @param msg the detail message
  562. */
  563. protected SharedConnectionNotInitializedException(String msg) {
  564. super(msg);
  565. }
  566. }
  567. }