Java Code Examples for org.apache.commons.lang3.time.DurationFormatUtils

The following examples show how to use org.apache.commons.lang3.time.DurationFormatUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: winter   Source File: ProgressReporter.java    License: Apache License 2.0 6 votes vote down vote up
public void report() {
	// report status every second
	LocalDateTime now = LocalDateTime.now();
	long durationSoFar = Duration.between(start, now).toMillis();
	if ((Duration.between(lastTime, now).toMillis()) > 1000) {
		if(total>0) {
			logger.info(String.format(
				"%s: %,d / %,d elements completed (%.2f%%) after %s",
				message, done, total,
				(double) done / (double) total * 100,
				DurationFormatUtils.formatDurationHMS(durationSoFar)));
		} else {
			logger.info(String.format(
				"%s: %,d elements completed after %s",
				message, done,
				DurationFormatUtils.formatDurationHMS(durationSoFar)));
		}
		lastTime = now;
	}
}
 
Example 2
Source Project: jlineup   Source File: ReportController.java    License: Apache License 2.0 6 votes vote down vote up
private static String getDurationAsString(JLineupRunStatus status) {

        final AtomicLong durationMillis = new AtomicLong();
        Instant startTime = status.getStartTime();

        status.getPauseTime().ifPresent(pauseTime -> durationMillis.addAndGet(Duration.between(startTime, pauseTime).toMillis()));
        status.getEndTime().ifPresent(endTime -> durationMillis.addAndGet(Duration.between(status.getResumeTime().orElse(endTime), endTime).toMillis()));

        if (status.getState() == State.BEFORE_RUNNING) {
           durationMillis.addAndGet(Duration.between(startTime, Instant.now()).toMillis());
        } else if (status.getState() == State.AFTER_RUNNING) {
            durationMillis.addAndGet(Duration.between(status.getResumeTime().orElse(Instant.now()), Instant.now()).toMillis());
        }

        return DurationFormatUtils.formatDuration(durationMillis.get(), "HH:mm:ss");
    }
 
Example 3
Source Project: etf-webapp   Source File: ViewController.java    License: European Union Public License 1.2 6 votes vote down vote up
@RequestMapping(value = {"/", "/etf", "/index.html"}, method = RequestMethod.GET)
public String overview(Model model) throws StorageException, ConfigurationException {
    testRunController.addMetaData(model);
    model.addAttribute("maxUploadSizeHr", FileUtils.byteCountToDisplaySize(
            configController.getPropertyAsLong(ETF_MAX_UPLOAD_SIZE)));
    model.addAttribute("maxUploadSize",
            configController.getPropertyAsLong(ETF_MAX_UPLOAD_SIZE));

    final long reportExp = configController.getPropertyAsLong(ETF_TESTREPORTS_LIFETIME_EXPIRATION);
    if (reportExp > 0) {
        model.addAttribute("maxTestRunLifetime",
                DurationFormatUtils.formatDurationWords(TimeUnit.MINUTES.toMillis(reportExp), true, true));
    }

    return "etf";
}
 
Example 4
Source Project: dhis2-core   Source File: Clock.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Timestamps the given message using the elapsed time of this Clock and
 * logs it using the logger.
 * @param message the message to log.
 * @return this Clock.
 */
public Clock logTime( String message )
{
    super.split();
    
    String time = DurationFormatUtils.formatDurationHMS( super.getSplitTime() ); 
    
    String msg = message + SEPARATOR + time;
    
    if ( log != null )
    {
        log.info( msg );
    }
    else
    {
        defaultLog.info( msg );
    }
    
    return this;
}
 
Example 5
Source Project: dsworkbench   Source File: SupportsModel.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    Defense elem = entries.get(rowIndex);
    switch (columnIndex) {
        case 0:
            return elem.getSupporter();
        case 1:
            return elem.getTarget();
        case 2:
            return new Date(elem.getBestSendTime());
        case 3:
            return new Date(elem.getWorstSendTime());
        case 4:

            long sendTime = elem.getBestSendTime();
            if (sendTime < System.currentTimeMillis()) {//if best in past, take worst
                sendTime = elem.getWorstSendTime();
            }
            long t = sendTime - System.currentTimeMillis();
            t = (t <= 0) ? 0 : t;
            return DurationFormatUtils.formatDuration(t, "HHH:mm:ss.SSS", true);
        default:
            return elem.isTransferredToBrowser();
    }
}
 
