public Optional<Employee> authenticate(String accessTokenId) throws AuthenticationException {

    // Check input, must be a valid UUID
    UUID accessTokenUUID;
    try {
      accessTokenUUID = UUID.fromString(accessTokenId);
    } catch (IllegalArgumentException e) {
      return Optional.absent();
    }

    // Get the access token from the database
    Optional<AccessToken> accessToken = accessTokenDAO.findAccessTokenById(accessTokenUUID);
    if (accessToken == null || !accessToken.isPresent()) {
      return Optional.absent();
    }

    // Check if the last access time is not too far in the past (the access token is expired)
    Period period = new Period(accessToken.get().getLastAccessUTC(), new DateTime());
    if (period.getMinutes() > ACCESS_TOKEN_EXPIRE_TIME_MIN) {
      return Optional.absent();
    }

    // Update the access time for the token
    accessTokenDAO.setLastAccessTime(accessTokenUUID, new DateTime());

    // Return the user's id for processing
    return Optional.of(accessToken.get().getEmployee());
  }
Exemplo n.º 2
0
 public static void blockUntil(String tag, DateTime startAt, long sleepTime) {
   PeriodFormatter pf =
       new PeriodFormatterBuilder()
           .printZeroAlways()
           .appendHours()
           .appendLiteral("小时")
           .appendMinutes()
           .appendLiteral("分")
           .appendSeconds()
           .appendLiteral("秒")
           .toFormatter();
   while (true) {
     DateTime now = DateTime.now();
     Period p = new Period(now, startAt);
     if (now.isAfter(startAt)) {
       System.out.println("时间到了, 启动!");
       break;
     } else {
       System.out.println("[" + tag + "]" + " 距离开始还有 " + p.toString(pf));
     }
     try {
       Thread.sleep(sleepTime);
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
   }
   System.out.println("执行...");
 }
 @Before
 public void setUp() {
   aggregator_0 =
       new UserActivityAggregatorImpl(
           Arrays.asList(UserProfileConstants.DEFAULT_CMD_TYPES), Period.parse("PT1m"), "test", 0);
   aggregator_1 =
       new UserActivityAggregatorImpl(
           Arrays.asList(UserProfileConstants.DEFAULT_CMD_TYPES),
           Period.parse("PT1m"),
           "test",
           5000);
 }
Exemplo n.º 4
0
 private static Period withTwoMostSignificantNonZeroFieldsOnly(Period period) {
   int nonZeroFieldsFound = 0;
   for (DurationFieldType durationFieldType : period.getFieldTypes()) {
     if (period.get(durationFieldType) != 0) {
       if (nonZeroFieldsFound < 2) {
         nonZeroFieldsFound++;
       } else {
         period = period.withField(durationFieldType, 0);
       }
     }
   }
   return period;
 }
Exemplo n.º 5
0
 @Transient
 public String getWorkage() {
   if (this.dob != null) {
     Calendar c = Calendar.getInstance();
     if (this.firstworktime == null) c.setTime(new Date());
     else c.setTime(firstworktime);
     Calendar cnow = Calendar.getInstance();
     cnow.setTime(new Date());
     Period p = new Period(c.getTimeInMillis(), cnow.getTimeInMillis(), PeriodType.yearMonthDay());
     Integer yearint = p.getYears();
     Integer monthint = p.getMonths();
     Integer dayint = p.getDays();
     return yearint.toString() + "年" + monthint.toString() + "月" + dayint.toString() + "日";
   } else return "";
 }
Exemplo n.º 6
0
    @Override
    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (o == null || getClass() != o.getClass()) {
        return false;
      }

      PeriodGranularity that = (PeriodGranularity) o;

      if (hasOrigin != that.hasOrigin) {
        return false;
      }
      if (origin != that.origin) {
        return false;
      }
      if (!chronology.equals(that.chronology)) {
        return false;
      }
      if (!period.equals(that.period)) {
        return false;
      }

      return true;
    }
Exemplo n.º 7
0
  private void repeatUpdateStats() {
    TextView view = (TextView) findViewById(R.id.totalClicks);
    view.setText(String.valueOf(clicks.getClicks()));

    view = (TextView) findViewById(R.id.timeDisplay);
    view.setText(periodFormat.print(period.normalizedStandard()));
  }
