Example usage for org.apache.commons.lang.time DurationFormatUtils formatDurationHMS

List of usage examples for org.apache.commons.lang.time DurationFormatUtils formatDurationHMS

Introduction

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

Prototype

public static String formatDurationHMS(long durationMillis) 

Source Link

Document

Formats the time gap as a string.

The format used is ISO8601-like: H:m:s.S.

Usage

From source file:org.silverpeas.migration.jcr.wysiwyg.purge.WysiwygDocumentPurger.java

/**
 * Gets the content of the given wysiwyg/language.
 * @param commonLogPart//from   w  ww  .  j  a v  a2 s.  c  om
 * @param wysiwygLangAttachment
 * @return a String that represents the content in UTF8, a dummy string if physical file does
 * not exist.
 */
private String getContent(String commonLogPart, SimpleDocument wysiwygLangAttachment) {
    long start = System.currentTimeMillis();
    ByteArrayOutputStream content = new ByteArrayOutputStream();
    try {
        service.getBinaryContent(content, wysiwygLangAttachment.getPk(), wysiwygLangAttachment.getLanguage());
        return content.toString(Charsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        console.printError(commonLogPart + " - doc=" + wysiwygLangAttachment.getNodeName() + ", lang="
                + wysiwygLangAttachment.getLanguage() + " - unsupported encoding", e);
        return UUID.randomUUID().toString();
    } catch (AttachmentException ae) {
        console.printError(commonLogPart + " - doc=" + wysiwygLangAttachment.getNodeName() + ", lang="
                + wysiwygLangAttachment.getLanguage() + " - inconsistent data, nothing is done", ae);
        return UUID.randomUUID().toString();
    } finally {
        console.printMessage(commonLogPart + " - getContent method - duration of "
                + DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - start));
    }
}

From source file:org.silverpeas.migration.jcr.wysiwyg.purge.WysiwygDocumentPurger.java

/**
 * Indicates if the content of given wysiwyg/language is empty.
 * @param commonLogPart/*from  w w w  . java  2s. co m*/
 * @param wysiwygLangAttachment
 * @return true if exists and is empty, false otherwise.
 */
private boolean isPhysicalFileExistingWithEmptyContent(String commonLogPart,
        SimpleDocument wysiwygLangAttachment) {
    long start = System.currentTimeMillis();
    try {
        File contentToVerify = new File(wysiwygLangAttachment.getAttachmentPath());
        return contentToVerify.isFile() && contentToVerify.length() == 0;
    } finally {
        console.printMessage(commonLogPart + " - isPhysicalFileExistingWithEmptyContent method  - duration of "
                + DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - start));
    }
}

From source file:org.silverpeas.migration.jcr.wysiwyg.purge.WysiwygPurger.java

/**
 * This method must be called to perform the purge treatment.
 * A thread pool is handled.//from ww w.  j a va  2s .com
 * @throws Exception
 */
public void purgeDocuments() throws Exception {
    Date startDate = new Date();
    getConsole().printMessage(
            "Starting the WYSIWYG purge process at " + DateUtil.formatAsISO8601WithUtcOffset(startDate));
    long totalNumberOfPurgedFiles = 0L;
    long totalNumberOfRenamedFiles = 0L;
    List<WysiwygDocumentPurger> mergers = buildWysiwygDocumentPurgers();
    List<Future<WysiwygDocumentPurger.Result>> results = executor.invokeAll(mergers);
    try {
        for (Future<WysiwygDocumentPurger.Result> result : results) {
            totalNumberOfPurgedFiles += result.get().getNbWysiwygContentPurged();
            totalNumberOfRenamedFiles += result.get().getNbWysiwygFilenameRenamed();
        }
    } catch (InterruptedException ex) {
        throw ex;
    } catch (Exception ex) {
        getConsole().printError(
                "Error during the purge or the physical WYSIWYG file renaming of wysiwyg contents " + ex, ex);
        throw ex;
    } finally {
        executor.shutdown();
    }
    getConsole().printMessage("Nb of purged wysiwyg contents : " + totalNumberOfPurgedFiles);
    getConsole().printMessage("Nb of renamed wysiwyg content file names : " + totalNumberOfRenamedFiles);
    Date endDate = new Date();
    getConsole().printMessage("Finishing the WYSIWYG purge process at "
            + DateUtil.formatAsISO8601WithUtcOffset(endDate) + " (total duration of "
            + DurationFormatUtils.formatDurationHMS(endDate.getTime() - startDate.getTime()) + ")");
    if (!RepositoryManager.isIsJcrTestEnv()) {
        this.service.shutdown();
    }
}