Example 6
Source Project: hawkbit   Source File: SPDateTimeUtil.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a formatted string of a duration in format '1 year 2 months 3
 * days 4 hours 5 minutes 6 seconds' zero values will be ignored in the
 * formatted string.
 *
 * @param startMillis
 *            the start milliseconds of the duration
 * @param endMillis
 *            the end milliseconds of the duration
 * @param i18N
 *            the i18n service to determine the correct string for e.g.
 *            'year'
 * @return a formatted string for duration label
 */
public static String getDurationFormattedString(final long startMillis, final long endMillis,
        final VaadinMessageSource i18N) {
    final String formatDuration = DurationFormatUtils.formatPeriod(startMillis, endMillis, DURATION_FORMAT, false,
            getBrowserTimeZone());

    final StringBuilder formattedDuration = new StringBuilder();
    final String[] split = formatDuration.split(",");

    for (int index = 0; index < split.length; index++) {
        if (index != 0 && formattedDuration.length() > 0) {
            formattedDuration.append(' ');
        }
        final int value = Integer.parseInt(split[index]);
        if (value != 0) {
            final String suffix = (value == 1) ? i18N.getMessage(DURATION_I18N.get(index).getSingle())
                    : i18N.getMessage(DURATION_I18N.get(index).getPlural());
            formattedDuration.append(value).append(' ').append(suffix);
        }

    }
    return formattedDuration.toString();

}
 
Example 7
Source Project: webanno   Source File: AnnotationDocumentExporter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void importData(ProjectImportRequest aRequest, Project aProject,
        ExportedProject aExProject, ZipFile aZip)
    throws Exception
{
    long start = currentTimeMillis();
    
    Map<String, SourceDocument> nameToDoc = documentService
            .listSourceDocuments(aProject).stream()
            .collect(toMap(SourceDocument::getName, identity()));
    
    importAnnotationDocuments(aExProject, aProject, nameToDoc);
    importAnnotationDocumentContents(aZip, aProject, nameToDoc);

    log.info("Imported [{}] annotation documents for project [{}] ({})",
            aExProject.getSourceDocuments().size(), aExProject.getName(),
            DurationFormatUtils.formatDurationWords(currentTimeMillis() - start, true, true));
}
 
Example 8
Source Project: james-project   Source File: DelaysAndMaxRetry.java    License: Apache License 2.0 6 votes vote down vote up
private static DelaysAndMaxRetry addExtraAttemptToLastDelay(int intendedMaxRetries, int extra, List<Delay> delayTimesList) throws MessagingException {
    if (delayTimesList.size() != 0) {
        Delay lastDelay = delayTimesList.get(delayTimesList.size() - 1);
        Duration lastDelayTime = lastDelay.getDelayTime();
        LOGGER.warn("Delay of {} is now attempted: {} times",
            DurationFormatUtils.formatDurationWords(lastDelayTime.toMillis(), true, true),
            lastDelay.getAttempts());
        return new DelaysAndMaxRetry(intendedMaxRetries,
            ImmutableList.copyOf(
                Iterables.concat(
                    Iterables.limit(delayTimesList, delayTimesList.size() - 1),
                    ImmutableList.of(new Delay(lastDelay.getAttempts() + extra, lastDelayTime)))));
    } else {
        throw new MessagingException("No delaytimes, cannot continue");
    }
}
 