Exemplo n.º 8
0
 private void updateStats() {
   TextView view = (TextView) findViewById(R.id.manualClicks);
   view.setText(String.valueOf(Button.getManualClicks()));
   period = new Period(startTime, new DateTime());
   view = (TextView) findViewById(R.id.timeDisplay);
   view.setText(period.toString());
 }
Exemplo n.º 9
0
  @JsonCreator
  public KafkaSupervisorIOConfig(
      @JsonProperty("topic") String topic,
      @JsonProperty("replicas") Integer replicas,
      @JsonProperty("taskCount") Integer taskCount,
      @JsonProperty("taskDuration") Period taskDuration,
      @JsonProperty("consumerProperties") Map<String, String> consumerProperties,
      @JsonProperty("startDelay") Period startDelay,
      @JsonProperty("period") Period period,
      @JsonProperty("useEarliestOffset") Boolean useEarliestOffset,
      @JsonProperty("completionTimeout") Period completionTimeout,
      @JsonProperty("lateMessageRejectionPeriod") Period lateMessageRejectionPeriod) {
    this.topic = Preconditions.checkNotNull(topic, "topic");
    this.consumerProperties = Preconditions.checkNotNull(consumerProperties, "consumerProperties");
    Preconditions.checkNotNull(
        consumerProperties.get(BOOTSTRAP_SERVERS_KEY),
        String.format("consumerProperties must contain entry for [%s]", BOOTSTRAP_SERVERS_KEY));

    this.replicas = (replicas != null ? replicas : 1);
    this.taskCount = (taskCount != null ? taskCount : 1);
    this.taskDuration = defaultDuration(taskDuration, "PT1H");
    this.startDelay = defaultDuration(startDelay, "PT5S");
    this.period = defaultDuration(period, "PT30S");
    this.useEarliestOffset = (useEarliestOffset != null ? useEarliestOffset : false);
    this.completionTimeout = defaultDuration(completionTimeout, "PT30M");
    this.lateMessageRejectionPeriod =
        (lateMessageRejectionPeriod == null
            ? Optional.<Duration>absent()
            : Optional.of(lateMessageRejectionPeriod.toStandardDuration()));
  }
Exemplo n.º 10
0
  public Element toXML() {
    Element result = new Element("timer");

    XMLUtil.createElement("title", getTitle(), result);
    XMLUtil.createElement("started", started == null ? "" : started.toString(), result);
    XMLUtil.createElement("total", period.toString(), result);
    XMLUtil.createElement("speed", update_speed, result);

    XMLUtil.createElement("x", getX(), result);
    XMLUtil.createElement("y", getY(), result);
    XMLUtil.createElement("width", getWidth(), result);
    XMLUtil.createElement("height", getHeight(), result);

    XMLUtil.createElement(
        "foreground", String.format("%08x", total.getForeground().getRGB()), result);
    XMLUtil.createElement(
        "background", String.format("%08x", panel.getBackground().getRGB()), result);

    XMLUtil.createElement("visible", isVisible(), result);

    Element times = new Element("times");
    for (TimeSpan ts : this.times) {
      times.addContent(ts.toXML());
    }
    result.addContent(times);
    return result;
  }
Exemplo n.º 11
0
 private String epocToSimpleDate(long epoc) {
   Period diff = new Period(epoc, System.currentTimeMillis(), PeriodType.standard());
   PeriodType type;
   if (diff.getMonths() > 0) {
     type = PeriodType.yearMonthDay();
   } else if (diff.getWeeks() > 0) {
     type = PeriodType.yearWeekDay();
   } else if (diff.getDays() > 0) {
     type = PeriodType.dayTime().withSecondsRemoved().withMillisRemoved().withMinutesRemoved();
   } else if (diff.getMinutes() > 0) {
     type = PeriodType.time().withMillisRemoved().withSecondsRemoved();
   } else {
     type = PeriodType.time().withMillisRemoved();
   }
   return PeriodFormat.getDefault().print(new Period(epoc, System.currentTimeMillis(), type));
 }
