Example usage for org.joda.time Period toString

List of usage examples for org.joda.time Period toString

Introduction

In this page you can find the example usage for org.joda.time Period toString.

Prototype

public String toString(PeriodFormatter formatter) 

Source Link

Document

Uses the specified formatter to convert this period to a String.

Usage

From source file:com.almende.bridge.resources.SimulatedResource.java

License:Apache License

private void addRouteProperties(Feature feature) {
    if (route != null) {
        feature.setProperty("eta", getEtaString());
        if (getEta().isAfterNow()) {
            Period period = new Duration(DateTime.now(), getEta()).toPeriod();
            feature.setProperty("minutesRemaining", period.toString(MINANDSECS));
            feature.setProperty("etaShort", getEta().toString("kk:mm:ss"));
        } else {//w w w . j a  v  a  2s .  c  om
            feature.setProperty("minutesRemaining", 0);
            feature.setProperty("etaShort", "00:00:00");
        }
    }
}

From source file:com.arpnetworking.tsdcore.sinks.KMonDSink.java

License:Apache License

/**
 * {@inheritDoc}/*from  w  w w.ja  v  a  2  s.c om*/
 */
@Override
protected Collection<byte[]> serialize(final PeriodicData periodicData) {
    final Period period = periodicData.getPeriod();
    final Multimap<String, AggregatedData> indexedData = prepareData(periodicData);
    final Multimap<String, Condition> indexedConditions = prepareConditions(periodicData.getConditions());

    // Serialize
    final List<byte[]> serializedData = Lists.newArrayListWithCapacity(indexedData.size());
    final StringBuilder stringBuilder = new StringBuilder();
    for (final String key : indexedData.keySet()) {
        final Collection<AggregatedData> namedData = indexedData.get(key);
        if (!namedData.isEmpty()) {
            stringBuilder.setLength(0);
            final AggregatedData first = Iterables.getFirst(namedData, null);
            final String name = new StringBuilder().append(first.getFQDSN().getService()).append("_")
                    .append(period.toString(ISOPeriodFormat.standard())).append("_")
                    .append(first.getFQDSN().getMetric()).toString();

            int maxStatus = 0;
            boolean hasAlert = false;
            final StringBuilder dataBuilder = new StringBuilder();
            for (final AggregatedData datum : namedData) {
                if (!datum.isSpecified()) {
                    continue;
                }

                dataBuilder.append(datum.getFQDSN().getStatistic().getName()).append("%3D")
                        .append(datum.getValue().getValue()).append("%3B");

                final String conditionKey = datum.getFQDSN().getService() + "_" + datum.getFQDSN().getMetric()
                        + "_" + datum.getFQDSN().getCluster() + "_" + datum.getFQDSN().getStatistic();
                for (final Condition condition : indexedConditions.get(conditionKey)) {
                    hasAlert = true;
                    maxStatus = serializeCondition(maxStatus, dataBuilder, datum, condition);
                }
            }

            // Don't send an empty payload
            if (dataBuilder.length() == 0) {
                continue;
            }

            stringBuilder.append("run_every=").append(period.toStandardSeconds().getSeconds())
                    .append("&has_alert=").append(hasAlert).append("&path=")
                    .append(first.getFQDSN().getCluster()).append("%2f")
                    .append(periodicData.getDimensions().get("host")).append("&monitor=").append(name)
                    .append("&status=").append(maxStatus).append("&timestamp=")
                    .append((int) Unit.SECOND.convert(periodicData.getStart().getMillis(), Unit.MILLISECOND))
                    .append("&output=").append(name).append("%7C").append(dataBuilder.toString());

            stringBuilder.setLength(stringBuilder.length() - 3);
            serializedData.add(stringBuilder.toString().getBytes(Charset.forName("UTF-8")));
        }
    }

    return serializedData;
}

From source file:com.arpnetworking.tsdcore.sinks.MonitordSink.java

License:Apache License

/**
 * {@inheritDoc}//from w w  w  .jav  a 2  s . c  om
 */