Example 9
Source Project: stratio-cassandra   Source File: StressMetrics.java    License: Apache License 2.0 6 votes vote down vote up
public void summarise()
{
    output.println("\n");
    output.println("Results:");

    TimingIntervals opHistory = timing.getHistory();
    TimingInterval history = opHistory.combine(settings.samples.historyCount);
    output.println(String.format("op rate                   : %.0f %s", history.opRate(), opHistory.opRates()));
    output.println(String.format("partition rate            : %.0f %s", history.partitionRate(), opHistory.partitionRates()));
    output.println(String.format("row rate                  : %.0f %s", history.rowRate(), opHistory.rowRates()));
    output.println(String.format("latency mean              : %.1f %s", history.meanLatency(), opHistory.meanLatencies()));
    output.println(String.format("latency median            : %.1f %s", history.medianLatency(), opHistory.medianLatencies()));
    output.println(String.format("latency 95th percentile   : %.1f %s", history.rankLatency(.95f), opHistory.rankLatencies(0.95f)));
    output.println(String.format("latency 99th percentile   : %.1f %s", history.rankLatency(0.99f), opHistory.rankLatencies(0.99f)));
    output.println(String.format("latency 99.9th percentile : %.1f %s", history.rankLatency(0.999f), opHistory.rankLatencies(0.999f)));
    output.println(String.format("latency max               : %.1f %s", history.maxLatency(), opHistory.maxLatencies()));
    output.println(String.format("Total partitions          : %d %s",   history.partitionCount, opHistory.partitionCounts()));
    output.println(String.format("Total errors              : %d %s",   history.errorCount, opHistory.errorCounts()));
    output.println(String.format("total gc count            : %.0f", totalGcStats.count));
    output.println(String.format("total gc mb               : %.0f", totalGcStats.bytes / (1 << 20)));
    output.println(String.format("total gc time (s)         : %.0f", totalGcStats.summs / 1000));
    output.println(String.format("avg gc time(ms)           : %.0f", totalGcStats.summs / totalGcStats.count));
    output.println(String.format("stdev gc time(ms)         : %.0f", totalGcStats.sdvms));
    output.println("Total operation time      : " + DurationFormatUtils.formatDuration(
            history.runTime(), "HH:mm:ss", true));
}
 
Example 10
Source Project: java-client   Source File: AndroidLogcatListenerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void verifyLogcatListenerCanBeAssigned() {
    final Semaphore messageSemaphore = new Semaphore(1);
    final Duration timeout = Duration.ofSeconds(15);

    driver.addLogcatMessagesListener((msg) -> messageSemaphore.release());
    driver.addLogcatConnectionListener(() -> System.out.println("Connected to the web socket"));
    driver.addLogcatDisconnectionListener(() -> System.out.println("Disconnected from the web socket"));
    driver.addLogcatErrorsListener(Throwable::printStackTrace);
    try {
        driver.startLogcatBroadcast();
        messageSemaphore.acquire();
        // This is needed for pushing some internal log messages
        driver.runAppInBackground(Duration.ofSeconds(1));
        assertTrue(String.format("Didn't receive any log message after %s timeout",
                DurationFormatUtils.formatDuration(timeout.toMillis(), "H:mm:ss", true)),
                messageSemaphore.tryAcquire(timeout.toMillis(), TimeUnit.MILLISECONDS));
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    } finally {
        messageSemaphore.release();
        driver.stopLogcatBroadcast();
    }
}
 
Example 11
Source Project: java-client   Source File: IOSSyslogListenerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void verifySyslogListenerCanBeAssigned() {
    final Semaphore messageSemaphore = new Semaphore(1);
    final Duration timeout = Duration.ofSeconds(15);

    driver.addSyslogMessagesListener((msg) -> messageSemaphore.release());
    driver.addSyslogConnectionListener(() -> System.out.println("Connected to the web socket"));
    driver.addSyslogDisconnectionListener(() -> System.out.println("Disconnected from the web socket"));
    driver.addSyslogErrorsListener(Throwable::printStackTrace);
    try {
        driver.startSyslogBroadcast();
        messageSemaphore.acquire();
        // This is needed for pushing some internal log messages
        driver.runAppInBackground(Duration.ofSeconds(1));
        assertTrue(String.format("Didn't receive any log message after %s timeout",
                DurationFormatUtils.formatDuration(timeout.toMillis(), "H:mm:ss", true)),
                messageSemaphore.tryAcquire(timeout.toMillis(), TimeUnit.MILLISECONDS));
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    } finally {
        messageSemaphore.release();
        driver.stopSyslogBroadcast();
    }
}
 
