01: /*
02: * Copyright 2005-2007 The Kuali Foundation.
03: *
04: * Licensed under the Educational Community License, Version 1.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.opensource.org/licenses/ecl1.php
09: *
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.kuali.test.monitor;
17:
18: import org.apache.commons.logging.Log;
19: import org.apache.commons.logging.LogFactory;
20:
21: /**
22: * Simplifies writing tests which have to iterate in place until something happens (or until some timeout occurs and lets the test
23: * fail).
24: */
25:
26: abstract public class ChangeMonitor {
27: private static final Log LOG = LogFactory
28: .getLog(ChangeMonitor.class);
29:
30: /**
31: * Iterates, with pauseSeconds seconds between iterations, until either the given ChangeMonitor's valueChanged method returns
32: * true, or at least maxWaitSeconds seconds have passed.
33: *
34: * @param monitor ChangeMonitor instance which watches for whatever change your test is waiting for
35: * @param maxWaitSeconds
36: * @param pauseSeconds
37: * @return true if the the ChangeMonitor's valueChanged method returned true before time ran out
38: */
39: public static boolean waitUntilChange(ChangeMonitor monitor,
40: int maxWaitSeconds, int pauseSeconds) throws Exception {
41: long maxWaitMs = maxWaitSeconds * 1000;
42: long pauseMs = pauseSeconds * 1000;
43:
44: boolean valueChanged = false;
45: boolean interrupted = false;
46: long startTimeMs = System.currentTimeMillis();
47: long endTimeMs = startTimeMs + maxWaitMs;
48:
49: Thread.sleep(pauseMs / 10); // the first time through, sleep a fraction of the specified time
50: valueChanged = monitor.valueChanged();
51: LOG.debug("starting wait loop");
52: while (!interrupted && !valueChanged
53: && (System.currentTimeMillis() < endTimeMs)) {
54: try {
55: if (LOG.isDebugEnabled()) {
56: LOG.debug("sleeping for " + pauseMs + " ms");
57: }
58: Thread.sleep(pauseMs);
59: } catch (InterruptedException e) {
60: interrupted = true;
61: }
62: LOG.debug("checking wait loop sentinel");
63: valueChanged = monitor.valueChanged();
64: }
65: LOG.debug("finished wait loop (" + valueChanged + ")");
66:
67: return valueChanged;
68: }
69:
70: /**
71: * @return true if the value being monitored has changed
72: */
73: abstract public boolean valueChanged() throws Exception;
74: }
|