/**
   * Find the current instance based on effectiveTime (i.e Action_Creation_Time or
   * Action_Start_Time)
   *
   * @return current instance i.e. current(0) returns null if effectiveTime is earlier than Initial
   *     Instance time of the dataset.
   */
  private static Calendar getCurrentInstance(Date effectiveTime, int instanceCount[]) {
    Date datasetInitialInstance = getInitialInstance();
    TimeUnit dsTimeUnit = getDSTimeUnit();
    TimeZone dsTZ = getDatasetTZ();
    // Convert Date to Calendar for corresponding TZ
    Calendar current = Calendar.getInstance();
    current.setTime(datasetInitialInstance);
    current.setTimeZone(dsTZ);

    Calendar calEffectiveTime = Calendar.getInstance();
    calEffectiveTime.setTime(effectiveTime);
    calEffectiveTime.setTimeZone(dsTZ);
    instanceCount[0] = 0;
    if (current.compareTo(calEffectiveTime) > 0) {
      // Nominal Time < initial Instance
      // TODO: getClass() call doesn't work from static method.
      // XLog.getLog("CoordELFunction.class").warn("ACTION CREATED BEFORE INITIAL INSTACE "+
      // current.getTime());
      return null;
    }
    Calendar origCurrent = (Calendar) current.clone();
    while (current.compareTo(calEffectiveTime) <= 0) {
      current = (Calendar) origCurrent.clone();
      instanceCount[0]++;
      current.add(dsTimeUnit.getCalendarUnit(), instanceCount[0] * getDSFrequency());
    }
    instanceCount[0]--;

    current = (Calendar) origCurrent.clone();
    current.add(dsTimeUnit.getCalendarUnit(), instanceCount[0] * getDSFrequency());
    return current;
  }
示例#2
0
    public TimeUnit deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
      String unit = json.getAsString();
      TimeUnit tu;

      try {
        tu = TimeUnit.from(unit);
      } catch (IllegalArgumentException e) {
        throw new ContextualJsonSyntaxException(
            unit, "is not a valid time unit, must be one of " + TimeUnit.toValueNames());
      }

      return tu;
    }
 /**
  * Returns the a date string while given a base date in 'strBaseDate', offset and unit (e.g. DAY,
  * MONTH, HOUR, MINUTE, MONTH).
  *
  * @param strBaseDate -- base date
  * @param offset -- any number
  * @param unit -- DAY, MONTH, HOUR, MINUTE, MONTH
  * @return date string
  * @throws Exception
  */
 public static String ph2_coord_dateOffset(String strBaseDate, int offset, String unit)
     throws Exception {
   Calendar baseCalDate = DateUtils.getCalendar(strBaseDate);
   StringBuilder buffer = new StringBuilder();
   baseCalDate.add(TimeUnit.valueOf(unit).getCalendarUnit(), offset);
   buffer.append(DateUtils.formatDateUTC(baseCalDate));
   return buffer.toString();
 }
  /**
   * @param n
   * @return n-th instance Date-Time from current instance for data-set
   *     <p>return empty string ("") if the Action_Creation_time or the n-th instance
   *     <p>is earlier than the Initial_Instance of dataset.
   * @throws Exception
   */
  private static String coord_current_sync(int n) throws Exception {
    int datasetFrequency = getDSFrequency(); // in minutes
    TimeUnit dsTimeUnit = getDSTimeUnit();
    int[] instCount = new int[1]; // used as pass by ref
    Calendar nominalInstanceCal = getCurrentInstance(getActionCreationtime(), instCount);
    if (nominalInstanceCal == null) {
      return "";
    }
    nominalInstanceCal = getInitialInstanceCal();
    int absInstanceCount = instCount[0] + n;
    nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(), datasetFrequency * absInstanceCount);

    if (nominalInstanceCal.getTime().compareTo(getInitialInstance()) < 0) {
      return "";
    }
    String str = DateUtils.formatDateUTC(nominalInstanceCal);
    return str;
  }