Example 12
Source Project: Singularity   Source File: SingularityNewTaskChecker.java    License: Apache License 2.0 6 votes vote down vote up
private void enqueueCheckWithDelay(
  final SingularityTask task,
  long delaySeconds,
  SingularityHealthchecker healthchecker
) {
  LOG.trace(
    "Enqueuing a new task check for task {} with delay {}",
    task.getTaskId(),
    DurationFormatUtils.formatDurationHMS(TimeUnit.SECONDS.toMillis(delaySeconds))
  );

  try {
    ScheduledFuture<?> future = executorService.schedule(
      getTaskCheck(task, healthchecker),
      delaySeconds,
      TimeUnit.SECONDS
    );
    taskIdToCheck.put(task.getTaskId().getId(), future);
  } catch (RejectedExecutionException ree) {
    LOG.warn(
      "Executor rejected execution, Singularity is shutting down, short circuiting"
    );
  }
}
 
Example 13
Source Project: airsonic-advanced   Source File: StringUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Formats a duration to M:SS or H:MM:SS or M:SS.mmm
 */
public static String formatDuration(long millis, boolean convertToHours) {
    String format = "m:ss";
    if (millis >= 3600000 && convertToHours) {
        format = "H:m" + format;
    }

    if (millis % 1000 != 0) {
        format = format + ".S";
    }

    return DurationFormatUtils.formatDuration(millis, format);
}
 
Example 14
Source Project: dev-tools   Source File: EpochController.java    License: Apache License 2.0 5 votes vote down vote up
@FXML
private void handleMillisToTime(final ActionEvent actionEvent) {
    tsToHumanField.setBorder(Border.EMPTY);
    try {
        long millis = Long.parseLong(tsToHumanField.getText());
        String result = DurationFormatUtils.formatDurationWords(millis, true, true);
        tsToHumanResult.setText(result);
    } catch (Exception e) {
        tsToHumanField.setBorder(Elements.alertBorder);
        tsToHumanResult.setText("");
    }
}
 
Example 15
Source Project: bisq-core   Source File: BSFormatter.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public String formatAccountAge(long durationMillis) {
    durationMillis = Math.max(0, durationMillis);
    String day = Res.get("time.day").toLowerCase();
    String days = Res.get("time.days");
    String format = "d\' " + days + "\'";
    return StringUtils.replaceOnce(DurationFormatUtils.formatDuration(durationMillis, format), "1 " + days, "1 " + day);
}
 
Example 16
Source Project: bisq-core   Source File: BSFormatter.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static String formatDurationAsWords(long durationMillis, boolean showSeconds) {
    String format = "";
    String second = Res.get("time.second");
    String minute = Res.get("time.minute");
    String hour = Res.get("time.hour").toLowerCase();
    String day = Res.get("time.day").toLowerCase();
    String days = Res.get("time.days");
    String hours = Res.get("time.hours");
    String minutes = Res.get("time.minutes");
    String seconds = Res.get("time.seconds");

    if (durationMillis >= DateUtils.MILLIS_PER_DAY) {
        format = "d\' " + days + ", \'";
    }

    if (showSeconds) {
        format += "H\' " + hours + ", \'m\' " + minutes + ", \'s\' " + seconds + "\'";
    } else
        format += "H\' " + hours + ", \'m\' " + minutes + "\'";

    String duration = durationMillis > 0 ? DurationFormatUtils.formatDuration(durationMillis, format) : "";

    duration = StringUtils.replacePattern(duration, "^1 " + seconds + "|\\b1 " + seconds, "1 " + second);
    duration = StringUtils.replacePattern(duration, "^1 " + minutes + "|\\b1 " + minutes, "1 " + minute);
    duration = StringUtils.replacePattern(duration, "^1 " + hours + "|\\b1 " + hours, "1 " + hour);
    duration = StringUtils.replacePattern(duration, "^1 " + days + "|\\b1 " + days, "1 " + day);
    return duration.trim();
}
 
Example 17
Source Project: kafka-message-tool   Source File: SenderConfigView.java    License: MIT License 5 votes vote down vote up
private void sendMessageTask() {
    final Instant now = Instant.now();
    msgTemplateSender.send(config,
            statusBarNotifier,
                           applicationSettings.appSettings().getRunBeforeFirstMessageSharedScriptContent(),
                           sendingSimulationModeCheckBox.isSelected());
    final Instant now1 = Instant.now();
    final Duration between = Duration.between(now, now1);
    Logger.info(String.format("Sending messages duration: %s",
                              DurationFormatUtils.formatDuration(between.toMillis(), "HH:mm:ss", true)));

}
 
