Example usage for org.joda.time Duration toPeriod

List of usage examples for org.joda.time Duration toPeriod

Introduction

In this page you can find the example usage for org.joda.time Duration toPeriod.

Prototype

public Period toPeriod() 

Source Link

Document

Converts this duration to a Period instance using the standard period type and the ISO chronology.

Usage

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 . j  a  va2s.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 www  . j a va2  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 w  w. j av a 2 s.c o  m
    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:net.sf.jacclog.service.importer.commands.internal.ImportStatsShellCommand.java

License:Apache License

private void renderEntries(final LogFileImporterStatistic statistic) {
    if (statistic.getEntries() != null && !statistic.getEntries().isEmpty()) {
        final int size = (statistic.getEntries().get(0).getFile() != null)
                ? statistic.getEntries().get(0).getFile().getFile().getPath().length() + 8
                : 32;/*from www .  j  a  v  a 2 s .c  o  m*/
        final String format = "%-" + size + "s%10s%18s";
        final StringBuilder builder = new StringBuilder();
        builder.append('\n');
        final Formatter formatter = new Formatter(builder);
        formatter.format(format, "Path", "Count", "Elapsed time");
        builder.append('\n');

        String path;
        Period p;
        int totalCount = 0;
        Duration totalElapsedTime = new Duration(0);
        for (final Entry entry : statistic.getEntries()) {
            path = entry.getFile().getFile().getPath();
            p = entry.getElapsedTime();
            totalElapsedTime = totalElapsedTime.plus(p.toStandardDuration());
            totalCount += entry.getCount();
            formatter.format(format, path, entry.getCount(), p.toString(FORMATTER));
            builder.append('\n');
        }

        builder.append('\n');
        builder.append("Total imported entries: " + totalCount);
        builder.append('\n');
        builder.append("Total processing time: " + totalElapsedTime.toPeriod().toString(FORMATTER));
        builder.append('\n');

        System.out.println(builder);
    } else {
        System.out.println("No files have been recently imported.");
    }
}

From source file:org.apache.beam.runners.core.metrics.SimpleExecutionState.java

License:Apache License

@VisibleForTesting
static String formatDuration(Duration duration) {
    return DURATION_FORMATTER.print(duration.toPeriod());
}

From source file:org.apache.pig.Main.java

License:Apache License

private static void printScriptRunTime(DateTime startTime) {
    DateTime endTime = new DateTime();
    Duration duration = new Duration(startTime, endTime);
    Period period = duration.toPeriod().normalizedStandard(PeriodType.time());
    log.info("Pig script completed in " + PeriodFormat.getDefault().print(period) + " (" + duration.getMillis()
            + " ms)");
}

From source file:org.cook_e.cook_e.ui.StepDialogFragment.java

License:Open Source License

/**
 * Sets up and returns a View to be displayed in the dialog
 *
 * @return the view to display//from   ww w.  j a v a2 s  .  com
 */
private View createView() {
    final View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_step, null);

    mDescriptionField = (EditText) view.findViewById(R.id.description_field);
    mDurationField = (EditText) view.findViewById(R.id.duration_field);
    mIngredientsField = (EditText) view.findViewById(R.id.ingredients_field);

    // Extract data from arguments
    final Bundle args = getArguments();
    if (args != null) {
        // Description
        final String description = args.getString(ARG_DESCRIPTION);
        mDescriptionField.setText(description);

        // Duration
        final Duration duration = (Duration) args.getSerializable(ARG_DURATION);
        if (duration == null) {
            throw new IllegalStateException("No duration argument");
        }
        final Period period = duration.toPeriod();
        final String durationString = mFormatter.print(period);
        mDurationField.setText(durationString);

        // Ingredients
        final List<String> ingredients = args.getStringArrayList(ARG_INGREDIENTS);
        if (ingredients == null) {
            throw new IllegalStateException("No ingredients argument");
        }
        final StringBuilder ingredientsString = new StringBuilder();
        for (String ingredient : ingredients) {
            ingredientsString.append(ingredient);
            ingredientsString.append('\n');
        }
        mIngredientsField.setText(ingredientsString);
    }

    return view;
}

From source file:org.cook_e.cook_e.ui.TimerFragment.java

License:Open Source License

private void updateTimer(ReadableDuration remainingTime) {
    // Round the duration down to remove milliseconds
    final Duration roundedTime = roundDownToSecond(remainingTime);
    final Period remainingPeriod = roundedTime.toPeriod();
    mTimerView.setText(mFormatter.print(remainingPeriod));
    mRemainingTime = remainingTime;//from   ww  w.ja  va  2s . c  om
}

From source file:org.fenixedu.bennu.core.filters.ProfilingFilter.java

License:Open Source License

private void log(String uri, Duration duration) {
    logger.debug(String.format("[%s] - %s", ISOPeriodFormat.standard().print(duration.toPeriod()), uri));
}

From source file:org.hawkular.metrics.core.impl.DateTimeService.java

License:Apache License

public DateTime getTimeSlice(DateTime dt, Duration duration) {
    Period p = duration.toPeriod();

    if (p.getYears() != 0) {
        return dt.yearOfEra().roundFloorCopy().minusYears(dt.getYearOfEra() % p.getYears());
    } else if (p.getMonths() != 0) {
        return dt.monthOfYear().roundFloorCopy().minusMonths((dt.getMonthOfYear() - 1) % p.getMonths());
    } else if (p.getWeeks() != 0) {
        return dt.weekOfWeekyear().roundFloorCopy().minusWeeks((dt.getWeekOfWeekyear() - 1) % p.getWeeks());
    } else if (p.getDays() != 0) {
        return dt.dayOfMonth().roundFloorCopy().minusDays((dt.getDayOfMonth() - 1) % p.getDays());
    } else if (p.getHours() != 0) {
        return dt.hourOfDay().roundFloorCopy().minusHours(dt.getHourOfDay() % p.getHours());
    } else if (p.getMinutes() != 0) {
        return dt.minuteOfHour().roundFloorCopy().minusMinutes(dt.getMinuteOfHour() % p.getMinutes());
    } else if (p.getSeconds() != 0) {
        return dt.secondOfMinute().roundFloorCopy().minusSeconds(dt.getSecondOfMinute() % p.getSeconds());
    }//  w  w  w. j ava 2s .c om
    return dt.millisOfSecond().roundCeilingCopy().minusMillis(dt.getMillisOfSecond() % p.getMillis());
}