@Override
protected Collection<byte[]> serialize(final PeriodicData periodicData) {
    final Period period = periodicData.getPeriod();
    final Multimap<String, AggregatedData> indexedData = prepareData(periodicData);
    final Multimap<String, Condition> indexedConditions = prepareConditions(periodicData.getConditions());

    // Serialize
    final List<byte[]> serializedData = Lists.newArrayListWithCapacity(indexedData.size());
    final StringBuilder stringBuilder = new StringBuilder();
    for (final String key : indexedData.keySet()) {
        final Collection<AggregatedData> namedData = indexedData.get(key);
        if (!namedData.isEmpty()) {
            stringBuilder.setLength(0);
            final AggregatedData first = Iterables.getFirst(namedData, null);
            final String name = new StringBuilder().append(first.getFQDSN().getService()).append("_")
                    .append(period.toString(ISOPeriodFormat.standard())).append("_")
                    .append(first.getFQDSN().getMetric()).toString();

            int maxStatus = 0;
            final StringBuilder dataBuilder = new StringBuilder();
            for (final AggregatedData datum : namedData) {
                if (!datum.isSpecified()) {
                    continue;
                }

                dataBuilder.append(datum.getFQDSN().getStatistic().getName()).append("%3D")
                        .append(datum.getValue().getValue()).append("%3B");

                final String conditionKey = datum.getFQDSN().getService() + "_" + datum.getFQDSN().getMetric()
                        + "_" + datum.getFQDSN().getCluster() + "_" + datum.getFQDSN().getStatistic();
                for (final Condition condition : indexedConditions.get(conditionKey)) {
                    dataBuilder.append(datum.getFQDSN().getStatistic().getName()).append("_")
                            .append(condition.getName()).append("%3D")
                            .append(condition.getThreshold().getValue()).append("%3B");

                    if (condition.isTriggered().isPresent() && condition.isTriggered().get()) {
                        // Collect the status of this metric
                        final Object severity = condition.getExtensions().get("severity");
                        int status = _unknownSeverityStatus;
                        if (severity != null && _severityToStatus.containsKey(severity)) {
                            status = _severityToStatus.get(severity);
                        }
                        maxStatus = Math.max(status, maxStatus);
                    }
                }
            }

            // Don't send an empty payload
            if (dataBuilder.length() == 0) {
                continue;
            }

            stringBuilder.append("run_every=").append(period.toStandardSeconds().getSeconds()).append("&path=")
                    .append(first.getFQDSN().getCluster()).append("%2f")
                    .append(periodicData.getDimensions().get("host")).append("&monitor=").append(name)
                    .append("&status=").append(maxStatus).append("&timestamp=")
                    .append((int) Unit.SECOND.convert(periodicData.getStart().getMillis(), Unit.MILLISECOND))
                    .append("&output=").append(name).append("%7C").append(dataBuilder.toString());

            stringBuilder.setLength(stringBuilder.length() - 3);
            serializedData.add(stringBuilder.toString().getBytes(Charset.forName("UTF-8")));
        }
    }

    return serializedData;
}

From source file:com.arpnetworking.tsdcore.sinks.WavefrontSink.java

License:Apache License

private String buildMetricName(final FQDSN fqdsn, final Period period) {
    return fqdsn.getService() + "." + period.toString(ISOPeriodFormat.standard()) + "."
            + fqdsn.getMetric().replace("/", ".") + "." + fqdsn.getStatistic().getName().replace(".", "_");
}

From source file:com.talvish.tales.services.Service.java

License:Apache License

/**
 * Method called when the service is stopping.
 * Subclasses cannot override this, but should
 * override the onStop method.//from   ww  w.  j  a va 2s . c om
 */
public final void stop() {
    try {
        Preconditions.checkState(
                this.lifecycleState == ExecutionLifecycleState.STARTED
                        || this.lifecycleState == ExecutionLifecycleState.RUNNING
                        || this.lifecycleState == ExecutionLifecycleState.SUSPENDED,
                "Cannot stop the service when the status is '%s'.", this.lifecycleState);
        this.lifecycleState = ExecutionLifecycleState.STOPPING;
        logger.info("Stopping service '{}'.", canonicalName);
        listeners.onStopping(this, this.lifecycleState);

        Period executionPeriod;

        // now we shutdown all of the interfaces
        logger.info("Stopping all interfaces.");
        this.interfaceManager.stop();

        // now let subclasses override, if any
        onStop();
        executionPeriod = status.calculateRunningTime();
        status.recordStop();
        this.lifecycleState = ExecutionLifecycleState.STOPPED;
        logger.info("Stopped service '{}' (ran for {}).", canonicalName,
                executionPeriod.toString(timeFormatter));
        listeners.onStopped(this, this.lifecycleState);

    } catch (Exception e) {
        logger.error("Forcing service exit during stop due to exception.", e);
        System.exit(1);
    }
}

From source file:com.thinkbiganalytics.DateTimeUtil.java

License:Apache License

public static String formatPeriod(Period period) {
    return period.toString(STANDARD_PERIOD_FORMAT);
}

