org.joda.time.format.PeriodFormatter Java Examples

The following examples show how to use org.joda.time.format.PeriodFormatter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Helpers.java    From bootstraped-multi-test-results-report with MIT License 6 votes vote down vote up
private Helper<Long> dateHelper() {
    return new Helper<Long>() {
        public CharSequence apply(Long arg0, Options arg1) throws IOException {
            PeriodFormatter formatter = new PeriodFormatterBuilder()
                .appendDays()
                .appendSuffix(" d : ")
                .appendHours()
                .appendSuffix(" h : ")
                .appendMinutes()
                .appendSuffix(" m : ")
                .appendSeconds()
                .appendSuffix(" s : ")
                .appendMillis()
                .appendSuffix(" ms")
                .toFormatter();
            return formatter.print(new Period((arg0 * 1) / 1000000));
        }
    };
}
 
Example #2
Source File: DateTimeUtils.java    From presto with Apache License 2.0 6 votes vote down vote up
private static Period parsePeriod(PeriodFormatter periodFormatter, String value)
{
    boolean negative = value.startsWith("-");
    if (negative) {
        value = value.substring(1);
    }

    Period period = periodFormatter.parsePeriod(value);
    for (DurationFieldType type : period.getFieldTypes()) {
        checkArgument(period.get(type) >= 0, "Period field %s is negative", type);
    }

    if (negative) {
        period = period.negated();
    }
    return period;
}
 
Example #3
Source File: DateTimeUtils.java    From presto with Apache License 2.0 6 votes vote down vote up
public static long parseYearMonthInterval(String value, IntervalField startField, Optional<IntervalField> endField)
{
    IntervalField end = endField.orElse(startField);

    if (startField == IntervalField.YEAR && end == IntervalField.MONTH) {
        PeriodFormatter periodFormatter = INTERVAL_YEAR_MONTH_FORMATTER;
        return parsePeriodMonths(value, periodFormatter, startField, end);
    }
    if (startField == IntervalField.YEAR && end == IntervalField.YEAR) {
        return parsePeriodMonths(value, INTERVAL_YEAR_FORMATTER, startField, end);
    }

    if (startField == IntervalField.MONTH && end == IntervalField.MONTH) {
        return parsePeriodMonths(value, INTERVAL_MONTH_FORMATTER, startField, end);
    }

    throw new IllegalArgumentException("Invalid year month interval qualifier: " + startField + " to " + end);
}
 
Example #4
Source File: LocalGatewayConfig.java    From hadoop-mini-clusters with Apache License 2.0 6 votes vote down vote up
public long getGatewayDeploymentsBackupAgeLimit() {
    PeriodFormatter f = (new PeriodFormatterBuilder()).appendDays().toFormatter();
    String s = this.get("gateway.deployment.backup.ageLimit", "-1");

    long d;
    try {
        Period e = Period.parse(s, f);
        d = e.toStandardDuration().getMillis();
        if (d < 0L) {
            d = -1L;
        }
    } catch (Exception var6) {
        d = -1L;
    }

    return d;
}
 
Example #5
Source File: GatewayConfigImpl.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public long getGatewayDeploymentsBackupAgeLimit() {
  PeriodFormatter f = new PeriodFormatterBuilder().appendDays().toFormatter();
  String s = get( DEPLOYMENTS_BACKUP_AGE_LIMIT, "-1" );
  long d;
  try {
    Period p = Period.parse( s, f );
    d = p.toStandardDuration().getMillis();
    if( d < 0 ) {
      d = -1;
    }
  } catch( Exception e ) {
    d = -1;
  }
  return d;
}
 
Example #6
Source File: SlackServerAdapter.java    From TCSlackNotifierPlugin with MIT License 6 votes vote down vote up
private void postFailureBuild(SRunningBuild build )
{
    String message = "";

    PeriodFormatter durationFormatter = new PeriodFormatterBuilder()
            .printZeroRarelyFirst()
            .appendHours()
            .appendSuffix(" hour", " hours")
            .appendSeparator(" ")
            .printZeroRarelyLast()
            .appendMinutes()
            .appendSuffix(" minute", " minutes")
            .appendSeparator(" and ")
            .appendSeconds()
            .appendSuffix(" second", " seconds")
            .toFormatter();

    Duration buildDuration = new Duration(1000*build.getDuration());

    message = String.format("Project '%s' build failed! ( %s )" , build.getFullName() , durationFormatter.print(buildDuration.toPeriod()));

    postToSlack(build, message, false);
}
 
