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()))
);
}
}
java类org.joda.time.format.PeriodFormat的实例源码
InstantValidator.java 文件源码
项目:verify-service-provider
阅读 17
收藏 0
点赞 0
评论 0
ListOfflineWorkflowsTool.java 文件源码
项目:ipst
阅读 18
收藏 0
点赞 0
评论 0
@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());
}
}
SimpleDoFnRunner.java 文件源码
项目:beam
阅读 16
收藏 0
点赞 0
评论 0
@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())));
}
}
ProcessorController.java 文件源码
项目:Crosslinks
阅读 18
收藏 0
点赞 0
评论 0
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()));
}
PrettyPrint.java 文件源码
项目:h2o-3
阅读 21
收藏 0
点赞 0
评论 0
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)));
}
ZergDaoModule.java 文件源码
项目:agathon
阅读 19
收藏 0
点赞 0
评论 0
@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();
}
ApplicationStarter.java 文件源码
项目:vertx-sfdc-platformevents
阅读 22
收藏 0
点赞 0
评论 0
/**
* 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);
}
}
LoggingBatchListener.java 文件源码
项目:oma-riista-web
阅读 20
收藏 0
点赞 0
评论 0
@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());
}
LoggingBatchListener.java 文件源码
项目:oma-riista-web
阅读 18
收藏 0
点赞 0
评论 0
@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();
}
ScanUploadSchedulingService.java 文件源码
项目:emodb
阅读 17
收藏 0
点赞 0
评论 0
/**
* 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()));
}
SimpleDoFnRunnerTest.java 文件源码
项目:beam
阅读 18
收藏 0
点赞 0
评论 0
/**
* 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)));
}
SimpleDoFnRunnerTest.java 文件源码
项目:beam
阅读 16
收藏 0
点赞 0
评论 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<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)));
}
NexusContextListener.java 文件源码
项目:nexus-public
阅读 21
收藏 0
点赞 0
评论 0
@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");
}
MainFragment.java 文件源码
项目:NFD-android
阅读 64
收藏 0
点赞 0
评论 0
@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);
}
}
TypedOutputStats.java 文件源码
项目:Crosslinks
阅读 21
收藏 0
点赞 0
评论 0
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;
}
ProcessorController.java 文件源码
项目:Crosslinks
阅读 17
收藏 0
点赞 0
评论 0
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));
}
}
TestPeriod_Basics.java 文件源码
项目:astor
阅读 22
收藏 0
点赞 0
评论 0
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()));
}
TestPeriod_Basics.java 文件源码
项目:astor
阅读 17
收藏 0
点赞 0
评论 0
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()));
}
Utils.java 文件源码
项目:dungeon
阅读 97
收藏 0
点赞 0
评论 0
/**
* 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);
}
AsyncPutCallStatsReporter.java 文件源码
项目:kinesis-log4j-appender
阅读 16
收藏 0
点赞 0
评论 0
/**
* 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");
}
}
Main.java 文件源码
项目:spork
阅读 17
收藏 0
点赞 0
评论 0
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)");
}
TestPeriod_Basics.java 文件源码
项目:versemem-android
阅读 18
收藏 0
点赞 0
评论 0
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()));
}
TimeValue.java 文件源码
项目:elasticsearch_my
阅读 22
收藏 0
点赞 0
评论 0
public String format(PeriodType type) {
Period period = new Period(millis());
return PeriodFormat.getDefault().withParseType(type).print(period);
}
MainActivity.java 文件源码
项目:RxDisposal
阅读 15
收藏 0
点赞 0
评论 0
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())
));
}
TimeValue.java 文件源码
项目:Elasticsearch
阅读 20
收藏 0
点赞 0
评论 0
public String format(PeriodType type) {
Period period = new Period(millis());
return PeriodFormat.getDefault().withParseType(type).print(period);
}
UptimeMain.java 文件源码
项目:beyondj
阅读 20
收藏 0
点赞 0
评论 0
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);
}
DefaultJobService.java 文件源码
项目:emodb
阅读 23
收藏 0
点赞 0
评论 0
/**
* 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;
}
CassandraUtils.java 文件源码
项目:sstable-tools
阅读 17
收藏 0
点赞 0
评论 0
public static String toDurationString(long duration, TimeUnit unit, boolean color) {
return wrapQuiet(PeriodFormat.getDefault().print(new Duration(unit.toMillis(duration)).toPeriod()), color);
}
Main.java 文件源码
项目:shaclRunner
阅读 20
收藏 0
点赞 0
评论 0
static void printTime(Instant start,Instant end) {
Period timeElapsed = new Period(start,end);
System.out.println("Time elapsed " +
PeriodFormat.getDefault().print(timeElapsed));
}
FaceStatusFragment.java 文件源码
项目:NFD-android
阅读 17
收藏 0
点赞 0
评论 0
@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);
}