Example 18
Source Project: sailfish-core   Source File: StatisticsUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String getLastResultExecutionTime(List<AggregatedReportRow> reportRows) {
    long spentTime = 0;

    for (AggregatedReportRow row : reportRows) {
        if (row.isMatrixRow()) {
            Long executionTime = row.getExecutionTime();
            if (executionTime == null) {
                continue;
            }
            spentTime += executionTime;
        }
    }

    return DurationFormatUtils.formatDuration(spentTime, "HH:mm:ss");
}
 
Example 19
Source Project: winter   Source File: RuleBasedMatchingAlgorithm.java    License: Apache License 2.0 5 votes vote down vote up
public void run() {
	LocalDateTime start = LocalDateTime.now();

	logger.info(String.format("Starting %s", getTaskName()));

	logger.info(String.format("Blocking %,d x %,d elements", getDataset1().size(), getDataset2().size()));
	
	// use the blocker to generate pairs
	Processable<Correspondence<RecordType, CorrespondenceType>> allPairs = runBlocking(getDataset1(), getDataset2(), getCorrespondences());
	
	logger.info(String
					.format("Matching %,d x %,d elements; %,d blocked pairs (reduction ratio: %s)",
							getDataset1().size(), getDataset2().size(),
							allPairs.size(), Double.toString(getReductionRatio())));
	
	// compare the pairs using the matching rule
	Processable<Correspondence<RecordType, CorrespondenceType>> result = allPairs.map(rule);
	
	// report total matching time
	LocalDateTime end = LocalDateTime.now();
	
	logger.info(String.format(
			"%s finished after %s; found %,d correspondences.",
			getTaskName(), DurationFormatUtils.formatDurationHMS(Duration.between(start, end).toMillis()), result.size()));
	
	if(rule.isDebugReportActive()){
		rule.writeDebugMatchingResultsToFile();
	}
	
	this.result = result;
}
 
Example 20
@Override
public Pongo measure(Project project) {
	BugsOpenTimeHistoricMetric avgBugOpenTime = new BugsOpenTimeHistoricMetric();
	if (uses.size() == 1) {
		BugsBugMetadataTransMetric usedBhm = ((BugMetadataTransMetricProvider)uses.get(0)).adapt(context.getProjectDB(project));
		long seconds = 0;
		int durations = 0;
		for (BugData bugData: usedBhm.getBugData()) {
			if (bugData.getLastClosedTime()!=null) {
				java.util.Date javaOpenTime = bugData.getCreationTime();
				java.util.Date javaCloseTime = bugData.getLastClosedTime();
				seconds += ( Date.duration(javaOpenTime, javaCloseTime) / 1000);
				durations++;
			}
		}
		
		if (durations>0)
		{
			long avgDuration = seconds / durations;
			double daysReal = ( (double) avgDuration ) / SECONDS_DAY;
			avgBugOpenTime.setAvgBugOpenTimeInDays(daysReal);
			int days = (int) daysReal;
			long lessThanDay = (avgDuration % SECONDS_DAY);
			String formatted = DurationFormatUtils.formatDuration(lessThanDay*1000, "HH:mm:ss:SS");
			avgBugOpenTime.setAvgBugOpenTime(days+":"+formatted);
			System.out.println(days + ":" + formatted);
			avgBugOpenTime.setBugsConsidered(durations);
		}

	}
	return avgBugOpenTime;
}
 
Example 21
Source Project: JuniperBot   Source File: CommonUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String formatDuration(long millis) {
    if (millis < 0) {
        millis = 0;
    }
    String format = "mm:ss";
    if (millis > 3600000) {
        format = "HH:mm:ss";
    }
    return DurationFormatUtils.formatDuration(millis, format);
}
 
Example 22
Source Project: Discord-Streambot   Source File: CStats.java    License: MIT License 5 votes vote down vote up
@Override
public void execute(MessageReceivedEvent e, String content) {
    if(isAllowed("", e.getAuthor().getId(), allows, 0, null)){
        Message message;
        MessageBuilder builder = new MessageBuilder();
        builder.appendString("Server count : " + dao.count(GuildEntity.class) + "\n");
        builder.appendString("Users reached : " + jda.getUsers().size() + "\n");
        RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
        builder.appendString("Uptime : " + DurationFormatUtils.formatDuration(rb.getUptime(), "ddd 'days', HH:mm:ss"));
        message = builder.build();
        MessageHandler.getInstance().addCreateToQueue(e.getAuthor().getPrivateChannel().getId(), MessageCreateAction.Type.PRIVATE, message);
    }
}
 
