本文整理汇总了Java中org.joda.time.format.PeriodFormat类的典型用法代码示例。如果您正苦于以下问题:Java PeriodFormat类的具体用法?Java PeriodFormat怎么用?Java PeriodFormat使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
PeriodFormat类属于org.joda.time.format包,在下文中一共展示了PeriodFormat类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: validate
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
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()))
);
}
}
示例2: run
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
@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());
}
}
示例3: checkTimestamp
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
@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())));
}
}
示例4: getDates
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
public String getDates() {
String retval = "";
if (getDateLastCrawled() != null) {
retval += "LastFinish " + getDateLastCrawled().getTime() + ", ";
}
if (started == null) {
return retval + "Not started...";
}
else {
retval += "Started " + started;
}
if (ended != null) {
retval += ", Ended " + ended;
}
Date endTime = ended != null ? ended : new Date();
return retval + ", Duration " + PeriodFormat.getDefault().print(new Period(endTime.getTime() - started.getTime()));
}
示例5: toAge
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
public static String toAge(Date from, Date to) {
if (from == null || to == null) return "N/A";
final Period period = new Period(from.getTime(), to.getTime());
DurationFieldType[] dtf = new ArrayList<DurationFieldType>() {{
add(DurationFieldType.years()); add(DurationFieldType.months());
add(DurationFieldType.days());
if (period.getYears() == 0 && period.getMonths() == 0 && period.getDays() == 0) {
add(DurationFieldType.hours());
add(DurationFieldType.minutes());
}
}}.toArray(new DurationFieldType[0]);
PeriodFormatter pf = PeriodFormat.getDefault();
return pf.print(period.normalizedStandard(PeriodType.forFields(dtf)));
}
示例6: provideAsyncHttpClientConfig
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
@Provides @Singleton
AsyncHttpClientConfig provideAsyncHttpClientConfig(
@Named(ZERG_CONNECTION_TIMEOUT_PROPERTY) Duration connectionTimeout,
@Named(ZERG_REQUEST_TIMEOUT_PROPERTY) Duration requestTimeout) {
PeriodFormatter formatter = PeriodFormat.getDefault();
log.info("Using connection timeout {} and request timeout {}",
formatter.print(connectionTimeout.toPeriod()), formatter.print(requestTimeout.toPeriod()));
return new AsyncHttpClientConfig.Builder()
.setAllowPoolingConnection(true)
.setConnectionTimeoutInMs(Ints.saturatedCast(connectionTimeout.getMillis()))
.setRequestTimeoutInMs(Ints.saturatedCast(requestTimeout.getMillis()))
.setFollowRedirects(true)
.setMaximumNumberOfRedirects(3)
.setMaxRequestRetry(1)
.build();
}
示例7: shutdownExecution
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
/**
* Executes the actual shutdown once one of the shutdown handlers has
* accepted the shutdown request
*
* @param response
* Tells the caller some metrics
*/
private void shutdownExecution(final HttpServerResponse response) {
final JsonObject goodby = new JsonObject();
goodby.put("Goodby", "It was a pleasure doing business with you");
goodby.put("StartDate", Utils.getDateString(this.startDate));
goodby.put("EndDate", Utils.getDateString(new Date()));
final Duration dur = new Duration(new DateTime(this.startDate), new DateTime());
goodby.put("Duration", PeriodFormat.getDefault().print(new Period(dur)));
response.putHeader(Constants.CONTENT_HEADER, Constants.CONTENT_TYPE_JSON).setStatusCode(202)
.end(goodby.encodePrettily());
try {
Future<Void> shutdownFuture = Future.future();
shutdownFuture.setHandler(fResult -> {
if (fResult.failed()) {
this.logger.fatal(fResult.cause());
System.exit(-1);
}
this.logger.info("Good by!");
this.getVertx().close(handler -> {
if (handler.failed()) {
this.logger.fatal(handler.cause());
}
System.exit(0);
});
});
this.shutDownVerticles(shutdownFuture);
} catch (Exception e) {
this.logger.fatal(e.getMessage(), e);
}
}
示例8: afterJob
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
@AfterJob
public void afterJob(JobExecution jobExecution) {
final Interval interval = new Interval(
jobExecution.getStartTime().getTime(),
System.currentTimeMillis());
LOG.info("Finished job: {} in {} with exitStatus={}",
jobExecution.getJobInstance().getJobName(),
PeriodFormat.getDefault().print(interval.toPeriod()),
jobExecution.getExitStatus());
}
示例9: afterStep
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
@AfterStep
public ExitStatus afterStep(StepExecution stepExecution) {
final Interval interval = new Interval(
stepExecution.getStartTime().getTime(),
System.currentTimeMillis());
LOG.debug("Finished step: {} in {}. read = {} write = {} commit = {} rollback = {} filter = {} skip = {}",
stepExecution.getStepName(), PeriodFormat.getDefault().print(interval.toPeriod()),
stepExecution.getReadCount(), stepExecution.getWriteCount(),
stepExecution.getCommitCount(), stepExecution.getRollbackCount(),
stepExecution.getFilterCount(),
stepExecution.getSkipCount());
return stepExecution.getExitStatus();
}
示例10: scheduleNextScanExecution
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
/**
* Schedules the scan and upload to execute at the given time, then daily at the same time afterward indefinitely.
*/
private void scheduleNextScanExecution(final ScheduledDailyScanUpload scanUpload, DateTime now, final DateTime nextExecTime) {
Duration delay = new Duration(now, nextExecTime);
// We deliberately chain scheduled scans instead of scheduling at a fixed rate to allow for
// each iteration to explicitly contain the expected execution time.
_service.schedule(
new Runnable() {
@Override
public void run() {
try {
startScheduledScan(scanUpload, nextExecTime);
} catch (Exception e) {
_log.error("Failed to start scheduled daily scan upload", e);
}
// Remove this scan from the pending set
if (_pendingScans.remove(scanUpload)) {
notifyPendingScanCountChanged();
}
// Schedule the next run
scheduleNextScanExecution(scanUpload, now(), nextExecTime.plusDays(1));
}
},
delay.getMillis(), TimeUnit.MILLISECONDS);
_log.info("Scan and upload to {} scheduled to execute at {} ({} from now)",
scanUpload.getRootDestination(), nextExecTime, delay.toPeriod().toString(PeriodFormat.getDefault()));
}
示例11: testBackwardsInTimeNoSkew
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
/**
* 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<Duration>(),
Collections.<TupleTag<?>>emptyList(),
mockStepContext,
WindowingStrategy.of(new GlobalWindows()));
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)));
}
示例12: testSkew
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
/**
* 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<Duration>(),
Collections.<TupleTag<?>>emptyList(),
mockStepContext,
WindowingStrategy.of(new GlobalWindows()));
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)));
}
示例13: contextDestroyed
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
@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)));
try {
lifecycleManager.to(KERNEL);
// dispose of JSR-250 components before logging goes
injector.getInstance(BeanManager.class).unmanage();
lifecycleManager.to(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");
}
示例14: onPostExecute
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
@Override
protected void
onPostExecute(ForwarderStatus fs) {
if (fs == null) {
// when failed, try after 0.5 seconds
m_handler.postDelayed(m_statusUpdateRunnable, 500);
} else {
m_versionView.setText(fs.getNfdVersion());
m_uptimeView.setText(PeriodFormat.getDefault().print(new Period(
fs.getCurrentTimestamp() - fs.getStartTimestamp())));
m_nameTreeEntriesView.setText(String.valueOf(
fs.getNNameTreeEntries()));
m_fibEntriesView.setText(String.valueOf(fs.getNFibEntries()));
m_pitEntriesView.setText(String.valueOf(fs.getNPitEntries()));
m_measurementEntriesView.setText(String.valueOf(
fs.getNMeasurementsEntries()));
m_csEntriesView.setText(String.valueOf(fs.getNCsEntries()));
m_inInterestsView.setText(String.valueOf(fs.getNInInterests()));
m_outInterestsView.setText(String.valueOf(fs.getNOutInterests()));
m_inDataView.setText(String.valueOf(fs.getNInDatas()));
m_outDataView.setText(String.valueOf(fs.getNOutDatas()));
m_inNacksView.setText(String.valueOf(fs.getNInNacks()));
m_outNacksView.setText(String.valueOf(fs.getNOutNacks()));
m_nfdStatusView.setVisibility(View.VISIBLE);
// refresh after 5 seconds
m_handler.postDelayed(m_statusUpdateRunnable, 5000);
}
}
示例15: toString
import org.joda.time.format.PeriodFormat; //导入依赖的package包/类
public String toString() {
String retval = type.toString() + ": " + getCount();
if (count.get() > 0 && elapsedTime.get() > 0) {
retval += ", rate time/person = " + PeriodFormat.getDefault().print(new Period(elapsedTime.get()/getCount()));
}
return retval;
}