下面列出了怎么用org.joda.time.format.PeriodFormat的API类实例代码及写法,或者点击链接到github查看源代码。
public void validate(DateTime instant, String instantName) {
Duration age = new Duration(instant, DateTime.now());
if (age.isLongerThan(MAXIMUM_INSTANT_AGE)) {
throw new SamlResponseValidationException(String.format("%s is too far in the past %s",
instantName,
PeriodFormat.getDefault().print(age.toPeriod()))
);
}
if (dateTimeComparator.isAfterNow(instant)) {
throw new SamlResponseValidationException(String.format("%s is in the future %s",
instantName,
instant.withZone(UTC).toString(dateHourMinuteSecond()))
);
}
}
@Override
public void run(CommandLine line, ToolRunningContext context) throws Exception {
try (OfflineApplication app = new RemoteOfflineApplicationImpl()) {
Map<String, OfflineWorkflowStatus> statuses = app.listWorkflows();
Table table = new Table(4, BorderStyle.CLASSIC_WIDE);
table.addCell("ID");
table.addCell("Running");
table.addCell("Step");
table.addCell("Time");
for (Map.Entry<String, OfflineWorkflowStatus> entry : statuses.entrySet()) {
String workflowId = entry.getKey();
OfflineWorkflowStatus status = entry.getValue();
Duration remaining = null;
if (status.getStartTime() != null) {
remaining = Duration.millis(status.getStartParameters().getDuration() * 60 * 1000)
.minus(new Duration(status.getStartTime(), DateTime.now()));
}
table.addCell(workflowId);
table.addCell(Boolean.toString(status.isRunning()));
table.addCell(status.getStep() != null ? status.getStep().toString() : "");
table.addCell(remaining != null ? PeriodFormat.getDefault().print(remaining.toPeriod()) : "");
}
context.getOutputStream().println(table.render());
}
}
@Test
public void performance() throws RepositoryNotFoundException {
// dmojito repo-create -n perftest3 -d "" -l "ar-SA" "zh-CN" "zh-TW" "cs-CZ" "da-DK" "de-DE" "el-GR" "en-GB" "es-AR" "es-MX" "es-ES" "fi-FI" "fr-FR" "hi-IN" "hu-HU" "id-ID" "it-IT" "ja-JP" "ko-KR" "ms-MY" "nb-NO" "nl-NL" "pl-PL" "pt-BR" "pt-PT" "ro-RO" "ru-RU" "sk-SK" "sv-SE" "th-TH" "tl-PH" "tr-TR" "uk-UA" "vi-VN"
String repoName = "perftest3";
Repository repository = repositoryClient.getRepositoryByName(repoName);
VirtualAsset v = new VirtualAsset();
v.setPath("default");
v.setRepositoryId(repository.getId());
v.setDeleted(false);
VirtualAsset virtualAsset = virtualAssetClient.createOrUpdate(v);
logger.debug("virtual asset id: {}", virtualAsset.getId());
DateTime start = DateTime.now();
// createSourceStrings(virtualAsset);
// importTranslations(repository, virtualAsset);
pullSourceString(virtualAsset, repository);
pullTranslations(virtualAsset, repository);
logger.debug("total: {}", PeriodFormat.getDefault().print(new Period(start, DateTime.now())));
}
void pullTranslations(VirtualAsset virtualAsset, Repository repository) {
logger.debug("pull translations");
repository.getRepositoryLocales().stream()
.sorted(Comparator.comparing(rl -> rl.getLocale().getBcp47Tag()))
.filter(rl -> rl.getParentLocale() != null)
.forEach(rl -> {
logger.debug("localized locale: {}", rl.getLocale().getBcp47Tag());
long start = System.currentTimeMillis();
List<VirtualAssetTextUnit> virtualAssetTextUnits = virtualAssetClient.getLocalizedTextUnits(virtualAsset.getId(), rl.getLocale().getId(), "REMOVE_UNTRANSLATED");
long end = System.currentTimeMillis();
logger.debug("file generation: {}", PeriodFormat.getDefault().print(new Period(start, end)));
// ObjectMapper objectMapper = new ObjectMapper();
// objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
// logger.debug(objectMapper.writeValueAsStringUnchecked(virtualAssetTextUnits));
});
}
@SuppressWarnings("deprecation") // Allowed Skew is deprecated for users, but must be respected
private void checkTimestamp(Instant timestamp) {
// The documentation of getAllowedTimestampSkew explicitly permits Long.MAX_VALUE to be used
// for infinite skew. Defend against underflow in that case for timestamps before the epoch
if (fn.getAllowedTimestampSkew().getMillis() != Long.MAX_VALUE
&& timestamp.isBefore(elem.getTimestamp().minus(fn.getAllowedTimestampSkew()))) {
throw new IllegalArgumentException(
String.format(
"Cannot output with timestamp %s. Output timestamps must be no earlier than the "
+ "timestamp of the current input (%s) minus the allowed skew (%s). See the "
+ "DoFn#getAllowedTimestampSkew() Javadoc for details on changing the allowed "
+ "skew.",
timestamp,
elem.getTimestamp(),
PeriodFormat.getDefault().print(fn.getAllowedTimestampSkew().toPeriod())));
}
}
private void pullSourceString(VirtualAsset virtualAsset, Repository repository) {
repository.getRepositoryLocales().stream()
.filter(rl -> rl.getParentLocale() == null)
.forEach(rl -> {
logger.debug("root locale: {}", rl.getLocale().getBcp47Tag());
long start = System.currentTimeMillis();
List<VirtualAssetTextUnit> virtualAssetTextUnits = virtualAssetClient.getLocalizedTextUnits(virtualAsset.getId(), rl.getLocale().getId(), "REMOVE_UNTRANSLATED");
long end = System.currentTimeMillis();
logger.debug("file generation: {}", PeriodFormat.getDefault().print(new Period(start, end)));
// ObjectMapper objectMapper = new ObjectMapper();
// objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
// logger.debug(objectMapper.writeValueAsStringUnchecked(virtualAssetTextUnits));
});
}
/**
* Demonstrates that attempting to output an element before the timestamp of the current element
* with zero {@link DoFn#getAllowedTimestampSkew() allowed timestamp skew} throws.
*/
@Test
public void testBackwardsInTimeNoSkew() {
SkewingDoFn fn = new SkewingDoFn(Duration.ZERO);
DoFnRunner<Duration, Duration> runner =
new SimpleDoFnRunner<>(
null,
fn,
NullSideInputReader.empty(),
new ListOutputManager(),
new TupleTag<>(),
Collections.emptyList(),
mockStepContext,
null,
Collections.emptyMap(),
WindowingStrategy.of(new GlobalWindows()),
DoFnSchemaInformation.create(),
Collections.emptyMap());
runner.startBundle();
// An element output at the current timestamp is fine.
runner.processElement(
WindowedValue.timestampedValueInGlobalWindow(Duration.ZERO, new Instant(0)));
thrown.expect(UserCodeException.class);
thrown.expectCause(isA(IllegalArgumentException.class));
thrown.expectMessage("must be no earlier");
thrown.expectMessage(
String.format("timestamp of the current input (%s)", new Instant(0).toString()));
thrown.expectMessage(
String.format(
"the allowed skew (%s)", PeriodFormat.getDefault().print(Duration.ZERO.toPeriod())));
// An element output before (current time - skew) is forbidden
runner.processElement(
WindowedValue.timestampedValueInGlobalWindow(Duration.millis(1L), new Instant(0)));
}
/**
* Demonstrates that attempting to output an element before the timestamp of the current element
* plus the value of {@link DoFn#getAllowedTimestampSkew()} throws, but between that value and the
* current timestamp succeeds.
*/
@Test
public void testSkew() {
SkewingDoFn fn = new SkewingDoFn(Duration.standardMinutes(10L));
DoFnRunner<Duration, Duration> runner =
new SimpleDoFnRunner<>(
null,
fn,
NullSideInputReader.empty(),
new ListOutputManager(),
new TupleTag<>(),
Collections.emptyList(),
mockStepContext,
null,
Collections.emptyMap(),
WindowingStrategy.of(new GlobalWindows()),
DoFnSchemaInformation.create(),
Collections.emptyMap());
runner.startBundle();
// Outputting between "now" and "now - allowed skew" succeeds.
runner.processElement(
WindowedValue.timestampedValueInGlobalWindow(Duration.standardMinutes(5L), new Instant(0)));
thrown.expect(UserCodeException.class);
thrown.expectCause(isA(IllegalArgumentException.class));
thrown.expectMessage("must be no earlier");
thrown.expectMessage(
String.format("timestamp of the current input (%s)", new Instant(0).toString()));
thrown.expectMessage(
String.format(
"the allowed skew (%s)",
PeriodFormat.getDefault().print(Duration.standardMinutes(10L).toPeriod())));
// Outputting before "now - allowed skew" fails.
runner.processElement(
WindowedValue.timestampedValueInGlobalWindow(Duration.standardHours(1L), new Instant(0)));
}
private void logMessage( String storageId, FileResource fileResource, Period timeDiff )
{
if ( storageId == null )
{
log.error( String.format( "Saving content for file resource failed: %s", fileResource.getUid() ) );
return;
}
log.info( String.format( "File stored with key: %s'. Upload finished in %s", storageId, timeDiff.toString( PeriodFormat.getDefault() ) ) );
}
@Override
public void contextDestroyed(final ServletContextEvent event) {
// event is ignored, apparently can also be null
// remove our dynamic filter
if (registration != null) {
registration.unregister();
registration = null;
}
// log uptime before triggering activity which may run into problems
long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
log.info("Uptime: {} ({})", PeriodFormat.getDefault().print(new Period(uptime)),
System.getProperty(NEXUS_FULL_EDITION, UNKNOWN));
try {
moveToPhase(OFF);
}
catch (final Exception e) {
log.error("Failed to stop nexus", e);
}
extender.doStop(); // stop tracking bundles
if (servletContext != null) {
servletContext = null;
}
injector = null;
SharedMetricRegistries.remove("nexus");
}
protected void checkTimestamp(WindowedValue<IN> ref, Instant timestamp) {
if (timestamp.isBefore(ref.getTimestamp().minus(doFn.getAllowedTimestampSkew()))) {
throw new IllegalArgumentException(String.format(
"Cannot output with timestamp %s. Output timestamps must be no earlier than the "
+ "timestamp of the current input (%s) minus the allowed skew (%s). See the "
+ "DoFn#getAllowedTimestmapSkew() Javadoc for details on changing the allowed skew.",
timestamp, ref.getTimestamp(),
PeriodFormat.getDefault().print(doFn.getAllowedTimestampSkew().toPeriod())));
}
}
public void testToString_PeriodFormatter() {
Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8);
assertEquals("1 year, 2 months, 3 weeks, 4 days, 5 hours, 6 minutes, 7 seconds and 8 milliseconds", test.toString(PeriodFormat.getDefault()));
test = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0 milliseconds", test.toString(PeriodFormat.getDefault()));
}
public void testToString_PeriodFormatter() {
Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8);
assertEquals("1 year, 2 months, 3 weeks, 4 days, 5 hours, 6 minutes, 7 seconds and 8 milliseconds", test.toString(PeriodFormat.getDefault()));
test = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0 milliseconds", test.toString(PeriodFormat.getDefault()));
}
/**
* This method is invoked when a log record is successfully sent to Kinesis.
* Though this is not too useful for production use cases, it provides a good
* debugging tool while tweaking parameters for the appender.
*/
@Override
public void onSuccess(PutRecordRequest request, PutRecordResult result) {
successfulRequestCount++;
if (logger.isDebugEnabled() && (successfulRequestCount + failedRequestCount) % 3000 == 0) {
logger.debug("Appender (" + appenderName + ") made " + successfulRequestCount
+ " successful put requests out of total " + (successfulRequestCount + failedRequestCount) + " in "
+ PeriodFormat.getDefault().print(new Period(startTime, DateTime.now())) + " since start");
}
}
private static void printScriptRunTime(DateTime startTime) {
DateTime endTime = new DateTime();
Duration duration = new Duration(startTime, endTime);
Period period = duration.toPeriod().normalizedStandard(PeriodType.time());
log.info("Pig script completed in "
+ PeriodFormat.getDefault().print(period)
+ " (" + duration.getMillis() + " ms)");
}
/**
* Given a duration in milliseconds, this method returns a human-readable period string.
*
* @param duration a duration in milliseconds, nonnegative
* @return a String
*/
public static String makePeriodString(long duration) {
if (duration < 0) {
throw new IllegalArgumentException("duration should be nonnegative.");
}
Period period = new Period(duration).normalizedStandard();
period = withMostSignificantNonZeroFieldsOnly(period, 1);
return PeriodFormat.wordBased(Locale.ENGLISH).print(period);
}
public String format(PeriodType type) {
Period period = new Period(millis());
return PeriodFormat.getDefault().withParseType(type).print(period);
}
String getElapsedTime(PollableTask pollableTask) {
Period period = new Period(pollableTask.getCreatedDate(), pollableTask.getFinishedDate());
return PeriodFormat.getDefault().print(period);
}
public static String toDurationString(long duration, TimeUnit unit, boolean color) {
return wrapQuiet(PeriodFormat.getDefault().print(new Duration(unit.toMillis(duration)).toPeriod()), color);
}
/** @return a human-readable formatted string for the given amount of nanos */
private static String formatElapsed(long nanos) {
return String.format("%s (%6.3g nanoseconds)",
PeriodFormat.getDefault().print(Period.millis((int)(nanos / 1000))),
(double) nanos);
}
private String getFormattedExpirationMinutes() {
int expirationMinutes = serverConfigurationService.getInt(MAX_PASSWORD_RESET_MINUTES, MAX_PASSWORD_RESET_MINUTES_DEFAULT);
Period period = new Period(expirationMinutes * 60 * 1000);
PeriodFormatter periodFormatter = PeriodFormat.wordBased(rl.getLocale());
return periodFormatter.print(period);
}
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java " + FilePublisher.class.getName() + " <file_path>");
System.err.println();
System.err.println("<file_path>\t-\tabsolute path for the input file, this file will be read line by line and ");
System.err.println("\t\t\tpublished to Kinesis");
System.exit(1);
}
String fileAbsolutePath = args[0];
File logFile = new File(fileAbsolutePath);
if (!logFile.exists() || !logFile.canRead()) {
System.err.println("File " + args[0] + " doesn't exist or is not readable.");
System.exit(2);
}
Logger kinesisLogger = Logger.getLogger("KinesisLogger");
int i = 0;
DateTime startTime = DateTime.now();
BufferedReader reader = new BufferedReader(new FileReader(logFile));
LOGGER.info("Started reading: " + fileAbsolutePath);
String line = null;
while ((line = reader.readLine()) != null) {
kinesisLogger.info(line);
i++;
if (i % 100 == 0 && LOGGER.isDebugEnabled()) {
LOGGER.debug("Total " + i + " records written to logger");
}
}
reader.close();
long bufferedRecordsCount = getBufferedRecordsCountFromKinesisAppenders();
while (bufferedRecordsCount > 0) {
LOGGER.info("Publisher threads within log4j appender are still working on sending " + bufferedRecordsCount
+ " buffered records to Kinesis");
try {
Thread.sleep(SLEEP_INTERVAL);
} catch (InterruptedException e) {
// do nothing
}
bufferedRecordsCount = getBufferedRecordsCountFromKinesisAppenders();
}
LOGGER.info("Published " + i + " records from " + fileAbsolutePath + " to the logger, took "
+ PeriodFormat.getDefault().print(new Period(startTime, DateTime.now())));
}
private String getFormattedExpirationMinutes() {
int expirationMinutes = serverConfigurationService.getInt(MAX_PASSWORD_RESET_MINUTES, MAX_PASSWORD_RESET_MINUTES_DEFAULT);
Period period = new Period(expirationMinutes * 60 * 1000);
PeriodFormatter periodFormatter = PeriodFormat.wordBased(rl.getLocale());
return periodFormatter.print(period);
}
/**
* Calculates the time Amforeas has been running and returns a string representing it, i.e. 2 days 10 hours...
* @return a string with the uptime.
*/
public String getUptime () {
Period period = new Period(this.start, new DateTime());
return PeriodFormat.getDefault().print(period);
}
public static void main(String[] args) {
//Period period = new Period(uptime, PeriodType.standard().withYearsRemoved().withWeeksRemoved().withMonthsRemoved().withMillisRemoved());
//MutablePeriod period = new Duration(uptime).toPeriod().toMutablePeriod();
long uptime = UPTIME_56_SECS;
// ah, ha -- this is super important -- need to normalize the period!
PeriodType periodType = PeriodType.standard().withYearsRemoved().withMonthsRemoved().withWeeksRemoved().withMillisRemoved();
Period period = new Period(uptime).normalizedStandard(periodType);
System.out.println("Uptime: " + uptime + " ms");
System.out.println("Weeks: " + period.getWeeks());
System.out.println("Days: " + period.getDays());
System.out.println("Millis: " + period.getMillis() + " ms");
// print out the uptime
String uptimeStyleString = PeriodFormatterUtil.getStandardUptimeStyle().print(period);
String linuxStyleString = PeriodFormatterUtil.getLinuxUptimeStyle().print(period);
System.out.println(uptimeStyleString);
System.out.println(linuxStyleString);
PeriodFormatter fmt = new PeriodFormatterBuilder()
.printZeroNever()
.appendDays()
.appendSuffix(" day ", " days ")
.appendHours()
.appendSuffix(" hours ")
.appendMinutes()
.appendSuffix(" mins ")
.printZeroAlways()
.appendSeconds()
.appendSuffix(" secs ")
.toFormatter();
String str0 = fmt.print(period);
System.out.println(str0);
String str1 = PeriodFormat.getDefault().print(period);
System.out.println(str1);
}
/**
* Converts some number of minutes into a presentable String'
* ie for English:
* 122 minutes -> 2 hours 2 minutes
* 121 minutes -> 2 hours 1 minute
* 120 minutes -> 2 hours
* 62 minutes -> 1 hour 2 minutes
* 61 minutes -> 1 hour 1 minute
* 60 minutes -> 1 hour
* 2 minutes -> 2 minutes
* 1 minutes -> 1 minute
* 0 minutes -> 0 minutes
* Works with other languages too.
* @param totalMinutes some number of minutes
* @return a presentable String representation of totalMinutes
*/
public String getFormattedMinutes(int totalMinutes)
{
// Create a joda time period (takes milliseconds)
Period period = new Period(totalMinutes*60*1000);
// format the period for the locale
/*
* Covers English, Danish, Dutch, French, German, Japanese, Portuguese, and Spanish.
* To translate into others, see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/PeriodFormat.html#wordBased(java.util.Locale)
* (ie. put the properties mentioned in http://joda-time.sourceforge.net/apidocs/src-html/org/joda/time/format/PeriodFormat.html#line.94 into the classpath resource bundle)
*/
PeriodFormatter periodFormatter = PeriodFormat.wordBased(getLocale());
return periodFormatter.print(period);
}
/**
* Converts some number of minutes into a presentable String'
* ie for English:
* 122 minutes -> 2 hours 2 minutes
* 121 minutes -> 2 hours 1 minute
* 120 minutes -> 2 hours
* 62 minutes -> 1 hour 2 minutes
* 61 minutes -> 1 hour 1 minute
* 60 minutes -> 1 hour
* 2 minutes -> 2 minutes
* 1 minutes -> 1 minute
* 0 minutes -> 0 minutes
* Works with other languages too.
* @param totalMinutes some number of minutes
* @return a presentable String representation of totalMinutes
*/
public String getFormattedMinutes(int totalMinutes)
{
// Create a joda time period (takes milliseconds)
Period period = new Period(totalMinutes*60*1000);
// format the period for the locale
/*
* Covers English, Danish, Dutch, French, German, Japanese, Portuguese, and Spanish.
* To translate into others, see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/PeriodFormat.html#wordBased(java.util.Locale)
* (ie. put the properties mentioned in http://joda-time.sourceforge.net/apidocs/src-html/org/joda/time/format/PeriodFormat.html#line.94 into the classpath resource bundle)
*/
PeriodFormatter periodFormatter = PeriodFormat.wordBased(getLocale());
return periodFormatter.print(period);
}
/**
* Converts some number of minutes into a presentable String'
* ie for English:
* 122 minutes -> 2 hours 2 minutes
* 121 minutes -> 2 hours 1 minute
* 120 minutes -> 2 hours
* 62 minutes -> 1 hour 2 minutes
* 61 minutes -> 1 hour 1 minute
* 60 minutes -> 1 hour
* 2 minutes -> 2 minutes
* 1 minutes -> 1 minute
* 0 minutes -> 0 minutes
* Works with other languages too.
* @param totalMinutes some number of minutes
* @return a presentable String representation of totalMinutes
*/
public String getFormattedMinutes(int totalMinutes)
{
// Create a joda time period (takes milliseconds)
Period period = new Period(totalMinutes*60*1000);
// format the period for the locale
/*
* Covers English, Danish, Dutch, French, German, Japanese, Portuguese, and Spanish.
* To translate into others, see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/PeriodFormat.html#wordBased(java.util.Locale)
* (ie. put the properties mentioned in http://joda-time.sourceforge.net/apidocs/src-html/org/joda/time/format/PeriodFormat.html#line.94 into the classpath resource bundle)
*/
PeriodFormatter periodFormatter = PeriodFormat.wordBased(getLocale());
return periodFormatter.print(period);
}
/**
* Converts some number of minutes into a presentable String'
* ie for English:
* 122 minutes -> 2 hours 2 minutes
* 121 minutes -> 2 hours 1 minute
* 120 minutes -> 2 hours
* 62 minutes -> 1 hour 2 minutes
* 61 minutes -> 1 hour 1 minute
* 60 minutes -> 1 hour
* 2 minutes -> 2 minutes
* 1 minutes -> 1 minute
* 0 minutes -> 0 minutes
* Works with other languages too.
* @param totalMinutes some number of minutes
* @return a presentable String representation of totalMinutes
*/
public String getFormattedMinutes(int totalMinutes)
{
// Create a joda time period (takes milliseconds)
Period period = new Period(totalMinutes*60*1000);
// format the period for the locale
/*
* Covers English, Danish, Dutch, French, German, Japanese, Portuguese, and Spanish.
* To translate into others, see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/PeriodFormat.html#wordBased(java.util.Locale)
* (ie. put the properties mentioned in http://joda-time.sourceforge.net/apidocs/src-html/org/joda/time/format/PeriodFormat.html#line.94 into the classpath resource bundle)
*/
PeriodFormatter periodFormatter = PeriodFormat.wordBased(getLocale());
return periodFormatter.print(period);
}