Java 类org.joda.time.format.PeriodFormat 实例源码

项目:verify-service-provider    文件:InstantValidator.java   
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()))
        );
    }
}
项目:ipst    文件:ListOfflineWorkflowsTool.java   
@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());
    }
}
项目:beam    文件:SimpleDoFnRunner.java   
@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())));
  }
}
项目:Crosslinks    文件:ProcessorController.java   
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())); 
}
项目:h2o-3    文件:PrettyPrint.java   
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)));
}
项目:agathon    文件:ZergDaoModule.java   
@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();
}
项目:vertx-sfdc-platformevents    文件:ApplicationStarter.java   
/**
 * 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);
    }
}
项目:oma-riista-web    文件:LoggingBatchListener.java   
@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());
}
项目:oma-riista-web    文件:LoggingBatchListener.java   
@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();
}
项目:emodb    文件:ScanUploadSchedulingService.java   
/**
 * 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()));
}
项目:beam    文件:SimpleDoFnRunnerTest.java   
/**
 * 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)));
}
项目:beam    文件:SimpleDoFnRunnerTest.java   
/**
 * 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)));
}
项目:nexus-public    文件:NexusContextListener.java   
@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");
}
项目:NFD-android    文件:MainFragment.java   
@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);
  }
}
项目:Crosslinks    文件:TypedOutputStats.java   
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;
}
项目:Crosslinks    文件:ProcessorController.java   
public String getRates() {
    if (stats.get(OutputType.PROCESSED).getCount() == 0) {
        return "None yet...";
    }
    else {
        int processed = stats.get(OutputType.PROCESSED).getCount();
        return "Throughput processed/person : " +  PeriodFormat.getDefault().print(new Period((new Date().getTime() - getStartDate().getTime())/processed));            
    }
}
项目:astor    文件:TestPeriod_Basics.java   
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()));
}
项目:astor    文件:TestPeriod_Basics.java   
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()));
}
项目:dungeon    文件:Utils.java   
/**
 * 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);
}
项目:kinesis-log4j-appender    文件:AsyncPutCallStatsReporter.java   
/**
 * 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");
  }
}
项目:spork    文件:Main.java   
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)");
}
项目:versemem-android    文件:TestPeriod_Basics.java   
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()));
}
项目:elasticsearch_my    文件:TimeValue.java   
public String format(PeriodType type) {
    Period period = new Period(millis());
    return PeriodFormat.getDefault().withParseType(type).print(period);
}
项目:RxDisposal    文件:MainActivity.java   
private void startWork() {
    // dispose of any previous streams
    stopWork();

    /*
     *  1) Stream that reports current time -
     *       This stream will always attempt to update the time until the Disposal is triggered
     *       This stream is ultimately registered to CompositeDisposal for handling multiple events
     */
    Observable.interval(1, TimeUnit.SECONDS)
            .map(aLong -> LocalTime.now())
            .map(time -> DateTimeFormat.mediumTime().print(time))
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(disposalAll.wrap(textView1::setText));

    /*
     *  2) Stream that reports a random ID -
     *       This stream will always attempt to post an ID the Disposal is triggered.
     *       This stream is ultimately registered to SimpleDisposal for handling individual events
     */
    Observable.interval(1, TimeUnit.SECONDS)
            .map(aLong -> UUID.randomUUID())
            .map(UUID::toString)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(disposalOne.wrap(textView2::setText));

    /*
     *  3) Stream that reports time elapsed -
     *       This stream will always attempt to update the time until the Disposal is triggered.
     *       This stream is ultimately registered to CompositeDisposal for handling multiple events.
     */
    Observable.interval(1, TimeUnit.SECONDS)
            .map(Duration::standardSeconds)
            .map(Duration::toPeriod)
            .map(period -> PeriodFormat.getDefault().print(period))
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(disposalAll.wrap(textView3::setText));

    /*
     *  4) Stream that simulates download progress -
     *      This stream will create random progress until it reaches 100 %
     *      This stream is registered to the SubscriptionAutoDisposal and will automatically
     *      dispose during onPause(...)
     */
    Random random = new Random(System.currentTimeMillis());
    Observable.interval(1, TimeUnit.SECONDS)
            .map((t) -> random.nextInt(5))
            .scan((x, y) -> x + y)
            .takeUntil((sum) -> sum > progressBar.getMax())
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(autoDisposal.wrap(
                    this::updateProgressBar,
                    this::handleError,
                    () -> updateProgressBar(progressBar.getMax())
            ));
}
项目:Elasticsearch    文件:TimeValue.java   
public String format(PeriodType type) {
    Period period = new Period(millis());
    return PeriodFormat.getDefault().withParseType(type).print(period);
}
项目:beyondj    文件:UptimeMain.java   
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);
    }
项目:emodb    文件:DefaultJobService.java   
/**
 * Dequeues the next job from the job queue and runs it.
 * @return True if a job was dequeued and executed, false if the queue was empty.
 */
