List of usage examples for org.joda.time Duration toPeriod
public Period toPeriod()
From source file:com.rubenlaguna.en4j.sync.SyncAction.java
License:Open Source License
public void actionPerformed(ActionEvent e) { // TODO implement action body final SynchronizationService sservice = Lookup.getDefault().lookup(SynchronizationService.class); Runnable task = new Runnable() { public void run() { DateTime startTime = new DateTime(); StatusDisplayer.getDefault().setStatusText("Sync started at " + startTime.toString("HH:mm")); if (toolbarPresenter.startAnimator()) { //dont run if it was already running sservice.sync();// w ww . j a va2 s . c om toolbarPresenter.stopAnimator(); if (sservice.isSyncFailed()) { StatusDisplayer.getDefault().setStatusText("Sync failed."); } else { DateTime finishTime = new DateTime(); Duration dur = new Duration(startTime, finishTime); Minutes minutes = dur.toPeriod().toStandardMinutes(); Seconds seconds = dur.toPeriod().minus(minutes).toStandardSeconds(); final String message = "sync finished at " + finishTime.toString("HH:mm") + ". Sync took " + minutes.getMinutes() + " minutes and " + seconds.getSeconds() + " seconds."; final StatusDisplayer.Message sbMess = StatusDisplayer.getDefault().setStatusText(message, 1); RP.post(new Runnable() { public void run() { sbMess.clear(10000); } }); } } } }; RP.post(task); }
From source file:com.spotify.helios.cli.Output.java
License:Apache License
public static String humanDuration(final Duration dur) { final Period p = dur.toPeriod().normalizedStandard(); if (dur.getStandardSeconds() == 0) { return "0 seconds"; } else if (dur.getStandardSeconds() < 60) { return format("%d second%s", p.getSeconds(), p.getSeconds() > 1 ? "s" : ""); } else if (dur.getStandardMinutes() < 60) { return format("%d minute%s", p.getMinutes(), p.getMinutes() > 1 ? "s" : ""); } else if (dur.getStandardHours() < 24) { return format("%d hour%s", p.getHours(), p.getHours() > 1 ? "s" : ""); } else {/*from w w w. j a va 2 s .c om*/ return format("%d day%s", dur.getStandardDays(), dur.getStandardDays() > 1 ? "s" : ""); } }
From source file:com.spotify.scio.bigtable.BigtableUtil.java
License:Apache License
/** * Updates all clusters within the specified Bigtable instance to a specified number of nodes. * Useful for increasing the number of nodes at the beginning of a job and decreasing it at * the end to lower costs yet still get high throughput during bulk ingests/dumps. * * @param bigtableOptions Bigtable Options * @param numberOfNodes New number of nodes in the cluster * @param sleepDuration How long to sleep after updating the number of nodes. Google recommends * at least 20 minutes before the new nodes are fully functional * @throws IOException If setting up channel pool fails * @throws InterruptedException If sleep fails *///from w w w. j a va 2 s. c o m public static void updateNumberOfBigtableNodes(final BigtableOptions bigtableOptions, final int numberOfNodes, final Duration sleepDuration) throws IOException, InterruptedException { final ChannelPool channelPool = ChannelPoolCreator.createPool(bigtableOptions.getInstanceAdminHost()); try { final BigtableInstanceClient bigtableInstanceClient = new BigtableInstanceGrpcClient(channelPool); final String instanceName = bigtableOptions.getInstanceName().toString(); // Fetch clusters in Bigtable instance final ListClustersRequest clustersRequest = ListClustersRequest.newBuilder().setParent(instanceName) .build(); final ListClustersResponse clustersResponse = bigtableInstanceClient.listCluster(clustersRequest); // For each cluster update the number of nodes for (Cluster cluster : clustersResponse.getClustersList()) { final Cluster updatedCluster = Cluster.newBuilder().setName(cluster.getName()) .setServeNodes(numberOfNodes).build(); LOG.info("Updating number of nodes to {} for cluster {}", numberOfNodes, cluster.getName()); bigtableInstanceClient.updateCluster(updatedCluster); } // Wait for the new nodes to be provisioned if (sleepDuration.getMillis() > 0) { LOG.info("Sleeping for {} after update", formatter.print(sleepDuration.toPeriod())); Thread.sleep(sleepDuration.getMillis()); } } finally { channelPool.shutdownNow(); } }
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:com.tmetrics.util.Localization.java
License:Open Source License
/** * Returns a stringified version of the given duration in the form of * HH:mm:ss./*from w w w . j av a 2 s . c o m*/ * @param duration The duration to be stringified. * @return A stringified version of the given duration. */ public static String printDuration(Duration duration) { return Localization.DURATION_FORMATTER.print(duration.toPeriod()); }
From source file:de.cubeisland.engine.core.util.converter.DurationConverter.java
License:Open Source License
@Override public Node toNode(Duration object) throws ConversionException { return StringNode.of(this.formatter.print(object.toPeriod())); }
From source file:de.cubeisland.engine.module.basics.command.general.InformationCommands.java
License:Open Source License
@Command(desc = "Displays chunk, memory and world information.") public void lag(CommandSender context, @Flag boolean reset) { if (reset) {/*from w w w . j a v a 2s.com*/ if (module.perms().COMMAND_LAG_RESET.isAuthorized(context)) { this.module.getLagTimer().resetLowestTPS(); context.sendTranslated(POSITIVE, "Reset lowest TPS!"); return; } context.sendTranslated(NEGATIVE, "You are not allowed to do this!"); return; } //Uptime: context.sendTranslated(POSITIVE, "[{text:CubeEngine-Basics:color=RED}]"); DateFormat df = SimpleDateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, context.getLocale()); Date start = new Date(ManagementFactory.getRuntimeMXBean().getStartTime()); Duration dura = new Duration(start.getTime(), System.currentTimeMillis()); context.sendTranslated(POSITIVE, "Server has been running since {input#uptime}", df.format(start)); context.sendTranslated(POSITIVE, "Uptime: {input#uptime}", formatter.print(dura.toPeriod())); //TPS: float tps = this.module.getLagTimer().getAverageTPS(); String color = tps == 20 ? DARK_GREEN.toString() : tps > 17 ? YELLOW.toString() : tps > 10 ? RED.toString() : tps == 0 ? (YELLOW.toString() + "NaN") : DARK_RED.toString(); context.sendTranslated(POSITIVE, "Current TPS: {input#color}{decimal#tps:1}", color, tps); Pair<Long, Float> lowestTPS = this.module.getLagTimer().getLowestTPS(); if (lowestTPS.getRight() != 20) { color = ChatFormat .parseFormats(tps > 17 ? YELLOW.toString() : tps > 10 ? RED.toString() : DARK_RED.toString()); Date date = new Date(lowestTPS.getLeft()); context.sendTranslated(POSITIVE, "Lowest TPS was {}{decimal#tps:1} ({input#date})", color, lowestTPS.getRight(), df.format(date)); long timeSinceLastLowTPS = System.currentTimeMillis() - this.module.getLagTimer().getLastLowTPS(); if (tps == 20 && TimeUnit.MINUTES.convert(timeSinceLastLowTPS, TimeUnit.MILLISECONDS) < 1) { context.sendTranslated(NEGATIVE, "TPS was low in the last minute!"); } } //Memory long memUse = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / 1048576; long memCom = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getCommitted() / 1048576; long memMax = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax() / 1048576; String memused; long memUsePercent = 100 * memUse / memMax; if (memUsePercent > 90) { if (memUsePercent > 95) { memused = DARK_RED.toString(); } else { memused = RED.toString(); } } else if (memUsePercent > 60) { memused = YELLOW.toString(); } else { memused = DARK_GREEN.toString(); } memused += memUse; context.sendTranslated(POSITIVE, "Memory Usage: {input#memused}/{integer#memcom}/{integer#memMax} MB", memused, memCom, memMax); //Worlds with loaded Chunks / Entities for (World world : Bukkit.getServer().getWorlds()) { String type = world.getEnvironment().name(); int loadedChunks = world.getLoadedChunks().length; int entities = world.getEntities().size(); context.sendTranslated(POSITIVE, "{world} ({input#environment}): {amount} chunks {amount} entities", world, type, loadedChunks, entities); } }
From source file:de.topobyte.osm4j.extra.extracts.TimeTable.java
License:Open Source License
public String htime(String key) { long millis = time(key); Duration duration = new Duration(millis); Period period = duration.toPeriod(); return formatter.print(period); }
From source file:edu.jhu.hlt.concrete.stanford.Runner.java
License:Open Source License
/** * @param args//from w ww .j a va2 s . c o m */ public static void main(String... args) { Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler()); Runner run = new Runner(); JCommander jc = new JCommander(run, args); jc.setProgramName(Runner.class.getName()); if (run.help) { jc.usage(); System.exit(0); } int nDocsSeen = 0; int nDocsFailed = 0; List<String> exIds = new ArrayList<>(); boolean haveSeenException = false; Path outF = Paths.get(run.outputPath); Path inp = Paths.get(run.inputPath); LOGGER.info("Input path: {}", inp.toString()); LOGGER.info("Output folder: {}", outF.toString()); try { new ExistingNonDirectoryFile(inp); if (!Files.exists(outF)) { LOGGER.info("Creating output directory."); Files.createDirectories(outF); } Path outFile = outF.resolve(run.outputName); if (Files.exists(outFile)) { if (run.overwrite) Files.delete(outFile); else { LOGGER.info("File exists and overwrite = false. Not continuing."); System.exit(1); } } PipelineLanguage lang = PipelineLanguage.getEnumeration(run.lang); Analytic<? extends WrappedCommunication> a; if (run.isInputTokenized) a = new AnnotateTokenizedConcrete(lang); else a = new AnnotateNonTokenizedConcrete(lang); StopWatch sw = new StopWatch(); sw.start(); LOGGER.info("Beginning ingest at: {}", new DateTime().toString()); try (InputStream in = Files.newInputStream(inp); OutputStream os = Files.newOutputStream(outFile); GzipCompressorOutputStream gout = new GzipCompressorOutputStream(os); TarArchiver arch = new TarArchiver(gout);) { TarGzArchiveEntryCommunicationIterator iter = new TarGzArchiveEntryCommunicationIterator(in); while (iter.hasNext()) { Communication c = iter.next(); nDocsSeen++; try { arch.addEntry(new ArchivableCommunication(a.annotate(c).getRoot())); } catch (AnalyticException e) { LOGGER.warn("Caught analytic exception on document: " + c.getId()); nDocsFailed++; exIds.add(c.getId()); haveSeenException = true; if (run.exitOnException) break; } } } if (run.exitOnException && haveSeenException) System.exit(1); sw.stop(); LOGGER.info("Ingest completed at: {}", new DateTime().toString()); Duration d = new Duration(sw.getTime()); Period p = d.toPeriod(); LOGGER.info("Ingest took {}d{}m{}s.", p.getDays(), p.getMinutes(), p.getSeconds()); final int seenLessFailed = nDocsSeen - nDocsFailed; float ratio = nDocsSeen > 0 ? (float) seenLessFailed / nDocsSeen * 100 : 0; LOGGER.info("Converted {}% of documents successfully. [{} / {} total]", ratio, seenLessFailed, nDocsSeen); if (haveSeenException) exIds.forEach(eid -> LOGGER.info("Caught exception on document: {}", eid)); } catch (IOException | NotFileException e) { throw new RuntimeException(e); } }