/** * Return given duration in a human-friendly format. For example, "4 * minutes" or "1 second". Returns only largest meaningful unit of time, * from seconds up to hours. * * The longest duration it supports is hours. * * This method assumes that there are 60 minutes in an hour, * 60 seconds in a minute and 1000 milliseconds in a second. * All currently supplied chronologies use this definition. */ public static CharSequence formatDuration(Context context, ReadableDuration readableDuration) { Resources res = context.getResources(); Duration duration = readableDuration.toDuration(); final int hours = (int) duration.getStandardHours(); if (hours != 0) { return res.getQuantityString(R.plurals.joda_time_android_duration_hours, hours, hours); } final int minutes = (int) duration.getStandardMinutes(); if (minutes != 0) { return res.getQuantityString(R.plurals.joda_time_android_duration_minutes, minutes, minutes); } final int seconds = (int) duration.getStandardSeconds(); return res.getQuantityString(R.plurals.joda_time_android_duration_seconds, seconds, seconds); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mRecipe = getArguments().getParcelable(ARG_RECIPE); mStep = getArguments().getParcelable(ARG_STEP); if (mRecipe == null) { throw new IllegalStateException("No recipe argument"); } if (mStep == null) { throw new IllegalStateException("No step argument"); } if (savedInstanceState != null) { // Restore remaining time mRemainingTime = (ReadableDuration) savedInstanceState.getSerializable(KEY_TIME_REMAINING); } else { // Get duration from step mRemainingTime = mStep.getTime(); } // Check parent if (!(getActivity() instanceof StepFinishListener)) { throw new IllegalStateException("The parent of this fragment must implement StepFinishListener"); } }
@Test public void testTerminationConditionsAfterTimeSinceNewOutput() { Instant now = Instant.now(); Watch.Growth.AfterTimeSinceNewOutput<Object> c = afterTimeSinceNewOutput(standardSeconds(5)); KV<Instant, ReadableDuration> state = c.forNewInput(now, null); assertFalse(c.canStopPolling(now, state)); assertFalse(c.canStopPolling(now.plus(standardSeconds(3)), state)); assertFalse(c.canStopPolling(now.plus(standardSeconds(6)), state)); state = c.onSeenNewOutput(now.plus(standardSeconds(3)), state); assertFalse(c.canStopPolling(now.plus(standardSeconds(3)), state)); assertFalse(c.canStopPolling(now.plus(standardSeconds(6)), state)); assertTrue(c.canStopPolling(now.plus(standardSeconds(9)), state)); state = c.onSeenNewOutput(now.plus(standardSeconds(5)), state); assertFalse(c.canStopPolling(now.plus(standardSeconds(3)), state)); assertFalse(c.canStopPolling(now.plus(standardSeconds(6)), state)); assertFalse(c.canStopPolling(now.plus(standardSeconds(9)), state)); assertTrue(c.canStopPolling(now.plus(standardSeconds(11)), state)); }
public void testGetDurationConverter() { DurationConverter c = ConverterManager.getInstance().getDurationConverter(new Long(0L)); assertEquals(Long.class, c.getSupportedType()); c = ConverterManager.getInstance().getDurationConverter(new Duration(123L)); assertEquals(ReadableDuration.class, c.getSupportedType()); c = ConverterManager.getInstance().getDurationConverter(new Interval(0L, 1000L)); assertEquals(ReadableInterval.class, c.getSupportedType()); c = ConverterManager.getInstance().getDurationConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getDurationConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getDurationConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} }
public void testGetPeriodConverter() { PeriodConverter c = ConverterManager.getInstance().getPeriodConverter(new Period(1, 2, 3, 4, 5, 6, 7, 8)); assertEquals(ReadablePeriod.class, c.getSupportedType()); c = ConverterManager.getInstance().getPeriodConverter(new Duration(123L)); assertEquals(ReadableDuration.class, c.getSupportedType()); c = ConverterManager.getInstance().getPeriodConverter(new Interval(0L, 1000L)); assertEquals(ReadableInterval.class, c.getSupportedType()); c = ConverterManager.getInstance().getPeriodConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getPeriodConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getPeriodConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} }
public String createLoginTokenForActiveUser(final ReadableDuration timeToLive) { final UserInfo activeUserInfo = getActiveUserInfo(); final DateTime now = DateUtil.now(); return Jwts.builder() .setSubject(activeUserInfo.getUsername()) .setIssuedAt(now.toDate()) .setExpiration(now.plus(timeToLive).toDate()) .setAudience(JwtAuthenticationProvider.AUD_LOGIN) .signWith(JwtAuthenticationProvider.JWT_SIGNATURE_ALG, securityConfigurationProperties.getJwtSecret()) .compact(); }
private void updateTimer(ReadableDuration remainingTime) { // Round the duration down to remove milliseconds final Duration roundedTime = roundDownToSecond(remainingTime); final Period remainingPeriod = roundedTime.toPeriod(); mTimerView.setText(mFormatter.print(remainingPeriod)); mRemainingTime = remainingTime; }
/** * Creates a Step * @param ingredients the ingredients required for this step * @param description a human-readable description of this step * @param duration an estimate of the time required to complete this step * @param isSimultaneous if this step can be done simultaneously * @throws NullPointerException if any parameter is null */ public Step(@NonNull List<String> ingredients, @NonNull String description, @NonNull ReadableDuration duration, boolean isSimultaneous, int index) { Objects.requireNonNull(ingredients, "ingredients must not be null"); Objects.requireNonNull(description, "description must not be null"); Objects.requireNonNull(duration, "duration must not be null"); mDescription = description; mTime = duration.toDuration(); mIngredients = new ArrayList<>(ingredients); this.mSimultaneous = isSimultaneous; mIndex = index; }
@Override public IntervalWindow decode(InputStream inStream) throws IOException, CoderException { Instant end = instantCoder.decode(inStream); ReadableDuration duration = durationCoder.decode(inStream); return new IntervalWindow(end.minus(duration), end); }
@Override public String toString(KV<Instant, ReadableDuration> state) { return "AfterTotalOf{" + "timeStarted=" + state.getKey() + ", maxTimeSinceInput=" + state.getValue() + '}'; }
@Override public boolean canStopPolling(Instant now, KV<Instant, ReadableDuration> state) { Instant timeOfLastNewOutput = state.getKey(); ReadableDuration maxTimeSinceNewOutput = state.getValue(); return timeOfLastNewOutput != null && new Duration(timeOfLastNewOutput, now).isLongerThan(maxTimeSinceNewOutput); }
@Override public String toString(KV<Instant, ReadableDuration> state) { return "AfterTimeSinceNewOutput{" + "timeOfLastNewOutput=" + state.getKey() + ", maxTimeSinceNewOutput=" + state.getValue() + '}'; }
@Override public void encode(ReadableDuration value, OutputStream outStream) throws CoderException, IOException { if (value == null) { throw new CoderException("cannot encode a null ReadableDuration"); } LONG_CODER.encode(toLong(value), outStream); }
@Test public void testTerminationConditionsAfterTotalOf() { Instant now = Instant.now(); Watch.Growth.AfterTotalOf<Object> c = afterTotalOf(standardSeconds(5)); KV<Instant, ReadableDuration> state = c.forNewInput(now, null); assertFalse(c.canStopPolling(now, state)); assertFalse(c.canStopPolling(now.plus(standardSeconds(3)), state)); assertTrue(c.canStopPolling(now.plus(standardSeconds(6)), state)); }
@Test public void testTerminationConditionsEitherOf() { Instant now = Instant.now(); Watch.Growth.AfterTotalOf<Object> a = afterTotalOf(standardSeconds(5)); Watch.Growth.AfterTotalOf<Object> b = afterTotalOf(standardSeconds(10)); Watch.Growth.BinaryCombined< Object, KV<Instant, ReadableDuration>, KV<Instant, ReadableDuration>> c = eitherOf(a, b); KV<KV<Instant, ReadableDuration>, KV<Instant, ReadableDuration>> state = c.forNewInput(now, null); assertFalse(c.canStopPolling(now.plus(standardSeconds(3)), state)); assertTrue(c.canStopPolling(now.plus(standardSeconds(7)), state)); assertTrue(c.canStopPolling(now.plus(standardSeconds(12)), state)); }
@Test public void testTerminationConditionsAllOf() { Instant now = Instant.now(); Watch.Growth.AfterTotalOf<Object> a = afterTotalOf(standardSeconds(5)); Watch.Growth.AfterTotalOf<Object> b = afterTotalOf(standardSeconds(10)); Watch.Growth.BinaryCombined< Object, KV<Instant, ReadableDuration>, KV<Instant, ReadableDuration>> c = allOf(a, b); KV<KV<Instant, ReadableDuration>, KV<Instant, ReadableDuration>> state = c.forNewInput(now, null); assertFalse(c.canStopPolling(now.plus(standardSeconds(3)), state)); assertFalse(c.canStopPolling(now.plus(standardSeconds(7)), state)); assertTrue(c.canStopPolling(now.plus(standardSeconds(12)), state)); }
/** * Converts a {@link ReadableDuration} into a Dataflow API duration string. */ public static String toCloudDuration(ReadableDuration duration) { // Note that since Joda objects use millisecond resolution, we always // produce either no fractional seconds or fractional seconds with // millisecond resolution. long millis = duration.getMillis(); long seconds = millis / 1000; millis = millis % 1000; if (millis == 0) { return String.format("%ds", seconds); } else { return String.format("%d.%03ds", seconds, millis); } }
@Override public void sleep(ReadableDuration duration) throws InterruptedException { checkArgument(duration.getMillis() >= 0); if (Thread.interrupted()) { throw new InterruptedException(); } clock.advanceBy(duration); }
/** * Constructs an interval from a start instant and a duration. * * @param start start of this interval, null means now * @param duration the duration of this interval, null means zero length * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the end instant exceeds the capacity of a long */ protected BaseInterval(ReadableInstant start, ReadableDuration duration) { super(); iChronology = DateTimeUtils.getInstantChronology(start); iStartMillis = DateTimeUtils.getInstantMillis(start); long durationMillis = DateTimeUtils.getDurationMillis(duration); iEndMillis = FieldUtils.safeAdd(iStartMillis, durationMillis); checkInterval(iStartMillis, iEndMillis); }
/** * Constructs an interval from a millisecond duration and an end instant. * * @param duration the duration of this interval, null means zero length * @param end end of this interval, null means now * @throws IllegalArgumentException if the end is before the start * @throws ArithmeticException if the start instant exceeds the capacity of a long */ protected BaseInterval(ReadableDuration duration, ReadableInstant end) { super(); iChronology = DateTimeUtils.getInstantChronology(end); iEndMillis = DateTimeUtils.getInstantMillis(end); long durationMillis = DateTimeUtils.getDurationMillis(duration); iStartMillis = FieldUtils.safeAdd(iEndMillis, -durationMillis); checkInterval(iStartMillis, iEndMillis); }
/** * Creates a period from the given start point and duration. * * @param startInstant the interval start, null means now * @param duration the duration of the interval, null means zero-length * @param type which set of fields this period supports, null means standard */ protected BasePeriod(ReadableInstant startInstant, ReadableDuration duration, PeriodType type) { super(); type = checkPeriodType(type); long startMillis = DateTimeUtils.getInstantMillis(startInstant); long durationMillis = DateTimeUtils.getDurationMillis(duration); long endMillis = FieldUtils.safeAdd(startMillis, durationMillis); Chronology chrono = DateTimeUtils.getInstantChronology(startInstant); iType = type; iValues = chrono.get(this, startMillis, endMillis); }
/** * Creates a period from the given duration and end point. * * @param duration the duration of the interval, null means zero-length * @param endInstant the interval end, null means now * @param type which set of fields this period supports, null means standard */ protected BasePeriod(ReadableDuration duration, ReadableInstant endInstant, PeriodType type) { super(); type = checkPeriodType(type); long durationMillis = DateTimeUtils.getDurationMillis(duration); long endMillis = DateTimeUtils.getInstantMillis(endInstant); long startMillis = FieldUtils.safeSubtract(endMillis, durationMillis); Chronology chrono = DateTimeUtils.getInstantChronology(endInstant); iType = type; iValues = chrono.get(this, startMillis, endMillis); }
/** * Compares this duration with the specified duration based on length. * * @param other a duration to check against * @return negative value if this is less, 0 if equal, or positive value if greater * @throws NullPointerException if the object is null * @throws ClassCastException if the given object is not supported */ public int compareTo(ReadableDuration other) { long thisMillis = this.getMillis(); long otherMillis = other.getMillis(); // cannot do (thisMillis - otherMillis) as it can overflow if (thisMillis < otherMillis) { return -1; } if (thisMillis > otherMillis) { return 1; } return 0; }
/** * Is the length of this duration equal to the duration passed in. * * @param duration another duration to compare to, null means zero milliseconds * @return true if this duration is equal to than the duration passed in */ public boolean isEqual(ReadableDuration duration) { if (duration == null) { duration = Duration.ZERO; } return compareTo(duration) == 0; }
/** * Is the length of this duration longer than the duration passed in. * * @param duration another duration to compare to, null means zero milliseconds * @return true if this duration is equal to than the duration passed in */ public boolean isLongerThan(ReadableDuration duration) { if (duration == null) { duration = Duration.ZERO; } return compareTo(duration) > 0; }
/** * Is the length of this duration shorter than the duration passed in. * * @param duration another duration to compare to, null means zero milliseconds * @return true if this duration is equal to than the duration passed in */ public boolean isShorterThan(ReadableDuration duration) { if (duration == null) { duration = Duration.ZERO; } return compareTo(duration) < 0; }
/** * Compares this object with the specified object for equality based * on the millisecond length. All ReadableDuration instances are accepted. * * @param duration a readable duration to check against * @return true if the length of the duration is equal */ public boolean equals(Object duration) { if (this == duration) { return true; } if (duration instanceof ReadableDuration == false) { return false; } ReadableDuration other = (ReadableDuration) duration; return (getMillis() == other.getMillis()); }
/** * @param duration */ public void block(ReadableDuration duration) { DateTime started = new DateTime(); logger.info("Started at " + started); DateTime endAt = started.plus(duration); logger.info("Will end at " + endAt); while (endAt.isAfterNow()) { //wait } }
@Override public Object create(Object request, SpecimenContext context) { if (!request.equals(ReadableDuration.class)) return new NoSpecimen(); return context.resolve(Duration.class); }