示例#5
0
 /**
  *
  * <!-- begin-user-doc -->
  * <!-- end-user-doc -->
  *
  * @generated
  */
 public TimeUnit createTimeUnitFromString(EDataType eDataType, String initialValue) {
   TimeUnit result = TimeUnit.get(initialValue);
   if (result == null)
     throw new IllegalArgumentException(
         "The value '"
             + initialValue
             + "' is not a valid enumerator of '"
             + eDataType.getName()
             + "'");
   return result;
 }
  private void calculateBarLeft(Date plannedStartTime, long startingPoint) {

    // Calendar c = Calendar.getInstance();
    // c.setTimeInMillis(startingPoint);
    //
    // c.set(Calendar.MINUTE, 0);
    // c.set(Calendar.SECOND, 0);
    // c.set(Calendar.MILLISECOND, 0);

    Calendar calculatedStartDate = timeUnit.calculateStartDate(startingPoint);
    long difference = plannedStartTime.getTime() - calculatedStartDate.getTimeInMillis();

    this.barLeft = new Long(difference / 1000 / 60).intValue();
  }
  private void calculateProgressLeft(long startTime, long startingPoint) {
    if (startTime == 0) {
      this.progressLeft = this.barLeft;
    } else {

      // Calendar c = Calendar.getInstance();
      // c.setTimeInMillis(startingPoint);
      //
      // c.set(Calendar.MINUTE, 0);
      // c.set(Calendar.SECOND, 0);
      // c.set(Calendar.MILLISECOND, 0);

      Calendar calculatedStartDate = timeUnit.calculateStartDate(startingPoint);
      long difference = startTime - calculatedStartDate.getTimeInMillis();

      progressLeft =
          new BigDecimal(difference)
              .divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP)
              .divide(new BigDecimal(60), 2, BigDecimal.ROUND_HALF_UP)
              .doubleValue();
    }
  }
  /**
   * @param offset
   * @return n-th available latest instance Date-Time for SYNC data-set
   * @throws Exception
   */
  private static String coord_latest_sync(int offset) throws Exception {
    if (offset > 0) {
      throw new RuntimeException(
          "For latest there is no meaning " + "of positive instance. n should be <=0" + offset);
    }
    ELEvaluator eval = ELEvaluator.getCurrent();
    String retVal = "";
    int datasetFrequency = (int) getDSFrequency(); // in minutes
    TimeUnit dsTimeUnit = getDSTimeUnit();
    int[] instCount = new int[1];
    Calendar nominalInstanceCal = getCurrentInstance(getActualTime(), instCount);
    if (nominalInstanceCal != null) {
      Calendar initInstance = getInitialInstanceCal();
      SyncCoordDataset ds = (SyncCoordDataset) eval.getVariable(DATASET);
      if (ds == null) {
        throw new RuntimeException("Associated Dataset should be defined with key " + DATASET);
      }
      String uriTemplate = ds.getUriTemplate();
      Configuration conf = (Configuration) eval.getVariable(CONFIGURATION);
      if (conf == null) {
        throw new RuntimeException(
            "Associated Configuration should be defined with key " + CONFIGURATION);
      }
      int available = 0;
      boolean resolved = false;
      String user =
          ParamChecker.notEmpty(
              (String) eval.getVariable(OozieClient.USER_NAME), OozieClient.USER_NAME);
      String group =
          ParamChecker.notEmpty(
              (String) eval.getVariable(OozieClient.GROUP_NAME), OozieClient.GROUP_NAME);
      String doneFlag = ds.getDoneFlag();
      while (nominalInstanceCal.compareTo(initInstance) >= 0) {
        ELEvaluator uriEval = getUriEvaluator(nominalInstanceCal);
        String uriPath = uriEval.evaluate(uriTemplate, String.class);
        String pathWithDoneFlag = uriPath;
        if (doneFlag.length() > 0) {
          pathWithDoneFlag += "/" + doneFlag;
        }
        if (isPathAvailable(pathWithDoneFlag, user, group, conf)) {
          XLog.getLog(CoordELFunctions.class)
              .debug("Found latest(" + available + "): " + pathWithDoneFlag);
          if (available == offset) {
            XLog.getLog(CoordELFunctions.class).debug("Found Latest File: " + pathWithDoneFlag);
            resolved = true;
            retVal = DateUtils.formatDateUTC(nominalInstanceCal);
            eval.setVariable("resolved_path", uriPath);
            break;
          }

          available--;
        }
        // nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(),
        // -datasetFrequency);
        nominalInstanceCal = (Calendar) initInstance.clone();
        instCount[0]--;
        nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(), instCount[0] * datasetFrequency);
        // DateUtils.moveToEnd(nominalInstanceCal, getDSEndOfFlag());
      }
      if (!resolved) {
        // return unchanged latest function with variable 'is_resolved'
        // to 'false'
        eval.setVariable("is_resolved", Boolean.FALSE);
        retVal = "${coord:latest(" + offset + ")}";
      } else {
        eval.setVariable("is_resolved", Boolean.TRUE);
      }
    } else { // No feasible nominal time
      eval.setVariable("is_resolved", Boolean.FALSE);
    }
    return retVal;
  }
 public int getDurationWidth() {
   return timeUnit.calculateSize(durationWidth);
 }