Example #7
Source File: SlackServerAdapter.java    From TCSlackNotifierPlugin with MIT License 6 votes vote down vote up
private void processSuccessfulBuild(SRunningBuild build) {

        String message = "";

        PeriodFormatter durationFormatter = new PeriodFormatterBuilder()
                    .printZeroRarelyFirst()
                    .appendHours()
                    .appendSuffix(" hour", " hours")
                    .appendSeparator(" ")
                    .printZeroRarelyLast()
                    .appendMinutes()
                    .appendSuffix(" minute", " minutes")
                    .appendSeparator(" and ")
                    .appendSeconds()
                    .appendSuffix(" second", " seconds")
                    .toFormatter();

        Duration buildDuration = new Duration(1000*build.getDuration());

        message = String.format("Project '%s' built successfully in %s." , build.getFullName() , durationFormatter.print(buildDuration.toPeriod()));

        postToSlack(build, message, true);
    }
 
Example #8
Source File: TimeBasedSubDirDatasetsFinder.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Return true iff input folder time is between compaction.timebased.min.time.ago and
 * compaction.timebased.max.time.ago.
 */
protected boolean folderWithinAllowedPeriod(Path inputFolder, DateTime folderTime) {
  DateTime currentTime = new DateTime(this.timeZone);
  PeriodFormatter periodFormatter = getPeriodFormatter();
  DateTime earliestAllowedFolderTime = getEarliestAllowedFolderTime(currentTime, periodFormatter);
  DateTime latestAllowedFolderTime = getLatestAllowedFolderTime(currentTime, periodFormatter);

  if (folderTime.isBefore(earliestAllowedFolderTime)) {
    log.info(String.format("Folder time for %s is %s, earlier than the earliest allowed folder time, %s. Skipping",
        inputFolder, folderTime, earliestAllowedFolderTime));
    return false;
  } else if (folderTime.isAfter(latestAllowedFolderTime)) {
    log.info(String.format("Folder time for %s is %s, later than the latest allowed folder time, %s. Skipping",
        inputFolder, folderTime, latestAllowedFolderTime));
    return false;
  } else {
    return true;
  }
}
 
Example #9
Source File: RecompactionConditionTest.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Test
public void testRecompactionConditionBasedOnDuration() {
  RecompactionConditionFactory factory = new RecompactionConditionBasedOnDuration.Factory();
  RecompactionCondition conditionBasedOnDuration = factory.createRecompactionCondition(dataset);
  DatasetHelper helper = mock (DatasetHelper.class);
  when(helper.getDataset()).thenReturn(dataset);
  PeriodFormatter periodFormatter = new PeriodFormatterBuilder().appendMonths().appendSuffix("m").appendDays().appendSuffix("d").appendHours()
      .appendSuffix("h").appendMinutes().appendSuffix("min").toFormatter();
  DateTime currentTime = getCurrentTime();

  Period period_A = periodFormatter.parsePeriod("11h59min");
  DateTime earliest_A = currentTime.minus(period_A);
  when(helper.getEarliestLateFileModificationTime()).thenReturn(Optional.of(earliest_A));
  when(helper.getCurrentTime()).thenReturn(currentTime);
  Assert.assertEquals(conditionBasedOnDuration.isRecompactionNeeded(helper), false);

  Period period_B = periodFormatter.parsePeriod("12h01min");
  DateTime earliest_B = currentTime.minus(period_B);
  when(helper.getEarliestLateFileModificationTime()).thenReturn(Optional.of(earliest_B));
  when(helper.getCurrentTime()).thenReturn(currentTime);
  Assert.assertEquals(conditionBasedOnDuration.isRecompactionNeeded(helper), true);
}
 
