下面列出了怎么用org.joda.time.format.PeriodFormatterBuilder的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
/**
* 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;
}
@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);
}
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 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;
}
}
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);
}
@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;
}
}
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;
}
}
/**
* 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;
}
/**
* 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 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());
}
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;
}
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);
}
private static PeriodFormatter cretePeriodFormatter(IntervalField startField, IntervalField endField)
{
if (endField == null) {
endField = startField;
}
List<PeriodParser> parsers = new ArrayList<>();
PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
switch (startField) {
case YEAR:
builder.appendYears();
parsers.add(builder.toParser());
if (endField == IntervalField.YEAR) {
break;
}
builder.appendLiteral("-");
// fall through
case MONTH:
builder.appendMonths();
parsers.add(builder.toParser());
if (endField != IntervalField.MONTH) {
throw new IllegalArgumentException("Invalid interval qualifier: " + startField + " to " + endField);
}
break;
case DAY:
builder.appendDays();
parsers.add(builder.toParser());
if (endField == IntervalField.DAY) {
break;
}
builder.appendLiteral(" ");
// fall through
case HOUR:
builder.appendHours();
parsers.add(builder.toParser());
if (endField == IntervalField.HOUR) {
break;
}
builder.appendLiteral(":");
// fall through
case MINUTE:
builder.appendMinutes();
parsers.add(builder.toParser());
if (endField == IntervalField.MINUTE) {
break;
}
builder.appendLiteral(":");
// fall through
case SECOND:
builder.appendSecondsWithOptionalMillis();
parsers.add(builder.toParser());
break;
}
return new PeriodFormatter(builder.toPrinter(), new OrderedPeriodParser(parsers));
}
@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();
}
}
}
}
}