Exemplo n.º 12
0
 @Override
 public int hashCode() {
   int result = period.hashCode();
   result = 31 * result + chronology.hashCode();
   result = 31 * result + (int) (origin ^ (origin >>> 32));
   result = 31 * result + (hasOrigin ? 1 : 0);
   return result;
 }
 private void checkAgainstTimespanRestriction(String timespan) {
   Duration duration = Period.parse(requestIntervalRestriction).toDurationFrom(new DateTime());
   if (duration.getMillis() < Interval.parse(timespan).toDurationMillis()) {
     throw new BadRequestException(
         "Requested timespan is to long, please use a period shorter than '"
             + requestIntervalRestriction
             + "'");
   }
 }
 /**
  * Calculates the number of days spanned in a period assuming 365 days per year, 30 days per
  * month, 7 days per week, 24 hours per day, 60 minutes per hour and 60 seconds per minute.
  *
  * @param period A period to retrieve the number of standard days for
  * @return The number of days spanned by the period.
  */
 protected static int getDaysInPeriod(final Period period) {
   int totalDays = 0;
   Period temp = new Period(period);
   if (period.getYears() > 0) {
     int years = period.getYears();
     totalDays += 365 * years;
     temp = temp.minusYears(years);
   }
   if (period.getMonths() > 0) {
     int months = period.getMonths();
     totalDays += 30 * period.getMonths();
     temp = temp.minusMonths(months);
   }
   return totalDays + temp.toStandardDays().getDays();
 }
Exemplo n.º 15
0
 private void setHigh(PointInTime high) {
   if (Precision.MILLISECOND.equals(high.getPrecision())) {
     this.high = high.clone();
   } else {
     this.high = high.promote().getHigh();
     if (isHighClosed()) {
       this.high = this.high.subtract(Period.millis(1));
     }
   }
 }
  private FlexOffer buildFlexOffer() {
    FlexOffer request = new FlexOffer();
    request.setTimeZone("Europe/Amsterdam");
    request.setPTUDuration(Period.minutes(15));
    request.setCurrency("EUR");
    request.setMessageMetadata(MessageMetadataBuilder.buildDefault());
    request.setCongestionPoint("agr.usef-example.com");

    return request;
  }
  /**
   * Parses a string into a Period object according to the replacers mapping. This allows for
   * duplicate fields (e.g. seconds being declared twice as in "2s 3 sec") with the duplicate fields
   * being added together (the above example would be the same as "5 seconds"). The order of the
   * fields is not important.
   *
   * @param dateOffset The parameter without the operator. If the operator is passed in it will be
   *     ignored
   * @return A period corresponding to the parsed input string
   */
  private Period toPeriod(final String dateOffset) {
    String regexp = "(\\d+) *([a-zA-z]+)";
    Period period = new Period();

    if (dateOffset == null || dateOffset.isEmpty()) return period;

    Pattern pattern = Pattern.compile(regexp);
    Matcher matcher = pattern.matcher(dateOffset);
    while (matcher.find()) {
      String svalue = matcher.toMatchResult().group(1);
      DurationFieldType fieldType = replacers.get(matcher.toMatchResult().group(2));
      if (fieldType != null) {
        // Note that both these methods do not modify their objects
        period = period.withFieldAdded(fieldType, Integer.parseInt(svalue));
      }
    }

    return period;
  }
Exemplo n.º 18
0
 private static boolean isCompoundPeriod(Period period) {
   int[] values = period.getValues();
   boolean single = false;
   for (int v : values) {
     if (v > 0) {
       if (single) return true;
       single = true;
     }
   }
   return false;
 }
Exemplo n.º 19
0
 public void testSubtractDays() {
   // This is a test for a bug in version 1.0. The dayOfMonth range
   // duration field did not match the monthOfYear duration field. This
   // caused an exception to be thrown when subtracting days.
   DateTime dt =
       new DateTime(1112306400000L, GJChronology.getInstance(DateTimeZone.forID("Europe/Berlin")));
   YearMonthDay ymd = dt.toYearMonthDay();
   while (ymd.toDateTimeAtMidnight().getDayOfWeek() != DateTimeConstants.MONDAY) {
     ymd = ymd.minus(Period.days(1));
   }
 }
Exemplo n.º 20
0
 public void test_zeroDateIsNotNever() throws Exception {
   Long at1January1970 = DateTimeOperations.convert(Period.seconds(0));
   Assert.assertFalse(
       DateTimeOperations.compare(
               at1January1970, CompareType.EQ, null, DateTimeFieldType.millisOfSecond())
           || DateTimeOperations.compare(
               at1January1970,
               CompareType.EQ,
               DateTimeOperations.never(),
               DateTimeFieldType.millisOfSecond()));
 }