From source file:com.twigasoft.templates.MinimalWorkingExample.java

public static String getTimestampDiff(Timestamp t) {
    final DateTime start = new DateTime(date.getTime());
    final DateTime end = new DateTime(t);
    Period p = new Period(start, end);
    PeriodFormatter formatter = new PeriodFormatterBuilder().printZeroAlways().minimumPrintedDigits(2)
            .appendYears().appendSuffix(" year", " years").appendSeparator(", ").appendMonths()
            .appendSuffix(" month", " months").appendSeparator(", ").appendDays().appendSuffix(" day", " days")
            .appendSeparator(" and ").appendHours().appendLiteral(":").appendMinutes().appendLiteral(":")
            .appendSeconds().toFormatter();
    return p.toString(formatter);
}

From source file:net.bashtech.geobot.MessageReplaceParser.java

License:Open Source License

public static String handleUntil(String message, String prefix, String suffix, PeriodFormatter formatter) {

    int commandStart = message.indexOf(prefix);
    int commandEnd = message.indexOf(suffix);

    if (commandStart + prefix.length() < commandEnd) {

        String replaced = message.substring(commandStart, commandEnd + suffix.length());
        String dateStr = message.substring(commandStart + prefix.length(), commandEnd);

        DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm");
        String until;//w ww.  j  ava  2 s.  com
        try {
            DateTime future = fmt.parseDateTime(dateStr);

            PeriodType pType = PeriodType.dayTime().withMillisRemoved().withSecondsRemoved();

            Period period = new Period(new DateTime(), future, pType);

            until = period.toString(formatter);

        } catch (IllegalArgumentException e) {
            until = "Unknown date";
            System.out.println(dateStr);
            e.printStackTrace();
        }

        message = message.replace(replaced, until);
    }
    return message;
}

From source file:net.sf.jacclog.service.analyzer.commands.internal.AnalyzeLogEntriesShellCommand.java

License:Apache License

private void analyzeEntries() {
    if (service != null) {
        final DateTimeFormatter format = DateTimeFormat.forPattern("yyyyMMdd");
        final DateTime from = format.parseDateTime(this.from);
        final DateTime to = (this.to != null) ? format.parseDateTime(this.to) : from.plusDays(1);
        final Interval interval = new Interval(from, to);
        final Period period = interval.toPeriod();

        final StringBuffer buffer = new StringBuffer();
        buffer.append("Analyse the log entries from '");
        buffer.append(from.toString()).append('\'');
        buffer.append(" to '").append(to);

        // print the period
        final String space = " ";
        buffer.append("'. The period includes ");
        final PeriodFormatter dateFormat = new PeriodFormatterBuilder().appendYears()
                .appendSuffix(" year", " years").appendSeparator(space).appendMonths()
                .appendSuffix(" month", " months").appendSeparator(space).appendWeeks()
                .appendSuffix(" week", " weeks").appendSeparator(space).appendDays()
                .appendSuffix(" day", " days").appendSeparator(space).appendHours()
                .appendSuffix(" hour", " hours").appendSeparator(space).appendMinutes()
                .appendSuffix(" minute", " minutes").appendSeparator(space).toFormatter();
        dateFormat.printTo(buffer, period);
        buffer.append('.');

        System.out.println(buffer.toString());

        final long maxResults = service.count(interval);
        if (maxResults > 0) {
            int maxCount = 0;
            if (proceed(maxResults)) {
                final long startTime = System.currentTimeMillis();

                final LogEntryAnalysisResult result = analyzerService.analyze(interval).toResult();
                final Map<UserAgentInfo, AtomicInteger> stats = result.getUserAgentInfos();
                System.out.println("User agent information count: " + stats.size());

                String name;//  w w  w .j  av a  2 s  .c  o m
                String osName;
                int count;
                for (final Entry<UserAgentInfo, AtomicInteger> entry : stats.entrySet()) {
                    name = entry.getKey().getName();
                    osName = entry.getKey().getOsName();
                    count = entry.getValue().get();
                    maxCount += count;
                    System.out.println(name + " (" + osName + ") \t" + count);
                }
                System.out.println("Sum: " + maxCount);

                final long elapsedTime = System.currentTimeMillis() - startTime;
                final Period p = new Period(elapsedTime);
                System.out.println("Total processing time: " + p.toString(FORMATTER));
            }
        } else {
            System.out.println("There is nothing to analyze.");
        }
    }
}

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  w  w  w  . j  a  v  a2  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.");
    }
}