From source file:org.soaplab.admin.ExploreStorage.java

/*************************************************************************
 * Print job info./*from w w  w  .ja  v a  2s. co  m*/
 *************************************************************************/
static void jobInfo(PersistentStorage storage, String jobId, String title) throws SoaplabException {
    JobState state = storage.getJobState(jobId);
    msgln(title + ": " + jobId + " (" + state + ")");
    msgln("\tcreated: " + DateFormatUtils.format(state.getCreated(), SoaplabConstants.DT_FORMAT));
    msgln("\tstarted: " + DateFormatUtils.format(state.getStarted(), SoaplabConstants.DT_FORMAT));
    msgln("\tended:   " + DateFormatUtils.format(state.getEnded(), SoaplabConstants.DT_FORMAT));
    msgln("\telapsed: " + DurationFormatUtils.formatDurationHMS(state.getElapsed()));
    msgln("\tlast event: " + state.getLastEvent());
}

From source file:org.soaplab.clients.BatchTestClient.java

/*************************************************************************
 * Call service as define in 'locator' (which also has an input
 * data for the service) and report results into a new entry in
 * 'reports'./*from w  ww . j  a  v a 2  s .c om*/
 *
 * It also returns its own report.
 *************************************************************************/
private static Properties callService(MyLocator locator, List<Properties> reports) {

    Properties report = new Properties();
    reports.add(report);
    String serviceName = locator.getServiceName();
    String inputLine = locator.getInputLine();
    report.setProperty(REPORT_SERVICE_NAME, serviceName);
    report.setProperty(REPORT_INPUT_LINE, inputLine);

    try {
        SoaplabBaseClient client = new SoaplabBaseClient(locator);

        // collect inputs from the input line
        BaseCmdLine cmd = null;
        if (StringUtils.isBlank(inputLine)) {
            cmd = new BaseCmdLine(new String[] {}, true);
        } else {
            cmd = new BaseCmdLine(
                    new StrTokenizer(inputLine, StrMatcher.charSetMatcher(" \t\f"), StrMatcher.quoteMatcher())
                            .getTokenArray(),
                    true);
        }
        SoaplabMap inputs = SoaplabMap
                .fromMap(InputUtils.collectInputs(cmd, SoaplabMap.toMaps(client.getInputSpec())));

        // any unrecognized inputs on the command-line?
        if (cmd.params.length > 0) {
            StringBuilder buf = new StringBuilder();
            buf.append("Unrecognized inputs: ");
            for (String arg : cmd.params)
                buf.append(arg + " ");
            report.setProperty(REPORT_ERROR_MESSAGE, buf.toString());
            report.setProperty(REPORT_JOB_STATUS, "NOT STARTED");
            return report;
        }

        // start service and wait for its completion
        String jobId = client.createAndRun(inputs);
        report.setProperty(REPORT_JOB_ID, jobId);
        client.waitFor(jobId);

        // save all info about just finished job
        String status = client.getStatus(jobId);
        report.setProperty(REPORT_JOB_STATUS, status);

        SoaplabMap times = client.getCharacteristics(jobId);
        Object elapsed = times.get(SoaplabConstants.TIME_ELAPSED);
        if (elapsed != null) {
            try {
                report.setProperty(REPORT_ELAPSED_TIME,
                        DurationFormatUtils.formatDurationHMS(Long.decode(elapsed.toString())));
            } catch (NumberFormatException e) {
            }
        }

        String lastEvent = client.getLastEvent(jobId);
        if (lastEvent != null)
            report.setProperty(REPORT_LAST_EVENT, lastEvent);

        if (!client.getLocator().getProtocol().equals(ClientConfig.PROTOCOL_AXIS1)) {
            // get result infos (about all available results)
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ResultUtils.formatResultInfo(SoaplabMap.toStringMaps(client.getResultsInfo(jobId)),
                    new PrintStream(bos));
            report.setProperty(REPORT_RESULTS_INFO, bos.toString());
        }
        // get results (but ignore them - except the special ones)
        client.getResults(jobId);
        Map<String, Object> results = SoaplabMap.toMap(client.getSomeResults(jobId,
                new String[] { SoaplabConstants.RESULT_REPORT, SoaplabConstants.RESULT_DETAILED_STATUS }));
        for (Iterator<String> it = results.keySet().iterator(); it.hasNext();) {
            String resultName = it.next();
            report.setProperty(resultName, results.get(resultName).toString());
        }

        // clean the job
        if (!locator.isEnabledKeepResults()) {
            client.destroy(jobId);
            report.remove(REPORT_JOB_ID);
        }

    } catch (Throwable e) {
        reportError(report, e);
    }
    return report;
}