@VisibleForTesting
boolean runNextJob() {
    try {
        Queue<Message> messages = _messageSupplier.get();
        Message message;

        while ((message = messages.poll()) != null) {
            String jobIdString = (String) message.getPayload();

            // If this job has recently reported that it cannot run on this server then skip it.
            DateTime now = new DateTime();
            DateTime delayUntilTime = _recentNotOwnerDelays.get(jobIdString, EPOCH);
            if (now.isBefore(delayUntilTime)) {
                _log.debug("Waiting {} for next attempt to run job locally: {}",
                        PeriodFormat.getDefault().print(new Interval(now, delayUntilTime).toPeriod()),
                        jobIdString);
                continue;
            }

            InterProcessMutex mutex = getMutex(jobIdString);

            if (!acquireMutex(mutex)) {
                _log.debug("Failed to get mutex for job {}", jobIdString);
                continue;
            }
            try {
                String jobTypeName = getJobTypeNameFromId(jobIdString);
                RegistryEntry<?, ?> entry = _jobHandlerRegistry.getRegistryEntry(jobTypeName);

                _log.info("Executing job {}... ", jobIdString);

                boolean ranLocally = run(jobIdString, entry);

                if (ranLocally) {
                    acknowledgeQueueMessage(message.getId());
                    _log.info("Executing job {}... DONE", jobIdString);
                } else {
                    // The job self-reported it could not be run locally.  Cache that knowledge and wait before
                    // attempting this job again.
                    _recentNotOwnerDelays.put(jobIdString, new DateTime().plus(_notOwnerRetryDelay));
                    _recentNotOwnerDelays.cleanUp();
                    _log.info("Executing job {}... not local", jobIdString);
                }
            } finally {
                mutex.release();
            }

            return true;
        }

        _log.debug("Job queue was empty or contained only non-local jobs");
    } catch (Throwable t) {
        _log.warn("runNextJob failed unexpectedly", t);
    }

    return false;
}
项目:sstable-tools    文件:CassandraUtils.java   
public static String toDurationString(long duration, TimeUnit unit, boolean color) {
    return wrapQuiet(PeriodFormat.getDefault().print(new Duration(unit.toMillis(duration)).toPeriod()), color);
}
项目:shaclRunner    文件:Main.java   
static void printTime(Instant start,Instant end) {
    Period timeElapsed = new Period(start,end);
        System.out.println("Time elapsed " + 
                PeriodFormat.getDefault().print(timeElapsed));
}
项目:NFD-android    文件:FaceStatusFragment.java   
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState)
{
  super.onActivityCreated(savedInstanceState);

  if (m_faceStatusAdapter == null) {
    // List items to be displayed; Used when creating
    // {@link net.named_data.nfd.FaceStatusFragment.FaceStatusAdapter}
    ArrayList<ListItem> listItems = new ArrayList<>();

    Resources res = getResources();
    m_scopes = res.getStringArray(R.array.face_scopes);
    m_linkTypes = res.getStringArray(R.array.face_link_types);
    m_persistencies = res.getStringArray(R.array.face_persistency);

    // Get face status information
    FaceStatus faceStatus = new FaceStatus();
    try {
      byte[] args = getArguments().getByteArray(EXTRA_FACE_INFORMATION);
      if (args == null) {
        throw new EncodingException("Not extra face in formation available");
      }
      faceStatus.wireDecode(new Blob(args).buf());
    } catch (EncodingException e) {
      G.Log("EXTRA_FACE_INFORMATION: EncodingException: " + e);
    }

    // Creating list of items to be displayed
    listItems.add(new ListItem(R.string.face_id, String.valueOf(faceStatus.getFaceId())));
    listItems.add(new ListItem(R.string.local_face_uri, faceStatus.getLocalUri()));
    listItems.add(new ListItem(R.string.remote_face_uri, faceStatus.getRemoteUri()));
    listItems.add(new ListItem(R.string.expires_in, faceStatus.getExpirationPeriod() < 0 ?
      getString(R.string.expire_never) :
      PeriodFormat.getDefault().print(new Period(faceStatus.getExpirationPeriod()))));
    listItems.add(new ListItem(R.string.face_scope, getScope(faceStatus.getFaceScope())));
    listItems.add(new ListItem(R.string.face_persistency, getPersistency(faceStatus.getFacePersistency())));
    listItems.add(new ListItem(R.string.link_type, getLinkType(faceStatus.getLinkType())));
    listItems.add(new ListItem(R.string.in_interests, String.valueOf(
      faceStatus.getNInInterests())));
    listItems.add(new ListItem(R.string.in_data, String.valueOf(faceStatus.getNInDatas())));
    listItems.add(new ListItem(R.string.out_interests, String.valueOf(
      faceStatus.getNOutInterests())));
    listItems.add(new ListItem(R.string.out_data, String.valueOf(faceStatus.getNOutDatas())));
    listItems.add(new ListItem(R.string.in_bytes, String.valueOf(faceStatus.getNInBytes())));
    listItems.add(new ListItem(R.string.out_bytes, String.valueOf(faceStatus.getNOutBytes())));

    m_faceStatusAdapter = new FaceStatusAdapter(getActivity(), listItems);
  }
  // setListAdapter must be called after addHeaderView.  Otherwise, there is an exception on some platforms.
  // http://stackoverflow.com/a/8141537/2150331
  setListAdapter(m_faceStatusAdapter);
}
项目:spacedog-server    文件:ESTimeValue.java   
public String format(PeriodType type) {
    Period period = new Period(millis());
    return PeriodFormat.getDefault().withParseType(type).print(period);
}
项目:kola    文件:Metrics.java   
@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("Metrics (Halstead){\n   ");
    sb.append("Number of Source Files: F=");
    sb.append(this.numFiles());
    sb.append(",\n   ");
    sb.append("Lines of Code: loc=");
    sb.append(this.linesOfCode());
    sb.append(",\n   ");
    sb.append("Number of distinct/unique Operators: n1=");
    sb.append(this.numDistinctOperators());
    sb.append(",\n   ");
    sb.append("Number of distinct/unique Operands: n2=");
    sb.append(this.numDistinctOperands());
    sb.append(",\n   ");
    sb.append("Number of Operators: N1=");
    sb.append(this.numOperators());
    sb.append(",\n   ");
    sb.append("Number of Operands: N2=");
    sb.append(this.numOperands());
    sb.append(",\n   ");
    sb.append("Length: N=");
    sb.append(this.length());
    sb.append(",\n   ");
    sb.append("Vocabulary: n=");
    sb.append(this.vocabulary());
    sb.append(",\n   ");
    sb.append("Volume: V=");
    sb.append(this.volume());
    sb.append(",\n   ");
    sb.append("Difficulty: D=");
    sb.append(this.difficulty());
    sb.append(",\n   ");
    sb.append("Effort to implement or understand: E=");
    sb.append(this.effort());
    sb.append(",\n   ");
    sb.append("Number of expected Bugs: B=");
    sb.append(this.expectedBugs());
    sb.append(",\n   ");
    sb.append("Time that should be taken: T=");
    sb.append(this.expectedTime().getStandardSeconds());
    sb.append("s (");
    sb.append(PeriodFormat.getDefault().print(this.expectedTime().toPeriod()));
    sb.append(")");
    sb.append("\n}");
    return sb.toString();
}
项目:mandrel    文件:TimeValue.java   
public String format(PeriodType type) {
    Period period = new Period(millis());
    return PeriodFormat.getDefault().withParseType(type).print(period);
}
项目:watchdog    文件:IntervalBase.java   
/** @return A human-readable duration. */
public String getDurationString() {
    Duration duration = getDuration();
    Period period = duration.toPeriod();
    return PeriodFormat.getDefault().print(period);
}
项目:iql    文件:IQLQuery.java   
/**
 * Throws UncheckedTimeoutException if current time is past the provided timeout timestamp.
 * @param timeoutTS timestamp of when the query times out in milliseconds
 */