Example #10
Source File: TimeAwareRecursiveCopyableDataset.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
public TimeAwareRecursiveCopyableDataset(FileSystem fs, Path rootPath, Properties properties, Path glob) {
  super(fs, rootPath, properties, glob);
  this.lookbackTime = properties.getProperty(LOOKBACK_TIME_KEY);
  PeriodFormatter periodFormatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d").appendHours().appendSuffix("h").appendMinutes().appendSuffix("m").toFormatter();
  this.lookbackPeriod = periodFormatter.parsePeriod(lookbackTime);
  this.datePattern = properties.getProperty(DATE_PATTERN_KEY);
  this.isPatternMinutely = isDatePatternMinutely(datePattern);
  this.isPatternHourly = !this.isPatternMinutely && isDatePatternHourly(datePattern);
  this.isPatternDaily = !this.isPatternMinutely && !this.isPatternHourly;
  this.currentTime = properties.containsKey(DATE_PATTERN_TIMEZONE_KEY) ? LocalDateTime.now(
      DateTimeZone.forID(DATE_PATTERN_TIMEZONE_KEY))
      : LocalDateTime.now(DateTimeZone.forID(DEFAULT_DATE_PATTERN_TIMEZONE));

  if (this.isPatternDaily) {
    Preconditions.checkArgument(isLookbackTimeStringDaily(this.lookbackTime), "Expected day format for lookback time; found hourly or minutely format");
    pattern = DatePattern.DAILY;
  } else if (this.isPatternHourly) {
    Preconditions.checkArgument(isLookbackTimeStringHourly(this.lookbackTime), "Expected hourly format for lookback time; found minutely format");
    pattern = DatePattern.HOURLY;
  } else {
    pattern = DatePattern.MINUTELY;
  }
}
 
Example #11
Source File: UIUtils.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
/**
 * Format the duration in milliseconds to a human readable String, with "yr", "days", "hr" etc prefixes
 *
 *
 * @param durationMs Duration in milliseconds
 * @return Human readable string
 */
public static String formatDuration(long durationMs){
    Period period = Period.seconds((int)(durationMs/1000L));
    Period p2 = period.normalizedStandard(PeriodType.yearMonthDayTime());

    PeriodFormatter formatter = new PeriodFormatterBuilder()
            .appendYears()
            .appendSuffix(" yr ")
            .appendMonths()
            .appendSuffix(" months ")
            .appendDays()
            .appendSuffix(" days ")
            .appendHours()
            .appendSuffix(" hr ")
            .appendMinutes()
            .appendSuffix(" min ")
            .appendSeconds()
            .appendSuffix(" sec")
            .toFormatter();

    return formatter.print(p2);
}
 
Example #12
Source File: HeaderUtil.java    From spring-rest-server with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Period getSessionMaxAge() {
    String maxAge = environment.getRequiredProperty("auth.session.maxAge");
    PeriodFormatter format = new PeriodFormatterBuilder()
            .appendDays()
            .appendSuffix("d", "d")
            .printZeroRarelyFirst()
            .appendHours()
            .appendSuffix("h", "h")
            .printZeroRarelyFirst()
            .appendMinutes()
            .appendSuffix("m", "m")
            .toFormatter();
    Period sessionMaxAge = format.parsePeriod(maxAge);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Session maxAge is: "+
                formatIfNotZero(sessionMaxAge.getDays(), "days", "day") +
                formatIfNotZero(sessionMaxAge.getHours(), "hours", "hour") +
                formatIfNotZero(sessionMaxAge.getMinutes(), "minutes", "minute")
        );
    }
    return sessionMaxAge;
}
 
Example #13
Source File: DiscordUtil.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
public static String getTimestamp(long duration) {
	PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
			.appendYears().appendSuffix("y ")
			.appendMonths().appendSuffix("m ")
			.appendWeeks().appendSuffix("w ")
			.appendDays().appendSuffix("d ")
			.appendHours().appendSuffix("h ")
			.appendMinutes().appendSuffix("m ")
			.appendSeconds().appendSuffix("s")
			.toFormatter();
	return periodFormatter.print(new Period(new Duration(duration)).normalizedStandard());
}
 
Example #14
Source File: SAXProcessor.java    From SAX with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generic method to convert the milliseconds into the elapsed time string.
 * 
 * @param start Start timestamp.
 * @param finish End timestamp.
 * @return String representation of the elapsed time.
 */
