Java Code Examples for org.joda.time.format.PeriodFormatter#parsePeriod()

The following examples show how to use org.joda.time.format.PeriodFormatter#parsePeriod() . 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: 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 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: 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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
Source File: TimeBasedSubDirDatasetsFinder.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
private DateTime getEarliestAllowedFolderTime(DateTime currentTime, PeriodFormatter periodFormatter) {
  String maxTimeAgoStr =
      this.state.getProp(COMPACTION_TIMEBASED_MAX_TIME_AGO, DEFAULT_COMPACTION_TIMEBASED_MAX_TIME_AGO);
  Period maxTimeAgo = periodFormatter.parsePeriod(maxTimeAgoStr);
  return currentTime.minus(maxTimeAgo);
}
 
Example 13
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 14
Source File: YouTubeVideo.java    From SkyTube with GNU General Public License v3.0 4 votes vote down vote up
public void setDurationInSeconds(String durationInSeconds) {
	PeriodFormatter formatter = ISOPeriodFormat.standard();
	Period p = formatter.parsePeriod(durationInSeconds);
	this.durationInSeconds = p.toStandardSeconds().getSeconds();
}
 
Example 15
Source File: UpdateCommand.java    From FlareBot with MIT License 4 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (PerGuildPermissions.isCreator(sender)) {
        if (args.length == 0) {
            update(false, channel);
        } else if (args.length == 1) {
            if (args[0].equalsIgnoreCase("force")) {
                update(true, channel);
            } else if (args[0].equalsIgnoreCase("no-active-channels")) {
                channel.sendMessage("I will now update to the latest version when no channels are playing music!")
                        .queue();
                if (Getters.getConnectedVoiceChannels() == 0) {
                    update(true, channel);
                } else {
                    if (!queued.getAndSet(true)) {
                        FlareBot.NOVOICE_UPDATING.set(true);
                    } else
                        channel.sendMessage("There is already an update queued!").queue();
                }
            } else if (args[0].equalsIgnoreCase("schedule")) {
                if (!queued.getAndSet(true)) {
                    FlareBot.instance().scheduleUpdate();
                    MessageUtils.sendSuccessMessage("Update scheduled for 12PM GMT!", channel);
                } else {
                    MessageUtils.sendErrorMessage("There is already an update queued!", channel);
                }
            } else if (args[0].equalsIgnoreCase("cancel")) {
                if (!queued.getAndSet(true)) {
                    MessageUtils.sendErrorMessage("There is no update queued!", channel);
                } else {
                    if (Scheduler.cancelTask("Scheduled-Update")) {
                        MessageUtils.sendSuccessMessage("Cancelled Update!", channel);
                    } else {
                        MessageUtils.sendErrorMessage("Could not cancel update!", channel);
                    }
                }
            } else {
                if (!queued.getAndSet(true)) {
                    Period p;
                    try {
                        PeriodFormatter formatter = new PeriodFormatterBuilder()
                                .appendDays().appendSuffix("d")
                                .appendHours().appendSuffix("h")
                                .appendMinutes().appendSuffix("m")
                                .appendSeconds().appendSuffix("s")
                                .toFormatter();
                        p = formatter.parsePeriod(args[0]);

                        new FlareBotTask("Scheduled-Update") {
                            @Override
                            public void run() {
                                update(true, channel);
                            }
                        }.delay(TimeUnit.SECONDS.toMillis(p.toStandardSeconds().getSeconds()));
                    } catch (IllegalArgumentException e) {
                        channel.sendMessage("That is an invalid time option!").queue();
                        return;
                    }
                    channel.sendMessage("I will now update to the latest version in " + p.toStandardSeconds()
                            .getSeconds() + " seconds.")
                            .queue();
                } else {
                    channel.sendMessage("There is already an update queued!").queue();
                }
            }
        }
    }
}
 
Example 16
Source File: PeriodConverter.java    From gson-jodatime-serialisers with MIT License 3 votes vote down vote up
/**
 * Gson invokes this call-back method during deserialization when it encounters a field of the
 * specified type. <p>
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link JsonDeserializationContext#deserialize(JsonElement, Type)} method to create objects
 * for any non-trivial field of the returned object. However, you should never invoke it on the
 * the same type passing {@code json} since that will cause an infinite loop (Gson will call your
 * call-back method again).
 * @param json The Json data being deserialized
 * @param typeOfT The type of the Object to deserialize to
 * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T}
 * @throws JsonParseException if json is not in the expected format of {@code typeOfT}
 */
@Override
public Period deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    throws JsonParseException
{
  // Do not try to deserialize null or empty values
  if (json.getAsString() == null || json.getAsString().isEmpty())
  {
    return null;
  }
  final PeriodFormatter fmt = ISOPeriodFormat.standard();
  return fmt.parsePeriod(json.getAsString());
}
 
Example 17
Source File: Period.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Parses a {@code Period} from the specified string using a formatter.
 * 
 * @param str  the string to parse, not null
 * @param formatter  the formatter to use, not null
 * @since 2.0
 */
public static Period parse(String str, PeriodFormatter formatter) {
    return formatter.parsePeriod(str);
}
 
Example 18
Source File: Period.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Parses a {@code Period} from the specified string using a formatter.
 * 
 * @param str  the string to parse, not null
 * @param formatter  the formatter to use, not null
 * @since 2.0
 */
public static Period parse(String str, PeriodFormatter formatter) {
    return formatter.parsePeriod(str);
}
 
Example 19
Source File: Time_5_Period_t.java    From coming with MIT License 2 votes vote down vote up
/**
 * Parses a {@code Period} from the specified string using a formatter.
 * 
 * @param str  the string to parse, not null
 * @param formatter  the formatter to use, not null
 * @since 2.0
 */
public static Period parse(String str, PeriodFormatter formatter) {
    return formatter.parsePeriod(str);
}
 
Example 20
Source File: Time_5_Period_s.java    From coming with MIT License 2 votes vote down vote up
/**
 * Parses a {@code Period} from the specified string using a formatter.
 * 
 * @param str  the string to parse, not null
 * @param formatter  the formatter to use, not null
 * @since 2.0
 */
public static Period parse(String str, PeriodFormatter formatter) {
    return formatter.parsePeriod(str);
}