Example 23
Source Project: dhis2-core   Source File: Clock.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Yields the elapsed time since the Clock was started as an HMS String.
 * @return the elapsed time.
 */
public String time()
{
    super.split();
    
    return DurationFormatUtils.formatDurationHMS( super.getSplitTime() );
}
 
Example 24
Source Project: dsworkbench   Source File: FarmTableModel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    FarmInformation elem = (FarmInformation) FarmManager.getSingleton().getAllElements().get(rowIndex);
    switch (columnIndex) {
        case 0:
            return elem.getStatus();
        case 1:
            return elem.isResourcesFoundInLastReport();
        case 2:
            return new Date(elem.getLastReport());
        case 3:
            return elem.getVillage().getShortName();
        case 4:
            return elem.getSiegeStatus();
        case 5:
            return elem.getWallLevel();
        case 6:
            return elem.getStorageStatus();
        case 7:
            long t = elem.getRuntimeInformation();
            t = (t <= 0) ? 0 : t;
            if (t == 0) {
                return "Keine Truppen unterwegs";
            }
            return DurationFormatUtils.formatDuration(t, "HH:mm:ss", true);
        case 8:
            return elem.getLastResult();
        default:
            return elem.getCorrectionFactor();
    }
}
 
Example 25
Source Project: webanno   Source File: SourceDocumentExporter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void importData(ProjectImportRequest aRequest, Project aProject,
        ExportedProject aExProject, ZipFile aZip)
    throws Exception
{
    long start = currentTimeMillis();

    importSourceDocuments(aExProject, aProject);
    importSourceDocumentContents(aZip, aProject);

    log.info("Imported [{}] source documents for project [{}] ({})",
            aExProject.getSourceDocuments().size(), aExProject.getName(),
            DurationFormatUtils.formatDurationWords(currentTimeMillis() - start, true, true));
}
 
Example 26
Source Project: james-project   Source File: ClientProvider.java    License: Apache License 2.0 5 votes vote down vote up
private RestHighLevelClient connect(ElasticSearchConfiguration configuration) {
    Duration waitDelay = Duration.ofMillis(configuration.getMinDelay());
    boolean suppressLeadingZeroElements = true;
    boolean suppressTrailingZeroElements = true;
    return Mono.fromCallable(() -> connectToCluster(configuration))
        .doOnError(e -> LOGGER.warn("Error establishing ElasticSearch connection. Next retry scheduled in {}",
            DurationFormatUtils.formatDurationWords(waitDelay.toMillis(), suppressLeadingZeroElements, suppressTrailingZeroElements), e))
        .retryWhen(Retry.backoff(configuration.getMaxRetries(), waitDelay).scheduler(Schedulers.elastic()))
        .publishOn(Schedulers.elastic())
        .block();
}
 
Example 27
Source Project: bisq   Source File: DisplayUtils.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static String formatAccountAge(long durationMillis) {
    durationMillis = Math.max(0, durationMillis);
    String day = Res.get("time.day").toLowerCase();
    String days = Res.get("time.days");
    String format = " d\' " + days + "\'";
    return StringUtils.strip(StringUtils.replaceOnce(DurationFormatUtils.formatDuration(durationMillis, format), " 1 " + days, " 1 " + day));
}
 