From source file:org.soaplab.clients.CmdLineClient.java

/*************************************************************************
 *
 * Entry point...// w  ww.j av  a  2s. c  o m
 *
 *************************************************************************/
public static void main(String[] args) {
    try {
        BaseCmdLine cmd = getCmdLine(args, CmdLineClient.class);

        // service location and protocol parameters
        ServiceLocator locator = InputUtils.getServiceLocator(cmd);

        // if we have a -job we may not need the -name (this is
        // just a hack, but not an important one, so who cares...)
        String jobId = cmd.getParam("-job");
        if (StringUtils.isNotEmpty(jobId) && StringUtils.isEmpty(locator.getServiceName())) {
            int posBegToken = jobId.indexOf("[");
            int posEndToken = jobId.indexOf("]");
            if (posBegToken > -1 && posEndToken > posBegToken) {
                locator.setServiceName(jobId.substring(posBegToken + 1, posEndToken));
            }
        }

        // list requests
        boolean listAll = cmd.hasOption("-l");
        boolean listServices = cmd.hasOption("-la");
        boolean listServicesWithDesc = cmd.hasOption("-lad");
        boolean listCategories = cmd.hasOption("-lc");
        String category = cmd.getParam("-category");
        String listSaveFile = cmd.getParam("-sl");

        if (cmd.params.length > 0) {
            // there are also non-list requests so a service name
            // is mandatory

            // where is the service
            if (StringUtils.isEmpty(locator.getServiceName())) {
                System.err.println("Service name must be given. Use '-name' or '-e'.");
                System.exit(1);
            }
        }

        SoaplabBaseClient client = new SoaplabBaseClient(locator);

        //
        // deal with list requests
        //

        PrintWriter pw = null;
        if (listSaveFile != null) {
            pw = new PrintWriter(listSaveFile);
        }

        if (listServices) {
            title("Available analyses:", pw);
            for (String analysis : client.getAvailableAnalyses())
                msgln(analysis, pw);
        }

        if (listServicesWithDesc) {
            title("Available analyses (with descriptions):", pw);
            SoaplabMap mapWithDesc = client.getAvailableAnalysesWithDescription();
            for (MapEntry entry : mapWithDesc.getEntries()) {
                msgln(entry.getKey(), pw);
                msgln("\t" + entry.getObjectValue(), pw);
            }
        }

        if (listCategories) {
            title("Available categories:", pw);
            for (String categ : client.getAvailableCategories())
                msgln(categ, pw);
        }

        if (listAll) {
            title("Available categories and analyses:", pw);
            for (String categ : client.getAvailableCategories()) {
                msgln(categ, pw);
                for (String analysis : client.getAvailableAnalysesInCategory(categ))
                    msgln("\t" + analysis, pw);
            }
        }

        if (category != null) {
            title("Category: " + category, pw);
            for (String analysis : client.getAvailableAnalysesInCategory(category))
                msgln(analysis, pw);
        }

        IOUtils.closeQuietly(pw);

        //
        // give me service's metadata
        //

        if (cmd.hasOption("-d")) {
            msgln(client.describe());
        }

        if (cmd.hasOption("-i") || cmd.hasOption("-ii")) {
            SoaplabMap[] attrs = client.getInputSpec();
            InputUtils.formatInputMetadata(SoaplabMap.toMaps(attrs), System.out, cmd.hasOption("-ii"), verbose);
        }

        if (cmd.hasOption("-o") || cmd.hasOption("-oo")) {
            SoaplabMap[] attrs = client.getResultSpec();
            InputUtils.formatOutputMetadata(SoaplabMap.toMaps(attrs), System.out, cmd.hasOption("-oo"),
                    verbose);
        }

        if (cmd.hasOption("-t")) {
            Map<String, Object> aType = SoaplabMap.toMap(client.getAnalysisType());
            title("Analysis properties:");
            if (aType != null) {
                for (Iterator<String> it = aType.keySet().iterator(); it.hasNext();) {
                    String key = it.next();
                    msgln(key + " => " + aType.get(key));
                }
                msgln("");
            }
        }

        //
        // deal with a job (creation, invocation, waiting for, killing...)
        //
        String jobIdFile = cmd.getParam("-jp");
        boolean createJob = cmd.hasOption("-j");
        boolean runJob = cmd.hasOption("-x");
        boolean waitForJob = cmd.hasOption("-w");
        boolean killJob = cmd.hasOption("-k");

        // collect inputs from the command line
        // (unless the job had been already created)
        SoaplabMap inputs = null;
        if (jobId == null && (createJob || runJob || waitForJob)) {
            inputs = SoaplabMap
                    .fromMap(InputUtils.collectInputs(cmd, SoaplabMap.toMaps(client.getInputSpec())));
        }

        //
        // read the rest of the command-line, including the result
        // names - so we can check that there are no unrecognized
        // parameters before we start any job
        //
        boolean getStatus = cmd.hasOption("-s");
        boolean getTimes = cmd.hasOption("-c");
        boolean getLastEvent = cmd.hasOption("-le");
        boolean doClean = cmd.hasOption("-clean");
        boolean getResultInfo = cmd.hasOption("-ri");
        boolean getResults = cmd.hasOption("-r");
        boolean printBinary = cmd.hasOption("-bp");
        boolean saveResults = cmd.hasOption("-sr");

        String[] resultNames = null;
        if (getResults) {
            // collect names of the results (from the command-line)
            resultNames = ResultUtils.collectResultNames(cmd, SoaplabMap.toMaps(client.getResultSpec()));
        }

        // any unrecognized parameter/option on the command-line?
        if (cmd.params.length > 0) {
            msg("Unrecognized or unused arguments (perhaps an \"action\" option missing?): ");
            for (String arg : cmd.params)
                msg(arg + " ");
            msgln("");
            System.exit(1);
        }

        // when we do not have a job ID from a previous invocation
        if (jobId == null) {
            if (waitForJob) {
                jobId = client.createAndRun(inputs);
                saveJobId(jobId, jobIdFile);
                client.waitFor(jobId);
            } else if (runJob) {
                jobId = client.createAndRun(inputs);
                saveJobId(jobId, jobIdFile);
            } else if (createJob) {
                jobId = client.createJob(inputs);
                saveJobId(jobId, jobIdFile);
            }

            // when we use a previously stored job ID
        } else {
            if (waitForJob) {
                client.waitFor(jobId);
            } else if (runJob) {
                client.run(jobId);
            } else if (killJob) {
                client.terminate(jobId);
            }
        }

        //
        // deal with the job status, characteristics and events
        // (makes sense only if we have a jobID)
        //
        if (jobId != null) {
            if (getStatus) {
                String status = client.getStatus(jobId);
                title("Status of job: " + jobId);
                msgln(status);
            }
            if (getTimes) {
                SoaplabMap times = client.getCharacteristics(jobId);
                title("Characteristics of job: " + jobId);
                Long millis = getLong(times.get(SoaplabConstants.TIME_CREATED));
                if (millis != null)
                    msgln("\tCreated: "
                            + DateFormatUtils.format(millis.longValue(), SoaplabConstants.DT_FORMAT));
                millis = getLong(times.get(SoaplabConstants.TIME_STARTED));
                if (millis != null)
                    msgln("\tStarted: "
                            + DateFormatUtils.format(millis.longValue(), SoaplabConstants.DT_FORMAT));
                millis = getLong(times.get(SoaplabConstants.TIME_ENDED));
                if (millis != null)
                    msgln("\tEnded:   "
                            + DateFormatUtils.format(millis.longValue(), SoaplabConstants.DT_FORMAT));
                Long ms = getLong(times.get(SoaplabConstants.TIME_ELAPSED));
                if (ms != null)
                    msgln("\tElapsed: " + DurationFormatUtils.formatDurationHMS(ms));
            }
            if (getLastEvent) {
                String lastEvent = client.getLastEvent(jobId);
                title("Last event reported for job: " + jobId);
                msgln(lastEvent);
            }
        }

        //
        // cleaning it all...
        // (does not make sense together with other options, except -job)
        //
        if (jobId != null && doClean)
            client.destroy(jobId);

        //
        // deal with results (makes sense only if we have a job ID)
        //
        if (jobId != null) {
            if (getResultInfo) {
                title("Results info for job: " + jobId);
                ResultUtils.formatResultInfo(SoaplabMap.toStringMaps(client.getResultsInfo(jobId)), System.out);
            }

            if (getResults || saveResults) {

                // getting results from the service (all or just some)
                Map<String, Object> results;
                if (resultNames.length == 0)
                    results = SoaplabMap.toMap(client.getResults(jobId));
                else
                    results = SoaplabMap.toMap(client.getSomeResults(jobId, resultNames));
                for (Iterator<String> it = results.keySet().iterator(); it.hasNext();) {
                    String resultName = it.next();
                    title(resultName);
                    String[] files = ResultUtils.handleResult(results.get(resultName), resultName,
                            (printBinary && !saveResults ? null : jobId), saveResults, System.out);
                    if (files != null) {
                        for (int i = 0; i < files.length; i++)
                            msgln("(written into: " + files[i] + ")");
                    }
                }
            }
        }

        exit(0);

    } catch (Throwable e) {
        processErrorAndExit(e);
    }
}

