(reasons);
+ }
}
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/ServiceWrapper.java b/jrugged-core/src/main/java/org/fishwife/jrugged/ServiceWrapper.java
index f06b41c9..84a5797b 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/ServiceWrapper.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/ServiceWrapper.java
@@ -18,36 +18,43 @@
import java.util.concurrent.Callable;
-/** Several of the "rugged" code patterns in this library can be used to
- * wrap an existing service in a "decorator" design pattern. This is the
- * common interface provided by these wrapping classes that affect normal
- * service calls.
- *
- * If you are more into aspect-oriented programming (AOP), then you can
- * also use the {@link ServiceWrapper} classes in your aspects.
+/**
+ * Several of the "rugged" code patterns in this library can be used to wrap an
+ * existing service in a "decorator" design pattern. This is the common
+ * interface provided by these wrapping classes that affect normal service
+ * calls.
+ *
+ * If you are more into aspect-oriented programming (AOP), then you can also use
+ * the {@link ServiceWrapper} classes in your aspects.
*/
public interface ServiceWrapper {
- /** Wraps a {@link Callable} in some fashion.
- * @param c the service call to wrap
- * @param The callable type I am wrapping
- * @return whatever c would normally return
- * @throws Exception if c throws one
- */
- T invoke(Callable c) throws Exception;
+ /**
+ * Wraps a {@link Callable} in some fashion.
+ *
+ * @param c the service call to wrap
+ * @param The callable type I am wrapping
+ * @return whatever c would normally return
+ * @throws Exception if c throws one
+ */
+ T invoke(Callable c) throws Exception;
- /** Wraps a {@link Runnable} in some fashion.
- * @param r the service call/task to wrap
- * @throws Exception if r throws one
- */
- void invoke(Runnable r) throws Exception;
+ /**
+ * Wraps a {@link Runnable} in some fashion.
+ *
+ * @param r the service call/task to wrap
+ * @throws Exception if r throws one
+ */
+ void invoke(Runnable r) throws Exception;
- /** Wraps a {@link Runnable} task in some fashion, and returns a
- * predetermined result on success.
- * @param r the service call/task to wrap
- * @param result what to return on success
- * @param The return TYPE that should emit
- * @return result
- * @throws Exception if r throws one
- */
- T invoke(Runnable r, T result) throws Exception;
+ /**
+ * Wraps a {@link Runnable} task in some fashion, and returns a predetermined
+ * result on success.
+ *
+ * @param r the service call/task to wrap
+ * @param result what to return on success
+ * @param The return TYPE that should emit
+ * @return result
+ * @throws Exception if r throws one
+ */
+ T invoke(Runnable r, T result) throws Exception;
}
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/ServiceWrapperChain.java b/jrugged-core/src/main/java/org/fishwife/jrugged/ServiceWrapperChain.java
index df7f92a2..4fd61acf 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/ServiceWrapperChain.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/ServiceWrapperChain.java
@@ -23,53 +23,53 @@
public class ServiceWrapperChain implements ServiceWrapper {
- private List wrappers;
+ private List wrappers;
- public ServiceWrapperChain(Collection wrappers) {
- ArrayList rev = new ArrayList();
- for(ServiceWrapper wrapper : wrappers) {
- rev.add(0, wrapper);
- }
- this.wrappers = rev;
- }
+ public ServiceWrapperChain(Collection wrappers) {
+ ArrayList rev = new ArrayList();
+ for (ServiceWrapper wrapper : wrappers) {
+ rev.add(0, wrapper);
+ }
+ this.wrappers = rev;
+ }
- private Callable wrap(final Callable c, final ServiceWrapper wrapper) {
- return new Callable() {
- public T call() throws Exception {
- return wrapper.invoke(c);
- }
- };
- }
+ private Callable wrap(final Callable c, final ServiceWrapper wrapper) {
+ return new Callable() {
+ public T call() throws Exception {
+ return wrapper.invoke(c);
+ }
+ };
+ }
- private Runnable wrap(final Runnable r, final ServiceWrapper wrapper) {
- return new Runnable() {
- public void run() {
- try {
- wrapper.invoke(r);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- };
- }
+ private Runnable wrap(final Runnable r, final ServiceWrapper wrapper) {
+ return new Runnable() {
+ public void run() {
+ try {
+ wrapper.invoke(r);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
+ }
- public T invoke(Callable c) throws Exception {
- for(ServiceWrapper wrapper : wrappers) {
- c = wrap(c, wrapper);
- }
- return c.call();
- }
+ public T invoke(Callable c) throws Exception {
+ for (ServiceWrapper wrapper : wrappers) {
+ c = wrap(c, wrapper);
+ }
+ return c.call();
+ }
- public void invoke(Runnable r) throws Exception {
- for(ServiceWrapper wrapper : wrappers) {
- r = wrap(r, wrapper);
- }
- r.run();
- }
+ public void invoke(Runnable r) throws Exception {
+ for (ServiceWrapper wrapper : wrappers) {
+ r = wrap(r, wrapper);
+ }
+ r.run();
+ }
- public T invoke(Runnable r, T result) throws Exception {
- invoke(r);
- return result;
- }
+ public T invoke(Runnable r, T result) throws Exception {
+ invoke(r);
+ return result;
+ }
}
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/ServiceWrapperFactory.java b/jrugged-core/src/main/java/org/fishwife/jrugged/ServiceWrapperFactory.java
index 8dfca610..33af70bf 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/ServiceWrapperFactory.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/ServiceWrapperFactory.java
@@ -17,17 +17,18 @@
package org.fishwife.jrugged;
/**
- * A {@link ServiceWrapperFactory} is a way to create several related
- * but distinct {@link ServiceWrapper} instances.
+ * A {@link ServiceWrapperFactory} is a way to create several related but
+ * distinct {@link ServiceWrapper} instances.
*
*/
public interface ServiceWrapperFactory {
- /**
- * Create a new ServiceWrapper using the given
- * (presumed unique) identifier.
- * @param name to apply to the new ServiceWrapper
- * @return ServiceWrapper
- */
- ServiceWrapper getWrapperWithName(String name);
+ /**
+ * Create a new ServiceWrapper using the given (presumed unique)
+ * identifier.
+ *
+ * @param name to apply to the new ServiceWrapper
+ * @return ServiceWrapper
+ */
+ ServiceWrapper getWrapperWithName(String name);
}
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/Status.java b/jrugged-core/src/main/java/org/fishwife/jrugged/Status.java
index c8e6f104..226a7ae6 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/Status.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/Status.java
@@ -16,78 +16,85 @@
*/
package org.fishwife.jrugged;
-/** Various components in the system need to report their status. This
- * enum standardizes on a set of conventions for reporting
- * this. Each {@link Status} has an integer value which can
- * be compared; higher values represent higher levels of functionality.
- * In addition, each {@link Status} has a {@link String} signal
- * which is either GREEN, YELLOW, or RED.
- *
- * The general notion is that the whole system (or a subsystem) should
- * only report GREEN status (UP) if everything is working as designed.
- * When subsystems start to go down, or the current system stops working,
- * status should drop to either YELLOW (DEGRADED) or RED (DOWN), depending
- * on whether service was still available in some form. For example, if
- * a cache subsystem goes down, we might report a YELLOW status because
- * we can attempt to serve without a cache. However, if a required database
- * goes down, we probably need to report a RED status, unable to serve
- * requests.
- *
- * A "rugged" system should be able to accurately (and responsively)
- * report on its status even if it is unable to perform its main functions.
- * This will assist operators in diagnosing the problem; a hung process
- * tells no tales.
+/**
+ * Various components in the system need to report their status. This
+ * enum standardizes on a set of conventions for reporting this.
+ * Each {@link Status} has an integer value which can be compared;
+ * higher values represent higher levels of functionality. In addition, each
+ * {@link Status} has a {@link String} signal which is either
+ * GREEN, YELLOW, or RED.
+ *
+ * The general notion is that the whole system (or a subsystem) should only
+ * report GREEN status (UP) if everything is working as designed. When
+ * subsystems start to go down, or the current system stops working, status
+ * should drop to either YELLOW (DEGRADED) or RED (DOWN), depending on whether
+ * service was still available in some form. For example, if a cache subsystem
+ * goes down, we might report a YELLOW status because we can attempt to serve
+ * without a cache. However, if a required database goes down, we probably need
+ * to report a RED status, unable to serve requests.
+ *
+ * A "rugged" system should be able to accurately (and responsively) report on
+ * its status even if it is unable to perform its main functions. This will
+ * assist operators in diagnosing the problem; a hung process tells no tales.
*/
public enum Status {
- /** Unrecoverable: we're basically dead for good. */
- FAILED(-2,"RED"),
+ /** Unrecoverable: we're basically dead for good. */
+ FAILED(-2, "RED"),
- /** Being initialized: not yet ready to serve. */
- INIT(-1,"RED"),
+ /** Being initialized: not yet ready to serve. */
+ INIT(-1, "RED"),
- /** Currently unavailable. */
- DOWN(0,"RED"),
+ /** Currently unavailable. */
+ DOWN(0, "RED"),
- /** Something's wrong, but we can still serve requests. */
- DEGRADED(1,"YELLOW"),
+ /** Something's wrong, but we can still serve requests. */
+ DEGRADED(1, "YELLOW"),
- /** Everything is operating as expected. */
- UP(2,"GREEN"),
+ /** Everything is operating as expected. */
+ UP(2, "GREEN"),
- /**
- * This status was introduced in a prior version of JRugged and so
- * is retained for backwards compatibility, but is specific
- * to {@link org.fishwife.jrugged.CircuitBreaker} states
- * and should not be used.
- */
- @Deprecated
- BYPASS(3, "GREEN");
+ /**
+ * This status was introduced in a prior version of JRugged and so is retained
+ * for backwards compatibility, but is specific to
+ * {@link org.fishwife.jrugged.CircuitBreaker} states and should not be used.
+ */
+ @Deprecated
+ BYPASS(3, "GREEN");
- private final int value;
- private final String signal;
+ private final int value;
+ private final String signal;
- Status(int value, String signal) {
- this.value = value;
- this.signal = signal;
- }
+ Status(int value, String signal) {
+ this.value = value;
+ this.signal = signal;
+ }
- /** Returns the current status as an integer. Higher values are for
- * states of higher functionality/availability.
- * @return int The value of current status
- */
- public int getValue() { return value; }
+ /**
+ * Returns the current status as an integer. Higher values are for states of
+ * higher functionality/availability.
+ *
+ * @return int The value of current status
+ */
+ public int getValue() {
+ return value;
+ }
- /** Returns the current GREEN/YELLOW/RED dashboard indicator
- * corresponding to this status.
- *
- * @return String The current signalling, RED, YELLOW, ETC.
- */
- public String getSignal() { return signal; }
+ /**
+ * Returns the current GREEN/YELLOW/RED dashboard indicator corresponding to
+ * this status.
+ *
+ * @return String The current signalling, RED, YELLOW, ETC.
+ */
+ public String getSignal() {
+ return signal;
+ }
- /** Returns whether the status indicates a system that is able
- * to serve requests.
- *
- * @return boolean Greater than ZERO settings mean availability
- */
- public boolean isAvailable() { return (value > 0); }
+ /**
+ * Returns whether the status indicates a system that is able to serve requests.
+ *
+ * @return boolean Greater than ZERO settings mean availability
+ */
+ public boolean isAvailable() {
+ return (value > 0);
+ }
};
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/SystemClock.java b/jrugged-core/src/main/java/org/fishwife/jrugged/SystemClock.java
index 5a36c3ed..20c45d66 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/SystemClock.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/SystemClock.java
@@ -21,15 +21,15 @@
*/
public class SystemClock implements Clock {
- /**
- * Returns the current system time in milliseconds.
- *
- * @return the difference, measured in milliseconds, between the current
- * time and midnight, January 1, 1970 UTC.
- * @see java.lang.System#currentTimeMillis()
- */
- public long currentTimeMillis() {
- return System.currentTimeMillis();
- }
+ /**
+ * Returns the current system time in milliseconds.
+ *
+ * @return the difference, measured in milliseconds, between the current time
+ * and midnight, January 1, 1970 UTC.
+ * @see java.lang.System#currentTimeMillis()
+ */
+ public long currentTimeMillis() {
+ return System.currentTimeMillis();
+ }
}
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/WindowedEventCounter.java b/jrugged-core/src/main/java/org/fishwife/jrugged/WindowedEventCounter.java
index 6d95d17a..51894936 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/WindowedEventCounter.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/WindowedEventCounter.java
@@ -24,162 +24,152 @@
*/
public class WindowedEventCounter {
- /**
- * The {@link Clock} to used to determine current time (override for
- * testing).
- */
- private Clock clock = new SystemClock();
-
- /**
- * Length of the window in milliseconds.
- */
- private long windowMillis;
-
- /**
- * Storage for the internal queue.
- */
- private final LinkedList queue = new LinkedList();
-
- /**
- * The maximum count this WindowedEventCounter can hold. Also, the maximum queue
- * size. Immutable.
- */
- private int capacity;
-
- /**
- * Sole constructor.
- *
- * @param capacity
- * maximum count this WindowedEventCounter can hold.
- * @param windowMillis
- * length of the interest window in milliseconds.
- * @throws IllegalArgumentException
- * if capacity is less than 1 or if windowMillis is less than 1.
- */
- public WindowedEventCounter(int capacity, long windowMillis) {
- if (capacity <= 0) {
- throw new IllegalArgumentException(
- "capacity must be greater than 0");
- }
- if (windowMillis <= 0) {
- throw new IllegalArgumentException(
- "windowMillis must be greater than 0");
- }
- this.windowMillis = windowMillis;
- this.capacity = capacity;
- }
-
- /**
- * Record a new event.
- */
- public void mark() {
- final long currentTimeMillis = clock.currentTimeMillis();
-
- synchronized (queue) {
- if (queue.size() == capacity) {
- /*
- * we're all filled up already, let's dequeue the oldest
- * timestamp to make room for this new one.
- */
- queue.removeFirst();
- }
- queue.addLast(currentTimeMillis);
- }
- }
-
- /**
- * Returns a count of in-window events.
- *
- * @return the the count of in-window events.
- */
- public int tally() {
- long currentTimeMillis = clock.currentTimeMillis();
-
- // calculates time for which we remove any errors before
- final long removeTimesBeforeMillis = currentTimeMillis - windowMillis;
-
- synchronized (queue) {
- // drain out any expired timestamps but don't drain past empty
- while (!queue.isEmpty() && queue.peek() < removeTimesBeforeMillis) {
- queue.removeFirst();
- }
- return queue.size();
- }
- }
-
- /**
- * Returns the length of the currently configured event window in
- * milliseconds.
- *
- * @return long
- */
- public long getWindowMillis() {
- return windowMillis;
- }
-
- /**
- * Specifies the maximum capacity of the counter.
- *
- * @param capacity
- * long
- * @throws IllegalArgumentException
- * if windowMillis is less than 1.
- */
- public void setCapacity(int capacity) {
- if (capacity <= 0) {
- throw new IllegalArgumentException("capacity must be greater than 0");
- }
-
- synchronized (queue) {
- // If the capacity was reduced, we remove oldest elements until the
- // queue fits inside the specified capacity
- if (capacity < this.capacity) {
- while (queue.size() > capacity) {
- queue.removeFirst();
- }
- }
- }
-
- this.capacity = capacity;
- }
-
- /**
- * Returns the maximum capacity this counter can hold.
- *
- * @return int
- */
- public int getCapacity() {
- return capacity;
- }
-
- /**
- * Specifies the length of the interest window in milliseconds.
- *
- * @param windowMillis
- * long
- * @throws IllegalArgumentException
- * if windowMillis is less than 1.
- */
- public void setWindowMillis(long windowMillis) {
- if (windowMillis <= 0) {
- throw new IllegalArgumentException("windowMillis must be greater than 0");
- }
-
- // changing windowMillis while tally() is draining expired events could
- // lead to weirdness, let's lock for this.
- synchronized (queue) {
- this.windowMillis = windowMillis;
- }
- }
-
- /**
- * Allow the internal {@link Clock} that is used for current time to be
- * overridden (for testing).
- *
- * @param clock Clock
- */
- protected void setClock(Clock clock) {
- this.clock = clock;
- }
+ /**
+ * The {@link Clock} to used to determine current time (override for testing).
+ */
+ private Clock clock = new SystemClock();
+
+ /**
+ * Length of the window in milliseconds.
+ */
+ private long windowMillis;
+
+ /**
+ * Storage for the internal queue.
+ */
+ private final LinkedList queue = new LinkedList();
+
+ /**
+ * The maximum count this WindowedEventCounter can hold. Also, the maximum queue
+ * size. Immutable.
+ */
+ private int capacity;
+
+ /**
+ * Sole constructor.
+ *
+ * @param capacity maximum count this WindowedEventCounter can hold.
+ * @param windowMillis length of the interest window in milliseconds.
+ * @throws IllegalArgumentException if capacity is less than 1 or if
+ * windowMillis is less than 1.
+ */
+ public WindowedEventCounter(int capacity, long windowMillis) {
+ if (capacity <= 0) {
+ throw new IllegalArgumentException("capacity must be greater than 0");
+ }
+ if (windowMillis <= 0) {
+ throw new IllegalArgumentException("windowMillis must be greater than 0");
+ }
+ this.windowMillis = windowMillis;
+ this.capacity = capacity;
+ }
+
+ /**
+ * Record a new event.
+ */
+ public void mark() {
+ final long currentTimeMillis = clock.currentTimeMillis();
+
+ synchronized (queue) {
+ if (queue.size() == capacity) {
+ /*
+ * we're all filled up already, let's dequeue the oldest timestamp to make room
+ * for this new one.
+ */
+ queue.removeFirst();
+ }
+ queue.addLast(currentTimeMillis);
+ }
+ }
+
+ /**
+ * Returns a count of in-window events.
+ *
+ * @return the the count of in-window events.
+ */
+ public int tally() {
+ long currentTimeMillis = clock.currentTimeMillis();
+
+ // calculates time for which we remove any errors before
+ final long removeTimesBeforeMillis = currentTimeMillis - windowMillis;
+
+ synchronized (queue) {
+ // drain out any expired timestamps but don't drain past empty
+ while (!queue.isEmpty() && queue.peek() < removeTimesBeforeMillis) {
+ queue.removeFirst();
+ }
+ return queue.size();
+ }
+ }
+
+ /**
+ * Returns the length of the currently configured event window in milliseconds.
+ *
+ * @return long
+ */
+ public long getWindowMillis() {
+ return windowMillis;
+ }
+
+ /**
+ * Specifies the maximum capacity of the counter.
+ *
+ * @param capacity long
+ * @throws IllegalArgumentException if windowMillis is less than 1.
+ */
+ public void setCapacity(int capacity) {
+ if (capacity <= 0) {
+ throw new IllegalArgumentException("capacity must be greater than 0");
+ }
+
+ synchronized (queue) {
+ // If the capacity was reduced, we remove oldest elements until the
+ // queue fits inside the specified capacity
+ if (capacity < this.capacity) {
+ while (queue.size() > capacity) {
+ queue.removeFirst();
+ }
+ }
+ }
+
+ this.capacity = capacity;
+ }
+
+ /**
+ * Returns the maximum capacity this counter can hold.
+ *
+ * @return int
+ */
+ public int getCapacity() {
+ return capacity;
+ }
+
+ /**
+ * Specifies the length of the interest window in milliseconds.
+ *
+ * @param windowMillis long
+ * @throws IllegalArgumentException if windowMillis is less than 1.
+ */
+ public void setWindowMillis(long windowMillis) {
+ if (windowMillis <= 0) {
+ throw new IllegalArgumentException("windowMillis must be greater than 0");
+ }
+
+ // changing windowMillis while tally() is draining expired events could
+ // lead to weirdness, let's lock for this.
+ synchronized (queue) {
+ this.windowMillis = windowMillis;
+ }
+ }
+
+ /**
+ * Allow the internal {@link Clock} that is used for current time to be
+ * overridden (for testing).
+ *
+ * @param clock Clock
+ */
+ protected void setClock(Clock clock) {
+ this.clock = clock;
+ }
}
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/WrappedException.java b/jrugged-core/src/main/java/org/fishwife/jrugged/WrappedException.java
index ac1a8c9b..9e08e180 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/WrappedException.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/WrappedException.java
@@ -18,9 +18,9 @@
public class WrappedException extends RuntimeException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- public WrappedException(Throwable cause) {
- super(cause);
- }
+ public WrappedException(Throwable cause) {
+ super(cause);
+ }
}
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/clocks/DefaultHardwareClock.java b/jrugged-core/src/main/java/org/fishwife/jrugged/clocks/DefaultHardwareClock.java
index 5cd61f78..3c714ce3 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/clocks/DefaultHardwareClock.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/clocks/DefaultHardwareClock.java
@@ -20,129 +20,150 @@
import org.fishwife.jrugged.interval.DiscreteInterval;
-/** This class captures the "most accurate system timer"
- * available via {@link System#nanoTime}, but also attempts to determine
- * the actual granularity of the timer (which might be greater than 1ns)
- * and present the measurement error inherent in taking clock measurements.
+/**
+ * This class captures the "most accurate system timer" available via
+ * {@link System#nanoTime}, but also attempts to determine the actual
+ * granularity of the timer (which might be greater than 1ns) and present the
+ * measurement error inherent in taking clock measurements.
*/
class DefaultHardwareClock implements HardwareClock {
- private static long DEFAULT_PERIOD_MILLIS = 100 * 1000L;
- private long periodMillis = DEFAULT_PERIOD_MILLIS;
- private static int DEFAULT_NUM_SAMPLES = 100;
-
- /** I sure hope we can count on the clock ticking at least once a
- * year. Normalize clock readings so that the returned intervals
- * land in reasonable positive ranges. */
- private static long MIN_CLOCK_TIME = 1000000000L * 3600 * 24 * 365;
-
- private AtomicLong lastSampleTime = new AtomicLong(0L);
- private int sampleIndex = 0;
- private long maxGranularity;
- private long[] samples;
- private Long offset;
- private Env env;
-
- /** Default constructor. */
- public DefaultHardwareClock() {
- this(new DefaultEnv(), DEFAULT_NUM_SAMPLES, DEFAULT_PERIOD_MILLIS);
- }
-
- /** Constructs a new HardwareClock with an alternative
- * implementation for various static system methods. Primarily useful
- * for testing.
- * @param env
- */
- public DefaultHardwareClock(Env env) {
- this(env, DEFAULT_NUM_SAMPLES, DEFAULT_PERIOD_MILLIS);
- }
-
- /** Constructs a new HardwareClock with all dependencies
- * and/or configuration specified.
- * @param env alternative implementation of required static system methods
- * @param numSamples how many granularity samples to keep historically (default
- * is 100)
- * @param periodMillis how often to sample the clock granularity, in milliseconds
- * (default is 100,000, or once every 100 seconds)
- */
- public DefaultHardwareClock(Env env, int numSamples, long periodMillis) {
- this.env = env;
- samples = new long[numSamples];
- this.periodMillis = periodMillis;
- }
-
- long elapsedTime(long start, long end) {
- if (end > start) return (end - start);
- return (Long.MAX_VALUE - start) + 1 + (end - Long.MIN_VALUE);
- }
-
- long sampleGranularity() {
- long start = env.nanoTime();
- long end;
- while((end = env.nanoTime()) == start) /* loop */;
- return elapsedTime(start, end);
- }
-
- /* (non-Javadoc)
- * @see org.fishwife.jrugged.clocks.HardwareClock#getGranularity()
- */
- public long getGranularity() {
- long now = env.currentTimeMillis();
- long curr = lastSampleTime.get();
- if (now - curr > periodMillis
- && lastSampleTime.compareAndSet(curr, now)) {
- samples[sampleIndex] = sampleGranularity();
- sampleIndex = (sampleIndex + 1) % samples.length;
- long max = 0L;
- for(long sample : samples) {
- if (sample > max) max = sample;
- }
- maxGranularity = max;
- }
- return maxGranularity;
- }
-
- /* (non-Javadoc)
- * @see org.fishwife.jrugged.clocks.HardwareClock#getNanoTime()
- */
- public DiscreteInterval getNanoTime() {
- long granularity = getGranularity();
- long err = granularity / 2;
- if (granularity % 2 == 1) err += 1;
- long now = env.nanoTime() + getOffset();
- return new DiscreteInterval(now - err, now + err);
- }
-
- private long getOffset() {
- if (offset != null) return offset;
- long now = env.nanoTime();
- offset = (now < MIN_CLOCK_TIME) ? (MIN_CLOCK_TIME - now) : (now - MIN_CLOCK_TIME);
- return offset;
- }
-
- /** Interface capturing various static methods that are dependencies
- * of this class; this allows us to switch them out for testing and
- * generally keep us loosely coupled from underlying platform API.
- */
- public static interface Env {
- /** @see {@link System#nanotime} */
- long nanoTime();
- /** @see {@link System#currentTimeMillis} */
- long currentTimeMillis();
- }
-
- /** The default implementation for static dependencies encapsulated
- * in the Env interface.
- */
- public static class DefaultEnv implements Env {
- /** Returns System.nanoTime(). */
- public long nanoTime() {
- return System.nanoTime();
- }
- /** Returns System.currentTimeMillis(). */
- public long currentTimeMillis() {
- return System.currentTimeMillis();
- }
- }
+ private static long DEFAULT_PERIOD_MILLIS = 100 * 1000L;
+ private long periodMillis = DEFAULT_PERIOD_MILLIS;
+ private static int DEFAULT_NUM_SAMPLES = 100;
+
+ /**
+ * I sure hope we can count on the clock ticking at least once a year. Normalize
+ * clock readings so that the returned intervals land in reasonable positive
+ * ranges.
+ */
+ private static long MIN_CLOCK_TIME = 1000000000L * 3600 * 24 * 365;
+
+ private AtomicLong lastSampleTime = new AtomicLong(0L);
+ private int sampleIndex = 0;
+ private long maxGranularity;
+ private long[] samples;
+ private Long offset;
+ private Env env;
+
+ /** Default constructor. */
+ public DefaultHardwareClock() {
+ this(new DefaultEnv(), DEFAULT_NUM_SAMPLES, DEFAULT_PERIOD_MILLIS);
+ }
+
+ /**
+ * Constructs a new HardwareClock with an alternative
+ * implementation for various static system methods. Primarily useful for
+ * testing.
+ *
+ * @param env
+ */
+ public DefaultHardwareClock(Env env) {
+ this(env, DEFAULT_NUM_SAMPLES, DEFAULT_PERIOD_MILLIS);
+ }
+
+ /**
+ * Constructs a new HardwareClock with all dependencies and/or
+ * configuration specified.
+ *
+ * @param env alternative implementation of required static system
+ * methods
+ * @param numSamples how many granularity samples to keep historically
+ * (default is 100)
+ * @param periodMillis how often to sample the clock granularity, in
+ * milliseconds (default is 100,000, or once every 100
+ * seconds)
+ */
+ public DefaultHardwareClock(Env env, int numSamples, long periodMillis) {
+ this.env = env;
+ samples = new long[numSamples];
+ this.periodMillis = periodMillis;
+ }
+
+ long elapsedTime(long start, long end) {
+ if (end > start)
+ return (end - start);
+ return (Long.MAX_VALUE - start) + 1 + (end - Long.MIN_VALUE);
+ }
+
+ long sampleGranularity() {
+ long start = env.nanoTime();
+ long end;
+ while ((end = env.nanoTime()) == start)
+ /* loop */;
+ return elapsedTime(start, end);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.fishwife.jrugged.clocks.HardwareClock#getGranularity()
+ */
+ public long getGranularity() {
+ long now = env.currentTimeMillis();
+ long curr = lastSampleTime.get();
+ if (now - curr > periodMillis && lastSampleTime.compareAndSet(curr, now)) {
+ samples[sampleIndex] = sampleGranularity();
+ sampleIndex = (sampleIndex + 1) % samples.length;
+ long max = 0L;
+ for (long sample : samples) {
+ if (sample > max)
+ max = sample;
+ }
+ maxGranularity = max;
+ }
+ return maxGranularity;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.fishwife.jrugged.clocks.HardwareClock#getNanoTime()
+ */
+ public DiscreteInterval getNanoTime() {
+ long granularity = getGranularity();
+ long err = granularity / 2;
+ if (granularity % 2 == 1)
+ err += 1;
+ long now = env.nanoTime() + getOffset();
+ return new DiscreteInterval(now - err, now + err);
+ }
+
+ private long getOffset() {
+ if (offset != null)
+ return offset;
+ long now = env.nanoTime();
+ offset = (now < MIN_CLOCK_TIME) ? (MIN_CLOCK_TIME - now) : (now - MIN_CLOCK_TIME);
+ return offset;
+ }
+
+ /**
+ * Interface capturing various static methods that are dependencies of this
+ * class; this allows us to switch them out for testing and generally keep us
+ * loosely coupled from underlying platform API.
+ */
+ public static interface Env {
+ /** @see {@link System#nanotime} */
+ long nanoTime();
+
+ /** @see {@link System#currentTimeMillis} */
+ long currentTimeMillis();
+ }
+
+ /**
+ * The default implementation for static dependencies encapsulated in the
+ * Env interface.
+ */
+ public static class DefaultEnv implements Env {
+ /** Returns System.nanoTime(). */
+ public long nanoTime() {
+ return System.nanoTime();
+ }
+
+ /** Returns System.currentTimeMillis(). */
+ public long currentTimeMillis() {
+ return System.currentTimeMillis();
+ }
+ }
}
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/clocks/HardwareClock.java b/jrugged-core/src/main/java/org/fishwife/jrugged/clocks/HardwareClock.java
index 7223969d..2a967795 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/clocks/HardwareClock.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/clocks/HardwareClock.java
@@ -18,29 +18,33 @@
import org.fishwife.jrugged.interval.DiscreteInterval;
-/** This interface provides access to the "most accurate system
- * timer" available, but also attempts to determine the actual
- * granularity of the timer (which might be greater than 1ns) and
- * present the measurement error inherent in taking clock measurements.
+/**
+ * This interface provides access to the "most accurate system timer"
+ * available, but also attempts to determine the actual granularity of the timer
+ * (which might be greater than 1ns) and present the measurement error inherent
+ * in taking clock measurements.
*/
interface HardwareClock {
- /** Gets the estimated hardware clock granularity. This is the
- * number of nanoseconds that elapse between ticks/updates of
- * the underlying hardware clock.
- * @return granularity in nanoseconds
- */
- long getGranularity();
+ /**
+ * Gets the estimated hardware clock granularity. This is the number of
+ * nanoseconds that elapse between ticks/updates of the underlying hardware
+ * clock.
+ *
+ * @return granularity in nanoseconds
+ */
+ long getGranularity();
- /** Get an estimate of the current hardware clock reading,
- * represented as a range of times. The +/- error should be half
- * of the measurement increment, which is the clock granularity
- * in our case. Thus, this effectively returns the hardware clock
- * reading +/- (half granularity), with conservative rounding.
- * @return DiscreteInterval representing the range of values the
- * current hardware clock time might fall within, represented in
- * nanoseconds.
- */
- DiscreteInterval getNanoTime();
+ /**
+ * Get an estimate of the current hardware clock reading, represented as a range
+ * of times. The +/- error should be half of the measurement increment, which is
+ * the clock granularity in our case. Thus, this effectively returns the
+ * hardware clock reading +/- (half granularity), with conservative rounding.
+ *
+ * @return DiscreteInterval representing the range of values the
+ * current hardware clock time might fall within, represented in
+ * nanoseconds.
+ */
+ DiscreteInterval getNanoTime();
}
\ No newline at end of file
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/clocks/Timer.java b/jrugged-core/src/main/java/org/fishwife/jrugged/clocks/Timer.java
index 80911f31..b3fb3daf 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/clocks/Timer.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/clocks/Timer.java
@@ -20,53 +20,61 @@
public class Timer {
- private HardwareClock clock;
- private boolean wasSet = false;
- private DiscreteInterval targetElapsedTime;
- private DiscreteInterval startTime;
- private DiscreteInterval targetEndTime;
+ private HardwareClock clock;
+ private boolean wasSet = false;
+ private DiscreteInterval targetElapsedTime;
+ private DiscreteInterval startTime;
+ private DiscreteInterval targetEndTime;
- public Timer() {
- this(new DefaultHardwareClock());
- }
+ public Timer() {
+ this(new DefaultHardwareClock());
+ }
- public Timer(HardwareClock clock) {
- this.clock = clock;
- }
+ public Timer(HardwareClock clock) {
+ this.clock = clock;
+ }
- public boolean set(long duration, long error) {
- if (error < clock.getGranularity()) return false;
- wasSet = true;
- targetElapsedTime = new DiscreteInterval(duration - error, duration + error);
- return true;
- }
+ public boolean set(long duration, long error) {
+ if (error < clock.getGranularity())
+ return false;
+ wasSet = true;
+ targetElapsedTime = new DiscreteInterval(duration - error, duration + error);
+ return true;
+ }
- public void start() {
- if (!wasSet) throw new IllegalStateException("cannot start a timer that has not been set");
- startTime = clock.getNanoTime();
- targetEndTime = startTime.plus(targetElapsedTime);
- }
+ public void start() {
+ if (!wasSet)
+ throw new IllegalStateException("cannot start a timer that has not been set");
+ startTime = clock.getNanoTime();
+ targetEndTime = startTime.plus(targetElapsedTime);
+ }
- public boolean hasElapsed() {
- if (startTime == null) return false;
- return (clock.getNanoTime().getMin() >= targetEndTime.getMin());
- }
+ public boolean hasElapsed() {
+ if (startTime == null)
+ return false;
+ return (clock.getNanoTime().getMin() >= targetEndTime.getMin());
+ }
- public boolean isLate() {
- if (startTime == null) return false;
- return (clock.getNanoTime().getMax() > targetEndTime.getMax());
- }
+ public boolean isLate() {
+ if (startTime == null)
+ return false;
+ return (clock.getNanoTime().getMax() > targetEndTime.getMax());
+ }
- public DiscreteInterval getTimeRemaining() {
- if (!wasSet) throw new IllegalStateException("cannot compute time remaining without having duration set");
- if (startTime == null) return targetElapsedTime;
- DiscreteInterval diff = targetEndTime.minus(clock.getNanoTime());
- return (diff.getMin() <= 0L) ? new DiscreteInterval(0L,0L) : diff;
- }
+ public DiscreteInterval getTimeRemaining() {
+ if (!wasSet)
+ throw new IllegalStateException("cannot compute time remaining without having duration set");
+ if (startTime == null)
+ return targetElapsedTime;
+ DiscreteInterval diff = targetEndTime.minus(clock.getNanoTime());
+ return (diff.getMin() <= 0L) ? new DiscreteInterval(0L, 0L) : diff;
+ }
- public void waitUntilElapsed() {
- if (!wasSet) throw new IllegalStateException("cannot wait until duration has been set");
- while(!hasElapsed()) /*spin*/;
- }
+ public void waitUntilElapsed() {
+ if (!wasSet)
+ throw new IllegalStateException("cannot wait until duration has been set");
+ while (!hasElapsed())
+ /* spin */;
+ }
}
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/control/Action.java b/jrugged-core/src/main/java/org/fishwife/jrugged/control/Action.java
index b787ebb5..b9c745f7 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/control/Action.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/control/Action.java
@@ -17,5 +17,5 @@
package org.fishwife.jrugged.control;
interface Action {
- void execute();
+ void execute();
}
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/control/ClosedLoop.java b/jrugged-core/src/main/java/org/fishwife/jrugged/control/ClosedLoop.java
index f4eeb587..f64ba674 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/control/ClosedLoop.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/control/ClosedLoop.java
@@ -18,27 +18,27 @@
class ClosedLoop, A extends Action> {
- private Controller controller;
- private M model;
+ private Controller controller;
+ private M model;
- ClosedLoop(Controller controller, M model) {
- this.controller = controller;
- this.model = model;
- }
+ ClosedLoop(Controller controller, M model) {
+ this.controller = controller;
+ this.model = model;
+ }
- void addObjective(Objective objective) {
- controller.addObjective(objective);
- }
+ void addObjective(Objective objective) {
+ controller.addObjective(objective);
+ }
- void withdrawObjective(Objective objective) {
- controller.withdrawObjective(objective);
- }
+ void withdrawObjective(Objective objective) {
+ controller.withdrawObjective(objective);
+ }
- void processEvent(E event) {
- model.update(event);
- controller.assessObjectives(model);
- A a = controller.selectAction(model);
- a.execute();
- }
+ void processEvent(E event) {
+ model.update(event);
+ controller.assessObjectives(model);
+ A a = controller.selectAction(model);
+ a.execute();
+ }
}
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/control/Controller.java b/jrugged-core/src/main/java/org/fishwife/jrugged/control/Controller.java
index ea005fd8..400046fe 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/control/Controller.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/control/Controller.java
@@ -17,11 +17,11 @@
package org.fishwife.jrugged.control;
interface Controller, A extends Action> {
- void addObjective(Objective objective);
+ void addObjective(Objective objective);
- void withdrawObjective(Objective objective);
+ void withdrawObjective(Objective objective);
- A selectAction(M model);
+ A selectAction(M model);
- void assessObjectives(M model);
+ void assessObjectives(M model);
}
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/control/Model.java b/jrugged-core/src/main/java/org/fishwife/jrugged/control/Model.java
index f3df6918..78e36966 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/control/Model.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/control/Model.java
@@ -17,5 +17,5 @@
package org.fishwife.jrugged.control;
interface Model {
- void update(E event);
+ void update(E event);
}
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/control/Objective.java b/jrugged-core/src/main/java/org/fishwife/jrugged/control/Objective.java
index b24ecf0b..536b2b66 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/control/Objective.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/control/Objective.java
@@ -17,8 +17,11 @@
package org.fishwife.jrugged.control;
interface Objective> {
- boolean isMetBy(M state);
- boolean hasFailed(M state);
- void succeed();
- void fail();
+ boolean isMetBy(M state);
+
+ boolean hasFailed(M state);
+
+ void succeed();
+
+ void fail();
}
diff --git a/jrugged-core/src/main/java/org/fishwife/jrugged/interval/DiscreteInterval.java b/jrugged-core/src/main/java/org/fishwife/jrugged/interval/DiscreteInterval.java
index fea57fb5..6ea8367f 100644
--- a/jrugged-core/src/main/java/org/fishwife/jrugged/interval/DiscreteInterval.java
+++ b/jrugged-core/src/main/java/org/fishwife/jrugged/interval/DiscreteInterval.java
@@ -16,120 +16,130 @@
*/
package org.fishwife.jrugged.interval;
-/** Representation of integer (long) intervals and associated arithmetic.
- * This is useful for representing numbers with inherent measurement error
- * or uncertainty; instead of a single value or a single value with a +/-
- * error, we represent this as a range of values. One of the interesting
- * properties of interval arithmetic is that errors are monotonically
- * nondecreasing as you perform additional operations on them.
+/**
+ * Representation of integer (long) intervals and associated arithmetic. This is
+ * useful for representing numbers with inherent measurement error or
+ * uncertainty; instead of a single value or a single value with a +/- error, we
+ * represent this as a range of values. One of the interesting properties of
+ * interval arithmetic is that errors are monotonically nondecreasing as you
+ * perform additional operations on them.
*/
public class DiscreteInterval {
- final private long min;
- final private long max;
+ final private long min;
+ final private long max;
- /** Creates an interval spanning a range between the two provided
- * value arguments, inclusive. Order matters for the arguments due
- * to wraparound overflow of longs; the range is defined as all the
- * values crossed by starting at 'min' and then incrementing until
- * 'max' is reached. Thus, this is the closed interval [min, max].
- * @param min minimum value of range
- * @param max maximum value of range
- */
- public DiscreteInterval(long min, long max) {
- this.min = min;
- this.max = max;
- }
+ /**
+ * Creates an interval spanning a range between the two provided value
+ * arguments, inclusive. Order matters for the arguments due to wraparound
+ * overflow of longs; the range is defined as all the values crossed by starting
+ * at 'min' and then incrementing until 'max' is reached. Thus, this is the
+ * closed interval [min, max].
+ *
+ * @param min minimum value of range
+ * @param max maximum value of range
+ */
+ public DiscreteInterval(long min, long max) {
+ this.min = min;
+ this.max = max;
+ }
- /** Returns the minimum value included in the interval.
- *
- * @return long min value included
- */
- public long getMin() {
- return min;
- }
+ /**
+ * Returns the minimum value included in the interval.
+ *
+ * @return long min value included
+ */
+ public long getMin() {
+ return min;
+ }
- /** Returns the maximum value included in the interval.
- *
- * @return long max value included
- */
- public long getMax() {
- return max;
- }
+ /**
+ * Returns the maximum value included in the interval.
+ *
+ * @return long max value included
+ */
+ public long getMax() {
+ return max;
+ }
- /** Returns the number of discrete values covered by this
- * range.
- *
- * @return long how many values are in my range
- */
- public long size() {
- return max - min + 1;
- }
+ /**
+ * Returns the number of discrete values covered by this range.
+ *
+ * @return long how many values are in my range
+ */
+ public long size() {
+ return max - min + 1;
+ }
- /** Returns an interval representing the addition of the
- * given interval with this one.
- * @param other interval to add to this one
- * @return interval sum
- */
- public DiscreteInterval plus(DiscreteInterval other) {
- return new DiscreteInterval(this.min + other.min, this.max + other.max);
- }
+ /**
+ * Returns an interval representing the addition of the given interval with this
+ * one.
+ *
+ * @param other interval to add to this one
+ * @return interval sum
+ */
+ public DiscreteInterval plus(DiscreteInterval other) {
+ return new DiscreteInterval(this.min + other.min, this.max + other.max);
+ }
- /** Returns an interval representing the negation of the
- * closed interval [-1,-1] with this one.
- * @return interval negation
- */
- public DiscreteInterval negate() {
- return new DiscreteInterval(-1 * this.max, -1 * this.min);
- }
+ /**
+ * Returns an interval representing the negation of the closed interval [-1,-1]
+ * with this one.
+ *
+ * @return interval negation
+ */
+ public DiscreteInterval negate() {
+ return new DiscreteInterval(-1 * this.max, -1 * this.min);
+ }
- /** Returns an interval representing the subtraction of the
- * given interval from this one.
- * @param other interval to subtract from this one
- * @return result of subtraction
- */
- public DiscreteInterval minus(DiscreteInterval other) {
- return new DiscreteInterval(this.min - other.max, this.max - other.min);
- }
+ /**
+ * Returns an interval representing the subtraction of the given interval from
+ * this one.
+ *
+ * @param other interval to subtract from this one
+ * @return result of subtraction
+ */
+ public DiscreteInterval minus(DiscreteInterval other) {
+ return new DiscreteInterval(this.min - other.max, this.max - other.min);
+ }
- /** Determines whether the given interval is completely
- * contained by this one.
- *
- * @param other Is this interval contained in my current interval
- * @return boolean contained or not contained that is the question
- */
- public boolean contains(DiscreteInterval other) {
- return (min <= other.getMin() && max >= other.getMax());
- }
+ /**
+ * Determines whether the given interval is completely contained by this one.
+ *
+ * @param other Is this interval contained in my current interval
+ * @return boolean contained or not contained that is the question
+ */
+ public boolean contains(DiscreteInterval other) {
+ return (min <= other.getMin() && max >= other.getMax());
+ }
- @Override
- public String toString() {
- return "[" + min + "," + max + "]";
- }
+ @Override
+ public String toString() {
+ return "[" + min + "," + max + "]";
+ }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (int) (max ^ (max >>> 32));
- result = prime * result + (int) (min ^ (min >>> 32));
- return result;
- }
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + (int) (max ^ (max >>> 32));
+ result = prime * result + (int) (min ^ (min >>> 32));
+ return result;
+ }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- DiscreteInterval other = (DiscreteInterval) obj;
- if (max != other.max)
- return false;
- if (min != other.min)
- return false;
- return true;
- }
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ DiscreteInterval other = (DiscreteInterval) obj;
+ if (max != other.max)
+ return false;
+ if (min != other.min)
+ return false;
+ return true;
+ }
}
-
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestCircuitBreaker.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestCircuitBreaker.java
index a2a7a739..4d99ef1d 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestCircuitBreaker.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestCircuitBreaker.java
@@ -35,12 +35,15 @@
import static org.junit.Assert.fail;
public class TestCircuitBreaker {
+
private CircuitBreaker impl;
private Callable mockCallable;
private Runnable mockRunnable;
private Clock mockClock;
- Status theStatus;
+
+ Status theStatus;
+
@SuppressWarnings("unchecked")
@Before
@@ -51,397 +54,392 @@ public void setUp() {
mockClock = createMock(Clock.class);
}
- @Test
- public void testInvokeWithRunnableResultAndResultReturnsResult() throws Exception {
- final Object result = new Object();
-
- mockRunnable.run();
- replay(mockRunnable);
- Object theReturned = impl.invoke(mockRunnable, result);
+ @Test
+ public void testInvokeWithRunnableResultAndResultReturnsResult() throws Exception {
+ final Object result = new Object();
- verify(mockRunnable);
- assertSame(result, theReturned);
- }
+ mockRunnable.run();
+ replay(mockRunnable);
- @Test
- public void testInvokeWithRunnableResultAndByPassReturnsResult() throws Exception {
- final Object result = new Object();
- impl.setByPassState(true);
-
- mockRunnable.run();
- replay(mockRunnable);
-
- Object theReturned = impl.invoke(mockRunnable, result);
-
- verify(mockRunnable);
- assertSame(result, theReturned);
- }
-
- @Test(expected = CircuitBreakerException.class)
- public void testInvokeWithRunnableResultAndTripHardReturnsException() throws Exception {
- final Object result = new Object();
- impl.tripHard();
-
- mockRunnable.run();
- replay(mockRunnable);
-
- impl.invoke(mockRunnable, result);
-
- verify(mockRunnable);
- }
-
- @Test
- public void testInvokeWithRunnableDoesNotError() throws Exception {
- mockRunnable.run();
- replay(mockRunnable);
-
- impl.invoke(mockRunnable);
-
- verify(mockRunnable);
- }
+ Object theReturned = impl.invoke(mockRunnable, result);
- @Test
- public void testInvokeWithRunnableAndByPassDoesNotError() throws Exception {
- impl.setByPassState(true);
-
- mockRunnable.run();
- replay(mockRunnable);
-
- impl.invoke(mockRunnable);
-
- verify(mockRunnable);
- }
-
- @Test(expected = CircuitBreakerException.class)
- public void testInvokeWithRunnableAndTripHardReturnsException() throws Exception {
- impl.tripHard();
-
- mockRunnable.run();
- replay(mockRunnable);
-
- impl.invoke(mockRunnable);
-
- verify(mockRunnable);
- }
-
- @Test
- public void testStaysClosedOnSuccess() throws Exception {
- impl.state = CircuitBreaker.BreakerState.CLOSED;
- final Object obj = new Object();
- expect(mockCallable.call()).andReturn(obj);
- replay(mockCallable);
-
- Object result = impl.invoke(mockCallable);
-
- verify(mockCallable);
- assertSame(obj, result);
- assertEquals(CircuitBreaker.BreakerState.CLOSED, impl.state);
- }
-
- @Test
- public void testOpensOnFailure() throws Exception {
- long start = System.currentTimeMillis();
- impl.state = CircuitBreaker.BreakerState.OPEN;
- expect(mockCallable.call()).andThrow(new RuntimeException());
- replay(mockCallable);
-
- try {
- impl.invoke(mockCallable);
- fail("should have thrown an exception");
- } catch (RuntimeException expected) {
- }
-
- long end = System.currentTimeMillis();
-
- verify(mockCallable);
- assertEquals(CircuitBreaker.BreakerState.OPEN, impl.state);
- assertTrue(impl.lastFailure.get() >= start);
- assertTrue(impl.lastFailure.get() <= end);
- }
-
- @Test
- public void testOpenDuringCooldownThrowsCBException()
- throws Exception {
+ verify(mockRunnable);
+ assertSame(result, theReturned);
+ }
- impl.state = CircuitBreaker.BreakerState.OPEN;
- impl.lastFailure.set(System.currentTimeMillis());
- replay(mockCallable);
+ @Test
+ public void testInvokeWithRunnableResultAndByPassReturnsResult() throws Exception {
+ final Object result = new Object();
+ impl.setByPassState(true);
- try {
- impl.invoke(mockCallable);
- fail("should have thrown an exception");
- } catch (CircuitBreakerException expected) {
- }
+ mockRunnable.run();
+ replay(mockRunnable);
- verify(mockCallable);
- assertEquals(CircuitBreaker.BreakerState.OPEN, impl.state);
- }
+ Object theReturned = impl.invoke(mockRunnable, result);
- @Test
- public void testOpenAfterCooldownGoesHalfClosed()
- throws Exception {
+ verify(mockRunnable);
+ assertSame(result, theReturned);
+ }
- impl.state = CircuitBreaker.BreakerState.OPEN;
- impl.resetMillis.set(1000);
- impl.lastFailure.set(System.currentTimeMillis() - 2000);
+ @Test(expected = CircuitBreakerException.class)
+ public void testInvokeWithRunnableResultAndTripHardReturnsException() throws Exception {
+ final Object result = new Object();
+ impl.tripHard();
- assertEquals(Status.DEGRADED, impl.getStatus());
- assertEquals(CircuitBreaker.BreakerState.HALF_CLOSED, impl.state);
- }
+ mockRunnable.run();
+ replay(mockRunnable);
- @Test
- public void testHalfClosedFailureOpensAgain()
- throws Exception {
+ impl.invoke(mockRunnable, result);
- impl.state = CircuitBreaker.BreakerState.HALF_CLOSED;
- impl.resetMillis.set(1000);
- impl.lastFailure.set(System.currentTimeMillis() - 2000);
+ verify(mockRunnable);
+ }
- long start = System.currentTimeMillis();
+ @Test
+ public void testInvokeWithRunnableDoesNotError() throws Exception {
+ mockRunnable.run();
+ replay(mockRunnable);
- expect(mockCallable.call()).andThrow(new RuntimeException());
- replay(mockCallable);
+ impl.invoke(mockRunnable);
- try {
- impl.invoke(mockCallable);
- fail("should have thrown exception");
- } catch (RuntimeException expected) {
- }
+ verify(mockRunnable);
+ }
- long end = System.currentTimeMillis();
+ @Test
+ public void testInvokeWithRunnableAndByPassDoesNotError() throws Exception {
+ impl.setByPassState(true);
- verify(mockCallable);
- assertEquals(CircuitBreaker.BreakerState.OPEN, impl.state);
- assertTrue(impl.lastFailure.get() >= start);
- assertTrue(impl.lastFailure.get() <= end);
- }
+ mockRunnable.run();
+ replay(mockRunnable);
- @Test
- public void testGetStatusNotUpdatingIsAttemptLive() throws Exception {
+ impl.invoke(mockRunnable);
- impl.resetMillis.set(50);
- impl.trip();
- assertEquals(CircuitBreaker.BreakerState.OPEN, impl.state);
- assertEquals(false, impl.isAttemptLive);
+ verify(mockRunnable);
+ }
- Thread.sleep(200);
+ @Test(expected = CircuitBreakerException.class)
+ public void testInvokeWithRunnableAndTripHardReturnsException() throws Exception {
+ impl.tripHard();
- // The getStatus()->canAttempt() call also updated isAttemptLive to true
- assertEquals(Status.DEGRADED.getValue(), impl.getStatus().getValue());
- assertEquals(false, impl.isAttemptLive);
- }
+ mockRunnable.run();
+ replay(mockRunnable);
- @Test
- public void testManualTripAndReset() throws Exception {
- impl.state = CircuitBreaker.BreakerState.OPEN;
- final Object obj = new Object();
- expect(mockCallable.call()).andReturn(obj);
- replay(mockCallable);
-
- impl.trip();
- try {
- impl.invoke(mockCallable);
- fail("Manual trip method failed.");
- } catch (CircuitBreakerException e) {
- }
-
- impl.reset();
-
- Object result = impl.invoke(mockCallable);
-
- verify(mockCallable);
- assertSame(obj, result);
- assertEquals(CircuitBreaker.BreakerState.CLOSED, impl.state);
- }
+ impl.invoke(mockRunnable);
- @Test
- public void testTripHard() throws Exception {
- expect(mockCallable.call()).andReturn("hi");
+ verify(mockRunnable);
+ }
- replay(mockCallable);
+ @Test
+ public void testStaysClosedOnSuccess() throws Exception {
+ impl.state = CircuitBreaker.BreakerState.CLOSED;
+ final Object obj = new Object();
+ expect(mockCallable.call()).andReturn(obj);
+ replay(mockCallable);
- impl.tripHard();
- try {
- impl.invoke(mockCallable);
- fail("exception expected after CircuitBreaker.tripHard()");
- } catch (CircuitBreakerException e) {
- }
- assertEquals(CircuitBreaker.BreakerState.OPEN, impl.state);
+ Object result = impl.invoke(mockCallable);
- impl.reset();
- impl.invoke(mockCallable);
- assertEquals(CircuitBreaker.BreakerState.CLOSED, impl.state);
+ verify(mockCallable);
+ assertSame(obj, result);
+ assertEquals(CircuitBreaker.BreakerState.CLOSED, impl.state);
+ }
- verify(mockCallable);
- }
+ @Test
+ public void testOpensOnFailure() throws Exception {
+ long start = System.currentTimeMillis();
+ impl.state = CircuitBreaker.BreakerState.OPEN;
+ expect(mockCallable.call()).andThrow(new RuntimeException());
+ replay(mockCallable);
- @Test
- public void testGetTripCount() throws Exception {
- long tripCount1 = impl.getTripCount();
+ try {
+ impl.invoke(mockCallable);
+ fail("should have thrown an exception");
+ } catch (RuntimeException expected) {
+ }
- impl.tripHard();
- long tripCount2 = impl.getTripCount();
- assertEquals(tripCount1 + 1, tripCount2);
+ long end = System.currentTimeMillis();
- impl.tripHard();
- assertEquals(tripCount2, impl.getTripCount());
- }
+ verify(mockCallable);
+ assertEquals(CircuitBreaker.BreakerState.OPEN, impl.state);
+ assertTrue(impl.lastFailure.get() >= start);
+ assertTrue(impl.lastFailure.get() <= end);
+ }
- @Test
- public void testGetStatusWhenOpen() {
- impl.state = CircuitBreaker.BreakerState.OPEN;
- Assert.assertEquals(Status.DOWN, impl.getStatus());
- }
+ @Test
+ public void testOpenDuringCooldownThrowsCBException() throws Exception {
- @Test
- public void testGetStatusWhenHalfClosed() {
- impl.state = CircuitBreaker.BreakerState.HALF_CLOSED;
- assertEquals(Status.DEGRADED, impl.getStatus());
- }
+ impl.state = CircuitBreaker.BreakerState.OPEN;
+ impl.lastFailure.set(System.currentTimeMillis());
+ replay(mockCallable);
- @Test
- public void testGetStatusWhenOpenBeforeReset() {
- impl.state = CircuitBreaker.BreakerState.CLOSED;
- impl.resetMillis.set(1000);
- impl.lastFailure.set(System.currentTimeMillis() - 50);
+ try {
+ impl.invoke(mockCallable);
+ fail("should have thrown an exception");
+ } catch (CircuitBreakerException expected) {
+ }
- assertEquals(Status.UP, impl.getStatus());
- }
+ verify(mockCallable);
+ assertEquals(CircuitBreaker.BreakerState.OPEN, impl.state);
+ }
- @Test
- public void testGetStatusWhenOpenAfterReset() {
- impl.state = CircuitBreaker.BreakerState.OPEN;
- impl.resetMillis.set(1000);
- impl.lastFailure.set(System.currentTimeMillis() - 2000);
+ @Test
+ public void testOpenAfterCooldownGoesHalfClosed() throws Exception {
- assertEquals(Status.DEGRADED, impl.getStatus());
- }
+ impl.state = CircuitBreaker.BreakerState.OPEN;
+ impl.resetMillis.set(1000);
+ impl.lastFailure.set(System.currentTimeMillis() - 2000);
- @Test
- public void testGetStatusAfterHardTrip() {
- impl.tripHard();
- impl.resetMillis.set(1000);
- impl.lastFailure.set(System.currentTimeMillis() - 2000);
+ assertEquals(Status.DEGRADED, impl.getStatus());
+ assertEquals(CircuitBreaker.BreakerState.HALF_CLOSED, impl.state);
+ }
- assertEquals(Status.DOWN, impl.getStatus());
- }
+ @Test
+ public void testHalfClosedFailureOpensAgain() throws Exception {
- @Test
- public void testStatusIsByPassWhenSet() {
- impl.setByPassState(true);
- assertEquals(Status.DEGRADED, impl.getStatus());
- }
+ impl.state = CircuitBreaker.BreakerState.HALF_CLOSED;
+ impl.resetMillis.set(1000);
+ impl.lastFailure.set(System.currentTimeMillis() - 2000);
- @Test
- public void testByPassIgnoresCurrentBreakerStateWhenSet() {
- impl.state = CircuitBreaker.BreakerState.OPEN;
- assertEquals(Status.DOWN, impl.getStatus());
+ long start = System.currentTimeMillis();
- impl.setByPassState(true);
- assertEquals(Status.DEGRADED, impl.getStatus());
+ expect(mockCallable.call()).andThrow(new RuntimeException());
+ replay(mockCallable);
+
+ try {
+ impl.invoke(mockCallable);
+ fail("should have thrown exception");
+ } catch (RuntimeException expected) {
+ }
+
+ long end = System.currentTimeMillis();
+
+ verify(mockCallable);
+ assertEquals(CircuitBreaker.BreakerState.OPEN, impl.state);
+ assertTrue(impl.lastFailure.get() >= start);
+ assertTrue(impl.lastFailure.get() <= end);
+ }
+
+ @Test
+ public void testGetStatusNotUpdatingIsAttemptLive() throws Exception {
+
+ impl.resetMillis.set(50);
+ impl.trip();
+ assertEquals(CircuitBreaker.BreakerState.OPEN, impl.state);
+ assertEquals(false, impl.isAttemptLive);
+
+ Thread.sleep(200);
+
+ // The getStatus()->canAttempt() call also updated isAttemptLive to true
+ assertEquals(Status.DEGRADED.getValue(), impl.getStatus().getValue());
+ assertEquals(false, impl.isAttemptLive);
+ }
+
+ @Test
+ public void testManualTripAndReset() throws Exception {
+ impl.state = CircuitBreaker.BreakerState.OPEN;
+ final Object obj = new Object();
+ expect(mockCallable.call()).andReturn(obj);
+ replay(mockCallable);
+
+ impl.trip();
+ try {
+ impl.invoke(mockCallable);
+ fail("Manual trip method failed.");
+ } catch (CircuitBreakerException e) {
+ }
+
+ impl.reset();
+
+ Object result = impl.invoke(mockCallable);
+
+ verify(mockCallable);
+ assertSame(obj, result);
+ assertEquals(CircuitBreaker.BreakerState.CLOSED, impl.state);
+ }
+
+ @Test
+ public void testTripHard() throws Exception {
+ expect(mockCallable.call()).andReturn("hi");
+
+ replay(mockCallable);
+
+ impl.tripHard();
+ try {
+ impl.invoke(mockCallable);
+ fail("exception expected after CircuitBreaker.tripHard()");
+ } catch (CircuitBreakerException e) {
+ }
+ assertEquals(CircuitBreaker.BreakerState.OPEN, impl.state);
+
+ impl.reset();
+ impl.invoke(mockCallable);
+ assertEquals(CircuitBreaker.BreakerState.CLOSED, impl.state);
+
+ verify(mockCallable);
+ }
+
+ @Test
+ public void testGetTripCount() throws Exception {
+ long tripCount1 = impl.getTripCount();
+
+ impl.tripHard();
+ long tripCount2 = impl.getTripCount();
+ assertEquals(tripCount1 + 1, tripCount2);
+
+ impl.tripHard();
+ assertEquals(tripCount2, impl.getTripCount());
+ }
+
+ @Test
+ public void testGetStatusWhenOpen() {
+ impl.state = CircuitBreaker.BreakerState.OPEN;
+ Assert.assertEquals(Status.DOWN, impl.getStatus());
+ }
+
+ @Test
+ public void testGetStatusWhenHalfClosed() {
+ impl.state = CircuitBreaker.BreakerState.HALF_CLOSED;
+ assertEquals(Status.DEGRADED, impl.getStatus());
+ }
+
+ @Test
+ public void testGetStatusWhenOpenBeforeReset() {
+ impl.state = CircuitBreaker.BreakerState.CLOSED;
+ impl.resetMillis.set(1000);
+ impl.lastFailure.set(System.currentTimeMillis() - 50);
+
+ assertEquals(Status.UP, impl.getStatus());
+ }
+
+ @Test
+ public void testGetStatusWhenOpenAfterReset() {
+ impl.state = CircuitBreaker.BreakerState.OPEN;
+ impl.resetMillis.set(1000);
+ impl.lastFailure.set(System.currentTimeMillis() - 2000);
+
+ assertEquals(Status.DEGRADED, impl.getStatus());
+ }
+
+ @Test
+ public void testGetStatusAfterHardTrip() {
+ impl.tripHard();
+ impl.resetMillis.set(1000);
+ impl.lastFailure.set(System.currentTimeMillis() - 2000);
+
+ assertEquals(Status.DOWN, impl.getStatus());
+ }
+
+ @Test
+ public void testStatusIsByPassWhenSet() {
+ impl.setByPassState(true);
+ assertEquals(Status.DEGRADED, impl.getStatus());
+ }
+
+ @Test
+ public void testByPassIgnoresCurrentBreakerStateWhenSet() {
+ impl.state = CircuitBreaker.BreakerState.OPEN;
+ assertEquals(Status.DOWN, impl.getStatus());
- impl.setByPassState(false);
- assertEquals(Status.DOWN, impl.getStatus());
- }
+ impl.setByPassState(true);
+ assertEquals(Status.DEGRADED, impl.getStatus());
- @Test
- public void testByPassIgnoresBreakerStateAndCallsWrappedMethod() throws Exception {
- expect(mockCallable.call()).andReturn("hi").anyTimes();
+ impl.setByPassState(false);
+ assertEquals(Status.DOWN, impl.getStatus());
+ }
- replay(mockCallable);
+ @Test
+ public void testByPassIgnoresBreakerStateAndCallsWrappedMethod() throws Exception {
+ expect(mockCallable.call()).andReturn("hi").anyTimes();
- impl.tripHard();
- impl.setByPassState(true);
+ replay(mockCallable);
- try {
- impl.invoke(mockCallable);
- } catch (CircuitBreakerException e) {
- fail("exception not expected when CircuitBreaker is bypassed.");
- }
- assertEquals(CircuitBreaker.BreakerState.OPEN, impl.state);
- assertEquals(Status.DEGRADED, impl.getStatus());
+ impl.tripHard();
+ impl.setByPassState(true);
- impl.reset();
- impl.setByPassState(false);
- impl.invoke(mockCallable);
- assertEquals(CircuitBreaker.BreakerState.CLOSED, impl.state);
+ try {
+ impl.invoke(mockCallable);
+ } catch (CircuitBreakerException e) {
+ fail("exception not expected when CircuitBreaker is bypassed.");
+ }
+ assertEquals(CircuitBreaker.BreakerState.OPEN, impl.state);
+ assertEquals(Status.DEGRADED, impl.getStatus());
- verify(mockCallable);
- }
+ impl.reset();
+ impl.setByPassState(false);
+ impl.invoke(mockCallable);
+ assertEquals(CircuitBreaker.BreakerState.CLOSED, impl.state);
- @Test
- public void testNotificationCallback() throws Exception {
+ verify(mockCallable);
+ }
- CircuitBreakerNotificationCallback cb = new CircuitBreakerNotificationCallback() {
- public void notify(Status s) {
- theStatus = s;
- }
- };
+ @Test
+ public void testNotificationCallback() throws Exception {
- impl.addListener(cb);
- impl.trip();
+ CircuitBreakerNotificationCallback cb = new CircuitBreakerNotificationCallback() {
+ public void notify(Status s) {
+ theStatus = s;
+ }
+ };
- assertNotNull(theStatus);
- assertEquals(Status.DOWN, theStatus);
- }
+ impl.addListener(cb);
+ impl.trip();
- @Test(expected = Throwable.class)
- public void circuitBreakerKeepsExceptionThatTrippedIt() throws Throwable {
+ assertNotNull(theStatus);
+ assertEquals(Status.DOWN, theStatus);
+ }
- try {
- impl.invoke(new FailingCallable("broken"));
- } catch (Exception e) {
+ @Test(expected = Throwable.class)
+ public void circuitBreakerKeepsExceptionThatTrippedIt() throws Throwable {
- }
+ try {
+ impl.invoke(new FailingCallable("broken"));
+ } catch (Exception e) {
- Throwable tripException = impl.getTripException();
- assertEquals("broken", tripException.getMessage());
- throw tripException;
- }
+ }
- @Test(expected = Throwable.class)
- public void resetCircuitBreakerStillHasTripException() throws Throwable {
+ Throwable tripException = impl.getTripException();
+ assertEquals("broken", tripException.getMessage());
+ throw tripException;
+ }
- try {
- impl.invoke(new FailingCallable("broken"));
- } catch (Exception e) {
+ @Test(expected = Throwable.class)
+ public void resetCircuitBreakerStillHasTripException() throws Throwable {
- }
- impl.reset();
+ try {
+ impl.invoke(new FailingCallable("broken"));
+ } catch (Exception e) {
- Throwable tripException = impl.getTripException();
- assertEquals("broken", tripException.getMessage());
- throw tripException;
- }
+ }
+ impl.reset();
- @Test
- public void circuitBreakerReturnsExceptionAsString() {
+ Throwable tripException = impl.getTripException();
+ assertEquals("broken", tripException.getMessage());
+ throw tripException;
+ }
- try {
- impl.invoke(new FailingCallable("broken"));
- } catch (Exception e) {
+ @Test
+ public void circuitBreakerReturnsExceptionAsString() {
- }
+ try {
+ impl.invoke(new FailingCallable("broken"));
+ } catch (Exception e) {
- Throwable tripException = impl.getTripException();
+ }
- String s = impl.getTripExceptionAsString();
+ Throwable tripException = impl.getTripException();
- assertTrue(impl.getTripExceptionAsString().startsWith("java.lang.Exception: broken\n"));
- assertTrue(impl.getTripExceptionAsString().contains("at org.fishwife.jrugged.TestCircuitBreaker$FailingCallable.call"));
- assertTrue(impl.getTripExceptionAsString().contains("Caused by: java.lang.Exception: The Cause\n"));
- }
+ String s = impl.getTripExceptionAsString();
- @Test
- public void neverTrippedCircuitBreakerReturnsNullForTripException() throws Exception {
+ assertTrue(impl.getTripExceptionAsString().startsWith("java.lang.Exception: broken\n"));
+ assertTrue(impl.getTripExceptionAsString()
+ .contains("at org.fishwife.jrugged.TestCircuitBreaker$FailingCallable.call"));
+ assertTrue(impl.getTripExceptionAsString().contains("Caused by: java.lang.Exception: The Cause\n"));
+ }
- impl.invoke(mockCallable);
+ @Test
+ public void neverTrippedCircuitBreakerReturnsNullForTripException() throws Exception {
- Throwable tripException = impl.getTripException();
+ impl.invoke(mockCallable);
- assertNull(tripException);
- }
@Test
public void testSettingClockReturnsSameClockWhenRequested() {
@@ -455,17 +453,23 @@ public void testSettingClockReturnsSameClockWhenRequested() {
private class FailingCallable implements Callable {
- private final String exceptionMessage;
- public FailingCallable(String exceptionMessage) {
- this.exceptionMessage = exceptionMessage;
- }
+ assertNull(tripException);
+ }
- Exception causeException = new Exception("The Cause");
+ private class FailingCallable implements Callable {
- public Object call() throws Exception {
- throw new Exception(exceptionMessage, causeException);
- }
- }
+ private final String exceptionMessage;
+
+ public FailingCallable(String exceptionMessage) {
+ this.exceptionMessage = exceptionMessage;
+ }
+
+ Exception causeException = new Exception("The Cause");
+
+ public Object call() throws Exception {
+ throw new Exception(exceptionMessage, causeException);
+ }
+ }
}
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestCircuitBreakerFactory.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestCircuitBreakerFactory.java
index cc46a031..eca9db12 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestCircuitBreakerFactory.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestCircuitBreakerFactory.java
@@ -28,147 +28,141 @@
public class TestCircuitBreakerFactory {
- private CircuitBreakerFactory factory;
- private CircuitBreakerConfig config;
-
- private static final int TEST_LIMIT = 5;
- private static final long TEST_WINDOW_MILLIS = 30000L;
- private static final long TEST_RESET_MILLIS = 10000L;
-
- @Before
- public void setUp() {
- factory = new CircuitBreakerFactory();
- config = new CircuitBreakerConfig(TEST_RESET_MILLIS,
- new DefaultFailureInterpreter(TEST_LIMIT, TEST_WINDOW_MILLIS));
- }
-
- @Test
- public void testCreateCircuitBreaker() {
- CircuitBreaker breaker = factory.createCircuitBreaker("testCreate", config);
- checkBreaker(breaker, TEST_LIMIT, TEST_WINDOW_MILLIS, TEST_RESET_MILLIS);
- }
-
- @Test
- public void testCreateDuplicateCircuitBreaker() {
- String name = "testCreate";
- CircuitBreaker createdBreaker = factory.createCircuitBreaker(name, config);
- CircuitBreaker secondBreaker = factory.createCircuitBreaker(name, config);
-
- assertSame(createdBreaker, secondBreaker);
- checkBreaker(createdBreaker, TEST_LIMIT, TEST_WINDOW_MILLIS, TEST_RESET_MILLIS);
- }
-
- @Test
- public void testCreateCircuitBreakerEmptyConfig() {
- CircuitBreakerConfig emptyConfig =
- new CircuitBreakerConfig(-1, new DefaultFailureInterpreter());
- CircuitBreaker breaker = factory.createCircuitBreaker("testCreateEmpty", emptyConfig);
-
- checkBreaker(breaker, 0, 0, 15000L); // These are the CircuitBreaker Defaults.
- }
-
- @Test
- public void testCreateCircuitBreakerNullFailureInterpreter() {
- CircuitBreakerConfig emptyConfig =
- new CircuitBreakerConfig(-1, null);
- CircuitBreaker breaker = factory.createCircuitBreaker("testCreateEmpty", emptyConfig);
-
- checkBreakerNoFailureInterpreter(breaker, 15000L); // These are the CircuitBreaker Defaults.
- }
-
- @Test
- public void testFindANamedCircuitBreaker() {
- String monitorName = "testFind";
- CircuitBreaker createdBreaker = factory.createCircuitBreaker(monitorName, config);
- CircuitBreaker foundBreaker = factory.findCircuitBreaker(monitorName);
- assertEquals(createdBreaker, foundBreaker);
- }
-
- @Test
- public void testFindNonExistentCircuitBreaker() {
- CircuitBreaker foundBreaker = factory.findCircuitBreaker("testNonExistent");
- assertNull(foundBreaker);
- }
-
- @Test
- public void testGetCircuitBreakerNames() {
- Set testSet = new HashSet();
- testSet.add("one");
- testSet.add("two");
- testSet.add("three");
- testSet.add("four");
-
- factory.createCircuitBreaker("one", config);
- factory.createCircuitBreaker("two", config);
- factory.createCircuitBreaker("three", config);
- factory.createCircuitBreaker("four", config);
- Set monitorNames = factory.getCircuitBreakerNames();
- assertEquals(testSet, monitorNames);
- }
-
- @Test
- public void testEmptyPropertyOverrides() {
- Properties overrideProperties = new Properties();
- factory.setProperties(overrideProperties);
- CircuitBreaker breaker = factory.createCircuitBreaker("emptyOverrides", config);
- checkBreaker(breaker, TEST_LIMIT, TEST_WINDOW_MILLIS, TEST_RESET_MILLIS);
- }
-
- @Test
- public void testPropertyOverrides() {
- Properties overrideProperties = new Properties();
- Integer overrideLimit = 10;
- Long overrideResetMillis = 50000L;
- Long overrideWindowMillis = 500000L;
- String name = "testOverrides";
-
- overrideProperties.put("circuit." + name + ".limit", overrideLimit.toString());
- overrideProperties.put("circuit." + name + ".resetMillis", overrideResetMillis.toString());
- overrideProperties.put("circuit." + name + ".windowMillis", overrideWindowMillis.toString());
- factory.setProperties(overrideProperties);
-
- CircuitBreaker breaker = factory.createCircuitBreaker(name, config);
- checkBreaker(breaker, overrideLimit, overrideWindowMillis, overrideResetMillis);
- }
-
- @Test
- public void testInvalidPropertyOverrides() {
- Properties overrideProperties = new Properties();
- String name = "testOverrides";
-
- overrideProperties.put("circuit." + name + ".limit", "badLimit");
- overrideProperties.put("circuit." + name + ".resetMillis", "badResetMillis");
- overrideProperties.put("circuit." + name + ".windowMillis", "badWindowMillis");
- factory.setProperties(overrideProperties);
-
- CircuitBreakerConfig emptyConfig =
- new CircuitBreakerConfig(-1, new DefaultFailureInterpreter());
- CircuitBreaker breaker = factory.createCircuitBreaker(name, emptyConfig);
- checkBreaker(breaker, 0, 0L, 15000L); // These are the CircuitBreaker defaults.
- assertNotNull(breaker);
- }
-
- private void checkBreaker(CircuitBreaker breaker,
- int expectedLimit,
- long expectedWindowMillis,
- long expectedResetMillis) {
-
- assertNotNull(breaker);
-
- DefaultFailureInterpreter failureInterpreter = (DefaultFailureInterpreter)breaker.getFailureInterpreter();
-
- if (failureInterpreter != null) {
- assertEquals(failureInterpreter.getLimit(), expectedLimit);
- assertEquals(failureInterpreter.getWindowMillis(), expectedWindowMillis);
- }
-
- assertEquals(breaker.getResetMillis(), expectedResetMillis);
- }
-
- private void checkBreakerNoFailureInterpreter(CircuitBreaker breaker,
- long expectedResetMillis) {
-
- assertNotNull(breaker);
- assertEquals(breaker.getResetMillis(), expectedResetMillis);
- }
+ private CircuitBreakerFactory factory;
+ private CircuitBreakerConfig config;
+
+ private static final int TEST_LIMIT = 5;
+ private static final long TEST_WINDOW_MILLIS = 30000L;
+ private static final long TEST_RESET_MILLIS = 10000L;
+
+ @Before
+ public void setUp() {
+ factory = new CircuitBreakerFactory();
+ config = new CircuitBreakerConfig(TEST_RESET_MILLIS,
+ new DefaultFailureInterpreter(TEST_LIMIT, TEST_WINDOW_MILLIS));
+ }
+
+ @Test
+ public void testCreateCircuitBreaker() {
+ CircuitBreaker breaker = factory.createCircuitBreaker("testCreate", config);
+ checkBreaker(breaker, TEST_LIMIT, TEST_WINDOW_MILLIS, TEST_RESET_MILLIS);
+ }
+
+ @Test
+ public void testCreateDuplicateCircuitBreaker() {
+ String name = "testCreate";
+ CircuitBreaker createdBreaker = factory.createCircuitBreaker(name, config);
+ CircuitBreaker secondBreaker = factory.createCircuitBreaker(name, config);
+
+ assertSame(createdBreaker, secondBreaker);
+ checkBreaker(createdBreaker, TEST_LIMIT, TEST_WINDOW_MILLIS, TEST_RESET_MILLIS);
+ }
+
+ @Test
+ public void testCreateCircuitBreakerEmptyConfig() {
+ CircuitBreakerConfig emptyConfig = new CircuitBreakerConfig(-1, new DefaultFailureInterpreter());
+ CircuitBreaker breaker = factory.createCircuitBreaker("testCreateEmpty", emptyConfig);
+
+ checkBreaker(breaker, 0, 0, 15000L); // These are the CircuitBreaker Defaults.
+ }
+
+ @Test
+ public void testCreateCircuitBreakerNullFailureInterpreter() {
+ CircuitBreakerConfig emptyConfig = new CircuitBreakerConfig(-1, null);
+ CircuitBreaker breaker = factory.createCircuitBreaker("testCreateEmpty", emptyConfig);
+
+ checkBreakerNoFailureInterpreter(breaker, 15000L); // These are the CircuitBreaker Defaults.
+ }
+
+ @Test
+ public void testFindANamedCircuitBreaker() {
+ String monitorName = "testFind";
+ CircuitBreaker createdBreaker = factory.createCircuitBreaker(monitorName, config);
+ CircuitBreaker foundBreaker = factory.findCircuitBreaker(monitorName);
+ assertEquals(createdBreaker, foundBreaker);
+ }
+
+ @Test
+ public void testFindNonExistentCircuitBreaker() {
+ CircuitBreaker foundBreaker = factory.findCircuitBreaker("testNonExistent");
+ assertNull(foundBreaker);
+ }
+
+ @Test
+ public void testGetCircuitBreakerNames() {
+ Set testSet = new HashSet();
+ testSet.add("one");
+ testSet.add("two");
+ testSet.add("three");
+ testSet.add("four");
+
+ factory.createCircuitBreaker("one", config);
+ factory.createCircuitBreaker("two", config);
+ factory.createCircuitBreaker("three", config);
+ factory.createCircuitBreaker("four", config);
+ Set monitorNames = factory.getCircuitBreakerNames();
+ assertEquals(testSet, monitorNames);
+ }
+
+ @Test
+ public void testEmptyPropertyOverrides() {
+ Properties overrideProperties = new Properties();
+ factory.setProperties(overrideProperties);
+ CircuitBreaker breaker = factory.createCircuitBreaker("emptyOverrides", config);
+ checkBreaker(breaker, TEST_LIMIT, TEST_WINDOW_MILLIS, TEST_RESET_MILLIS);
+ }
+
+ @Test
+ public void testPropertyOverrides() {
+ Properties overrideProperties = new Properties();
+ Integer overrideLimit = 10;
+ Long overrideResetMillis = 50000L;
+ Long overrideWindowMillis = 500000L;
+ String name = "testOverrides";
+
+ overrideProperties.put("circuit." + name + ".limit", overrideLimit.toString());
+ overrideProperties.put("circuit." + name + ".resetMillis", overrideResetMillis.toString());
+ overrideProperties.put("circuit." + name + ".windowMillis", overrideWindowMillis.toString());
+ factory.setProperties(overrideProperties);
+
+ CircuitBreaker breaker = factory.createCircuitBreaker(name, config);
+ checkBreaker(breaker, overrideLimit, overrideWindowMillis, overrideResetMillis);
+ }
+
+ @Test
+ public void testInvalidPropertyOverrides() {
+ Properties overrideProperties = new Properties();
+ String name = "testOverrides";
+
+ overrideProperties.put("circuit." + name + ".limit", "badLimit");
+ overrideProperties.put("circuit." + name + ".resetMillis", "badResetMillis");
+ overrideProperties.put("circuit." + name + ".windowMillis", "badWindowMillis");
+ factory.setProperties(overrideProperties);
+
+ CircuitBreakerConfig emptyConfig = new CircuitBreakerConfig(-1, new DefaultFailureInterpreter());
+ CircuitBreaker breaker = factory.createCircuitBreaker(name, emptyConfig);
+ checkBreaker(breaker, 0, 0L, 15000L); // These are the CircuitBreaker defaults.
+ assertNotNull(breaker);
+ }
+
+ private void checkBreaker(CircuitBreaker breaker, int expectedLimit, long expectedWindowMillis,
+ long expectedResetMillis) {
+
+ assertNotNull(breaker);
+
+ DefaultFailureInterpreter failureInterpreter = (DefaultFailureInterpreter) breaker.getFailureInterpreter();
+
+ if (failureInterpreter != null) {
+ assertEquals(failureInterpreter.getLimit(), expectedLimit);
+ assertEquals(failureInterpreter.getWindowMillis(), expectedWindowMillis);
+ }
+
+ assertEquals(breaker.getResetMillis(), expectedResetMillis);
+ }
+
+ private void checkBreakerNoFailureInterpreter(CircuitBreaker breaker, long expectedResetMillis) {
+
+ assertNotNull(breaker);
+ assertEquals(breaker.getResetMillis(), expectedResetMillis);
+ }
}
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestConstantFlowRegulator.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestConstantFlowRegulator.java
index 5081f961..67badc6d 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestConstantFlowRegulator.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestConstantFlowRegulator.java
@@ -30,99 +30,99 @@
import static org.junit.Assert.assertTrue;
public class TestConstantFlowRegulator {
- private ConstantFlowRegulator impl;
- private Callable mockCallable;
- private Runnable mockRunnable;
-
- @SuppressWarnings("unchecked")
- @Before
- public void setUp() {
- impl = new ConstantFlowRegulator();
- mockCallable = createMock(Callable.class);
- mockRunnable = createMock(Runnable.class);
- }
-
- @Test
- public void testConfiguration() {
- impl.setRequestPerSecondThreshold(50);
-
- assertEquals(50, impl.getRequestPerSecondThreshold());
- }
-
- @Test
- public void testRPSThresholdDefault() {
- assertEquals(-1, impl.getRequestPerSecondThreshold());
- }
-
- @Test
- public void testFlowThrottlerCanProceedWhenThresholdIsDefault() {
- assertTrue(impl.canProceed());
- }
-
- @Test
- public void testCanProceedWhenThresholdLessThanConfigured() {
- impl.setRequestPerSecondThreshold(50);
-
- assertTrue(impl.canProceed());
- }
-
- @Test (expected=Exception.class)
- public void testThrowsExceptionWhenCallableCanNotProceed() throws Exception {
- final Object obj = new Object();
-
- expect(mockCallable.call()).andReturn(obj);
- expectLastCall().anyTimes();
- replay(mockCallable);
-
- impl.setRequestPerSecondThreshold(1);
-
- for (int i = 0; i < 5; i++) {
- try {
- impl.invoke(mockCallable);
- }
- catch (FlowRateExceededException e) {
- System.out.println(e.getMessage());
- //Ignore these
- }
- }
-
- impl.invoke(mockCallable);
-
- verify(mockCallable);
- }
-
- public class DomainException extends Exception {}
-
- public class TestConstantFlowRegulatorExceptionMapper
- implements ConstantFlowRegulatorExceptionMapper {
- public DomainException map(ConstantFlowRegulator flowRegulator, FlowRateExceededException e) {
- return new DomainException();
- }
- }
-
- @Test (expected=DomainException.class)
- public void testThrowsMappedExceptionWhenCanNotProceed() throws Exception {
- impl.setRequestPerSecondThreshold(1);
- impl.setExceptionMapper(new TestConstantFlowRegulatorExceptionMapper());
- for (int i = 0; i < 5; i++) {
- impl.invoke(mockCallable);
- }
- }
-
- @Test (expected=Exception.class)
- public void testThrowsExceptionWhenRunnableCanNotProceed() throws Exception {
- impl.setRequestPerSecondThreshold(1);
- for (int i = 0; i < 5; i++) {
- impl.invoke(mockRunnable);
- }
- }
-
- @Test (expected=DomainException.class)
- public void testThrowsMappedExceptionWhenCanNotProceedViaConstructor() throws Exception {
- ConstantFlowRegulator impl = new ConstantFlowRegulator(1, new TestConstantFlowRegulatorExceptionMapper());
- for (int i = 0; i < 5; i++) {
- impl.invoke(mockCallable);
- }
- }
+ private ConstantFlowRegulator impl;
+ private Callable mockCallable;
+ private Runnable mockRunnable;
+
+ @SuppressWarnings("unchecked")
+ @Before
+ public void setUp() {
+ impl = new ConstantFlowRegulator();
+ mockCallable = createMock(Callable.class);
+ mockRunnable = createMock(Runnable.class);
+ }
+
+ @Test
+ public void testConfiguration() {
+ impl.setRequestPerSecondThreshold(50);
+
+ assertEquals(50, impl.getRequestPerSecondThreshold());
+ }
+
+ @Test
+ public void testRPSThresholdDefault() {
+ assertEquals(-1, impl.getRequestPerSecondThreshold());
+ }
+
+ @Test
+ public void testFlowThrottlerCanProceedWhenThresholdIsDefault() {
+ assertTrue(impl.canProceed());
+ }
+
+ @Test
+ public void testCanProceedWhenThresholdLessThanConfigured() {
+ impl.setRequestPerSecondThreshold(50);
+
+ assertTrue(impl.canProceed());
+ }
+
+ @Test(expected = Exception.class)
+ public void testThrowsExceptionWhenCallableCanNotProceed() throws Exception {
+ final Object obj = new Object();
+
+ expect(mockCallable.call()).andReturn(obj);
+ expectLastCall().anyTimes();
+ replay(mockCallable);
+
+ impl.setRequestPerSecondThreshold(1);
+
+ for (int i = 0; i < 5; i++) {
+ try {
+ impl.invoke(mockCallable);
+ } catch (FlowRateExceededException e) {
+ System.out.println(e.getMessage());
+ // Ignore these
+ }
+ }
+
+ impl.invoke(mockCallable);
+
+ verify(mockCallable);
+ }
+
+ public class DomainException extends Exception {
+ }
+
+ public class TestConstantFlowRegulatorExceptionMapper
+ implements ConstantFlowRegulatorExceptionMapper {
+ public DomainException map(ConstantFlowRegulator flowRegulator, FlowRateExceededException e) {
+ return new DomainException();
+ }
+ }
+
+ @Test(expected = DomainException.class)
+ public void testThrowsMappedExceptionWhenCanNotProceed() throws Exception {
+ impl.setRequestPerSecondThreshold(1);
+ impl.setExceptionMapper(new TestConstantFlowRegulatorExceptionMapper());
+ for (int i = 0; i < 5; i++) {
+ impl.invoke(mockCallable);
+ }
+ }
+
+ @Test(expected = Exception.class)
+ public void testThrowsExceptionWhenRunnableCanNotProceed() throws Exception {
+ impl.setRequestPerSecondThreshold(1);
+ for (int i = 0; i < 5; i++) {
+ impl.invoke(mockRunnable);
+ }
+ }
+
+ @Test(expected = DomainException.class)
+ public void testThrowsMappedExceptionWhenCanNotProceedViaConstructor() throws Exception {
+ ConstantFlowRegulator impl = new ConstantFlowRegulator(1, new TestConstantFlowRegulatorExceptionMapper());
+ for (int i = 0; i < 5; i++) {
+ impl.invoke(mockCallable);
+ }
+ }
}
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestDefaultFailureInterpreter.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestDefaultFailureInterpreter.java
index 60fce7ee..43e7e352 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestDefaultFailureInterpreter.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestDefaultFailureInterpreter.java
@@ -24,95 +24,95 @@
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
-public final class TestDefaultFailureInterpreter{
-
- private DefaultFailureInterpreter impl;
-
- @Before
- public void setUp() {
- impl = new DefaultFailureInterpreter();
- }
-
- // constructor tests
- @Test
- public void testDefaultConstructor() {
-
- assertEquals(0, impl.getLimit());
- assertEquals(0, impl.getWindowMillis());
-
- assertEquals(0, impl.getIgnore().size());
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Test
- public void testConstructorWithIgnore() {
- final Class exnClass = RuntimeException.class;
- final Class[] myIgnore = { exnClass };
-
- impl = new DefaultFailureInterpreter(myIgnore);
-
- assertEquals(0, impl.getLimit());
- assertEquals(0, impl.getWindowMillis());
-
- assertEquals(1, impl.getIgnore().size());
- for(Class clazz : impl.getIgnore()) {
- assertSame(clazz, exnClass);
- }
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Test
- public void testConstructorWithIgnoreAndTolerance() {
- final Class exnClass = RuntimeException.class;
- final Class[] myIgnore = { exnClass };
- final int frequency = 7777;
- final long time = 1234L;
-
- impl = new DefaultFailureInterpreter(myIgnore, frequency, time);
-
- assertEquals(frequency, impl.getLimit());
- assertEquals(time, impl.getWindowMillis());
-
- assertEquals(1, impl.getIgnore().size());
- for(Class clazz : impl.getIgnore()) {
- assertSame(clazz, exnClass);
- }
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Test
- public void testIgnoredExceptionDoesNotTrip() {
- final Class ignoreClass = IOException.class;
- final Class[] myIgnore = { ignoreClass };
-
- impl.setIgnore(myIgnore);
- assertFalse(impl.shouldTrip(new IOException()));
- }
-
- @Test
- public void testAnyExceptionTripsByDefault() {
- assertTrue(impl.shouldTrip(new IOException()));
- }
-
- @Test
- public void testDoesntTripIfFailuresAreWithinTolerance() {
- impl.setLimit(2);
- impl.setWindowMillis(1000);
- Exception exn1 = new Exception();
- Exception exn2 = new Exception();
- boolean result = impl.shouldTrip(exn1);
- assertFalse("this should be false 1",result);
- result = impl.shouldTrip(exn2);
- assertFalse("this should be false 2",result);
- }
-
- @Test
- public void testTripsIfFailuresExceedTolerance() {
- impl.setLimit(2);
- impl.setWindowMillis(1000);
- assertFalse("this should be false 1",impl.shouldTrip(new Exception()));
- assertFalse("this should be false 2",impl.shouldTrip(new Exception()));
- assertTrue("this should be true 3",impl.shouldTrip(new Exception()));
- }
+public final class TestDefaultFailureInterpreter {
+
+ private DefaultFailureInterpreter impl;
+
+ @Before
+ public void setUp() {
+ impl = new DefaultFailureInterpreter();
+ }
+
+ // constructor tests
+ @Test
+ public void testDefaultConstructor() {
+
+ assertEquals(0, impl.getLimit());
+ assertEquals(0, impl.getWindowMillis());
+
+ assertEquals(0, impl.getIgnore().size());
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ @Test
+ public void testConstructorWithIgnore() {
+ final Class exnClass = RuntimeException.class;
+ final Class[] myIgnore = { exnClass };
+
+ impl = new DefaultFailureInterpreter(myIgnore);
+
+ assertEquals(0, impl.getLimit());
+ assertEquals(0, impl.getWindowMillis());
+
+ assertEquals(1, impl.getIgnore().size());
+ for (Class clazz : impl.getIgnore()) {
+ assertSame(clazz, exnClass);
+ }
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ @Test
+ public void testConstructorWithIgnoreAndTolerance() {
+ final Class exnClass = RuntimeException.class;
+ final Class[] myIgnore = { exnClass };
+ final int frequency = 7777;
+ final long time = 1234L;
+
+ impl = new DefaultFailureInterpreter(myIgnore, frequency, time);
+
+ assertEquals(frequency, impl.getLimit());
+ assertEquals(time, impl.getWindowMillis());
+
+ assertEquals(1, impl.getIgnore().size());
+ for (Class clazz : impl.getIgnore()) {
+ assertSame(clazz, exnClass);
+ }
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ @Test
+ public void testIgnoredExceptionDoesNotTrip() {
+ final Class ignoreClass = IOException.class;
+ final Class[] myIgnore = { ignoreClass };
+
+ impl.setIgnore(myIgnore);
+ assertFalse(impl.shouldTrip(new IOException()));
+ }
+
+ @Test
+ public void testAnyExceptionTripsByDefault() {
+ assertTrue(impl.shouldTrip(new IOException()));
+ }
+
+ @Test
+ public void testDoesntTripIfFailuresAreWithinTolerance() {
+ impl.setLimit(2);
+ impl.setWindowMillis(1000);
+ Exception exn1 = new Exception();
+ Exception exn2 = new Exception();
+ boolean result = impl.shouldTrip(exn1);
+ assertFalse("this should be false 1", result);
+ result = impl.shouldTrip(exn2);
+ assertFalse("this should be false 2", result);
+ }
+
+ @Test
+ public void testTripsIfFailuresExceedTolerance() {
+ impl.setLimit(2);
+ impl.setWindowMillis(1000);
+ assertFalse("this should be false 1", impl.shouldTrip(new Exception()));
+ assertFalse("this should be false 2", impl.shouldTrip(new Exception()));
+ assertTrue("this should be true 3", impl.shouldTrip(new Exception()));
+ }
}
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestFailureInterpreter.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestFailureInterpreter.java
index f2012e8c..e2af75a8 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestFailureInterpreter.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestFailureInterpreter.java
@@ -27,54 +27,55 @@
public final class TestFailureInterpreter {
- @SuppressWarnings("unchecked")
- @Test
- public void testAcceptableException() throws Exception {
- final RuntimeException theExn = new RuntimeException();
- final Callable callable = createMock(Callable.class);
- final FailureInterpreter interpreter = createMock(FailureInterpreter.class);
- final CircuitBreaker cb = new CircuitBreaker(interpreter);
-
- expect(callable.call()).andThrow(theExn);
- expect(interpreter.shouldTrip(theExn)).andReturn(false);
-
- replay(callable);
- replay(interpreter);
-
- try {
- cb.invoke(callable);
- fail("exception expected.");
- } catch (Exception e) {}
-
- assertEquals("Status should be UP", Status.UP, cb.getStatus());
- verify(callable);
- verify(interpreter);
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void testUnacceptableException() throws Exception {
- final RuntimeException theExn = new RuntimeException();
- final Callable callable = createMock(Callable.class);
- final FailureInterpreter interpreter = createMock(FailureInterpreter.class);
- final CircuitBreaker cb = new CircuitBreaker(interpreter);
-
- expect(callable.call()).andThrow(theExn);
- expect(interpreter.shouldTrip(theExn))
- .andReturn(true);
-
- replay(callable);
- replay(interpreter);
-
- try {
- cb.invoke(callable);
- fail("exception expected.");
- } catch (Exception e) {}
-
- verify(callable);
- verify(interpreter);
-
- assertEquals("Status should be DOWN", Status.DOWN, cb.getStatus());
- }
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testAcceptableException() throws Exception {
+ final RuntimeException theExn = new RuntimeException();
+ final Callable callable = createMock(Callable.class);
+ final FailureInterpreter interpreter = createMock(FailureInterpreter.class);
+ final CircuitBreaker cb = new CircuitBreaker(interpreter);
+
+ expect(callable.call()).andThrow(theExn);
+ expect(interpreter.shouldTrip(theExn)).andReturn(false);
+
+ replay(callable);
+ replay(interpreter);
+
+ try {
+ cb.invoke(callable);
+ fail("exception expected.");
+ } catch (Exception e) {
+ }
+
+ assertEquals("Status should be UP", Status.UP, cb.getStatus());
+ verify(callable);
+ verify(interpreter);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testUnacceptableException() throws Exception {
+ final RuntimeException theExn = new RuntimeException();
+ final Callable callable = createMock(Callable.class);
+ final FailureInterpreter interpreter = createMock(FailureInterpreter.class);
+ final CircuitBreaker cb = new CircuitBreaker(interpreter);
+
+ expect(callable.call()).andThrow(theExn);
+ expect(interpreter.shouldTrip(theExn)).andReturn(true);
+
+ replay(callable);
+ replay(interpreter);
+
+ try {
+ cb.invoke(callable);
+ fail("exception expected.");
+ } catch (Exception e) {
+ }
+
+ verify(callable);
+ verify(interpreter);
+
+ assertEquals("Status should be DOWN", Status.DOWN, cb.getStatus());
+ }
}
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestInitializer.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestInitializer.java
index f3497431..c8c51822 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestInitializer.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestInitializer.java
@@ -28,97 +28,97 @@
import static org.junit.Assert.assertTrue;
public class TestInitializer {
- private Initializable mockClient;
- private Initializer impl;
-
- @Before
- public void setUp() {
- mockClient = createMock(Initializable.class);
- impl = new Initializer(mockClient);
- }
-
- @Test
- public void testFirstTimeTrial() throws Exception {
- mockClient.tryInit();
- mockClient.afterInit();
- replay(mockClient);
-
- impl.initialize();
- Thread.sleep(5);
-
- verify(mockClient);
- assertTrue(impl.isInitialized());
- assertFalse(impl.isCancelled());
- assertEquals(1, impl.getNumAttempts());
- }
-
- public void testThirdTimesACharm() throws Exception {
- mockClient.tryInit();
- expectLastCall().andThrow(new RuntimeException()).times(2);
- mockClient.tryInit();
- mockClient.afterInit();
- replay(mockClient);
-
- impl.setRetryMillis(1);
- impl.initialize();
- Thread.sleep(5);
-
- assertTrue(impl.isInitialized());
- assertFalse(impl.isCancelled());
- assertEquals(3, impl.getNumAttempts());
- verify(mockClient);
- }
-
- @Test
- public void testExceededRetries() throws Exception {
- mockClient.tryInit();
- expectLastCall().andThrow(new RuntimeException()).times(2);
- replay(mockClient);
-
- impl.setMaxRetries(2);
- impl.setRetryMillis(30);
- impl.initialize();
- Thread.sleep(100);
-
- assertFalse(impl.isInitialized());
- assertFalse(impl.isCancelled());
- assertEquals(2, impl.getNumAttempts());
- verify(mockClient);
- }
-
- @Test
- public void testExceededRetriesAndCallbackTriggeredSuccessfully() throws Exception {
- mockClient.tryInit();
- expectLastCall().andThrow(new RuntimeException()).times(2);
-
- mockClient.configuredRetriesMetOrExceededWithoutSuccess();
- replay(mockClient);
-
- impl.setMaxRetries(2);
- impl.setRetryMillis(3);
- impl.initialize();
- Thread.sleep(10);
-
- assertFalse(impl.isInitialized());
- assertFalse(impl.isCancelled());
- assertEquals(2, impl.getNumAttempts());
- verify(mockClient);
- }
-
- @Test
- public void testCancellation() throws Exception {
- mockClient.tryInit();
- expectLastCall().andThrow(new RuntimeException());
- replay(mockClient);
-
- impl.initialize();
- Thread.sleep(1);
- impl.destroy();
-
- assertFalse(impl.isInitialized());
- assertTrue(impl.isCancelled());
- assertEquals(1, impl.getNumAttempts());
- verify(mockClient);
- }
+ private Initializable mockClient;
+ private Initializer impl;
+
+ @Before
+ public void setUp() {
+ mockClient = createMock(Initializable.class);
+ impl = new Initializer(mockClient);
+ }
+
+ @Test
+ public void testFirstTimeTrial() throws Exception {
+ mockClient.tryInit();
+ mockClient.afterInit();
+ replay(mockClient);
+
+ impl.initialize();
+ Thread.sleep(5);
+
+ verify(mockClient);
+ assertTrue(impl.isInitialized());
+ assertFalse(impl.isCancelled());
+ assertEquals(1, impl.getNumAttempts());
+ }
+
+ public void testThirdTimesACharm() throws Exception {
+ mockClient.tryInit();
+ expectLastCall().andThrow(new RuntimeException()).times(2);
+ mockClient.tryInit();
+ mockClient.afterInit();
+ replay(mockClient);
+
+ impl.setRetryMillis(1);
+ impl.initialize();
+ Thread.sleep(5);
+
+ assertTrue(impl.isInitialized());
+ assertFalse(impl.isCancelled());
+ assertEquals(3, impl.getNumAttempts());
+ verify(mockClient);
+ }
+
+ @Test
+ public void testExceededRetries() throws Exception {
+ mockClient.tryInit();
+ expectLastCall().andThrow(new RuntimeException()).times(2);
+ replay(mockClient);
+
+ impl.setMaxRetries(2);
+ impl.setRetryMillis(30);
+ impl.initialize();
+ Thread.sleep(100);
+
+ assertFalse(impl.isInitialized());
+ assertFalse(impl.isCancelled());
+ assertEquals(2, impl.getNumAttempts());
+ verify(mockClient);
+ }
+
+ @Test
+ public void testExceededRetriesAndCallbackTriggeredSuccessfully() throws Exception {
+ mockClient.tryInit();
+ expectLastCall().andThrow(new RuntimeException()).times(2);
+
+ mockClient.configuredRetriesMetOrExceededWithoutSuccess();
+ replay(mockClient);
+
+ impl.setMaxRetries(2);
+ impl.setRetryMillis(3);
+ impl.initialize();
+ Thread.sleep(10);
+
+ assertFalse(impl.isInitialized());
+ assertFalse(impl.isCancelled());
+ assertEquals(2, impl.getNumAttempts());
+ verify(mockClient);
+ }
+
+ @Test
+ public void testCancellation() throws Exception {
+ mockClient.tryInit();
+ expectLastCall().andThrow(new RuntimeException());
+ replay(mockClient);
+
+ impl.initialize();
+ Thread.sleep(1);
+ impl.destroy();
+
+ assertFalse(impl.isInitialized());
+ assertTrue(impl.isCancelled());
+ assertEquals(1, impl.getNumAttempts());
+ verify(mockClient);
+ }
}
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestLatencyTracker.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestLatencyTracker.java
index 3bdf7e24..4e515f0f 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestLatencyTracker.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestLatencyTracker.java
@@ -27,45 +27,44 @@
import static org.junit.Assert.fail;
public class TestLatencyTracker {
- private LatencyTracker impl;
+ private LatencyTracker impl;
- @Before
- public void setUp() {
- impl = new LatencyTracker();
- }
+ @Before
+ public void setUp() {
+ impl = new LatencyTracker();
+ }
- @Test
- public void testCallableSuccess() throws Exception {
- final Object o = new Object();
+ @Test
+ public void testCallableSuccess() throws Exception {
+ final Object o = new Object();
- Object result = impl.invoke(new Callable() {
- public Object call() throws Exception {
- Thread.sleep(1);
- return o;
- }
- });
+ Object result = impl.invoke(new Callable() {
+ public Object call() throws Exception {
+ Thread.sleep(1);
+ return o;
+ }
+ });
- assertSame(result, o);
- assertTrue(impl.getLastSuccessMillis() > 0);
- assertEquals(0, impl.getLastFailureMillis());
- }
+ assertSame(result, o);
+ assertTrue(impl.getLastSuccessMillis() > 0);
+ assertEquals(0, impl.getLastFailureMillis());
+ }
- @Test
- public void testCallableFailure() throws Exception {
+ @Test
+ public void testCallableFailure() throws Exception {
- try {
- impl.invoke(new Callable() {
- public Object call() throws Exception {
- Thread.sleep(1);
- throw new Exception();
- }
- });
- fail("should have thrown exception");
- }
- catch (Exception expected) {
- }
+ try {
+ impl.invoke(new Callable() {
+ public Object call() throws Exception {
+ Thread.sleep(1);
+ throw new Exception();
+ }
+ });
+ fail("should have thrown exception");
+ } catch (Exception expected) {
+ }
- assertTrue(impl.getLastFailureMillis() > 0);
- assertEquals(0, impl.getLastSuccessMillis());
- }
+ assertTrue(impl.getLastFailureMillis() > 0);
+ assertEquals(0, impl.getLastSuccessMillis());
+ }
}
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestPercentErrPerTimeFailureInterpreter.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestPercentErrPerTimeFailureInterpreter.java
index bb72cc8c..27a8fc5a 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestPercentErrPerTimeFailureInterpreter.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestPercentErrPerTimeFailureInterpreter.java
@@ -23,283 +23,264 @@
public class TestPercentErrPerTimeFailureInterpreter {
- private class DummyRunnable implements Runnable {
-
- public void run() {
-
- }
- }
-
- private class DummyRunnableException implements Runnable {
-
- public void run() {
- throw new RuntimeException();
- }
- }
-
- private class DummyMyRunnableException implements Runnable {
-
- public void run() {
- throw new MyRuntimeException();
- }
- }
-
- private class MyRuntimeException extends RuntimeException {
-
- }
-
- @Test
- public void testTripsWhenNoWindowConditionsExist() {
- PercentErrPerTimeFailureInterpreter pept = new PercentErrPerTimeFailureInterpreter();
-
- assertTrue(pept.shouldTrip(new Exception()));
- }
-
- @Test
- @SuppressWarnings("unchecked")
- public void testDoesNotTripWhenExceptionIsIgnored() {
- PercentErrPerTimeFailureInterpreter pept = new PercentErrPerTimeFailureInterpreter();
- pept.setIgnore(new Class[] {MyRuntimeException.class});
-
- assertFalse(pept.shouldTrip(new MyRuntimeException()));
- assertTrue(pept.shouldTrip(new Exception()));
- }
-
- @Test
- public void testTripsWhenPercentErrorInWindowIsGreaterThanConfigured() throws Exception {
- PercentErrPerTimeFailureInterpreter pept = new PercentErrPerTimeFailureInterpreter();
- RequestCounter rc = new RequestCounter();
- pept.setRequestCounter(rc);
- pept.setPercent(51);
- pept.setWindowMillis(5000);
-
- try {
- rc.invoke(new DummyRunnable());
- rc.invoke(new DummyRunnable());
- rc.invoke(new DummyRunnable());
- }
- catch (Exception e) {
- pept.shouldTrip(e);
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertTrue(pept.shouldTrip(e));
- }
- }
-
- @Test
- public void testTripsWhenPercentErrorInWindowIsEqualConfigured() throws Exception {
- PercentErrPerTimeFailureInterpreter pept = new PercentErrPerTimeFailureInterpreter();
- RequestCounter rc = new RequestCounter();
- pept.setRequestCounter(rc);
- pept.setPercent(50);
- pept.setWindowMillis(5000);
-
- try {
- rc.invoke(new DummyRunnable());
- rc.invoke(new DummyRunnable());
- rc.invoke(new DummyRunnable());
- }
- catch (Exception e) {
- pept.shouldTrip(e);
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertTrue(pept.shouldTrip(e));
- }
- }
-
- @Test
- public void testDoesNotTripWhenPercentErrorInWindowIsLessThanConfigured() throws Exception {
- PercentErrPerTimeFailureInterpreter pept = new PercentErrPerTimeFailureInterpreter();
- RequestCounter rc = new RequestCounter();
- pept.setRequestCounter(rc);
- pept.setPercent(51);
- pept.setWindowMillis(2500);
-
- try {
- rc.invoke(new DummyRunnable());
- rc.invoke(new DummyRunnable());
- rc.invoke(new DummyRunnable());
- }
- catch (Exception e) {
- pept.shouldTrip(e);
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
- }
-
- @Test
- public void testDoesNotTripWhenRequestCountInWindowIsLessThanThreshold() throws Exception {
- PercentErrPerTimeFailureInterpreter pept = new PercentErrPerTimeFailureInterpreter();
- RequestCounter rc = new RequestCounter();
- pept.setRequestCounter(rc);
- pept.setPercent(51);
- pept.setWindowMillis(250000);
- pept.setRequestThreshold(8);
-
- try {
- rc.invoke(new DummyRunnable());
- rc.invoke(new DummyRunnable());
- rc.invoke(new DummyRunnable());
- } catch (Exception e) {
- pept.shouldTrip(e);
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- } catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- } catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- } catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- //seventh total request, fourth failure, pushes percentage to 57%, but should not trip because total number
- //of requests is below threshold of 8
- try {
- rc.invoke(new DummyRunnableException());
- } catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
- }
-
- @Test
- public void testTripsOnSecondWindowWithRequestThresholdConfigured() throws Exception {
- PercentErrPerTimeFailureInterpreter pept = new PercentErrPerTimeFailureInterpreter();
- RequestCounter rc = new RequestCounter();
- pept.setRequestCounter(rc);
- pept.setPercent(50);
- pept.setWindowMillis(1000);
- pept.setRequestThreshold(5);
-
- //
- // First window - 1 valid request, 3 failures valid requests, less than request window, not tripped
- //
- rc.invoke(new DummyRunnable());
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- // Sleep to reset the window
- Thread.sleep(1100);
-
- //
- // Second Window - 2 failures, 2 success, 1 failure - should trip at the end.
- //
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertFalse(pept.shouldTrip(e));
- }
-
- rc.invoke(new DummyRunnable());
- rc.invoke(new DummyRunnable());
-
- try {
- rc.invoke(new DummyRunnableException());
- }
- catch (Exception e) {
- assertTrue(pept.shouldTrip(e));
- }
-
-
- }
+ private class DummyRunnable implements Runnable {
+
+ public void run() {
+
+ }
+ }
+
+ private class DummyRunnableException implements Runnable {
+
+ public void run() {
+ throw new RuntimeException();
+ }
+ }
+
+ private class DummyMyRunnableException implements Runnable {
+
+ public void run() {
+ throw new MyRuntimeException();
+ }
+ }
+
+ private class MyRuntimeException extends RuntimeException {
+
+ }
+
+ @Test
+ public void testTripsWhenNoWindowConditionsExist() {
+ PercentErrPerTimeFailureInterpreter pept = new PercentErrPerTimeFailureInterpreter();
+
+ assertTrue(pept.shouldTrip(new Exception()));
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ public void testDoesNotTripWhenExceptionIsIgnored() {
+ PercentErrPerTimeFailureInterpreter pept = new PercentErrPerTimeFailureInterpreter();
+ pept.setIgnore(new Class[] { MyRuntimeException.class });
+
+ assertFalse(pept.shouldTrip(new MyRuntimeException()));
+ assertTrue(pept.shouldTrip(new Exception()));
+ }
+
+ @Test
+ public void testTripsWhenPercentErrorInWindowIsGreaterThanConfigured() throws Exception {
+ PercentErrPerTimeFailureInterpreter pept = new PercentErrPerTimeFailureInterpreter();
+ RequestCounter rc = new RequestCounter();
+ pept.setRequestCounter(rc);
+ pept.setPercent(51);
+ pept.setWindowMillis(5000);
+
+ try {
+ rc.invoke(new DummyRunnable());
+ rc.invoke(new DummyRunnable());
+ rc.invoke(new DummyRunnable());
+ } catch (Exception e) {
+ pept.shouldTrip(e);
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertTrue(pept.shouldTrip(e));
+ }
+ }
+
+ @Test
+ public void testTripsWhenPercentErrorInWindowIsEqualConfigured() throws Exception {
+ PercentErrPerTimeFailureInterpreter pept = new PercentErrPerTimeFailureInterpreter();
+ RequestCounter rc = new RequestCounter();
+ pept.setRequestCounter(rc);
+ pept.setPercent(50);
+ pept.setWindowMillis(5000);
+
+ try {
+ rc.invoke(new DummyRunnable());
+ rc.invoke(new DummyRunnable());
+ rc.invoke(new DummyRunnable());
+ } catch (Exception e) {
+ pept.shouldTrip(e);
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertTrue(pept.shouldTrip(e));
+ }
+ }
+
+ @Test
+ public void testDoesNotTripWhenPercentErrorInWindowIsLessThanConfigured() throws Exception {
+ PercentErrPerTimeFailureInterpreter pept = new PercentErrPerTimeFailureInterpreter();
+ RequestCounter rc = new RequestCounter();
+ pept.setRequestCounter(rc);
+ pept.setPercent(51);
+ pept.setWindowMillis(2500);
+
+ try {
+ rc.invoke(new DummyRunnable());
+ rc.invoke(new DummyRunnable());
+ rc.invoke(new DummyRunnable());
+ } catch (Exception e) {
+ pept.shouldTrip(e);
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+ }
+
+ @Test
+ public void testDoesNotTripWhenRequestCountInWindowIsLessThanThreshold() throws Exception {
+ PercentErrPerTimeFailureInterpreter pept = new PercentErrPerTimeFailureInterpreter();
+ RequestCounter rc = new RequestCounter();
+ pept.setRequestCounter(rc);
+ pept.setPercent(51);
+ pept.setWindowMillis(250000);
+ pept.setRequestThreshold(8);
+
+ try {
+ rc.invoke(new DummyRunnable());
+ rc.invoke(new DummyRunnable());
+ rc.invoke(new DummyRunnable());
+ } catch (Exception e) {
+ pept.shouldTrip(e);
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ // seventh total request, fourth failure, pushes percentage to 57%, but should
+ // not trip because total number
+ // of requests is below threshold of 8
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+ }
+
+ @Test
+ public void testTripsOnSecondWindowWithRequestThresholdConfigured() throws Exception {
+ PercentErrPerTimeFailureInterpreter pept = new PercentErrPerTimeFailureInterpreter();
+ RequestCounter rc = new RequestCounter();
+ pept.setRequestCounter(rc);
+ pept.setPercent(50);
+ pept.setWindowMillis(1000);
+ pept.setRequestThreshold(5);
+
+ //
+ // First window - 1 valid request, 3 failures valid requests, less than request
+ // window, not tripped
+ //
+ rc.invoke(new DummyRunnable());
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ // Sleep to reset the window
+ Thread.sleep(1100);
+
+ //
+ // Second Window - 2 failures, 2 success, 1 failure - should trip at the end.
+ //
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertFalse(pept.shouldTrip(e));
+ }
+
+ rc.invoke(new DummyRunnable());
+ rc.invoke(new DummyRunnable());
+
+ try {
+ rc.invoke(new DummyRunnableException());
+ } catch (Exception e) {
+ assertTrue(pept.shouldTrip(e));
+ }
+
+ }
}
-
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestPerformanceMonitor.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestPerformanceMonitor.java
index eabaebaa..9a31b724 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestPerformanceMonitor.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestPerformanceMonitor.java
@@ -22,89 +22,86 @@
public class TestPerformanceMonitor {
- @Test
- public void testSuccessAndFailureCounts() {
- int numberOfTimesToTryAMethodCall = 500;
- int numberOfAttemptsBeforeThrowingException = 5;
- int expectedNumberOfFailures =
- numberOfTimesToTryAMethodCall
- / numberOfAttemptsBeforeThrowingException;
-
- int expectedNumberOfSuccess = numberOfTimesToTryAMethodCall
- - expectedNumberOfFailures;
-
- PerformanceMonitor perfMon = new PerformanceMonitor();
-
- final OccasionalExceptionPerformer performer =
- new OccasionalExceptionPerformer(numberOfAttemptsBeforeThrowingException);
-
- for(int i=0; i testSet = new HashSet();
- testSet.add("one");
- testSet.add("two");
- testSet.add("three");
- testSet.add("four");
+ @Test
+ public void testGetPerformanceMonitorNames() {
+ Set testSet = new HashSet();
+ testSet.add("one");
+ testSet.add("two");
+ testSet.add("three");
+ testSet.add("four");
- factory.createPerformanceMonitor("one");
- factory.createPerformanceMonitor("two");
- factory.createPerformanceMonitor("three");
- factory.createPerformanceMonitor("four");
- Set monitorNames = factory.getPerformanceMonitorNames();
- assertEquals(testSet, monitorNames);
- }
+ factory.createPerformanceMonitor("one");
+ factory.createPerformanceMonitor("two");
+ factory.createPerformanceMonitor("three");
+ factory.createPerformanceMonitor("four");
+ Set monitorNames = factory.getPerformanceMonitorNames();
+ assertEquals(testSet, monitorNames);
+ }
}
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestRequestCounter.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestRequestCounter.java
index dd26e200..ea56efb2 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestRequestCounter.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestRequestCounter.java
@@ -10,110 +10,110 @@
import org.junit.Test;
public class TestRequestCounter {
-
- private RequestCounter impl;
-
- @Before
- public void setUp() {
- impl = new RequestCounter();
- }
-
- @Test
- public void testCountersInitiallyZero() {
- assertArrayEquals(new long[] {0L, 0L, 0L}, impl.sample());
- }
-
- @Test
- public void testSucceedingCallable() throws Exception {
- final Object o = new Object();
-
- Object result = impl.invoke(new Callable() {
- public Object call() throws Exception {
- return o;
- }
- });
-
- assertSame(o, result);
- assertArrayEquals(new long[] {1L, 1L, 0L}, impl.sample());
- }
-
- @Test
- public void testFailingCallable() throws Exception {
- final Exception ex = new Exception();
-
- try {
- impl.invoke(new Callable() {
- public Object call() throws Exception {
- throw ex;
- }
- });
- fail("should have thrown exception");
- } catch (Exception e) {
- assertSame(ex, e);
- }
-
- assertArrayEquals(new long[] {1L, 0L, 1L}, impl.sample());
- }
-
- @Test
- public void testSucceedingRunnable() throws Exception {
- impl.invoke(new Runnable() {
- public void run() {
- // no-op
- }
- });
-
- assertArrayEquals(new long[] {1L, 1L, 0L}, impl.sample());
- }
-
- @Test
- public void testFailingRunnable() {
- final RuntimeException rtex = new RuntimeException();
-
- try {
- impl.invoke(new Runnable() {
- public void run() {
- throw rtex;
- }
- });
- fail("should have thrown exception");
- } catch (Exception e) {
- assertSame(rtex, e);
- }
-
- assertArrayEquals(new long[] {1L, 0L, 1L}, impl.sample());
- }
-
- @Test
- public void testSucceedingRunnableWithResult() throws Exception {
- final Object o = new Object();
-
- Object result = impl.invoke(new Runnable() {
- public void run() {
- // no-op
- }
- }, o);
-
- assertSame(o, result);
- assertArrayEquals(new long[] {1L, 1L, 0L}, impl.sample());
- }
-
- @Test
- public void testFailingRunnableWithResult() {
- final Object o = new Object();
- final RuntimeException rtex = new RuntimeException();
-
- try {
- impl.invoke(new Runnable() {
- public void run() {
- throw rtex;
- }
- }, o);
- fail("should have thrown exception");
- } catch (Exception e) {
- assertSame(rtex, e);
- }
-
- assertArrayEquals(new long[] {1L, 0L, 1L}, impl.sample());
- }
+
+ private RequestCounter impl;
+
+ @Before
+ public void setUp() {
+ impl = new RequestCounter();
+ }
+
+ @Test
+ public void testCountersInitiallyZero() {
+ assertArrayEquals(new long[] { 0L, 0L, 0L }, impl.sample());
+ }
+
+ @Test
+ public void testSucceedingCallable() throws Exception {
+ final Object o = new Object();
+
+ Object result = impl.invoke(new Callable() {
+ public Object call() throws Exception {
+ return o;
+ }
+ });
+
+ assertSame(o, result);
+ assertArrayEquals(new long[] { 1L, 1L, 0L }, impl.sample());
+ }
+
+ @Test
+ public void testFailingCallable() throws Exception {
+ final Exception ex = new Exception();
+
+ try {
+ impl.invoke(new Callable() {
+ public Object call() throws Exception {
+ throw ex;
+ }
+ });
+ fail("should have thrown exception");
+ } catch (Exception e) {
+ assertSame(ex, e);
+ }
+
+ assertArrayEquals(new long[] { 1L, 0L, 1L }, impl.sample());
+ }
+
+ @Test
+ public void testSucceedingRunnable() throws Exception {
+ impl.invoke(new Runnable() {
+ public void run() {
+ // no-op
+ }
+ });
+
+ assertArrayEquals(new long[] { 1L, 1L, 0L }, impl.sample());
+ }
+
+ @Test
+ public void testFailingRunnable() {
+ final RuntimeException rtex = new RuntimeException();
+
+ try {
+ impl.invoke(new Runnable() {
+ public void run() {
+ throw rtex;
+ }
+ });
+ fail("should have thrown exception");
+ } catch (Exception e) {
+ assertSame(rtex, e);
+ }
+
+ assertArrayEquals(new long[] { 1L, 0L, 1L }, impl.sample());
+ }
+
+ @Test
+ public void testSucceedingRunnableWithResult() throws Exception {
+ final Object o = new Object();
+
+ Object result = impl.invoke(new Runnable() {
+ public void run() {
+ // no-op
+ }
+ }, o);
+
+ assertSame(o, result);
+ assertArrayEquals(new long[] { 1L, 1L, 0L }, impl.sample());
+ }
+
+ @Test
+ public void testFailingRunnableWithResult() {
+ final Object o = new Object();
+ final RuntimeException rtex = new RuntimeException();
+
+ try {
+ impl.invoke(new Runnable() {
+ public void run() {
+ throw rtex;
+ }
+ }, o);
+ fail("should have thrown exception");
+ } catch (Exception e) {
+ assertSame(rtex, e);
+ }
+
+ assertArrayEquals(new long[] { 1L, 0L, 1L }, impl.sample());
+ }
}
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestRolledUpMonitoredService.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestRolledUpMonitoredService.java
index 29d75791..6928b05b 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestRolledUpMonitoredService.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestRolledUpMonitoredService.java
@@ -29,142 +29,142 @@
public class TestRolledUpMonitoredService {
- private RolledUpMonitoredService rolledUpService;
-
- MonitoredService mockService1;
-
- MonitoredService mockService2;
-
- private static final String ROLLEDUP_SERVICE_NAME = "Rolledup Service";
- private static final String SERVICE_1_NAME="Service 1";
- private static final String SERVICE_2_NAME="Service 2";
-
- private static final String SERVICE_1_REASON = "Service 1 Reason";
- private static final String SERVICE_2_REASON = "Service 2 Reason";
-
- @Before
- public void setUp() {
- mockService1 = createMock(MonitoredService.class);
- mockService2 = createMock(MonitoredService.class);
- List criticals = new ArrayList();
- criticals.add(mockService1);
- List nonCriticals = new ArrayList();
- nonCriticals.add(mockService2);
-
- rolledUpService = new RolledUpMonitoredService(ROLLEDUP_SERVICE_NAME, criticals, nonCriticals);
- }
-
- @Test
- public void testAllUp() {
- expect(mockService1.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_1_NAME, Status.UP));
- expect(mockService2.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_2_NAME, Status.UP));
- replay(mockService1);
- replay(mockService2);
-
- ServiceStatus serviceStatus = rolledUpService.getServiceStatus();
-
- assertEquals(ROLLEDUP_SERVICE_NAME, serviceStatus.getName());
- assertEquals(serviceStatus.getStatus(), Status.UP);
- }
-
- @Test
- public void testCriticalDegraded() {
- expect(mockService1.getServiceStatus()).andReturn(
- new ServiceStatus(SERVICE_1_NAME, Status.DEGRADED, SERVICE_1_REASON));
- expect(mockService2.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_2_NAME, Status.UP));
- replay(mockService1);
- replay(mockService2);
-
- ServiceStatus serviceStatus = rolledUpService.getServiceStatus();
-
- assertEquals(ROLLEDUP_SERVICE_NAME, serviceStatus.getName());
- assertEquals(serviceStatus.getStatus(), Status.DEGRADED);
- assertTrue(serviceStatus.getReasons().contains(SERVICE_1_NAME + ":" + SERVICE_1_REASON));
- }
-
- @Test
- public void testNonCriticalDegraded() {
- expect(mockService1.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_1_NAME, Status.UP));
- expect(mockService2.getServiceStatus()).andReturn(
- new ServiceStatus(SERVICE_2_NAME, Status.DEGRADED, SERVICE_2_REASON));
- replay(mockService1);
- replay(mockService2);
-
- ServiceStatus serviceStatus = rolledUpService.getServiceStatus();
-
- assertEquals(ROLLEDUP_SERVICE_NAME, serviceStatus.getName());
- assertEquals(serviceStatus.getStatus(), Status.DEGRADED);
- assertTrue(serviceStatus.getReasons().contains(SERVICE_2_NAME + ":" + SERVICE_2_REASON));
- }
-
- @Test
- public void testCritialAndNonCriticalDegraded() {
- expect(mockService1.getServiceStatus()).andReturn(
- new ServiceStatus(SERVICE_1_NAME, Status.DEGRADED, SERVICE_1_REASON));
- expect(mockService2.getServiceStatus()).andReturn(
- new ServiceStatus(SERVICE_2_NAME, Status.DEGRADED, SERVICE_2_REASON));
- replay(mockService1);
- replay(mockService2);
-
- ServiceStatus serviceStatus = rolledUpService.getServiceStatus();
-
- assertEquals(ROLLEDUP_SERVICE_NAME, serviceStatus.getName());
- assertEquals(serviceStatus.getStatus(), Status.DEGRADED);
- assertTrue(serviceStatus.getReasons().contains(SERVICE_1_NAME + ":" + SERVICE_1_REASON));
- assertTrue(serviceStatus.getReasons().contains(SERVICE_2_NAME + ":" + SERVICE_2_REASON));
- }
-
- @Test
- public void testNonCritialDown() {
- expect(mockService1.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_1_NAME, Status.UP));
- expect(mockService2.getServiceStatus()).andReturn(
- new ServiceStatus(SERVICE_2_NAME, Status.DOWN, SERVICE_2_REASON));
- replay(mockService1);
- replay(mockService2);
-
- ServiceStatus serviceStatus = rolledUpService.getServiceStatus();
-
- assertEquals(ROLLEDUP_SERVICE_NAME, serviceStatus.getName());
- assertEquals(serviceStatus.getStatus(), Status.DEGRADED);
- assertTrue(serviceStatus.getReasons().contains(SERVICE_2_NAME + ":" + SERVICE_2_REASON));
- }
-
- @Test
- public void testGetServiceStatusList() {
- expect(mockService1.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_1_NAME, Status.UP)).times(2);
- expect(mockService2.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_2_NAME, Status.UP)).times(2);
- replay(mockService1);
- replay(mockService2);
-
- List statusList = rolledUpService.getAllStatuses();
-
- assertTrue(statusList.contains(mockService1.getServiceStatus()));
- assertTrue(statusList.contains(mockService2.getServiceStatus()));
- }
-
- @Test
- public void testGetCriticalServiceStatusList() {
- expect(mockService1.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_1_NAME, Status.UP)).times(2);
- expect(mockService2.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_2_NAME, Status.UP)).times(2);
- replay(mockService1);
- replay(mockService2);
-
- List statusList = rolledUpService.getCriticalStatuses();
-
- assertTrue(statusList.contains(mockService1.getServiceStatus()));
- assertFalse(statusList.contains(mockService2.getServiceStatus()));
- }
-
- @Test
- public void testGetNonCriticalServiceStatusList() {
- expect(mockService1.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_1_NAME, Status.UP)).times(2);
- expect(mockService2.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_2_NAME, Status.UP)).times(2);
- replay(mockService1);
- replay(mockService2);
-
- List statusList = rolledUpService.getNonCriticalStatuses();
-
- assertFalse(statusList.contains(mockService1.getServiceStatus()));
- assertTrue(statusList.contains(mockService2.getServiceStatus()));
- }
+ private RolledUpMonitoredService rolledUpService;
+
+ MonitoredService mockService1;
+
+ MonitoredService mockService2;
+
+ private static final String ROLLEDUP_SERVICE_NAME = "Rolledup Service";
+ private static final String SERVICE_1_NAME = "Service 1";
+ private static final String SERVICE_2_NAME = "Service 2";
+
+ private static final String SERVICE_1_REASON = "Service 1 Reason";
+ private static final String SERVICE_2_REASON = "Service 2 Reason";
+
+ @Before
+ public void setUp() {
+ mockService1 = createMock(MonitoredService.class);
+ mockService2 = createMock(MonitoredService.class);
+ List criticals = new ArrayList();
+ criticals.add(mockService1);
+ List nonCriticals = new ArrayList();
+ nonCriticals.add(mockService2);
+
+ rolledUpService = new RolledUpMonitoredService(ROLLEDUP_SERVICE_NAME, criticals, nonCriticals);
+ }
+
+ @Test
+ public void testAllUp() {
+ expect(mockService1.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_1_NAME, Status.UP));
+ expect(mockService2.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_2_NAME, Status.UP));
+ replay(mockService1);
+ replay(mockService2);
+
+ ServiceStatus serviceStatus = rolledUpService.getServiceStatus();
+
+ assertEquals(ROLLEDUP_SERVICE_NAME, serviceStatus.getName());
+ assertEquals(serviceStatus.getStatus(), Status.UP);
+ }
+
+ @Test
+ public void testCriticalDegraded() {
+ expect(mockService1.getServiceStatus())
+ .andReturn(new ServiceStatus(SERVICE_1_NAME, Status.DEGRADED, SERVICE_1_REASON));
+ expect(mockService2.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_2_NAME, Status.UP));
+ replay(mockService1);
+ replay(mockService2);
+
+ ServiceStatus serviceStatus = rolledUpService.getServiceStatus();
+
+ assertEquals(ROLLEDUP_SERVICE_NAME, serviceStatus.getName());
+ assertEquals(serviceStatus.getStatus(), Status.DEGRADED);
+ assertTrue(serviceStatus.getReasons().contains(SERVICE_1_NAME + ":" + SERVICE_1_REASON));
+ }
+
+ @Test
+ public void testNonCriticalDegraded() {
+ expect(mockService1.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_1_NAME, Status.UP));
+ expect(mockService2.getServiceStatus())
+ .andReturn(new ServiceStatus(SERVICE_2_NAME, Status.DEGRADED, SERVICE_2_REASON));
+ replay(mockService1);
+ replay(mockService2);
+
+ ServiceStatus serviceStatus = rolledUpService.getServiceStatus();
+
+ assertEquals(ROLLEDUP_SERVICE_NAME, serviceStatus.getName());
+ assertEquals(serviceStatus.getStatus(), Status.DEGRADED);
+ assertTrue(serviceStatus.getReasons().contains(SERVICE_2_NAME + ":" + SERVICE_2_REASON));
+ }
+
+ @Test
+ public void testCritialAndNonCriticalDegraded() {
+ expect(mockService1.getServiceStatus())
+ .andReturn(new ServiceStatus(SERVICE_1_NAME, Status.DEGRADED, SERVICE_1_REASON));
+ expect(mockService2.getServiceStatus())
+ .andReturn(new ServiceStatus(SERVICE_2_NAME, Status.DEGRADED, SERVICE_2_REASON));
+ replay(mockService1);
+ replay(mockService2);
+
+ ServiceStatus serviceStatus = rolledUpService.getServiceStatus();
+
+ assertEquals(ROLLEDUP_SERVICE_NAME, serviceStatus.getName());
+ assertEquals(serviceStatus.getStatus(), Status.DEGRADED);
+ assertTrue(serviceStatus.getReasons().contains(SERVICE_1_NAME + ":" + SERVICE_1_REASON));
+ assertTrue(serviceStatus.getReasons().contains(SERVICE_2_NAME + ":" + SERVICE_2_REASON));
+ }
+
+ @Test
+ public void testNonCritialDown() {
+ expect(mockService1.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_1_NAME, Status.UP));
+ expect(mockService2.getServiceStatus())
+ .andReturn(new ServiceStatus(SERVICE_2_NAME, Status.DOWN, SERVICE_2_REASON));
+ replay(mockService1);
+ replay(mockService2);
+
+ ServiceStatus serviceStatus = rolledUpService.getServiceStatus();
+
+ assertEquals(ROLLEDUP_SERVICE_NAME, serviceStatus.getName());
+ assertEquals(serviceStatus.getStatus(), Status.DEGRADED);
+ assertTrue(serviceStatus.getReasons().contains(SERVICE_2_NAME + ":" + SERVICE_2_REASON));
+ }
+
+ @Test
+ public void testGetServiceStatusList() {
+ expect(mockService1.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_1_NAME, Status.UP)).times(2);
+ expect(mockService2.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_2_NAME, Status.UP)).times(2);
+ replay(mockService1);
+ replay(mockService2);
+
+ List statusList = rolledUpService.getAllStatuses();
+
+ assertTrue(statusList.contains(mockService1.getServiceStatus()));
+ assertTrue(statusList.contains(mockService2.getServiceStatus()));
+ }
+
+ @Test
+ public void testGetCriticalServiceStatusList() {
+ expect(mockService1.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_1_NAME, Status.UP)).times(2);
+ expect(mockService2.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_2_NAME, Status.UP)).times(2);
+ replay(mockService1);
+ replay(mockService2);
+
+ List statusList = rolledUpService.getCriticalStatuses();
+
+ assertTrue(statusList.contains(mockService1.getServiceStatus()));
+ assertFalse(statusList.contains(mockService2.getServiceStatus()));
+ }
+
+ @Test
+ public void testGetNonCriticalServiceStatusList() {
+ expect(mockService1.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_1_NAME, Status.UP)).times(2);
+ expect(mockService2.getServiceStatus()).andReturn(new ServiceStatus(SERVICE_2_NAME, Status.UP)).times(2);
+ replay(mockService1);
+ replay(mockService2);
+
+ List statusList = rolledUpService.getNonCriticalStatuses();
+
+ assertFalse(statusList.contains(mockService1.getServiceStatus()));
+ assertTrue(statusList.contains(mockService2.getServiceStatus()));
+ }
}
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestSampledQuantile.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestSampledQuantile.java
index 97303c51..704c98f4 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestSampledQuantile.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestSampledQuantile.java
@@ -25,185 +25,186 @@
public class TestSampledQuantile {
- private SampledQuantile impl;
-
- @Before
- public void setUp() {
- impl = new SampledQuantile();
- }
-
- @Test
- public void quantileWithNoSamplesShouldReturnZero() {
- assertEquals(0, impl.getPercentile(50));
- }
-
- @Test
- public void quantileWithOneSampleShouldReturnThatSample() {
- impl.addSample(42);
- assertEquals(42, impl.getPercentile(50));
- }
-
- @Test
- public void medianOfThreeSamplesIsMiddleSample() {
- impl.addSample(42);
- impl.addSample(41);
- impl.addSample(43);
- assertEquals(42, impl.getPercentile(50));
- }
-
- @Test
- public void medianOfFiveSamplesWithRepeatsStillWorks() {
- impl.addSample(41);
- impl.addSample(43);
- impl.addSample(42);
- impl.addSample(41);
- impl.addSample(43);
- assertEquals(42, impl.getPercentile(50));
- }
-
- @Test
- public void medianOfTwoSamplesIsTheirAverage() {
- impl.addSample(41);
- impl.addSample(43);
- assertEquals(42, impl.getPercentile(50));
- }
-
- @Test
- public void canGetMedianAsExpressedInQuantiles() {
- impl.addSample(42);
- impl.addSample(41);
- impl.addSample(43);
- assertEquals(42, impl.getQuantile(1,2));
- }
-
- @Test
- public void canGetMedianDirectly() {
- impl.addSample(42);
- impl.addSample(41);
- impl.addSample(43);
- assertEquals(42, impl.getMedian());
- }
-
- @Test
- public void zerothQuantileShouldThrowException() {
- impl.addSample(41);
- try {
- impl.getQuantile(0,7);
- fail("should have thrown exception");
- } catch (SampledQuantile.QuantileOutOfBoundsException expected) {
- }
- }
-
- @Test
- public void qthQuantileShouldThrowException() {
- impl.addSample(41);
- try {
- impl.getQuantile(7,7);
- fail("should have thrown exception");
- } catch (SampledQuantile.QuantileOutOfBoundsException expected) {
- }
- }
-
- @Test
- public void canSpecifyMaxSamples() {
- impl = new SampledQuantile(10);
- for(int i=0; i<20; i++) impl.addSample(0);
- assertEquals(10, impl.getNumSamples());
- }
-
- @Test
- public void canSpecifyCurrentTimeWhenAddingSample() {
- impl.addSample(41, System.currentTimeMillis());
- }
-
- @Test
- public void ignoresSamplesOutsideOfSpecifiedSecondWindow() {
- impl = new SampledQuantile(60, TimeUnit.SECONDS);
- long now = System.currentTimeMillis();
- impl.addSample(7, now - 90 * 1000L);
- impl.addSample(42, now);
- assertEquals(42, impl.getPercentile(50, now+1));
- }
-
- @Test
- public void ignoresSamplesOutsideOfSpecifiedNanosecondWindow() {
- impl = new SampledQuantile(60 * 1000000000L, TimeUnit.NANOSECONDS);
- long now = System.currentTimeMillis();
- impl.addSample(7, now - 90 * 1000L);
- impl.addSample(42, now);
- assertEquals(42, impl.getPercentile(50, now+1));
- }
-
- @Test
- public void ignoresSamplesOutsideOfSpecifiedMicrosecondWindow() {
- impl = new SampledQuantile(60 * 1000000L, TimeUnit.MICROSECONDS);
- long now = System.currentTimeMillis();
- impl.addSample(7, now - 90 * 1000L);
- impl.addSample(42, now);
- assertEquals(42, impl.getPercentile(50, now+1));
- }
-
- @Test
- public void ignoresSamplesOutsideOfSpecifiedMillisecondWindow() {
- impl = new SampledQuantile(60 * 1000L, TimeUnit.MILLISECONDS);
- long now = System.currentTimeMillis();
- impl.addSample(7, now - 90 * 1000L);
- impl.addSample(42, now);
- assertEquals(42, impl.getPercentile(50, now+1));
- }
-
- @Test
- public void ignoresSamplesOutsideOfSpecifiedMinuteWindow() {
- impl = new SampledQuantile(60L, TimeUnit.SECONDS);
- long now = System.currentTimeMillis();
- impl.addSample(7, now - 90 * 1000L);
- impl.addSample(42, now);
- assertEquals(42, impl.getPercentile(50, now+1));
- }
-
- @Test
- public void ignoresSamplesOutsideOfSpecifiedHourWindow() {
- impl = new SampledQuantile(3600L, TimeUnit.SECONDS);
- long now = System.currentTimeMillis();
- impl.addSample(7, now - 5400 * 1000L);
- impl.addSample(42, now);
- assertEquals(42, impl.getPercentile(50, now+1));
- }
-
- @Test
- public void ignoresSamplesOutsideOfSpecifiedDayWindow() {
- impl = new SampledQuantile(86400L, TimeUnit.SECONDS);
- long now = System.currentTimeMillis();
- impl.addSample(7, now - 2 * 24 * 3600 * 1000L);
- impl.addSample(42, now);
- assertEquals(42, impl.getPercentile(50, now+1));
- }
-
- @Test
- public void windowedSamplingWorks() {
- long t0 = System.currentTimeMillis();
- impl = new SampledQuantile(10, 60L, TimeUnit.SECONDS, t0);
- for(int t=0; t<30 * 1000; t++) {
- impl.addSample(1L, t0 + t);
- }
- long t1 = t0 + 30 * 1000L;
- assertEquals(1L, impl.getPercentile(50, t1));
-
- for(int t=0; t<60*1000; t++) {
- impl.addSample(2L, t1 + t);
- }
- long t2 = t1 + 60 * 1000L;
- assertEquals(2L, impl.getPercentile(50, t2));
- impl.addSample(3L, t2+1);
- }
-
- @Test
- public void windowedSamplingHandlesLongTimesBetweenSamples() {
- long t0 = System.currentTimeMillis();
- impl = new SampledQuantile(10, 60L, TimeUnit.SECONDS, t0);
- impl.addSample(1L, t0 + 1);
- long t1 = t0 + 90 * 1000L;
- impl.addSample(2L, t1);
- assertEquals(2L, impl.getPercentile(50, t1));
- }
+ private SampledQuantile impl;
+
+ @Before
+ public void setUp() {
+ impl = new SampledQuantile();
+ }
+
+ @Test
+ public void quantileWithNoSamplesShouldReturnZero() {
+ assertEquals(0, impl.getPercentile(50));
+ }
+
+ @Test
+ public void quantileWithOneSampleShouldReturnThatSample() {
+ impl.addSample(42);
+ assertEquals(42, impl.getPercentile(50));
+ }
+
+ @Test
+ public void medianOfThreeSamplesIsMiddleSample() {
+ impl.addSample(42);
+ impl.addSample(41);
+ impl.addSample(43);
+ assertEquals(42, impl.getPercentile(50));
+ }
+
+ @Test
+ public void medianOfFiveSamplesWithRepeatsStillWorks() {
+ impl.addSample(41);
+ impl.addSample(43);
+ impl.addSample(42);
+ impl.addSample(41);
+ impl.addSample(43);
+ assertEquals(42, impl.getPercentile(50));
+ }
+
+ @Test
+ public void medianOfTwoSamplesIsTheirAverage() {
+ impl.addSample(41);
+ impl.addSample(43);
+ assertEquals(42, impl.getPercentile(50));
+ }
+
+ @Test
+ public void canGetMedianAsExpressedInQuantiles() {
+ impl.addSample(42);
+ impl.addSample(41);
+ impl.addSample(43);
+ assertEquals(42, impl.getQuantile(1, 2));
+ }
+
+ @Test
+ public void canGetMedianDirectly() {
+ impl.addSample(42);
+ impl.addSample(41);
+ impl.addSample(43);
+ assertEquals(42, impl.getMedian());
+ }
+
+ @Test
+ public void zerothQuantileShouldThrowException() {
+ impl.addSample(41);
+ try {
+ impl.getQuantile(0, 7);
+ fail("should have thrown exception");
+ } catch (SampledQuantile.QuantileOutOfBoundsException expected) {
+ }
+ }
+
+ @Test
+ public void qthQuantileShouldThrowException() {
+ impl.addSample(41);
+ try {
+ impl.getQuantile(7, 7);
+ fail("should have thrown exception");
+ } catch (SampledQuantile.QuantileOutOfBoundsException expected) {
+ }
+ }
+
+ @Test
+ public void canSpecifyMaxSamples() {
+ impl = new SampledQuantile(10);
+ for (int i = 0; i < 20; i++)
+ impl.addSample(0);
+ assertEquals(10, impl.getNumSamples());
+ }
+
+ @Test
+ public void canSpecifyCurrentTimeWhenAddingSample() {
+ impl.addSample(41, System.currentTimeMillis());
+ }
+
+ @Test
+ public void ignoresSamplesOutsideOfSpecifiedSecondWindow() {
+ impl = new SampledQuantile(60, TimeUnit.SECONDS);
+ long now = System.currentTimeMillis();
+ impl.addSample(7, now - 90 * 1000L);
+ impl.addSample(42, now);
+ assertEquals(42, impl.getPercentile(50, now + 1));
+ }
+
+ @Test
+ public void ignoresSamplesOutsideOfSpecifiedNanosecondWindow() {
+ impl = new SampledQuantile(60 * 1000000000L, TimeUnit.NANOSECONDS);
+ long now = System.currentTimeMillis();
+ impl.addSample(7, now - 90 * 1000L);
+ impl.addSample(42, now);
+ assertEquals(42, impl.getPercentile(50, now + 1));
+ }
+
+ @Test
+ public void ignoresSamplesOutsideOfSpecifiedMicrosecondWindow() {
+ impl = new SampledQuantile(60 * 1000000L, TimeUnit.MICROSECONDS);
+ long now = System.currentTimeMillis();
+ impl.addSample(7, now - 90 * 1000L);
+ impl.addSample(42, now);
+ assertEquals(42, impl.getPercentile(50, now + 1));
+ }
+
+ @Test
+ public void ignoresSamplesOutsideOfSpecifiedMillisecondWindow() {
+ impl = new SampledQuantile(60 * 1000L, TimeUnit.MILLISECONDS);
+ long now = System.currentTimeMillis();
+ impl.addSample(7, now - 90 * 1000L);
+ impl.addSample(42, now);
+ assertEquals(42, impl.getPercentile(50, now + 1));
+ }
+
+ @Test
+ public void ignoresSamplesOutsideOfSpecifiedMinuteWindow() {
+ impl = new SampledQuantile(60L, TimeUnit.SECONDS);
+ long now = System.currentTimeMillis();
+ impl.addSample(7, now - 90 * 1000L);
+ impl.addSample(42, now);
+ assertEquals(42, impl.getPercentile(50, now + 1));
+ }
+
+ @Test
+ public void ignoresSamplesOutsideOfSpecifiedHourWindow() {
+ impl = new SampledQuantile(3600L, TimeUnit.SECONDS);
+ long now = System.currentTimeMillis();
+ impl.addSample(7, now - 5400 * 1000L);
+ impl.addSample(42, now);
+ assertEquals(42, impl.getPercentile(50, now + 1));
+ }
+
+ @Test
+ public void ignoresSamplesOutsideOfSpecifiedDayWindow() {
+ impl = new SampledQuantile(86400L, TimeUnit.SECONDS);
+ long now = System.currentTimeMillis();
+ impl.addSample(7, now - 2 * 24 * 3600 * 1000L);
+ impl.addSample(42, now);
+ assertEquals(42, impl.getPercentile(50, now + 1));
+ }
+
+ @Test
+ public void windowedSamplingWorks() {
+ long t0 = System.currentTimeMillis();
+ impl = new SampledQuantile(10, 60L, TimeUnit.SECONDS, t0);
+ for (int t = 0; t < 30 * 1000; t++) {
+ impl.addSample(1L, t0 + t);
+ }
+ long t1 = t0 + 30 * 1000L;
+ assertEquals(1L, impl.getPercentile(50, t1));
+
+ for (int t = 0; t < 60 * 1000; t++) {
+ impl.addSample(2L, t1 + t);
+ }
+ long t2 = t1 + 60 * 1000L;
+ assertEquals(2L, impl.getPercentile(50, t2));
+ impl.addSample(3L, t2 + 1);
+ }
+
+ @Test
+ public void windowedSamplingHandlesLongTimesBetweenSamples() {
+ long t0 = System.currentTimeMillis();
+ impl = new SampledQuantile(10, 60L, TimeUnit.SECONDS, t0);
+ impl.addSample(1L, t0 + 1);
+ long t1 = t0 + 90 * 1000L;
+ impl.addSample(2L, t1);
+ assertEquals(2L, impl.getPercentile(50, t1));
+ }
}
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestServiceRetrier.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestServiceRetrier.java
index 2d99cc37..e5f33549 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestServiceRetrier.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestServiceRetrier.java
@@ -32,264 +32,263 @@
public class TestServiceRetrier {
- private class DummyCallable implements Callable {
+ private class DummyCallable implements Callable {
- private String _message;
- private int _count = 0;
- private int _failCount = 5;
- private Exception _exception;
+ private String _message;
+ private int _count = 0;
+ private int _failCount = 5;
+ private Exception _exception;
- public DummyCallable (String message, int failCount) {
- this(message, failCount, new Exception("FAIL!"));
- }
+ public DummyCallable(String message, int failCount) {
+ this(message, failCount, new Exception("FAIL!"));
+ }
- public DummyCallable (String message, int failCount, Exception exception) {
- _message = message;
- _failCount = failCount;
- _exception = exception;
- }
+ public DummyCallable(String message, int failCount, Exception exception) {
+ _message = message;
+ _failCount = failCount;
+ _exception = exception;
+ }
- public String call() throws Exception {
+ public String call() throws Exception {
- _count++;
- if (_count < _failCount)
- throw _exception;
+ _count++;
+ if (_count < _failCount)
+ throw _exception;
- return _message;
- }
+ return _message;
+ }
- public int getCount() {
- return _count;
- }
- }
+ public int getCount() {
+ return _count;
+ }
+ }
- private class DummyRunnable implements Runnable {
+ private class DummyRunnable implements Runnable {
- private int _count = 0;
- private int _failCount = 5;
+ private int _count = 0;
+ private int _failCount = 5;
- public DummyRunnable (int failCount) {
- _failCount = failCount;
- }
+ public DummyRunnable(int failCount) {
+ _failCount = failCount;
+ }
- public void run(){
+ public void run() {
- _count++;
- if (_count < _failCount)
- throw new RuntimeException("FAIL! " + _count);
- }
+ _count++;
+ if (_count < _failCount)
+ throw new RuntimeException("FAIL! " + _count);
+ }
- public int getCount() {
- return _count;
- }
- }
+ public int getCount() {
+ return _count;
+ }
+ }
- class CaptureSleepServiceRetrier extends ServiceRetrier {
+ class CaptureSleepServiceRetrier extends ServiceRetrier {
- private int _sleepCallCount = 0;
- private List _capturedSleepValues = new ArrayList();
+ private int _sleepCallCount = 0;
+ private List _capturedSleepValues = new ArrayList();
- @Override
- protected void sleep(long millis) {
- _sleepCallCount++;
- _capturedSleepValues.add(millis);
- }
+ @Override
+ protected void sleep(long millis) {
+ _sleepCallCount++;
+ _capturedSleepValues.add(millis);
+ }
- public int getSleepCallCount() {
- return _sleepCallCount;
- }
+ public int getSleepCallCount() {
+ return _sleepCallCount;
+ }
- public List getCapturedSleepValues() {
- return _capturedSleepValues;
- }
- }
+ public List getCapturedSleepValues() {
+ return _capturedSleepValues;
+ }
+ }
- @Test
- public void testInvokeSucceedsWithNoRetries() throws Exception {
+ @Test
+ public void testInvokeSucceedsWithNoRetries() throws Exception {
- DummyCallable foo = new DummyCallable("Foo!", 5);
+ DummyCallable foo = new DummyCallable("Foo!", 5);
- ServiceRetrier retrier = new ServiceRetrier();
- retrier.setDelay(100);
- retrier.setMaxTries(5);
- retrier.setDoubleDelay(false);
+ ServiceRetrier retrier = new ServiceRetrier();
+ retrier.setDelay(100);
+ retrier.setMaxTries(5);
+ retrier.setDoubleDelay(false);
- String result = retrier.invoke(foo);
- assertEquals(5, foo.getCount());
- assertEquals("Foo!", result);
- }
+ String result = retrier.invoke(foo);
+ assertEquals(5, foo.getCount());
+ assertEquals("Foo!", result);
+ }
- @Test
- public void testInvokeSucceedsWithRetries() throws Exception {
+ @Test
+ public void testInvokeSucceedsWithRetries() throws Exception {
- DummyCallable foo = new DummyCallable("Foo!", 5);
+ DummyCallable foo = new DummyCallable("Foo!", 5);
- ServiceRetrier retrier = new ServiceRetrier(100, 5);
- retrier.setDoubleDelay(false);
+ ServiceRetrier retrier = new ServiceRetrier(100, 5);
+ retrier.setDoubleDelay(false);
- String result = retrier.invoke(foo);
- assertEquals(5, foo.getCount());
- assertEquals("Foo!", result);
- }
+ String result = retrier.invoke(foo);
+ assertEquals(5, foo.getCount());
+ assertEquals("Foo!", result);
+ }
- @Test
- public void testInvokeSucceedsWithRetriesAndEmptyRetryOn() throws Exception {
+ @Test
+ public void testInvokeSucceedsWithRetriesAndEmptyRetryOn() throws Exception {
- DummyCallable foo = new DummyCallable("Foo!", 5);
+ DummyCallable foo = new DummyCallable("Foo!", 5);
- ServiceRetrier retrier = new ServiceRetrier(100, 5);
+ ServiceRetrier retrier = new ServiceRetrier(100, 5);
- @SuppressWarnings("unchecked")
- Class extends Throwable>[] retryOn = new Class[0];
- retrier.setRetryOn(retryOn);
+ @SuppressWarnings("unchecked")
+ Class extends Throwable>[] retryOn = new Class[0];
+ retrier.setRetryOn(retryOn);
- String result = retrier.invoke(foo);
- assertEquals(5, foo.getCount());
- assertEquals("Foo!", result);
- }
+ String result = retrier.invoke(foo);
+ assertEquals(5, foo.getCount());
+ assertEquals("Foo!", result);
+ }
- @Test
- public void testInvokeSucceedsWithRetriesAndSpecificExceptionInRetryOn() throws Exception {
+ @Test
+ public void testInvokeSucceedsWithRetriesAndSpecificExceptionInRetryOn() throws Exception {
- DummyCallable foo = new DummyCallable("Foo!", 5, new IOException());
+ DummyCallable foo = new DummyCallable("Foo!", 5, new IOException());
- ServiceRetrier retrier = new ServiceRetrier(100, 5);
+ ServiceRetrier retrier = new ServiceRetrier(100, 5);
- @SuppressWarnings("unchecked")
- Class extends Throwable>[] retryOn = new Class[] { IllegalArgumentException.class, IOException.class };
- retrier.setRetryOn(retryOn);
+ @SuppressWarnings("unchecked")
+ Class extends Throwable>[] retryOn = new Class[] { IllegalArgumentException.class, IOException.class };
+ retrier.setRetryOn(retryOn);
- String result = retrier.invoke(foo);
- assertEquals(5, foo.getCount());
- assertEquals("Foo!", result);
- }
+ String result = retrier.invoke(foo);
+ assertEquals(5, foo.getCount());
+ assertEquals("Foo!", result);
+ }
+ @Test
+ public void testConstructorWithNoArgs() {
+ ServiceRetrier serviceRetrier = new ServiceRetrier();
+ Assert.assertEquals(1000, serviceRetrier.getDelay());
+ Assert.assertEquals(10, serviceRetrier.getMaxTries());
+ assertFalse(serviceRetrier.isDoubleDelay());
+ assertFalse(serviceRetrier.isThrowCauseException());
+ Assert.assertEquals(null, serviceRetrier.getRetryOn());
+ }
- @Test
- public void testConstructorWithNoArgs() {
- ServiceRetrier serviceRetrier = new ServiceRetrier();
- Assert.assertEquals(1000, serviceRetrier.getDelay());
- Assert.assertEquals(10, serviceRetrier.getMaxTries());
- assertFalse(serviceRetrier.isDoubleDelay());
- assertFalse(serviceRetrier.isThrowCauseException());
- Assert.assertEquals(null, serviceRetrier.getRetryOn());
- }
-
- @Test
- public void testConstructorWithDelayAndMaxTries() throws Exception {
- ServiceRetrier retrier = new ServiceRetrier(100, 5);
- assertEquals(5, retrier.getMaxTries());
- assertEquals(100, retrier.getDelay());
- }
-
- @Test
- public void testConfigurationWithAll() throws Exception {
- @SuppressWarnings("unchecked")
- Class[] retryOn = new Class[0];
-
- ServiceRetrier retrier = new ServiceRetrier(100, 5, true, true, retryOn);
- assertEquals(5, retrier.getMaxTries());
- assertEquals(100, retrier.getDelay());
- assertTrue(retrier.isDoubleDelay());
- assertTrue(retrier.isThrowCauseException());
- assertSame(retryOn, retrier.getRetryOn());
- }
-
- @Test
- public void testInvokeSucceedRunnable() throws Exception {
-
- DummyRunnable foo = new DummyRunnable(5);
-
- ServiceRetrier retrier = new ServiceRetrier();
- retrier.setDelay(100);
- retrier.setMaxTries(5);
- retrier.setDoubleDelay(false);
-
- retrier.invoke(foo);
- assertEquals(5, foo.getCount());
- }
-
- @Test
- public void testInvokeSucceedRunnableResult() throws Exception {
-
- DummyRunnable foo = new DummyRunnable(5);
-
- ServiceRetrier retrier = new ServiceRetrier();
- retrier.setDelay(100);
- retrier.setMaxTries(5);
- retrier.setDoubleDelay(false);
-
- String result = "Foo!";
- retrier.invoke(foo, result);
- assertEquals(5, foo.getCount());
- assertEquals("Foo!", result);
- }
-
- @Test
- public void testDoubleDelay() throws Exception {
-
- DummyCallable foo = new DummyCallable("Foo!", 5);
-
- CaptureSleepServiceRetrier retrier = new CaptureSleepServiceRetrier();
- retrier.setDelay(100);
- retrier.setMaxTries(5);
- retrier.setDoubleDelay(true);
-
- retrier.invoke(foo);
-
- assertTrue(retrier.isDoubleDelay());
- assertEquals(4, retrier.getSleepCallCount());
- assertEquals(100L, (long)retrier.getCapturedSleepValues().get(0));
- assertEquals(200L, (long)retrier.getCapturedSleepValues().get(1));
- assertEquals(400L, (long)retrier.getCapturedSleepValues().get(2));
- assertEquals(800L, (long)retrier.getCapturedSleepValues().get(3));
- }
-
- @Test
- public void testInvokeFail() {
-
- DummyCallable foo = new DummyCallable("Foo!", 4);
-
- ServiceRetrier retrier = new ServiceRetrier();
- retrier.setDelay(100);
- retrier.setMaxTries(3);
- retrier.setDoubleDelay(false);
-
- try {
- retrier.invoke(foo);
- fail("Should have thrown exception");
- } catch (Exception ex) {
- // pass
- }
- }
-
- @Test
- public void testInvokeFailsWithUnexpectedException() throws Exception {
-
- DummyCallable foo = new DummyCallable("Foo!", 2);
- ServiceRetrier retrier = new ServiceRetrier(100, 5);
-
- @SuppressWarnings("unchecked")
- Class extends Throwable>[] retryOn = new Class[] { IOException.class };
- retrier.setRetryOn(retryOn);
-
- try {
- retrier.invoke(foo);
- fail("Should have thrown exception");
- } catch (Exception ex) {
- // pass
- }
- }
-
- @Test(expected=IllegalArgumentException.class)
- public void testMaxTriesLessThanOneThrowsException() throws Exception {
- ServiceRetrier retrier = new ServiceRetrier();
- retrier.setMaxTries(-1);
- }
-
- @Test(expected=IllegalArgumentException.class)
- public void testDelayLessThanZeroThrowsException() throws Exception {
- ServiceRetrier retrier = new ServiceRetrier();
- retrier.setDelay(-1);
- }
+ @Test
+ public void testConstructorWithDelayAndMaxTries() throws Exception {
+ ServiceRetrier retrier = new ServiceRetrier(100, 5);
+ assertEquals(5, retrier.getMaxTries());
+ assertEquals(100, retrier.getDelay());
+ }
+
+ @Test
+ public void testConfigurationWithAll() throws Exception {
+ @SuppressWarnings("unchecked")
+ Class[] retryOn = new Class[0];
+
+ ServiceRetrier retrier = new ServiceRetrier(100, 5, true, true, retryOn);
+ assertEquals(5, retrier.getMaxTries());
+ assertEquals(100, retrier.getDelay());
+ assertTrue(retrier.isDoubleDelay());
+ assertTrue(retrier.isThrowCauseException());
+ assertSame(retryOn, retrier.getRetryOn());
+ }
+
+ @Test
+ public void testInvokeSucceedRunnable() throws Exception {
+
+ DummyRunnable foo = new DummyRunnable(5);
+
+ ServiceRetrier retrier = new ServiceRetrier();
+ retrier.setDelay(100);
+ retrier.setMaxTries(5);
+ retrier.setDoubleDelay(false);
+
+ retrier.invoke(foo);
+ assertEquals(5, foo.getCount());
+ }
+
+ @Test
+ public void testInvokeSucceedRunnableResult() throws Exception {
+
+ DummyRunnable foo = new DummyRunnable(5);
+
+ ServiceRetrier retrier = new ServiceRetrier();
+ retrier.setDelay(100);
+ retrier.setMaxTries(5);
+ retrier.setDoubleDelay(false);
+
+ String result = "Foo!";
+ retrier.invoke(foo, result);
+ assertEquals(5, foo.getCount());
+ assertEquals("Foo!", result);
+ }
+
+ @Test
+ public void testDoubleDelay() throws Exception {
+
+ DummyCallable foo = new DummyCallable("Foo!", 5);
+
+ CaptureSleepServiceRetrier retrier = new CaptureSleepServiceRetrier();
+ retrier.setDelay(100);
+ retrier.setMaxTries(5);
+ retrier.setDoubleDelay(true);
+
+ retrier.invoke(foo);
+
+ assertTrue(retrier.isDoubleDelay());
+ assertEquals(4, retrier.getSleepCallCount());
+ assertEquals(100L, (long) retrier.getCapturedSleepValues().get(0));
+ assertEquals(200L, (long) retrier.getCapturedSleepValues().get(1));
+ assertEquals(400L, (long) retrier.getCapturedSleepValues().get(2));
+ assertEquals(800L, (long) retrier.getCapturedSleepValues().get(3));
+ }
+
+ @Test
+ public void testInvokeFail() {
+
+ DummyCallable foo = new DummyCallable("Foo!", 4);
+
+ ServiceRetrier retrier = new ServiceRetrier();
+ retrier.setDelay(100);
+ retrier.setMaxTries(3);
+ retrier.setDoubleDelay(false);
+
+ try {
+ retrier.invoke(foo);
+ fail("Should have thrown exception");
+ } catch (Exception ex) {
+ // pass
+ }
+ }
+
+ @Test
+ public void testInvokeFailsWithUnexpectedException() throws Exception {
+
+ DummyCallable foo = new DummyCallable("Foo!", 2);
+ ServiceRetrier retrier = new ServiceRetrier(100, 5);
+
+ @SuppressWarnings("unchecked")
+ Class extends Throwable>[] retryOn = new Class[] { IOException.class };
+ retrier.setRetryOn(retryOn);
+
+ try {
+ retrier.invoke(foo);
+ fail("Should have thrown exception");
+ } catch (Exception ex) {
+ // pass
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testMaxTriesLessThanOneThrowsException() throws Exception {
+ ServiceRetrier retrier = new ServiceRetrier();
+ retrier.setMaxTries(-1);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testDelayLessThanZeroThrowsException() throws Exception {
+ ServiceRetrier retrier = new ServiceRetrier();
+ retrier.setDelay(-1);
+ }
}
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestServiceStatus.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestServiceStatus.java
index f1c63399..98aed565 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestServiceStatus.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestServiceStatus.java
@@ -28,81 +28,81 @@
public class TestServiceStatus {
- private ServiceStatus serviceStatus;
-
- @Test
- public void testServiceStatus() {
-
- String name = "name";
- Status status = Status.UP;
-
- serviceStatus = new ServiceStatus(name, status);
-
- assertEquals(name, serviceStatus.getName());
- assertEquals(status, serviceStatus.getStatus());
- assertNotNull(serviceStatus.getReasons());
- assertTrue(serviceStatus.getReasons().isEmpty());
- }
-
- @Test
- public void testServiceStatusWithNullReason() {
-
- String name = "name";
- Status status = Status.UP;
-
- serviceStatus = new ServiceStatus(name, status, (String)null);
-
- assertEquals(name, serviceStatus.getName());
- assertEquals(status, serviceStatus.getStatus());
- assertNotNull(serviceStatus.getReasons());
- assertTrue(serviceStatus.getReasons().isEmpty());
- }
-
- @Test
- public void testServiceStatusWithNullReasons() {
-
- String name = "name";
- Status status = Status.UP;
-
- serviceStatus = new ServiceStatus(name, status, (List)null);
-
- assertEquals(name, serviceStatus.getName());
- assertEquals(status, serviceStatus.getStatus());
- assertNotNull(serviceStatus.getReasons());
- assertTrue(serviceStatus.getReasons().isEmpty());
- }
-
- @Test
- public void testServiceStatusWithReason() {
-
- String name = "name";
- Status status = Status.UP;
- String reason = "reason";
-
- serviceStatus = new ServiceStatus(name, status, reason);
-
- assertEquals(name, serviceStatus.getName());
- assertEquals(status, serviceStatus.getStatus());
- assertNotNull(serviceStatus.getReasons());
- assertTrue(serviceStatus.getReasons().contains(reason));
- }
-
- @Test
- public void testServiceStatusWithReasons() {
- String name = "name";
- Status status = Status.UP;
- String reason1 = "reason1";
- String reason2 = "reason2";
- List reasonList = new ArrayList();
- reasonList.add(reason1);
- reasonList.add(reason2);
-
- serviceStatus = new ServiceStatus(name, status, reasonList);
- assertEquals(name, serviceStatus.getName());
- assertEquals(status, serviceStatus.getStatus());
- assertNotNull(serviceStatus.getReasons());
- assertTrue(serviceStatus.getReasons().contains(reason1));
- assertTrue(serviceStatus.getReasons().contains(reason2));
- assertNotSame(serviceStatus.getReasons(), reasonList);
- }
+ private ServiceStatus serviceStatus;
+
+ @Test
+ public void testServiceStatus() {
+
+ String name = "name";
+ Status status = Status.UP;
+
+ serviceStatus = new ServiceStatus(name, status);
+
+ assertEquals(name, serviceStatus.getName());
+ assertEquals(status, serviceStatus.getStatus());
+ assertNotNull(serviceStatus.getReasons());
+ assertTrue(serviceStatus.getReasons().isEmpty());
+ }
+
+ @Test
+ public void testServiceStatusWithNullReason() {
+
+ String name = "name";
+ Status status = Status.UP;
+
+ serviceStatus = new ServiceStatus(name, status, (String) null);
+
+ assertEquals(name, serviceStatus.getName());
+ assertEquals(status, serviceStatus.getStatus());
+ assertNotNull(serviceStatus.getReasons());
+ assertTrue(serviceStatus.getReasons().isEmpty());
+ }
+
+ @Test
+ public void testServiceStatusWithNullReasons() {
+
+ String name = "name";
+ Status status = Status.UP;
+
+ serviceStatus = new ServiceStatus(name, status, (List) null);
+
+ assertEquals(name, serviceStatus.getName());
+ assertEquals(status, serviceStatus.getStatus());
+ assertNotNull(serviceStatus.getReasons());
+ assertTrue(serviceStatus.getReasons().isEmpty());
+ }
+
+ @Test
+ public void testServiceStatusWithReason() {
+
+ String name = "name";
+ Status status = Status.UP;
+ String reason = "reason";
+
+ serviceStatus = new ServiceStatus(name, status, reason);
+
+ assertEquals(name, serviceStatus.getName());
+ assertEquals(status, serviceStatus.getStatus());
+ assertNotNull(serviceStatus.getReasons());
+ assertTrue(serviceStatus.getReasons().contains(reason));
+ }
+
+ @Test
+ public void testServiceStatusWithReasons() {
+ String name = "name";
+ Status status = Status.UP;
+ String reason1 = "reason1";
+ String reason2 = "reason2";
+ List reasonList = new ArrayList();
+ reasonList.add(reason1);
+ reasonList.add(reason2);
+
+ serviceStatus = new ServiceStatus(name, status, reasonList);
+ assertEquals(name, serviceStatus.getName());
+ assertEquals(status, serviceStatus.getStatus());
+ assertNotNull(serviceStatus.getReasons());
+ assertTrue(serviceStatus.getReasons().contains(reason1));
+ assertTrue(serviceStatus.getReasons().contains(reason2));
+ assertNotSame(serviceStatus.getReasons(), reasonList);
+ }
}
diff --git a/jrugged-core/src/test/java/org/fishwife/jrugged/TestServiceWrapperChain.java b/jrugged-core/src/test/java/org/fishwife/jrugged/TestServiceWrapperChain.java
index 31e775a1..d7b4eb46 100644
--- a/jrugged-core/src/test/java/org/fishwife/jrugged/TestServiceWrapperChain.java
+++ b/jrugged-core/src/test/java/org/fishwife/jrugged/TestServiceWrapperChain.java
@@ -9,247 +9,247 @@
import org.junit.Test;
-
public class TestServiceWrapperChain {
- private ServiceWrapperChain impl;
-
- @Test
- public void callableJustGetsInvokedWithNoWrappers() throws Exception {
- impl = new ServiceWrapperChain(new ArrayList());
- final Object out = new Object();
- Callable c = new Callable() {
- public Object call() throws Exception {
- return out;
- }
- };
- assertSame(out, impl.invoke(c));
- }
-
- @Test
- public void runnableJustGetsRunWithNoWrappers() throws Exception {
- Runnable r = createMock(Runnable.class);
- impl = new ServiceWrapperChain(new ArrayList());
- r.run();
- replay(r);
- impl.invoke(r);
- verify(r);
- }
-
- @Test
- public void runnableWithResultJustGetsRunWithNoWrappers() throws Exception {
- Runnable r = createMock(Runnable.class);
- impl = new ServiceWrapperChain(new ArrayList());
- final Object out = new Object();
- r.run();
- replay(r);
- Object result = impl.invoke(r, out);
- verify(r);
- assertSame(out, result);
- }
-
- @Test
- public void callableWithOneWrapperRunsThroughWrapper() throws Exception {
- final Object out = new Object();
- Callable c = new Callable() {
- public Object call() throws Exception {
- return null;
- }
- };
- ServiceWrapper wrapper = createMock(ServiceWrapper.class);
- impl = new ServiceWrapperChain(Arrays.asList(wrapper));
-
- expect(wrapper.invoke(c)).andReturn(out);
- replay(wrapper);
- Object result = impl.invoke(c);
- verify(wrapper);
- assertSame(out, result);
- }
-
- @Test
- public void runnableWithOneWrapperRunsThroughWrapper() throws Exception {
- Runnable r = createMock(Runnable.class);
- ServiceWrapper wrapper = createMock(ServiceWrapper.class);
- impl = new ServiceWrapperChain(Arrays.asList(wrapper));
-
- wrapper.invoke(r);
- replay(wrapper);
- replay(r);
- impl.invoke(r);
- verify(wrapper);
- verify(r);
- }
-
- @Test
- public void runnableWithReturnWithOneWrapperRunsThroughWrapper() throws Exception {
- final Object out = new Object();
- Runnable r = createMock(Runnable.class);
- ServiceWrapper wrapper = createMock(ServiceWrapper.class);
- impl = new ServiceWrapperChain(Arrays.asList(wrapper));
-
- wrapper.invoke(r);
- replay(wrapper);
- replay(r);
- Object result = impl.invoke(r, out);
- verify(wrapper);
- verify(r);
- assertSame(out, result);
- }
-
- @Test
- public void callableWithTwoWrappersRunsThroughFirstWrapperFirst() throws Exception {
- final Object out1 = new Object();
- final Object out2 = new Object();
- Callable c = new NullCallable();
- ServiceWrapper wrapper1 = new NullWrapper() {
- @SuppressWarnings("unchecked")
- @Override
- public T invoke(Callable c) throws Exception {
- return (T)out1;
- }
- };
- ServiceWrapper wrapper2 = new NullWrapper() {
- @SuppressWarnings("unchecked")
- @Override
- public T invoke(Callable c) throws Exception {
- return (T)out2;
- }
- };
- impl = new ServiceWrapperChain(Arrays.asList(wrapper1, wrapper2));
- assertSame(out1, impl.invoke(c));
- }
-
- @Test
- public void runnableWithTwoWrappersRunsThroughFirstWrapperFirst() throws Exception {
- Runnable r = new NullRunnable();
- final Flag f1 = new Flag();
- final Flag f2 = new Flag();
- ServiceWrapper wrapper1 = new NullWrapper() {
- @Override
- public void invoke(Runnable r) throws Exception {
- f1.set = true;
- }
- };
- ServiceWrapper wrapper2 = new NullWrapper() {
- @Override
- public void invoke(Runnable r) throws Exception {
- f2.set = false;
- }
- };
- impl = new ServiceWrapperChain(Arrays.asList(wrapper1, wrapper2));
- impl.invoke(r);
- assertTrue(f1.set);
- assertFalse(f2.set);
- }
-
- @Test
- public void runnableWithReturnWithTwoWrappersRunsThroughFirstWrapperFirst() throws Exception {
- final Object out = new Object();
- Runnable r = new NullRunnable();
- final Flag f1 = new Flag();
- final Flag f2 = new Flag();
- ServiceWrapper wrapper1 = new NullWrapper() {
- @Override
- public void invoke(Runnable r) throws Exception {
- f1.set = true;
- }
- };
- ServiceWrapper wrapper2 = new NullWrapper() {
- @Override
- public void invoke(Runnable r) throws Exception {
- f2.set = false;
- }
- };
- impl = new ServiceWrapperChain(Arrays.asList(wrapper1, wrapper2));
- Object result = impl.invoke(r, out);
- assertTrue(f1.set);
- assertFalse(f2.set);
- assertSame(out, result);
- }
-
- @Test
- public void callableWithTwoNullWrappersThreadsProperly() throws Exception {
- final Object out = new Object();
- Callable c = new Callable() {
- public Object call() throws Exception {
- return out;
- }
- };
- NullWrapper wrapper1 = new NullWrapper();
- NullWrapper wrapper2 = new NullWrapper();
- impl = new ServiceWrapperChain(Arrays.asList((ServiceWrapper)wrapper1, (ServiceWrapper)wrapper2));
- Object result = impl.invoke(c);
- assertTrue(wrapper1.invokedCallable);
- assertTrue(wrapper2.invokedCallable);
- assertSame(out, result);
- }
-
- @Test
- public void runnableWithTwoNullWrappersThreadsProperly() throws Exception {
- final Flag f = new Flag();
- Runnable r = new Runnable() {
- public void run() {
- f.set = true;
- }
- };
- NullWrapper wrapper1 = new NullWrapper();
- NullWrapper wrapper2 = new NullWrapper();
- impl = new ServiceWrapperChain(Arrays.asList((ServiceWrapper)wrapper1, (ServiceWrapper)wrapper2));
- impl.invoke(r);
- assertTrue(wrapper1.invokedRunnable);
- assertTrue(wrapper2.invokedRunnable);
- assertTrue(f.set);
- }
-
- @Test
- public void runnableWithReturnWithTwoNullWrappersThreadsProperly() throws Exception {
- final Object out = new Object();
- final Flag f = new Flag();
- Runnable r = new Runnable() {
- public void run() {
- f.set = true;
- }
- };
- NullWrapper wrapper1 = new NullWrapper();
- NullWrapper wrapper2 = new NullWrapper();
- impl = new ServiceWrapperChain(Arrays.asList((ServiceWrapper)wrapper1, (ServiceWrapper)wrapper2));
- Object result = impl.invoke(r, out);
- assertTrue(wrapper1.invokedRunnable);
- assertTrue(wrapper2.invokedRunnable);
- assertTrue(f.set);
- assertSame(out, result);
- }
-
- private static class Flag {
- public boolean set = false;
- }
-
- private static class NullRunnable implements Runnable {
- public void run() { }
- }
-
- private static class NullCallable implements Callable {
- public Object call() throws Exception {
- return null;
- }
- }
-
- private static class NullWrapper implements ServiceWrapper {
- public boolean invokedCallable;
- public boolean invokedRunnable;
-
- public