Exemplo n.º 21
0
  @Transient
  public String getAge() {
    if (this.dob != null) {
      Calendar c = Calendar.getInstance();
      c.setTime(this.dob);
      Calendar cnow = Calendar.getInstance();
      cnow.setTime(new Date());

      Period p = new Period(c.getTimeInMillis(), cnow.getTimeInMillis(), PeriodType.yearMonthDay());
      Integer yearint = p.getYears();
      Integer monthint = p.getMonths();
      Integer dayint = p.getDays();

      //			Integer yearint = cnow.get(Calendar.YEAR) - c.get(Calendar.YEAR);
      //			if(cnow.get(Calendar.DAY_OF_YEAR) < c.get(Calendar.DAY_OF_YEAR))
      //				yearint--;
      //			Integer monthint = (cnow.get(Calendar.MONTH) - c.get(Calendar.MONTH) + 12)%12;
      //			Integer dayint  = (cnow.get(Calendar.DAY_OF_MONTH) - c.get(Calendar.DAY_OF_MONTH)+30)%30;
      return yearint.toString() + "岁" + monthint.toString() + "月" + dayint.toString() + "日";
    } else return "";
  }
Exemplo n.º 22
0
  /**
   * Builds and returns earliest text when given a resources bundle.
   *
   * @param formats an array of strings containing formats for [no-alarm-active, < minute, xx-yy-zz,
   *     xx-yy, xx] where xx, yy, zz can be either day, hours, minutes (non-respectively).
   * @param partsFormat an array of strings containing part formats for [day, month, hour].
   * @param diff difference between now and ats.
   * @param ats an AlarmTimestamp: the information about the alarm & its timestamp.
   * @return the built time-to string.
   */
  public static final String getTimeToText(
      String[] formats, String[] partFormats, Period diff, AlarmTimestamp ats) {
    String earliestText;

    // Not real? = we don't have any alarms active.
    if (ats == AlarmTimestamp.INVALID) {
      earliestText = formats[0];
    } else {
      int[] diffVal = {
        Math.abs(diff.getDays()), Math.abs(diff.getHours()), Math.abs(diff.getMinutes())
      };

      // What fields are set?
      BitSet setFields = new BitSet(3);
      setFields.set(0, diffVal[0] != 0);
      setFields.set(1, diffVal[1] != 0);
      setFields.set(2, diffVal[2] != 0);
      int cardinality = setFields.cardinality();

      earliestText = formats[cardinality + 1];

      if (cardinality > 0) {
        List<String> args = new ArrayList<String>(3);

        for (int i = setFields.nextSetBit(0); i >= 0; i = setFields.nextSetBit(i + 1)) {
          args.add(partFormats[i]);
        }

        // Finally format everything.
        earliestText = String.format(earliestText, args.toArray());

        earliestText = String.format(earliestText, diffVal[0], diffVal[1], diffVal[2]);
      } else {
        // only seconds remains until it goes off.
        earliestText = formats[1];
      }
    }

    return earliestText;
  }
Exemplo n.º 23
0
 public void test_westernHemisphereTime() throws Exception {
   Long yesterday =
       DateTimeOperations.convert(
           (new DateTime(2009, 7, 23, 13, 18, 20, 0, DateTimeZone.forID("UTC"))));
   Assert.assertEquals(
       DateTimeOperations.print(
           yesterday, DateTimeFormat.shortTime(), null, DateTimeZone.forID("America/New_York")),
       DateTimeOperations.print(
           (DateTimeArithmetics.minus(yesterday, Period.hours(11))),
           DateTimeFormat.shortTime(),
           null,
           DateTimeZone.forID("Asia/Bangkok")));
 }