From source file:org.soaplab.services.Reporter.java

/******************************************************************************
 * Create a 'report' result from data reported so far, and from
 * the current job status. <p>// w ww.j  a v  a  2s.  co m
 *
 * Note that a report can be created more than once, potentially
 * with richer property set each time. <p>
 *
 * TBD: how to deal with BIG reports - with memory problem...
 ******************************************************************************/
protected String createReportResult() {

    // 1) create "termination status"
    StringBuilder buf = new StringBuilder();
    buf.append("Summary:\n\tCompleted: ");
    if (state.isSuccessful())
        if (errBuf.length() > 0)
            buf.append("Maybe\n");
        else
            buf.append("Successfully\n");
    else if (state.isErroneous())
        buf.append("Erroneously\n");
    else if (state.isInProgress())
        buf.append("...in progress\n");
    else
        buf.append("Unknown\n");
    String ts = state.formatDetailedState();
    if (ts != null)
        buf.append("\tTermination status: " + ts + "\n");
    long started = state.getStarted();
    if (started > 0) {
        buf.append("\tStarted:   ");
        buf.append(DateFormatUtils.format(started, SoaplabConstants.DT_FORMAT));
        buf.append("\n");
    }
    long ended = state.getEnded();
    if (ended > 0) {
        buf.append("\tEnded:     ");
        buf.append(DateFormatUtils.format(ended, SoaplabConstants.DT_FORMAT));
        buf.append("\n");
    }
    long elapsed = state.getElapsed();
    if (elapsed > 0) {
        buf.append("\tDuration:  ");
        buf.append(DurationFormatUtils.formatDurationHMS(elapsed));
        buf.append("\n");
    }

    // 2) create report from report properties
    if (reportProps.size() > 0 || errBuf.length() > 0 || msgBuf.length() > 0)
        buf.append("Report:\n");
    buf.append(new String(reportProperties()));

    // 3) add the main and error messages
    if (errBuf.length() > 0) {
        buf.append(errBuf);
        buf.append("\n");
    }
    if (msgBuf.length() > 0) {
        buf.append(msgBuf);
        buf.append("\n");
    }

    // 4) add contents of registered files
    for (Enumeration<String> en = fileProps.keys(); en.hasMoreElements();) {
        String key = en.nextElement();
        File file = fileProps.get(key);
        buf.append(key);
        buf.append(":\n");
        buf.append(tryFile(file));
        buf.append("\n");
    }

    return buf.toString();
}

