View Javadoc

1   package com.atlassian.plugin.util;
2   
3   import org.apache.commons.logging.Log;
4   import org.apache.commons.logging.LogFactory;
5   
6   import static java.lang.Thread.sleep;
7   
8   /**
9    * Utility methods for synchronising on asynchronous processes
10   */
11  public class WaitUntil
12  {
13      private static final Log log = LogFactory.getLog(WaitUntil.class);
14  
15      private WaitUntil() {}
16  
17      /**
18       * Invokes the wait condition, trying every second for 10 seconds
19       *
20       * @param waitCondition The condition that determines when to stop waiting
21       * @return True if the condition returned true
22       */
23      public static boolean invoke(WaitCondition waitCondition)
24      {
25          return invoke(waitCondition, 10);
26      }
27  
28      /**
29       * Invokes the wait condition, trying every second for the configured seconds
30       *
31       * @param waitCondition The condition that determines when to stop waiting
32       * @param tries The number of tries to attempt
33       * @return True if the condition returned true
34       */
35      public static boolean invoke(WaitCondition waitCondition, int tries)
36      {
37          boolean successful = false;
38          for (int count = tries; count > 0; count--)
39          {
40              if (waitCondition.isFinished())
41              {
42                  successful = true;
43                  break;
44              }
45  
46              if (log.isInfoEnabled())
47              {
48                  log.info(waitCondition.getWaitMessage() + ", " + count + " tries remaining");
49              }
50              try
51              {
52                  sleep(1000);
53              } catch (InterruptedException e)
54              {
55                  break;
56              }
57          }
58          return successful;
59  
60      }
61  
62      /**
63       * The condition to determine when to stop waiting
64       */
65      public static interface WaitCondition
66      {
67          /**
68           * If the condition has been finished
69           * @return True if finished and should stop waiting
70           */
71          boolean isFinished();
72  
73          /**
74           * Gets the wait message to log for each try
75           * @return The string to print describing why the code is waiting
76           */
77          String getWaitMessage();
78      }
79  }