org.joda.time.format.PeriodFormatterBuilder Java Examples

The following examples show how to use org.joda.time.format.PeriodFormatterBuilder. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
Source File: VanitygenPanel.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
public VanitygenPanel() {
    super(MessageKey.vanity_address, AwesomeIcon.VIMEO_SQUARE);
    passwordGetter = new PasswordPanel.PasswordGetter(VanitygenPanel.this);
    remainingTimeFormatter = new PeriodFormatterBuilder().printZeroNever().appendYears().appendSuffix
            (LocaliserUtils.getString("vanity_time_year_suffix")).appendMonths().appendSuffix
            (LocaliserUtils.getString("vanity_time_month_suffix")).appendDays().appendSuffix
            (LocaliserUtils.getString("vanity_time_day_suffix")).appendHours().appendSuffix
            (LocaliserUtils.getString("vanity_time_hour_suffix")).appendMinutes()
            .appendSuffix(LocaliserUtils.getString("vanity_time_minute_suffix"))
            .appendSeconds().appendSuffix(LocaliserUtils.getString
                    ("vanity_time_second_suffix")).toFormatter();
    setOkAction(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (isInCalculatingView) {
                generateAddress();
            } else {
                showCalculate();
            }
        }
    });
    if (OSUtils.isWindows() && SystemUtil.isSystem32()) {
        ecKeyType = BitherSetting.ECKeyType.UNCompressed;
    }
}
 
Example #8
Source File: VanitygenPanel.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
public VanitygenPanel() {
    super(MessageKey.vanity_address, AwesomeIcon.VIMEO_SQUARE);
    passwordGetter = new PasswordPanel.PasswordGetter(VanitygenPanel.this);
    remainingTimeFormatter = new PeriodFormatterBuilder().printZeroNever().appendYears().appendSuffix
            (LocaliserUtils.getString("vanity_time_year_suffix")).appendMonths().appendSuffix
            (LocaliserUtils.getString("vanity_time_month_suffix")).appendDays().appendSuffix
            (LocaliserUtils.getString("vanity_time_day_suffix")).appendHours().appendSuffix
            (LocaliserUtils.getString("vanity_time_hour_suffix")).appendMinutes()
            .appendSuffix(LocaliserUtils.getString("vanity_time_minute_suffix"))
            .appendSeconds().appendSuffix(LocaliserUtils.getString
                    ("vanity_time_second_suffix")).toFormatter();
    setOkAction(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (isInCalculatingView) {
                generateAddress();
            } else {
                showCalculate();
            }
        }
    });
    if (OSUtils.isWindows() && SystemUtil.isSystem32()) {
        ecKeyType = BitherSetting.ECKeyType.UNCompressed;
    }
}
 
Example #9
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 #10
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 #11
Source File: TimestampPickerController.java    From science-journal with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
public TimestampPickerController(
    Locale locale,
    boolean isStartCrop,
    String negativePrefix,
    String hourMinuteDivider,
    String minuteSecondDivider,
    OnTimestampErrorListener errorListener) {
  this.locale = locale;
  this.isStartCrop = isStartCrop;
  this.errorListener = errorListener;
  this.negativePrefix = negativePrefix;
  // Builds the formatter, which will be used to read and write timestamp strings.
  periodFormatter =
      new PeriodFormatterBuilder()
          .rejectSignedValues(true) // Applies to all fields
          .printZeroAlways() // Applies to all fields
          .appendHours()
          .appendLiteral(hourMinuteDivider)
          .minimumPrintedDigits(2) // Applies to minutes and seconds
          .appendMinutes()
          .appendLiteral(minuteSecondDivider)
          .appendSecondsWithMillis()
          .toFormatter()
          .withLocale(this.locale);
}
 
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: DurationUtils.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
/**
 * Parses a duration from a period formatted string. Values are accepted in the following formats:
 *
 * <p>Formats Ns - Seconds. Example: 5s<br>
 * Nm - Minutes. Example: 13m<br>
 * Nh - Hours. Example: 2h
 *
 * <pre>
 * parseDuration(null) = NullPointerException()
 * parseDuration("")   = Duration.standardSeconds(0)
 * parseDuration("2s") = Duration.standardSeconds(2)
 * parseDuration("5m") = Duration.standardMinutes(5)
 * parseDuration("3h") = Duration.standardHours(3)
 * </pre>
 *
 * @param value The period value to parse.
 * @return The {@link Duration} parsed from the supplied period string.
 */
public static Duration parseDuration(String value) {
  checkNotNull(value, "The specified duration must be a non-null value!");

  PeriodParser parser =
      new PeriodFormatterBuilder()
          .appendSeconds()
          .appendSuffix("s")
          .appendMinutes()
          .appendSuffix("m")
          .appendHours()
          .appendSuffix("h")
          .toParser();

  MutablePeriod period = new MutablePeriod();
  parser.parseInto(period, value, 0, Locale.getDefault());

  Duration duration = period.toDurationFrom(new DateTime(0));
  checkArgument(duration.getMillis() > 0, "The window duration must be greater than 0!");

  return duration;
}
 
Example #14
Source File: DurationUtils.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
/**
 * Parses a duration from a period formatted string. Values are accepted in the following formats:
 *
 * <p>Formats Ns - Seconds. Example: 5s<br>
 * Nm - Minutes. Example: 13m<br>
 * Nh - Hours. Example: 2h
 *
 * <pre>
 * parseDuration(null) = NullPointerException()
 * parseDuration("")   = Duration.standardSeconds(0)
 * parseDuration("2s") = Duration.standardSeconds(2)
 * parseDuration("5m") = Duration.standardMinutes(5)
 * parseDuration("3h") = Duration.standardHours(3)
 * </pre>
 *
 * @param value The period value to parse.
 * @return The {@link Duration} parsed from the supplied period string.
 */
public static Duration parseDuration(String value) {
  checkNotNull(value, "The specified duration must be a non-null value!");

  PeriodParser parser =
      new PeriodFormatterBuilder()
          .appendSeconds()
          .appendSuffix("s")
          .appendMinutes()
          .appendSuffix("m")
          .appendHours()
          .appendSuffix("h")
          .toParser();

  MutablePeriod period = new MutablePeriod();
  parser.parseInto(period, value, 0, Locale.getDefault());

  Duration duration = period.toDurationFrom(new DateTime(0));
  checkArgument(duration.getMillis() > 0, "The window duration must be greater than 0!");

  return duration;
}
 
Example #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #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: 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 #23
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 #24
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 #25
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 #26
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 #27
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));
}
 
Example #28
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 #29
Source File: SelectBetweenTimeBasedPolicy.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
protected static Period getLookBackPeriod(String lookbackTime) {
  PeriodFormatter periodFormatter =
      new PeriodFormatterBuilder().appendYears().appendSuffix("y").appendMonths().appendSuffix("M").appendDays()
          .appendSuffix("d").appendHours().appendSuffix("h").appendMinutes().appendSuffix("m").toFormatter();
  return periodFormatter.parsePeriod(lookbackTime);
}
 
Example #30
Source File: RecompactionConditionBasedOnDuration.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
private static PeriodFormatter getPeriodFormatter() {
  return new PeriodFormatterBuilder().appendMonths().appendSuffix("m").appendDays().appendSuffix("d").appendHours()
      .appendSuffix("h").appendMinutes().appendSuffix("min").toFormatter();
}