From source file:org.sonatype.nexus.index.NexusScanningListener.java

@Override
public void scanningFinished(final IndexingContext ctx, final ScanningResult result) {
    TaskUtil.checkInterruption();//from w  w w . ja va  2 s.  c  o  m
    int removed = 0;
    try {
        if (!fullReindex && !isProxy) {
            // HOSTED-nonFull only, perform delete detection too (remove stuff from index that is removed from repository
            removed = removeDeletedArtifacts(result.getRequest().getStartingPath());
        }
        // rebuild groups, as methods moved out from IndexerEngine does not maintain groups anymore
        // as it makes no sense to do it during batch invocation of update method
        context.rebuildGroups();
        context.commit();
    } catch (IOException ex) {
        result.addException(ex);
    }

    result.setTotalFiles(discovered);
    result.setDeletedFiles(removed);
    result.getExceptions().addAll(exceptions);

    if (result.getDeletedFiles() > 0 || result.getTotalFiles() > 0) {
        try {
            context.updateTimestamp(true);
            context.optimize();
        } catch (Exception ex) {
            result.addException(ex);
        }
    }
    logger.info(
            "Scanning of repositoryID=\"{}\" finished: scanned={}, added={}, updated={}, removed={}, scanningDuration={}",
            context.getRepositoryId(), discovered, added, updated, removed,
            DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - scanningStarted));
}

