mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Matthew Swift
16.40.2016 8a7ff716fed166cd42ec42faaabb7d70e317f884
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Copyright 2015-2016 ForgeRock AS.
 */
package org.opends.server.util;
 
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
 
import org.forgerock.util.Reject;
 
/**
 * Timer useful for testing: it helps to write loops that repeatedly runs code until some condition
 * is met.
 */
public interface TestTimer
{
  /**
   * Equivalent to {@code Callable<Void>} or a {@code Runnable} that can throw exception.
   * <p>
   * <b>Note:</b> The name has been designed to stay close to {@code Callable<Void>} to allow to
   * easily change test code back and forth between {@code java.util.Callable} and
   * {@code CallableVoid} while writing the test code. It also avoids name collisions while writing
   * the rest of the OpenDJ code base.
   */
  public static interface CallableVoid
  {
    /**
     * Equivalent of {@link Runnable#run()} or {@link Callable#call()}.
     *
     * @throws Exception
     *           if an error occurred
     * @see {@link Runnable#run()}
     * @see {@link Callable#call()}
     */
    void call() throws Exception;
  }
 
  /**
   * Repeatedly call the supplied callable (respecting a sleep interval) until:
   * <ul>
   * <li>it returns,</li>
   * <li>it throws an exception other than {@link AssertionError},</li>
   * <li>the current timer times out.</li>
   * </ul>
   * If the current timer times out, then it will:
   * <ul>
   * <li>either rethrow an {@link AssertionError} thrown by the callable,</li>
   * <li>or return {@code null}.</li>
   * </ul>
   * <p>
   * Note: The test code in the callable can be written as any test code outside a callable. In
   * particular, asserts can and should be used inside the {@link Callable#call()} method.
   *
   * @param callable
   *          the callable to repeat until success
   * @param <R>
   *          The return type of the callable
   * @return the value returned by the callable (may be {@code null}), or {@code null} if the timer
   *         times out
   * @throws Exception
   *           The exception thrown by the provided callable
   * @throws InterruptedException
   *           If the thread is interrupted while sleeping
   */
  <R> R repeatUntilSuccess(Callable<R> callable) throws Exception, InterruptedException;
 
  /**
   * Repeatedly call the supplied callable (respecting a sleep interval) until:
   * <ul>
   * <li>it returns,</li>
   * <li>it throws an exception other than {@link AssertionError},</li>
   * <li>the current timer times out.</li>
   * </ul>
   * If the current timer times out, then it will:
   * <ul>
   * <li>either rethrow an {@link AssertionError} thrown by the callable,</li>
   * <li>or return {@code null}.</li>
   * </ul>
   * <p>
   * Note: The test code in the callable can be written as any test code outside a callable. In
   * particular, asserts can and should be used inside the {@link TestTimer.Callable#call()} method.
   *
   * @param callable
   *          the callable to repeat until success
   * @throws Exception
   *           The exception thrown by the provided callable
   * @throws InterruptedException
   *           If the thread is interrupted while sleeping
   */
  void repeatUntilSuccess(CallableVoid callable) throws Exception, InterruptedException;
 
  /** Builder for a {@link TestTimer}. */
  public static final class Builder
  {
    private long maxSleepTimeInMillis;
    private long sleepTimes;
 
    /**
     * Configures the maximum sleep duration.
     *
     * @param time
     *          the duration
     * @param unit
     *          the time unit for the duration
     * @return this builder
     */
    public Builder maxSleep(long time, TimeUnit unit)
    {
      Reject.ifFalse(time > 0, "time must be positive");
      this.maxSleepTimeInMillis = unit.toMillis(time);
      return this;
    }
 
    /**
     * Configures the duration for sleep times.
     *
     * @param time
     *          the duration
     * @param unit
     *          the time unit for the duration
     * @return this builder
     */
    public Builder sleepTimes(long time, TimeUnit unit)
    {
      Reject.ifFalse(time > 0, "time must be positive");
      this.sleepTimes = unit.toMillis(time);
      return this;
    }
 
    /**
     * Creates a new timer and start it.
     *
     * @return a new timer
     */
    public TestTimer toTimer()
    {
      return new SteppingTimer(this);
    }
  }
 
  /** A {@link TestTimer} that sleeps in steps and sleeps at maximum {@code nbSteps * sleepTimes}. */
  public static class SteppingTimer implements TestTimer
  {
    private final long sleepTime;
    private final long totalNbSteps;
    private long nbStepsRemaining;
 
    private SteppingTimer(Builder builder)
    {
      this.sleepTime = builder.sleepTimes;
      this.totalNbSteps = sleepTime > 0 ? builder.maxSleepTimeInMillis / sleepTime : 0;
      this.nbStepsRemaining = totalNbSteps;
    }
 
    /**
     * Returns whether the timer has reached the timeout. This method may block by sleeping.
     *
     * @return {@code true} if the timer has reached the timeout, {@code false} otherwise
     * @throws InterruptedException if the thread has been interrupted
     */
    private boolean hasTimedOut() throws InterruptedException
    {
      final boolean done = hasTimedOutNoSleep();
      if (!done)
      {
        Thread.sleep(sleepTime);
        nbStepsRemaining--;
      }
      return done;
    }
 
    /**
     * Returns whether the timer has reached the timeout, without sleep.
     *
     * @return {@code true} if the timer has reached the timeout, {@code false} otherwise
     */
    private boolean hasTimedOutNoSleep()
    {
      return nbStepsRemaining <= 0;
    }
 
    @Override
    public <R> R repeatUntilSuccess(Callable<R> callable) throws Exception, InterruptedException
    {
      do
      {
        try
        {
          return callable.call();
        }
        catch (AssertionError e)
        {
          if (hasTimedOutNoSleep())
          {
            throw e;
          }
        }
      }
      while (!hasTimedOut());
      return null;
    }
 
    @Override
    public void repeatUntilSuccess(final CallableVoid callable) throws Exception, InterruptedException
    {
      repeatUntilSuccess(new Callable<Void>()
      {
        @Override
        public Void call() throws Exception
        {
          callable.call();
          return null;
        }
      });
    }
 
    @Override
    public String toString()
    {
      return totalNbSteps * sleepTime + " ms max sleep time"
          + " (" + totalNbSteps + " steps x " + sleepTime + " ms)"
          + ", remaining = " + nbStepsRemaining + " steps";
    }
  }
}