Example usage for org.apache.commons.lang3.time DurationFormatUtils formatPeriod

List of usage examples for org.apache.commons.lang3.time DurationFormatUtils formatPeriod

Introduction

In this page you can find the example usage for org.apache.commons.lang3.time DurationFormatUtils formatPeriod.

Prototype

public static String formatPeriod(final long startMillis, final long endMillis, final String format) 

Source Link

Document

Formats the time gap as a string, using the specified format.

Usage

From source file:com.thruzero.common.core.utils.DateTimeFormatUtilsExt.java

public static String formatElapsedTime(final long startMillis, final long endMillis) {
    String result = DurationFormatUtils.formatPeriod(startMillis, endMillis, "s.SSS");

    return result;
}

From source file:e.pkg3.pkg6a.acertijo.acertijo.java

private void botonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonActionPerformed
    int numero_Usuario = 0;
    try {//from w w  w  .  j  a  va 2 s.  co  m
        numero_Usuario = Integer.valueOf(texto.getText());
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(this, "Introduce un Numero");
        e.printStackTrace();
        contador++;
    }

    int resta = numero_Aleatorio - numero_Usuario;

    if (resta < 0) {
        area.setText("El numero es menor que " + numero_Usuario);
    }
    if (resta > 0) {
        area.setText("El numero es mayor que " + numero_Usuario);
    }
    contador++;
    if (resta == 0) {
        Calendar fin = Calendar.getInstance();
        String formato = "HH:mm:ss";
        long inicioMilis = (inicio.get(Calendar.HOUR) * 3600000L) + (inicio.get(Calendar.MINUTE) * 60000L)
                + (inicio.get(Calendar.SECOND) * 1000L);
        long finalMilis = (fin.get(Calendar.HOUR) * 3600000L) + (fin.get(Calendar.MINUTE) * 60000L)
                + (fin.get(Calendar.SECOND) * 1000L);
        String duracion = DurationFormatUtils.formatPeriod(inicioMilis, finalMilis, formato);

        area.setText("El numero es Correcto!\n");
        area.append("Acertado en " + contador + " intentos\n");
        area.append("Acertado en " + duracion);
        contador = 0;
        boton.setEnabled(false);
        texto.setEnabled(false);
    }

}

From source file:com.blackducksoftware.integration.hub.detect.Application.java

@Override
public void run(final ApplicationArguments applicationArguments) throws Exception {
    final long startTime = System.currentTimeMillis();

    //Events, Status and Exit Codes are required even if boot fails.
    EventSystem eventSystem = new EventSystem();
    DetectStatusManager statusManager = new DetectStatusManager(eventSystem);

    ExitCodeUtility exitCodeUtility = new ExitCodeUtility();
    ExitCodeManager exitCodeManager = new ExitCodeManager(eventSystem, exitCodeUtility);

    ReportManager reportManager = ReportManager.createDefault(eventSystem);

    //Before boot even begins, we create a new Spring context for Detect to work within.
    logger.info("Preparing detect.");
    DetectRun detectRun = DetectRun.createDefault();
    DetectContext detectContext = new DetectContext(detectRun);

    BootResult bootResult = null;//from   w  ww  .ja v a2s.c o m
    Optional<RunResult> runResult = Optional.empty();
    try {
        logger.info("Detect boot begin.");
        BootManager bootManager = new BootManager(new BootFactory());
        bootResult = bootManager.boot(detectRun, applicationArguments.getSourceArgs(), environment, eventSystem,
                detectContext);
        logger.info("Detect boot completed.");
    } catch (final Exception e) {
        logger.error("Detect boot failed.");
        exitCodeManager.requestExitCode(e);
    }
    if (bootResult != null && bootResult.bootType == BootResult.BootType.CONTINUE) {
        logger.info("Detect will attempt to run.");
        RunManager runManager = new RunManager(detectContext);
        try {
            logger.info("Detect run begin: " + detectRun.getRunId());
            runResult = Optional.ofNullable(runManager.run());
            logger.info("Detect run completed.");
        } catch (final Exception e) {
            if (e.getMessage() != null) {
                logger.error("Detect run failed: " + e.getMessage());
            } else {
                logger.error("Detect run failed: " + e.getClass().getSimpleName());
            }
            logger.debug("An exception was thrown during the detect run.", e);
            exitCodeManager.requestExitCode(e);
        }
        try {
            logger.info("Detect will attempt to shutdown.");
            DiagnosticManager diagnosticManager = detectContext.getBean(DiagnosticManager.class);
            DirectoryManager directoryManager = detectContext.getBean(DirectoryManager.class);
            DetectConfiguration detectConfiguration = detectContext.getBean(DetectConfiguration.class);
            ConnectivityManager connectivityManager = detectContext.getBean(ConnectivityManager.class);
            ShutdownManager shutdownManager = new ShutdownManager(connectivityManager, statusManager,
                    exitCodeManager, directoryManager, detectConfiguration, reportManager, diagnosticManager);
            logger.info("Detect shutdown begin.");
            shutdownManager.shutdown(runResult);
            logger.info("Detect shutdown completed.");
        } catch (final Exception e) {
            logger.error("Detect shutdown failed.");
            exitCodeManager.requestExitCode(e);
        }
    } else {
        logger.debug("Detect will NOT attempt to run.");
    }

    logger.info("All detect actions completed.");

    //Determine how detect should actually exit
    boolean printOutput = true;
    boolean shouldForceSuccess = false;
    if (bootResult != null && bootResult.detectConfiguration != null) {
        printOutput = !bootResult.detectConfiguration
                .getBooleanProperty(DetectProperty.DETECT_SUPPRESS_RESULTS_OUTPUT, PropertyAuthority.None);
        shouldForceSuccess = bootResult.detectConfiguration
                .getBooleanProperty(DetectProperty.DETECT_FORCE_SUCCESS, PropertyAuthority.None);
    }

    //Generally, when requesting a failure status, an exit code is also requested, but if it is not, we default to an unknown error.
    if (statusManager.hasAnyFailure()) {
        eventSystem.publishEvent(Event.ExitCode, new ExitCodeRequest(ExitCodeType.FAILURE_UNKNOWN_ERROR,
                "A failure status was requested by one or more of Detect's tools."));
    }

    //Find the final (as requested) exit code
    ExitCodeType finalExitCode = exitCodeManager.getWinningExitCode();

    //Print detect's status
    if (printOutput) {
        reportManager.printDetectorIssues();
        statusManager.logDetectResults(new Slf4jIntLogger(logger), finalExitCode);
    }

    //Print duration of run
    final long endTime = System.currentTimeMillis();
    logger.info(String.format("Detect duration: %s",
            DurationFormatUtils.formatPeriod(startTime, endTime, "HH'h' mm'm' ss's' SSS'ms'")));

    //Exit with formal exit code
    if (finalExitCode != ExitCodeType.SUCCESS && shouldForceSuccess) {
        logger.warn(String.format("Forcing success: Exiting with exit code 0. Ignored exit code was %s.",
                finalExitCode.getExitCode()));
        System.exit(0);
    } else if (finalExitCode != ExitCodeType.SUCCESS) {
        logger.error(String.format("Exiting with code %s - %s", finalExitCode.getExitCode(),
                finalExitCode.toString()));
    }

    System.exit(finalExitCode.getExitCode());
}

