当前位置: 首页>>代码示例>>Java>>正文


Java PeriodFormat类代码示例

本文整理汇总了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()))
        );
    }
}
 
开发者ID:alphagov,项目名称:verify-service-provider,代码行数:17,代码来源:InstantValidator.java

示例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());
    }
}
 
开发者ID:itesla,项目名称:ipst,代码行数:26,代码来源:ListOfflineWorkflowsTool.java

示例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())));
  }
}
 
开发者ID:apache,项目名称:beam,代码行数:18,代码来源:SimpleDoFnRunner.java

示例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())); 
}
 
开发者ID:CTSIatUCSF,项目名称:Crosslinks,代码行数:18,代码来源:ProcessorController.java

示例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)));
}
 
开发者ID:h2oai,项目名称:h2o-3,代码行数:17,代码来源:PrettyPrint.java

示例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();
}
 
开发者ID:signal,项目名称:agathon,代码行数:17,代码来源:ZergDaoModule.java

示例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);
	}
}
 
开发者ID:Stwissel,项目名称:vertx-sfdc-platformevents,代码行数:37,代码来源:ApplicationStarter.java

示例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());
}
 
开发者ID:suomenriistakeskus,项目名称:oma-riista-web,代码行数:12,代码来源:LoggingBatchListener.java

示例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();
}
 
开发者ID:suomenriistakeskus,项目名称:oma-riista-web,代码行数:16,代码来源:LoggingBatchListener.java

示例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()));
}
 
开发者ID:bazaarvoice,项目名称:emodb,代码行数:33,代码来源:ScanUploadSchedulingService.java

示例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)));
}
 
开发者ID:apache,项目名称:beam,代码行数:35,代码来源:SimpleDoFnRunnerTest.java

示例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)));
}
 
开发者ID:apache,项目名称:beam,代码行数:37,代码来源:SimpleDoFnRunnerTest.java

示例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");
}
 
开发者ID:sonatype,项目名称:nexus-public,代码行数:37,代码来源:NexusContextListener.java

示例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);
  }
}
 
开发者ID:named-data-mobile,项目名称:NFD-android,代码行数:34,代码来源:MainFragment.java

示例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;
}
 
开发者ID:CTSIatUCSF,项目名称:Crosslinks,代码行数:8,代码来源:TypedOutputStats.java


注:本文中的org.joda.time.format.PeriodFormat类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。