Exemplo n.º 24
0
 public void test_londonAndMoscowShortTime() throws Exception {
   Long current = System.currentTimeMillis();
   Assert.assertEquals(
       DateTimeOperations.print(
           current,
           DateTimeFormat.shortTime(),
           new Locale("ru", "RU", ""),
           DateTimeZone.forID("Europe/London")),
       DateTimeOperations.print(
           (DateTimeArithmetics.minus(current, Period.hours(3))),
           DateTimeFormat.shortTime(),
           new Locale("ru", "RU", ""),
           DateTimeZone.forID("Europe/Moscow")));
 }
  /**
   * Convenience method to obtain the patient's (maximum) age in months.
   *
   * @return The patient's age in months at the time the given observations were taken.
   */
  protected int calculateAgeInMonths(Obs... observations) {
    long dateTaken = Long.MIN_VALUE;

    if (observations != null) {
      for (Obs obs : observations) {
        if (obs != null && obs.getObsDatetime() != null) {
          // determine the date the observation was taken (take the greater of the two)
          dateTaken = Math.max(dateTaken, obs.getObsDatetime().getTime());
        }
      }
    }

    if (dateTaken == Long.MIN_VALUE || dateTaken < birthdate.getTime()) {
      // unable to calculate patient's age!
      return 0;
    }

    // calculate how old this person was, in months, when the observations were taken
    final Period period = new Interval(birthdate.getTime(), dateTaken).toPeriod();
    final int ageInMonths = period.getYears() * 12 + period.getMonths();

    // return the patient's age in months
    return ageInMonths;
  }
  /**
   * Adds adjustment to the shortest set time range in period. E.g. period("5 days 3 hours", 1) ->
   * "5 days 4 hours". This will fall back to adjusting years if no field in the period is set.
   *
   * @param period The period to be adjusted
   * @param adjustment The adjustment. Note that positive values will result in larger periods and
   *     an earlier time
   * @return The adjusted period
   */
  private Period adjust(final Period period, int adjustment) {
    if (adjustment == 0) return period;

    // Order is VERY important here
    LinkedHashMap<Integer, DurationFieldType> map = new LinkedHashMap<>();
    map.put(period.getSeconds(), DurationFieldType.seconds());
    map.put(period.getMinutes(), DurationFieldType.minutes());
    map.put(period.getHours(), DurationFieldType.hours());
    map.put(period.getDays(), DurationFieldType.days());
    map.put(period.getWeeks(), DurationFieldType.weeks());
    map.put(period.getMonths(), DurationFieldType.months());
    map.put(period.getYears(), DurationFieldType.years());

    for (Map.Entry<Integer, DurationFieldType> entry : map.entrySet()) {
      if (entry.getKey() > 0) {
        return period.withFieldAdded(entry.getValue(), adjustment);
      }
    }
    // Fall back to modifying years
    return period.withFieldAdded(DurationFieldType.years(), adjustment);
  }
Exemplo n.º 27
0
 protected void actionToggle() {
   if (started == null) {
     miToggle.setText("Stop");
     started = new DateTime();
     timer.start();
   } else {
     miToggle.setText("Start");
     DateTime end = new DateTime();
     TimeSpan ts = new TimeSpan(started, end);
     times.add(ts);
     period = period.plus(ts.getPeriod()).normalizedStandard();
     started = null;
     timer.stop();
     updateTimes();
   }
 }
Exemplo n.º 28
0
 private long truncateMillisPeriod(final long t) {
   // toStandardDuration assumes days are always 24h, and hours are always 60 minutes,
   // which may not always be the case, e.g if there are daylight saving changes.
   if (chronology.days().isPrecise() && chronology.hours().isPrecise()) {
     final long millis = period.toStandardDuration().getMillis();
     long offset = t % millis - origin % millis;
     if (offset < 0) {
       offset += millis;
     }
     return t - offset;
   } else {
     throw new UnsupportedOperationException(
         "Period cannot be converted to milliseconds as some fields mays vary in length with chronology "
             + chronology.toString());
   }
 }
Exemplo n.º 29
0
 protected void actionAdjustment() {
   String result =
       (String) JOptionPane.showInputDialog(this, "Enter an adjustment", "0 00:00:00.000");
   if (result != null && !result.isEmpty()) {
     try {
       Period adjustment = format_short.parsePeriod(result);
       DateTime start = new DateTime();
       DateTime end = start.plus(adjustment);
       TimeSpan ts = new TimeSpan(start, end);
       times.add(ts);
       period = period.plus(adjustment);
       updateTimes();
     } catch (IllegalArgumentException ex) {
       JOptionPane.showMessageDialog(this, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
     }
   }
 }
Exemplo n.º 30
0
 public void test_westernHemisphereDate() throws Exception {
   Long yesterday =
       DateTimeOperations.convert(
           (new DateTime(2009, 7, 23, 13, 18, 20, 0, DateTimeZone.forID("UTC"))));
   Assert.assertFalse(
       (DateTimeOperations.print(
               yesterday,
               DateTimeFormat.fullDate(),
               Locale.US,
               DateTimeZone.forID("America/New_York")))
           .equals(
               DateTimeOperations.print(
                   (DateTimeArithmetics.plus(yesterday, Period.hours(22))),
                   DateTimeFormat.fullDate(),
                   Locale.US,
                   DateTimeZone.forID("Asia/Bangkok"))));
 }