From source file:org.apache.maven.plugins.scmpublish.AbstractScmPublishMojo.java

/**
 * Check-in content from scm checkout.//from w w  w . j  av  a 2  s. c o  m
 *
 * @throws MojoExecutionException
 */
protected void checkinFiles() throws MojoExecutionException {
    if (skipCheckin) {
        return;
    }

    ScmFileSet updatedFileSet = new ScmFileSet(checkoutDirectory);
    try {
        long start = System.currentTimeMillis();

        CheckInScmResult checkinResult = checkScmResult(
                scmProvider.checkIn(scmRepository, updatedFileSet, new ScmBranch(scmBranch), checkinComment),
                "check-in files to SCM");

        logInfo("Checked in %d file(s) to revision %s in %s", checkinResult.getCheckedInFiles().size(),
                checkinResult.getScmRevision(),
                DurationFormatUtils.formatPeriod(start, System.currentTimeMillis(), "H' h 'm' m 's' s'"));
    } catch (ScmException e) {
        throw new MojoExecutionException("Failed to perform SCM checkin", e);
    }
}

From source file:org.kuali.coeus.common.framework.person.KcPerson.java

/**
 * Calculates the age based on a date of birth and the current system date.
 * @param dob the date of birth/*from ww w. j  ava 2  s.  c  o  m*/
 * @return the age in days
 */
private Integer calcAge(Date dob) {
    return Integer.getInteger(DurationFormatUtils.formatPeriod(dob.getTime(), new Date().getTime(), "y"));
}

From source file:taximetro.Taximetro.java

private void botonFinalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonFinalActionPerformed
    //Activacion de botones
    botonInicio.setEnabled(true);/*from www .  j a va2  s  . c o  m*/
    botonFinal.setEnabled(false);
    //Aqui va el ticket
    ++numeroTicket;
    Calendar ahora2 = Calendar.getInstance();
    String horaTexto2 = String.valueOf(ahora2.get(Calendar.HOUR_OF_DAY));
    horaTexto2 += ":" + (String.valueOf(ahora2.get(Calendar.MINUTE)));
    horaTexto2 += ":" + (String.valueOf(ahora2.get(Calendar.SECOND)));

    //Tiempo transcurrido        
    String formato = "HH:mm:ss";
    long inicioMilis = (ahora.get(Calendar.HOUR) * 3600000L) + (ahora.get(Calendar.MINUTE) * 60000L)
            + (ahora.get(Calendar.SECOND) * 1000L);
    long finalMilis = (ahora2.get(Calendar.HOUR) * 3600000L) + (ahora2.get(Calendar.MINUTE) * 60000L)
            + (ahora2.get(Calendar.SECOND) * 1000L);
    String duracion = DurationFormatUtils.formatPeriod(inicioMilis, finalMilis, formato);

    double precio = 0.5 + (((finalMilis / 1000) - (inicioMilis / 1000)) * (0.5 / 60));
    double iva = precio * 0.21;
    double total = (precio + iva);
    DecimalFormat formatoEuros = new DecimalFormat("####.##");

    area.append("\nHora bajada de bandera: " + horaTexto2 + "\nDuracin del trayecto: " + duracion
            + "\nTarifa por minuto: 0.50 " + "\nCoste bajada de bandera: 0.50 " + "\n\nPrecio: "
            + (formatoEuros.format(precio)) + " " + "\nIVA(21%): " + (formatoEuros.format(iva)) + " "
            + "\nImporte Total: " + (formatoEuros.format(total)) + " ");

}