public static String timeToString(long start, long finish) {

  Duration duration = new Duration(finish - start); // in milliseconds
  PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d")
      .appendHours().appendSuffix("h").appendMinutes().appendSuffix("m").appendSeconds()
      .appendSuffix("s").appendMillis().appendSuffix("ms").toFormatter();

  return formatter.print(duration.toPeriod());

}
 
Example #15
Source File: StringConverter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Extracts duration values from an object of this converter's type, and
 * sets them into the given ReadWritableDuration.
 *
 * @param period  period to get modified
 * @param object  the String to convert, must not be null
 * @param chrono  the chronology to use
 * @return the millisecond duration
 * @throws ClassCastException if the object is invalid
 */
public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) {
    String str = (String) object;
    PeriodFormatter parser = ISOPeriodFormat.standard();
    period.clear();
    int pos = parser.parseInto(period, str, 0);
    if (pos < str.length()) {
        if (pos < 0) {
            // Parse again to get a better exception thrown.
            parser.withParseType(period.getPeriodType()).parseMutablePeriod(str);
        }
        throw new IllegalArgumentException("Invalid format: \"" + str + '"');
    }
}
 
Example #16
Source File: MediathekShow.java    From zapp with MIT License 5 votes vote down vote up
public String getFormattedDuration() {
	int duration;
	try {
		duration = Integer.parseInt(this.duration);
	} catch (NumberFormatException e) {
		return "?";
	}

	Period period = Duration.standardSeconds(duration).toPeriod();
	PeriodFormatter formatter = (period.getHours() > 0) ? hourPeriodFormatter : secondsPeriodFormatter;
	return period.toString(formatter);
}
 
Example #17
Source File: GatewayConfigImpl.java    From knox with Apache License 2.0 5 votes vote down vote up
private static long parseNetworkTimeout(String s ) {
  PeriodFormatter f = new PeriodFormatterBuilder()
      .appendMinutes().appendSuffix("m"," min")
      .appendSeconds().appendSuffix("s"," sec")
      .appendMillis().toFormatter();
  Period p = Period.parse( s, f );
  return p.toStandardDuration().getMillis();
}
 
Example #18
Source File: DefaultHttpClientFactory.java    From knox with Apache License 2.0 5 votes vote down vote up
private static long parseTimeout( String s ) {
  PeriodFormatter f = new PeriodFormatterBuilder()
      .appendMinutes().appendSuffix("m"," min")
      .appendSeconds().appendSuffix("s"," sec")
      .appendMillis().toFormatter();
  Period p = Period.parse( s, f );
  return p.toStandardDuration().getMillis();
}
 
Example #19
Source File: JodaPeriodFormatter.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Gets create period {@link PeriodFormatter} instances.
 * 
 * @param locale
 * @return
 */
private synchronized static PeriodFormatter getPeriodFormatter(Locale locale) {
	notNullOf(locale, "locale");

	PeriodFormatter formatter = localizedPeriodFormatters.get(locale);
	if (isNull(formatter)) {
		PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
		builder.appendYears().appendSuffix(" ".concat(getLocalizedMessage("period.formatter.year")).concat(" "),
				" ".concat(getLocalizedMessage("period.formatter.years").concat(" ")));

		builder.appendMonths().appendSuffix(" ".concat(getLocalizedMessage("period.formatter.month")).concat(" "),
				" ".concat(getLocalizedMessage("period.formatter.months").concat(" ")));

		builder.appendWeeks().appendSuffix(" ".concat(getLocalizedMessage("period.formatter.week")).concat(" "),
				" ".concat(getLocalizedMessage("period.formatter.weeks").concat(" ")));

		builder.appendDays().appendSuffix(" ".concat(getLocalizedMessage("period.formatter.day")).concat(" "),
				" ".concat(getLocalizedMessage("period.formatter.days").concat(" ")));

		builder.appendHours().appendSuffix(" ".concat(getLocalizedMessage("period.formatter.hour")).concat(" "),
				" ".concat(getLocalizedMessage("period.formatter.hours").concat(" ")));

		builder.appendMinutes().appendSuffix(" ".concat(getLocalizedMessage("period.formatter.minute")).concat(" "),
				" ".concat(getLocalizedMessage("period.formatter.minutes").concat(" ")));

		builder.appendSeconds().appendSuffix(" ".concat(getLocalizedMessage("period.formatter.second")).concat(" "),
				" ".concat(getLocalizedMessage("period.formatter.seconds").concat(" ")));

		formatter = builder.printZeroNever().toFormatter();
		localizedPeriodFormatters.put(locale, formatter);
	}

	return formatter;
}
 
