List of usage examples for org.joda.time.format PeriodFormat getDefault
public static PeriodFormatter getDefault()
From source file:com.predic8.membrane.core.interceptor.ratelimit.RateLimitInterceptor.java
License:Apache License
public void setResponseToServiceUnavailable(Exchange exc) throws UnsupportedEncodingException { Header hd = new Header(); DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZoneUTC() .withLocale(Locale.US); hd.add("Date", dateFormatter.print(DateTime.now())); hd.add("X-LimitDuration", PeriodFormat.getDefault().print(rateLimitStrategy.requestLimitDuration.toPeriod())); hd.add("X-LimitRequests", Integer.toString(rateLimitStrategy.requestLimit)); String ip = exc.getRemoteAddrIp(); DateTime availableAgainDateTime = rateLimitStrategy.getServiceAvailableAgainTime(ip); hd.add("X-LimitReset", Long.toString(availableAgainDateTime.getMillis())); StringBuilder bodyString = new StringBuilder(); DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa"); bodyString.append(ip).append(" exceeded the rate limit of ").append(rateLimitStrategy.requestLimit) .append(" requests per ") .append(PeriodFormat.getDefault().print(rateLimitStrategy.requestLimitDuration.toPeriod())) .append(". The next request can be made at ").append(dtFormatter.print(availableAgainDateTime)); Response resp = ResponseBuilder.newInstance().status(429, "Too Many Requests.") .contentType(MimeType.TEXT_PLAIN_UTF8).header(hd).body(bodyString.toString()).build(); exc.setResponse(resp);//from www. j a v a2 s . c o m }
From source file:com.predic8.membrane.core.interceptor.ratelimit.RateLimitInterceptor.java
License:Apache License
@Override public String getShortDescription() { return "Limits incoming requests. It limits to " + rateLimitStrategy.getRequestLimit() + " requests every " + PeriodFormat.getDefault().print(rateLimitStrategy.getRequestLimitDuration().toPeriod()) + "."; }
From source file:com.tcl.gateway.firehose.log4j.helper.AsyncPutCallStatsReporter.java
License:Open Source License
/** * 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. *///from w ww . jav a 2 s .co m @Override public void onSuccess(PutRecordBatchRequest request, PutRecordBatchResult 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"); } }
From source file:com.technophobia.substeps.report.DetailedJsonBuilder.java
License:Open Source License
private String convert(long runningDurationMillis) { Duration duration = new Duration(runningDurationMillis); PeriodFormatter formatter = PeriodFormat.getDefault(); return formatter.print(duration.toPeriod()); }
From source file:com.thoughtworks.go.i18n.Localizer.java
License:Apache License
public String localize(Duration d) { if (d.equals(new Duration(0))) return ""; return PeriodFormat.getDefault().withLocale(currentLocale.getLocale()).print(d.toPeriod()); }
From source file:eu.itesla_project.offline.tools.ListOfflineWorkflowsTool.java
License:Mozilla Public License
@Override public void run(CommandLine line) 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())); }// w ww . ja v a 2 s . c o m 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()) : ""); } System.out.println(table.render()); } }
From source file:google.registry.export.CheckSnapshotAction.java
License:Open Source License
private void checkAndLoadSnapshotIfComplete() { Set<String> kindsToLoad = ImmutableSet.copyOf(Splitter.on(',').split(kindsToLoadParam)); DatastoreBackupInfo backup = getBackup(); // Stop now if the backup is not complete. if (!backup.getStatus().equals(BackupStatus.COMPLETE)) { Duration runningTime = backup.getRunningTime(); if (runningTime.isShorterThan(MAXIMUM_BACKUP_RUNNING_TIME)) { // Backup might still be running, so send a 304 to have the task retry. throw new NotModifiedException(String.format("Datastore backup %s still pending", snapshotName)); } else {//from w w w. ja v a2 s .com // Declare the backup a lost cause, and send 204 No Content so the task will // not be retried. String message = String.format("Datastore backup %s abandoned - not complete after %s", snapshotName, PeriodFormat.getDefault().print(runningTime.toPeriod() .normalizedStandard(PeriodType.dayTime().withMillisRemoved()))); throw new NoContentException(message); } } // Get a compact string to identify this snapshot in BigQuery by trying to parse the unique // suffix out of the snapshot name and falling back to the start time as a string. String snapshotId = snapshotName.startsWith(ExportSnapshotAction.SNAPSHOT_PREFIX) ? snapshotName.substring(ExportSnapshotAction.SNAPSHOT_PREFIX.length()) : backup.getStartTime().toString("YYYYMMdd_HHmmss"); // Log a warning if kindsToLoad is not a subset of the exported snapshot kinds. if (!backup.getKinds().containsAll(kindsToLoad)) { logger.warningfmt("Kinds to load included non-exported kinds: %s", Sets.difference(kindsToLoad, backup.getKinds())); } // Load kinds from the snapshot, limited to those also in kindsToLoad (if it's present). ImmutableSet<String> exportedKindsToLoad = ImmutableSet .copyOf(intersection(backup.getKinds(), kindsToLoad)); String message = String.format("Datastore backup %s complete - ", snapshotName); if (exportedKindsToLoad.isEmpty()) { message += "no kinds to load into BigQuery"; } else { enqueueLoadSnapshotTask(snapshotId, backup.getGcsFilename().get(), exportedKindsToLoad); message += "BigQuery load task enqueued"; } logger.info(message); response.setPayload(message); }
From source file:google.registry.export.CheckSnapshotServlet.java
License:Open Source License
@Override public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws IOException { String snapshotName;//from w ww .j a va 2s.com String kindsToLoadParam; // TODO(b/28266757): Remove this try/catch/rethrow block once this servlet is Daggerized. try { snapshotName = extractRequiredParameter(req, SNAPSHOT_NAME_PARAM); kindsToLoadParam = extractRequiredParameter(req, SNAPSHOT_KINDS_TO_LOAD_PARAM); } catch (BadRequestException e) { throw new IllegalArgumentException(e.getMessage()); } Set<String> kindsToLoad = ImmutableSet.copyOf(Splitter.on(',').split(kindsToLoadParam)); // Look up the backup by the provided name, stopping if we can't find it. DatastoreBackupInfo backup; try { backup = backupService.findByName(snapshotName); } catch (IllegalArgumentException e) { String message = String.format("Bad backup name %s: %s", snapshotName, e.getMessage()); logger.severe(e, message); // TODO(b/19081569): Ideally this would return a 2XX error so the task would not be retried, // but we might abandon backups that start late and haven't yet written to datastore. // We could fix that by replacing this with a two-phase polling strategy. rsp.sendError(SC_BAD_REQUEST, htmlEscaper().escape(message)); return; } // Stop now if the backup is not complete. if (!backup.getStatus().equals(BackupStatus.COMPLETE)) { Duration runningTime = backup.getRunningTime(); if (runningTime.isShorterThan(MAXIMUM_BACKUP_RUNNING_TIME)) { // Backup might still be running, so send a 304 to have the task retry. rsp.sendError(SC_NOT_MODIFIED, htmlEscaper().escape(String.format("Datastore backup %s still pending", snapshotName))); } else { // Declare the backup a lost cause, and send 202 Accepted so the task will not be retried. String message = String.format("Datastore backup %s abandoned - not complete after %s", snapshotName, PeriodFormat.getDefault().print(runningTime.toPeriod() .normalizedStandard(PeriodType.dayTime().withMillisRemoved()))); logger.severe(message); rsp.sendError(SC_ACCEPTED, htmlEscaper().escape(message)); } return; } // Get a compact string to identify this snapshot in BigQuery by trying to parse the unique // suffix out of the snapshot name and falling back to the start time as a string. String snapshotId = snapshotName.startsWith(ExportSnapshotServlet.SNAPSHOT_PREFIX) ? snapshotName.substring(ExportSnapshotServlet.SNAPSHOT_PREFIX.length()) : backup.getStartTime().toString("YYYYMMdd_HHmmss"); // Log a warning if kindsToLoad is not a subset of the exported snapshot kinds. if (!backup.getKinds().containsAll(kindsToLoad)) { logger.warningfmt("Kinds to load included non-exported kinds: %s", Sets.difference(kindsToLoad, backup.getKinds())); } // Load kinds from the snapshot, limited to those also in kindsToLoad (if it's present). ImmutableSet<String> exportedKindsToLoad = ImmutableSet .copyOf(intersection(backup.getKinds(), kindsToLoad)); String message = String.format("Datastore backup %s complete - ", snapshotName); if (exportedKindsToLoad.isEmpty()) { message += "no kinds to load into BigQuery"; } else { enqueueLoadSnapshotTask(snapshotId, backup.getGcsFilename().get(), exportedKindsToLoad); message += "BigQuery load task enqueued"; } logger.info(message); rsp.getWriter().write(message); }
From source file:io.mandrel.common.unit.TimeValue.java
License:Apache License
public String format(PeriodType type) { Period period = new Period(millis()); return PeriodFormat.getDefault().withParseType(type).print(period); }
From source file:jongo.rest.xstream.Usage.java
License:Open Source License
/** * Calculates the time Jongo has been running and returns a string representing it, i.e. 2 days 10 hours... * @return a string with the uptime.//from www. j a v a 2 s .c o m */ public String getUptime() { Period period = new Period(this.start, new DateTime()); return PeriodFormat.getDefault().print(period); }