public void checkTimeout(long timeoutTS) {
    if(System.currentTimeMillis() > timeoutTS) {
        throw new UncheckedTimeoutException("The query took longer than the allowed timeout of " + executionTimeout.toString(PeriodFormat.getDefault()));
    }
}
项目:kinesis-log4j-appender    文件:FilePublisher.java   
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())));
}
项目:bosparser    文件:TimeUtil.java   
public static String fromSeconds(Integer seconds) {
    //Seconds s = Seconds.seconds(seconds);
    return PeriodFormat.getDefault().print(new Period(0, 0, seconds, 0)
            .normalizedStandard());
}
项目:mycollab    文件:DateTimeUtils.java   
public static String getPrettyDurationValue(Date date, Locale locale) {
    Period period = new Period(new LocalDate(date), LocalDate.now());
    PeriodFormatter formatter = PeriodFormat.wordBased(locale);
    return formatter.print(period);
}
项目:lightblue-migrator    文件:NMPMonitor.java   
/**
 * Returns the period in msecs
 */
private static long parsePeriod(String periodStr) {
    PeriodFormatter fmt = PeriodFormat.getDefault();
    Period p = fmt.parsePeriod(periodStr);
    return p.toStandardDuration().getMillis();
}
项目:lightblue-migrator    文件:ConsistencyCheckerController.java   
/**
 * Returns the period in msecs
 */
public static long parsePeriod(String periodStr) {
    PeriodFormatter fmt = PeriodFormat.getDefault();
    Period p = fmt.parsePeriod(periodStr);
    return p.toStandardDuration().getMillis();
}