From source file:org.sonatype.nexus.proxy.attributes.upgrade.AttributeUpgraderThread.java

@Override
public void run() {
    try {/*from w  ww .j a  v  a 2 s.co m*/
        // defer actual start a bit to not start prematurely (ie. nexus boot not done yet, let it "calm down")
        throttleRun();
    } catch (InterruptedException e) {
        // thread will die off
        return;
    }

    try {
        if (!isUpgradeDone(null)) {
            boolean weHadSkippedRepositories = false;
            final long started = System.currentTimeMillis();
            List<Repository> reposes = repositoryRegistry.getRepositories();
            for (Repository repo : reposes) {
                if (shouldUpgradeRepository(repo)) {
                    if (LocalStatus.IN_SERVICE.equals(repo.getLocalStatus())) {
                        if (!isUpgradeDone(repo.getId())) {
                            try {
                                logger.info("Upgrading legacy attributes of repository {}.",
                                        RepositoryStringUtils.getHumanizedNameString(repo));

                                ResourceStoreRequest req = new ResourceStoreRequest(
                                        RepositoryItemUid.PATH_ROOT);
                                req.getRequestContext().put(WalkerThrottleController.CONTEXT_KEY,
                                        throttleController);
                                req.getRequestContext().put(RecreateAttributesWalker.FORCE_ATTRIBUTE_RECREATION,
                                        Boolean.FALSE);
                                req.getRequestContext().put(RecreateAttributesWalker.LEGACY_ATTRIBUTES_ONLY,
                                        Boolean.TRUE);
                                repo.recreateAttributes(req, null);
                                markUpgradeDone(repo.getId());
                                logger.info("Upgrade of legacy attributes of repository {} done.",
                                        RepositoryStringUtils.getHumanizedNameString(repo));
                            } catch (WalkerException e) {
                                weHadSkippedRepositories = true;
                                logger.error(
                                        "Problems during legacy attribute upgrade of repository {}, skipping it. Please fix the problems and retry the upgrade.",
                                        RepositoryStringUtils.getHumanizedNameString(repo), e);
                            } catch (IOException e) {
                                logger.error("Unable to perform file write to legacy attributes directory: {}",
                                        legacyAttributesDirectory.getAbsolutePath());

                                throw e;
                            }
                        } else {
                            logger.debug(
                                    "Skipping legacy attributes of repository {}, already marked as upgraded.",
                                    RepositoryStringUtils.getHumanizedNameString(repo));
                        }
                    } else {
                        weHadSkippedRepositories = true;
                        logger.info(
                                "Deferring legacy attributes upgrade of repository {}, is out of service. Upgrade will be automatically retried once repository will be in service, and upgrade restarted (next restart of Nexus or manually invoked over JMX).",
                                RepositoryStringUtils.getHumanizedNameString(repo));
                    }
                }
            }

            final String totalRuntimeString = DurationFormatUtils
                    .formatDurationHMS(System.currentTimeMillis() - started);

            if (!weHadSkippedRepositories) {
                try {
                    // mark instance as upgraded
                    markUpgradeDone(null);
                } catch (IOException e) {
                    logger.error("Unable to perform file write to legacy attributes directory: {}",
                            legacyAttributesDirectory.getAbsolutePath());

                    throw e;
                }

                logger.info(
                        "Legacy attribute directory upgrade finished without any errors. Please delete, move or rename the \"{}\" folder. Total runtime {}",
                        legacyAttributesDirectory.getAbsolutePath(), totalRuntimeString);
            } else {
                logger.info(
                        "Legacy attribute directory upgrade was partially completed. Please see prior log messages for details. Total runtime {}",
                        totalRuntimeString);
            }
        }
    } catch (IOException e) {
        // if we are here, that means that one of the isUpgradeDone or markUpgradeDone puked.
        // Write failures are already noted above (see catches around markUpgradeDone).
        logger.error(
                "Stopping legacy attributes upgrade because of file read/write related problems. Please fix the problems and retry the upgrade.",
                e);
    }
}

From source file:org.sonatype.nexus.scheduling.AbstractNexusTask.java

protected String getLoggedMessage(final String action, final long started) {
    final String startedStr = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(started);
    final String durationStr = DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - started);

    return String.format("%s (started %s, runtime %s)", getLoggedMessage(action), startedStr, durationStr);
}