示例#10
0
 @Override
 public void writeToParcel(Parcel dest, int flags) {
   dest.writeInt(timeInterval);
   dest.writeInt(timeUnit.ordinal());
 }
示例#11
0
 private Duration(Parcel in) {
   timeInterval = in.readInt();
   timeUnit = TimeUnit.values()[in.readInt()];
 }
示例#12
0
 public static Long convertTime(Long time, TimeUnit from, TimeUnit to) {
   return (time == null) ? null : new Long((time.longValue() * from.getFactor()) / to.getFactor());
 }
示例#13
0
 public String format() {
   return units.formatFull(dateTime.getMillis());
 }
示例#14
0
 public RoughTime plus(TimeUnit unit, int times) {
   RoughTime r = copy();
   unit.addTo(r, times);
   return r;
 }
示例#15
0
  public void calculateDiagramBars() {
    long startTime = instance != null ? instance.getStartTime().getTime() : 0;

    // calculate status and color
    this.calculateStatus(model, instance, predecessor);

    if (model.getPlannedStartTime() != null && model.getPlannedTerminationTime() != null) {
      // calculate barWidth
      this.calculateBarWidth(model.getPlannedStartTime(), model.getPlannedTerminationTime());

      // calculate barLeft
      this.calculateBarLeft(model.getPlannedStartTime(), startingPoint);
    }

    // calculate progressLeft
    this.calculateProgressLeft(startTime, startingPoint);

    // calculate progressWidth
    Calendar calculatedStartDate = timeUnit.calculateStartDate(startingPoint);
    this.progressWidth = 0;
    long duration = instance != null ? instance.getDuration() : 0;
    if (instance != null) {
      if (instance.getTerminationTime() != null) {
        this.progressWidth =
            new BigDecimal(new Long(duration).doubleValue())
                .divide(new BigDecimal(1000), BigDecimal.ROUND_HALF_UP)
                .divide(new BigDecimal(60), BigDecimal.ROUND_HALF_UP)
                .intValue();
      } else {
        BigDecimal nowBD =
            new BigDecimal(
                new Long(timeProvider.getCurrentTime() - calculatedStartDate.getTimeInMillis())
                    .doubleValue());
        double nowInTimeUnit =
            nowBD
                .divide(new BigDecimal(1000), 1, BigDecimal.ROUND_HALF_UP)
                .divide(new BigDecimal(60), 1, BigDecimal.ROUND_HALF_UP)
                .doubleValue();
        this.progressWidth = timeUnit.calculateSize(nowInTimeUnit) - getProgressLeft();
      }
    }

    if (model.getEstimatedDuration() != 0) {
      // calculate progress
      this.calculateProgress(duration, model.getEstimatedDuration());
      progressCalculated = true;
    }

    this.calculateIconStatus(instance);

    // calculate durationWidth
    this.durationWidth = new Long(model.getEstimatedDuration()).intValue() / 1000 / 60;

    if (model.getSuccessorId() != null && !"".equals(model.getSuccessorId())) {
      this.dependencyHeight = 0;
      //         this.dependencyWidth = 1;
    }

    // completed process instance
    if (instance != null && instance.getTerminationTime() != null) {
      this.completed = "background-color: #EEEFF7;";
      // this.durationWidth = 0;
      // this.barWidth = 0;
      // this.progressColor = this.color;
    }
  }
示例#16
0
 public long convert(long d, TimeUnit u) {
   return u.toHours(d);
 }
示例#17
0
 public long convert(long d, TimeUnit u) {
   return u.toSeconds(d);
 }
示例#18
0
 public int getProgressLeft() {
   return timeUnit.calculateSize(progressLeft);
 }
示例#19
0
 public int getBarLeft() {
   return timeUnit.calculateSize(barLeft);
 }
示例#20
0
 public int getBarWidth() {
   return timeUnit.calculateSize(barWidth);
 }