Example #20
Source File: CompactionTimeRangeVerifier.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public Result verify (FileSystemDataset dataset) {
  final DateTime earliest;
  final DateTime latest;
  try {
    CompactionPathParser.CompactionParserResult result = new CompactionPathParser(state).parse(dataset);
    DateTime folderTime = result.getTime();
    DateTimeZone timeZone = DateTimeZone.forID(this.state.getProp(MRCompactor.COMPACTION_TIMEZONE, MRCompactor.DEFAULT_COMPACTION_TIMEZONE));
    DateTime compactionStartTime = new DateTime(this.state.getPropAsLong(CompactionSource.COMPACTION_INIT_TIME), timeZone);
    PeriodFormatter formatter = new PeriodFormatterBuilder().appendMonths().appendSuffix("m").appendDays().appendSuffix("d").appendHours()
            .appendSuffix("h").toFormatter();

    // Dataset name is like 'Identity/MemberAccount' or 'PageViewEvent'
    String datasetName = result.getDatasetName();

    // get earliest time
    String maxTimeAgoStrList = this.state.getProp(TimeBasedSubDirDatasetsFinder.COMPACTION_TIMEBASED_MAX_TIME_AGO, TimeBasedSubDirDatasetsFinder.DEFAULT_COMPACTION_TIMEBASED_MAX_TIME_AGO);
    String maxTimeAgoStr = getMachedLookbackTime(datasetName, maxTimeAgoStrList, TimeBasedSubDirDatasetsFinder.DEFAULT_COMPACTION_TIMEBASED_MAX_TIME_AGO);
    Period maxTimeAgo = formatter.parsePeriod(maxTimeAgoStr);
    earliest = compactionStartTime.minus(maxTimeAgo);

    // get latest time
    String minTimeAgoStrList = this.state.getProp(TimeBasedSubDirDatasetsFinder.COMPACTION_TIMEBASED_MIN_TIME_AGO, TimeBasedSubDirDatasetsFinder.DEFAULT_COMPACTION_TIMEBASED_MIN_TIME_AGO);
    String minTimeAgoStr = getMachedLookbackTime(datasetName, minTimeAgoStrList, TimeBasedSubDirDatasetsFinder.DEFAULT_COMPACTION_TIMEBASED_MIN_TIME_AGO);
    Period minTimeAgo = formatter.parsePeriod(minTimeAgoStr);
    latest = compactionStartTime.minus(minTimeAgo);

    if (earliest.isBefore(folderTime) && latest.isAfter(folderTime)) {
      log.debug("{} falls in the user defined time range", dataset.datasetRoot());
      return new Result(true, "");
    }
  } catch (Exception e) {
    log.error("{} cannot be verified because of {}", dataset.datasetRoot(), ExceptionUtils.getFullStackTrace(e));
    return new Result(false, e.toString());
  }
  return new Result(false, dataset.datasetRoot() + " is not in between " + earliest + " and " + latest);
}
 
Example #21
Source File: TimeAwareRecursiveCopyableDataset.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private boolean isLookbackTimeStringDaily(String lookbackTime) {
  PeriodFormatter periodFormatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d").toFormatter();
  try {
    periodFormatter.parsePeriod(lookbackTime);
    return true;
  } catch (Exception e) {
    return false;
  }
}
 
Example #22
Source File: TimeAwareRecursiveCopyableDataset.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private boolean isLookbackTimeStringHourly(String lookbackTime) {
  PeriodFormatter periodFormatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d").appendHours().appendSuffix("h").toFormatter();
  try {
    periodFormatter.parsePeriod(lookbackTime);
    return true;
  } catch (Exception e) {
    return false;
  }
}
 
