View Javadoc
1   package ejava.util.jms;
2   
3   import javax.jms.Connection;
4   import javax.jms.ConnectionFactory;
5   import javax.jms.JMSException;
6   
7   import org.slf4j.Logger;
8   import org.slf4j.LoggerFactory;
9   
10  public class JMSUtil {
11      private static final Logger logger = LoggerFactory.getLogger(JMSUtil.class);
12      
13      /**
14       * Performs a JMS createConnection and will wait supplied number of seconds before 
15       * giving up. This gives a starting server time to start during IT tests.
16       * @param connFactory
17       * @param user
18       * @param password
19       * @param waitSecs
20       * @return connection created. Caller must close.
21       * @throws JMSException 
22       */
23      public static Connection createConnection(ConnectionFactory connFactory, String user, String password, int waitSecs) 
24              throws JMSException {
25          logger.debug("creating JMS connection waitSecs={}", waitSecs);
26          
27          Connection connection=null;
28          //wait increments should be at least 1sec
29          long interval=Math.max(waitSecs*1000/10, 1000);
30          for (int elapsed=0; elapsed<(waitSecs*1000); elapsed += interval) {
31              if (elapsed + interval < waitSecs*1000) {
32                  try {
33                      connection = user==null ?
34                              connFactory.createConnection() :
35                              connFactory.createConnection(user, password);
36                  } catch (Throwable ex) {
37                      logger.debug("waiting for connFactory.createConnection({})={}", connFactory.getClass().getSimpleName(), ex.getMessage());
38                      try { Thread.sleep(interval); } catch (Exception ex2) {}
39                  }
40              } else {
41                  connection = user==null ?
42                          connFactory.createConnection() :
43                          connFactory.createConnection(user, password);
44              }
45          }
46          return connection;
47      }
48  }