下面列出了怎么用org.joda.time.format.PeriodFormatter的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
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;
}
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));
}
};
}
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;
}
@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;
}
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);
}
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);
}
/**
* 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;
}
}
@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);
}
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;
}
}
/**
* 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);
}
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;
}
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);
}
}
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);
}
}
/**
* 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;
}
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);
}
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());
}
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));
}
/**
* 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());
}
/**
* 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 + '"');
}
}
/**
* 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 + '"');
}
}
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();
}
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();
}
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);
}
private boolean isLookbackTimeStringDaily(String lookbackTime) {
PeriodFormatter periodFormatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d").toFormatter();
try {
periodFormatter.parsePeriod(lookbackTime);
return true;
} catch (Exception e) {
return false;
}
}
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;
}
}
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);
}
@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);
}
@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();
}
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;
}