Example #23
Source File: UnixTimestampRecursiveCopyableDataset.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public UnixTimestampRecursiveCopyableDataset(FileSystem fs, Path rootPath, Properties properties, Path glob) {
  super(fs, rootPath, properties, glob);
  this.lookbackTime = properties.getProperty(TimeAwareRecursiveCopyableDataset.LOOKBACK_TIME_KEY);
  this.versionSelectionPolicy =
      VersionSelectionPolicy.valueOf(properties.getProperty(VERSION_SELECTION_POLICY).toUpperCase());
  PeriodFormatter periodFormatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d").toFormatter();
  this.lookbackPeriod = periodFormatter.parsePeriod(lookbackTime);
  String timestampRegex = properties.getProperty(TIMESTAMP_REGEEX, DEFAULT_TIMESTAMP_REGEX);
  this.timestampPattern = Pattern.compile(timestampRegex);
  this.dateTimeZone = DateTimeZone.forID(properties
      .getProperty(TimeAwareRecursiveCopyableDataset.DATE_PATTERN_TIMEZONE_KEY,
          TimeAwareRecursiveCopyableDataset.DEFAULT_DATE_PATTERN_TIMEZONE));
  this.currentTime = LocalDateTime.now(this.dateTimeZone);
}
 
Example #24
Source File: TimeAwareRecursiveCopyableDatasetTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void setUp() throws IOException {
  Assert.assertTrue(NUM_LOOKBACK_DAYS < MAX_NUM_DAILY_DIRS);
  Assert.assertTrue(NUM_LOOKBACK_HOURS < MAX_NUM_HOURLY_DIRS);

  this.fs = FileSystem.getLocal(new Configuration());

  baseDir1 = new Path("/tmp/src/ds1/hourly");
  if (fs.exists(baseDir1)) {
    fs.delete(baseDir1, true);
  }
  fs.mkdirs(baseDir1);

  baseDir2 = new Path("/tmp/src/ds1/daily");
  if (fs.exists(baseDir2)) {
    fs.delete(baseDir2, true);
  }
  fs.mkdirs(baseDir2);

  baseDir3 = new Path("/tmp/src/ds2/daily");
  if (fs.exists(baseDir3)) {
    fs.delete(baseDir3, true);
  }
  fs.mkdirs(baseDir3);
  PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d").appendHours().appendSuffix("h").toFormatter();
  Period period = formatter.parsePeriod(NUM_LOOKBACK_DAYS_HOURS_STR);
}
 
Example #25
Source File: DateTimeUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
private static long parsePeriodMonths(String value, PeriodFormatter periodFormatter, IntervalField startField, IntervalField endField)
{
    try {
        Period period = parsePeriod(periodFormatter, value);
        return IntervalYearMonth.toMonths(
                period.getValue(YEAR_FIELD),
                period.getValue(MONTH_FIELD));
    }
    catch (IllegalArgumentException e) {
        throw invalidInterval(e, value, startField, endField);
    }
}
 
Example #26
Source File: ProgressImpl.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void success() {
  jobExecution.setEndDate(Instant.now());
  jobExecution.setStatus(SUCCESS);
  jobExecution.setProgressInt(jobExecution.getProgressMax());
  Duration yourDuration = Duration.millis(timeRunning());
  Period period = yourDuration.toPeriod();
  PeriodFormatter periodFormatter =
      new PeriodFormatterBuilder()
          .appendDays()
          .appendSuffix("d ")
          .appendHours()
          .appendSuffix("h ")
          .appendMinutes()
          .appendSuffix("m ")
          .appendSeconds()
          .appendSuffix("s ")
          .appendMillis()
          .appendSuffix("ms ")
          .toFormatter();
  String timeSpent = periodFormatter.print(period);
  JOB_EXECUTION_LOG.info("Execution successful. Time spent: {}", timeSpent);
  sendEmail(
      jobExecution.getSuccessEmail(),
      jobExecution.getType() + " job succeeded.",
      jobExecution.getLog());
  update();
  JobExecutionHolder.unset();
}
 
Example #27
Source File: WebAppConfiguration.java    From jerseyoauth2 with MIT License 5 votes vote down vote up
private Duration parseDuration(String initParameter, Duration defaultDuration)
{
	if (initParameter!=null)
	{
		PeriodFormatter formatter = new PeriodFormatterBuilder()
    		.appendDays().appendSuffix("d ")
    		.appendHours().appendSuffix("h ")
    		.appendMinutes().appendSuffix("min")
    		.toFormatter();
		Period p = formatter.parsePeriod(initParameter);
		return p.toDurationFrom(DateTime.now());
	} else
		return defaultDuration;
}
 