Example 28
Source Project: bisq   Source File: FormattingUtils.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static String formatDurationAsWords(long durationMillis, boolean showSeconds, boolean showZeroValues) {
    String format = "";
    String second = Res.get("time.second");
    String minute = Res.get("time.minute");
    String hour = Res.get("time.hour").toLowerCase();
    String day = Res.get("time.day").toLowerCase();
    String days = Res.get("time.days");
    String hours = Res.get("time.hours");
    String minutes = Res.get("time.minutes");
    String seconds = Res.get("time.seconds");

    if (durationMillis >= DateUtils.MILLIS_PER_DAY) {
        format = "d\' " + days + ", \'";
    }

    if (showSeconds) {
        format += "H\' " + hours + ", \'m\' " + minutes + ", \'s\' " + seconds + "\'";
    } else {
        format += "H\' " + hours + ", \'m\' " + minutes + "\'";
    }

    String duration = durationMillis > 0 ? DurationFormatUtils.formatDuration(durationMillis, format) : "";

    duration = StringUtils.replacePattern(duration, "^1 " + seconds + "|\\b1 " + seconds, "1 " + second);
    duration = StringUtils.replacePattern(duration, "^1 " + minutes + "|\\b1 " + minutes, "1 " + minute);
    duration = StringUtils.replacePattern(duration, "^1 " + hours + "|\\b1 " + hours, "1 " + hour);
    duration = StringUtils.replacePattern(duration, "^1 " + days + "|\\b1 " + days, "1 " + day);

    if (!showZeroValues) {
        duration = duration.replace(", 0 seconds", "");
        duration = duration.replace(", 0 minutes", "");
        duration = duration.replace(", 0 hours", "");
        duration = StringUtils.replacePattern(duration, "^0 days, ", "");
        duration = StringUtils.replacePattern(duration, "^0 hours, ", "");
        duration = StringUtils.replacePattern(duration, "^0 minutes, ", "");
        duration = StringUtils.replacePattern(duration, "^0 seconds, ", "");
    }
    return duration.trim();
}
 
Example 29
Source Project: appstatus   Source File: JvmPropertyProvider.java    License: Apache License 2.0 5 votes vote down vote up
public Map<String, String> getProperties() {
    Map<String, String> map = new TreeMap<String, String>();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();

    List<String> aList = runtimeMXBean.getInputArguments();
    String parameters = "";
    for (int i = 0; i < aList.size(); i++) {
        parameters = parameters + " " + aList.get(i);
    }
    map.put("params", parameters);

    map.put("name", runtimeMXBean.getVmName());
    map.put("vendor", runtimeMXBean.getVmVendor());
    map.put("version", runtimeMXBean.getVmVersion());
    map.put("specification", runtimeMXBean.getSpecVersion());
    map.put("uptime", DurationFormatUtils.formatDurationHMS(runtimeMXBean.getUptime()));

    Date date = new Date(runtimeMXBean.getStartTime());
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    map.put("start time", sdf.format(date));

    MemoryMXBean memory = ManagementFactory.getMemoryMXBean();

    MemoryUsage heap = memory.getHeapMemoryUsage();
    map.put("memory. (heap)", readableFileSize(heap.getUsed()) + "/" + readableFileSize(heap.getCommitted()) + " min:" + readableFileSize(heap.getInit()) + " max:" + readableFileSize(heap.getMax()));
    MemoryUsage nonheap = memory.getNonHeapMemoryUsage();
    map.put("memory (non heap)", readableFileSize(nonheap.getUsed()) + "/" + readableFileSize(nonheap.getCommitted()) + " min:" + readableFileSize(nonheap.getInit()) + " max:" + readableFileSize(nonheap.getMax()));

    return map;
}
 
Example 30
Source Project: Singularity   Source File: SmtpMailer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add needed information to the rate limit email Jade context.
 * @param request SingularityRequest that the rate limit email is about.
 * @param emailType what the email is about.
 * @return template properties to add to the Jade context.
 */
private Map<String, Object> getRateLimitTemplateProperties(
  SingularityRequest request,
  final SingularityEmailType emailType
) {
  final Builder<String, Object> templateProperties = ImmutableMap.<String, Object>builder();

  templateProperties.put(
    "singularityRequestLink",
    mailTemplateHelpers.getSingularityRequestLink(request.getId())
  );
  templateProperties.put(
    "rateLimitAfterNotifications",
    Integer.toString(smtpConfiguration.getRateLimitAfterNotifications())
  );
  templateProperties.put(
    "rateLimitPeriodFormat",
    DurationFormatUtils.formatDurationHMS(smtpConfiguration.getRateLimitPeriodMillis())
  );
  templateProperties.put(
    "rateLimitCooldownFormat",
    DurationFormatUtils.formatDurationHMS(
      smtpConfiguration.getRateLimitCooldownMillis()
    )
  );
  templateProperties.put("emailType", emailType.name());
  templateProperties.put("requestId", request.getId());
  templateProperties.put("color", emailType.getColor());

  return templateProperties.build();
}