StoryDuration.java

  1. package org.jbehave.core.model;

  2. import org.apache.commons.lang3.builder.ToStringBuilder;
  3. import org.apache.commons.lang3.builder.ToStringStyle;

  4. public class StoryDuration {

  5.     private static final int CANCEL_TIMEOUT_RATIO = 20;

  6.     private long startedAtMillis;
  7.     private long durationInMillis;
  8.     private final long timeoutInSecs;
  9.     private final long cancelTimeoutInSecs;

  10.     public StoryDuration(long timeoutInSecs) {
  11.         this(System.currentTimeMillis(), timeoutInSecs);
  12.     }

  13.     public StoryDuration(long startedAtMillis, long timeoutInSecs) {
  14.         this.startedAtMillis = startedAtMillis;
  15.         this.timeoutInSecs = timeoutInSecs;
  16.         this.cancelTimeoutInSecs = timeoutInSecs / CANCEL_TIMEOUT_RATIO;
  17.     }

  18.     public long getDurationInSecs() {
  19.         return durationInMillis / 1000;
  20.     }

  21.     public long getTimeoutInSecs() {
  22.         return timeoutInSecs;
  23.     }

  24.     public StoryDuration setDurationInSecs(long durationInSecs) {
  25.         this.durationInMillis = durationInSecs * 1000;
  26.         return this;
  27.     }

  28.     public StoryDuration update() {
  29.         this.durationInMillis = elapsedTimeInMillis();
  30.         return this;
  31.     }

  32.     private long elapsedTimeInMillis() {
  33.         return System.currentTimeMillis() - startedAtMillis;
  34.     }    

  35.     public boolean timedOut() {
  36.         return timeoutInSecs != 0 && getDurationInSecs() > timeoutInSecs;
  37.     }

  38.     public boolean cancelTimedOut() {
  39.         return cancelTimeoutInSecs == 0 || getDurationInSecs() > timeoutInSecs + cancelTimeoutInSecs;
  40.     }

  41.     @Override
  42.     public String toString() {
  43.         return ToStringBuilder.reflectionToString(this, ToStringStyle.SIMPLE_STYLE);
  44.     }
  45. }