示例#21
0
 public long convert(long d, TimeUnit u) {
   return u.toMinutes(d);
 }
 /**
  * Acquires the lock if it is not held by another thread within the given waiting time and the
  * current thread has not been {@link Thread#interrupt interrupted}.
  *
  * <p>Acquires the lock if it is not held by another thread and returns immediately with the value
  * <tt>true</tt>, setting the lock hold count to one. If this lock has been set to use a fair
  * ordering policy then an available lock <em>will not</em> be acquired if any other threads are
  * waiting for the lock. This is in contrast to the {@link #tryLock()} method. If you want a timed
  * <tt>tryLock</tt> that does permit barging on a fair lock then combine the timed and un-timed
  * forms together:
  *
  * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
  * </pre>
  *
  * <p>If the current thread already holds this lock then the hold count is incremented by one and
  * the method returns <tt>true</tt>.
  *
  * <p>If the lock is held by another thread then the current thread becomes disabled for thread
  * scheduling purposes and lies dormant until one of three things happens:
  *
  * <ul>
  *   <li>The lock is acquired by the current thread; or
  *   <li>Some other thread {@link Thread#interrupt interrupts} the current thread; or
  *   <li>The specified waiting time elapses
  * </ul>
  *
  * <p>If the lock is acquired then the value <tt>true</tt> is returned and the lock hold count is
  * set to one.
  *
  * <p>If the current thread:
  *
  * <ul>
  *   <li>has its interrupted status set on entry to this method; or
  *   <li>is {@link Thread#interrupt interrupted} while acquiring the lock,
  * </ul>
  *
  * then {@link InterruptedException} is thrown and the current thread's interrupted status is
  * cleared.
  *
  * <p>If the specified waiting time elapses then the value <tt>false</tt> is returned. If the time
  * is less than or equal to zero, the method will not wait at all.
  *
  * <p>In this implementation, as this method is an explicit interruption point, preference is
  * given to responding to the interrupt over normal or reentrant acquisition of the lock, and over
  * reporting the elapse of the waiting time.
  *
  * @param timeout the time to wait for the lock
  * @param unit the time unit of the timeout argument
  * @return <tt>true</tt> if the lock was free and was acquired by the current thread, or the lock
  *     was already held by the current thread; and <tt>false</tt> if the waiting time elapsed
  *     before the lock could be acquired.
  * @throws InterruptedException if the current thread is interrupted
  * @throws NullPointerException if unit is null
  */
 public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
   return sync.tryLock(unit.toNanos(timeout));
 }
示例#23
0
 public long convert(long d, TimeUnit u) {
   return u.toNanos(d);
 }
示例#24
0
public class Chronometer {
  ////////////////////////////////////////////////////////////////////////////
  // ATTRIBUTE(S)
  ////////////////////////////////////////////////////////////////////////////

  // Time units
  public static final int N_TIME_UNITS = TimeUnit.values().length;
  // Information of the chronometer
  private final long[] time = new long[N_TIME_UNITS];
  private final double[] timeByUnit = new double[N_TIME_UNITS];
  private long begin = 0L, end = 0L;
  private Long difference = 0L;
  private String representation = Strings.EMPTY;

  ////////////////////////////////////////////////////////////////////////////
  // CONSTRUCTOR(S)
  ////////////////////////////////////////////////////////////////////////////

  public Chronometer() {}

  ////////////////////////////////////////////////////////////////////////////
  // CHRONOMETER
  ////////////////////////////////////////////////////////////////////////////

  public void start() {
    begin = System.currentTimeMillis();
  }

  public Long stop() {
    end = System.currentTimeMillis();
    compute();
    return difference;
  }

  private void compute() {
    difference = end - begin;
    timeByUnit[0] = difference;
    time[0] = (long) (timeByUnit[0] % 1000);
    for (int i = 1; i < N_TIME_UNITS; ++i) {
      timeByUnit[i] = difference / (1000. * Math.pow(60, i - 1));
      time[i] = (long) (timeByUnit[i] % 60);
    }
    representation =
        time[TimeUnit.HOUR.index]
            + ":"
            + time[TimeUnit.MINUTE.index]
            + ":"
            + time[TimeUnit.SECOND.index]
            + "."
            + time[TimeUnit.MILLISECOND.index];
  }

  public long getMilliseconds() {
    return difference;
  }

  public double getSeconds() {
    return timeByUnit[TimeUnit.SECOND.index];
  }

  public double getMinutes() {
    return timeByUnit[TimeUnit.MINUTE.index];
  }

  public double getHours() {
    return timeByUnit[TimeUnit.HOUR.index];
  }

  public void setValue(final long value) {
    begin = 0;
    end = value;
    compute();
  }

  ////////////////////////////////////////////////////////////////////////////
  // OBJECT
  ////////////////////////////////////////////////////////////////////////////

  @Override
  public String toString() {
    return representation;
  }

  ////////////////////////////////////////////////////////////////////////////
  // ENUM(S)
  ////////////////////////////////////////////////////////////////////////////

  public enum TimeUnit {
    MILLISECOND(0),
    SECOND(1),
    MINUTE(2),
    HOUR(3);
    public int index;

    private TimeUnit(final int index) {
      this.index = index;
    }
  }
}