Example #28
Source File: DateTimeUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
public static long parsePeriodMillis(PeriodFormatter periodFormatter, String value, IntervalField startField, IntervalField endField)
{
    try {
        Period period = parsePeriod(periodFormatter, value);
        return IntervalDayTime.toMillis(
                period.getValue(DAY_FIELD),
                period.getValue(HOUR_FIELD),
                period.getValue(MINUTE_FIELD),
                period.getValue(SECOND_FIELD),
                period.getValue(MILLIS_FIELD));
    }
    catch (IllegalArgumentException e) {
        throw invalidInterval(e, value, startField, endField);
    }
}
 
Example #29
Source File: RRTime.java    From RedReader with GNU General Public License v3.0 5 votes vote down vote up
public static String formatDurationFrom(final Context context, final long startTime) {
	final String space = " ";
	final String comma = ",";
	final String separator = comma + space;

	final long endTime = utcCurrentTimeMillis();
	final DateTime dateTime = new DateTime(endTime);
	final DateTime localDateTime = dateTime.withZone(DateTimeZone.getDefault());
	Period period = new Duration(startTime, endTime).toPeriodTo(localDateTime);

	PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
			.appendYears().appendSuffix(space).appendSuffix(context.getString(R.string.time_year), context.getString(R.string.time_years)).appendSeparator(separator)
			.appendMonths().appendSuffix(space).appendSuffix(context.getString(R.string.time_month), context.getString(R.string.time_months)).appendSeparator(separator)
			.appendDays().appendSuffix(space).appendSuffix(context.getString(R.string.time_day), context.getString(R.string.time_days)).appendSeparator(separator)
			.appendHours().appendSuffix(space).appendSuffix(context.getString(R.string.time_hour), context.getString(R.string.time_hours)).appendSeparator(separator)
			.appendMinutes().appendSuffix(space).appendSuffix(context.getString(R.string.time_min), context.getString(R.string.time_mins)).appendSeparator(separator)
			.appendSeconds().appendSuffix(space).appendSuffix(context.getString(R.string.time_sec), context.getString(R.string.time_secs)).appendSeparator(separator)
			.appendMillis().appendSuffix(space).appendSuffix(context.getString(R.string.time_ms))
			.toFormatter();

	String duration = periodFormatter.print(period.normalizedStandard(PeriodType.yearMonthDayTime()));

	List<String> parts = Arrays.asList(duration.split(comma));
	if (parts.size() >= 2) {
		duration = parts.get(0) + comma + parts.get(1);
	}

	return String.format(context.getString(R.string.time_ago), duration);
}
 
Example #30
Source File: AuthenticationService.java    From cerberus with Apache License 2.0 5 votes vote down vote up
private AuthTokenResponse createToken(
    String principal,
    PrincipalType principalType,
    Map<String, String> metadata,
    String vaultStyleTTL) {

  PeriodFormatter formatter =
      new PeriodFormatterBuilder()
          .appendHours()
          .appendSuffix("h")
          .appendMinutes()
          .appendSuffix("m")
          .toFormatter();

  Period ttl = formatter.parsePeriod(vaultStyleTTL);
  long ttlInMinutes = ttl.toStandardMinutes().getMinutes();

  // todo eliminate this data coming from a map which may or may not contain the data and force
  // the data to be
  // required as method parameters
  boolean isAdmin = Boolean.valueOf(metadata.get(METADATA_KEY_IS_ADMIN));
  String groups = metadata.get(METADATA_KEY_GROUPS);
  int refreshCount =
      Integer.parseInt(metadata.getOrDefault(METADATA_KEY_TOKEN_REFRESH_COUNT, "0"));

  CerberusAuthToken tokenResult =
      authTokenService.generateToken(
          principal, principalType, isAdmin, groups, ttlInMinutes, refreshCount);

  return new AuthTokenResponse()
      .setClientToken(tokenResult.getToken())
      .setPolicies(Collections.emptySet())
      .setMetadata(metadata)
      .setLeaseDuration(
          Duration.between(tokenResult.getCreated(), tokenResult.getExpires()).getSeconds())
      .setRenewable(PrincipalType.USER.equals(principalType));
}