Example usage for org.joda.time Duration getStandardSeconds

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

Introduction

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

Prototype

public long getStandardSeconds() 

Source Link

Document

Gets the length of this duration in seconds assuming that there are the standard number of milliseconds in a second.

Usage

From source file:com.spotify.helios.cli.Output.java

License:Apache License

public static String humanDuration(final Duration dur) {
    final Period p = dur.toPeriod().normalizedStandard();

    if (dur.getStandardSeconds() == 0) {
        return "0 seconds";
    } else if (dur.getStandardSeconds() < 60) {
        return format("%d second%s", p.getSeconds(), p.getSeconds() > 1 ? "s" : "");
    } else if (dur.getStandardMinutes() < 60) {
        return format("%d minute%s", p.getMinutes(), p.getMinutes() > 1 ? "s" : "");
    } else if (dur.getStandardHours() < 24) {
        return format("%d hour%s", p.getHours(), p.getHours() > 1 ? "s" : "");
    } else {/*ww  w  .  ja  v  a  2s . c  om*/
        return format("%d day%s", dur.getStandardDays(), dur.getStandardDays() > 1 ? "s" : "");
    }
}

From source file:com.squarespace.template.plugins.PluginDateUtils.java

License:Apache License

public static void humanizeDate(long instantMs, long baseMs, String tzId, boolean showSeconds,
        StringBuilder buf) {//from   www. ja v a2  s  .c o  m
    DateTimeZone timeZone = DateTimeZone.forID(tzId);
    int offset = timeZone.getOffset(instantMs);
    Duration delta = new Duration(baseMs - instantMs + offset);

    int days = (int) delta.getStandardDays();
    int years = (int) Math.floor(days / 365.0);
    if (years > 0) {
        humanizeDatePlural(years, DatePartType.YEAR, buf);
        return;
    }
    int months = (int) Math.floor(days / 30.0);
    if (months > 0) {
        humanizeDatePlural(months, DatePartType.MONTH, buf);
        return;
    }
    int weeks = (int) Math.floor(days / 7.0);
    if (weeks > 0) {
        humanizeDatePlural(weeks, DatePartType.WEEK, buf);
        return;
    }
    if (days > 0) {
        humanizeDatePlural(days, DatePartType.DAY, buf);
        return;
    }
    int hours = (int) delta.getStandardHours();
    if (hours > 0) {
        humanizeDatePlural(hours, DatePartType.HOUR, buf);
        return;
    }
    int mins = (int) delta.getStandardMinutes();
    if (mins > 0) {
        humanizeDatePlural(mins, DatePartType.MINUTE, buf);
        return;
    }
    int secs = (int) delta.getStandardSeconds();
    if (showSeconds) {
        humanizeDatePlural(secs, DatePartType.SECOND, buf);
        return;
    }
    buf.append("less than a minute ago");
}

From source file:com.tomtom.speedtools.services.push.implementation.gcm.GCMConnector.java

License:Apache License

@Override
public PushToken push(@Nonnull final Notification notification, @Nonnull final PushToken pushToken)
        throws PushConnectionException, InvalidPushTokenException {
    assert notification != null;
    assert pushToken != null;

    LOG.debug("push: pushToken={}", pushToken);

    if (!gcmProperties.isEnabled()) {
        LOG.debug("sendPush: notification not sent because connector is disabled, pushToken={}",
                logId(pushToken.getToken()));
        return pushToken;
    }/*from w ww.  ja  v  a2  s. c  o m*/

    // Create a Sender.
    final Sender sender = new GCMSender(gcmProperties.getEndpoint(), gcmProperties.getApiKey());

    // Create the Message.
    final String pushMessage = notification.getMessage();
    final JsonRenderable jsonPayload = notification.getPayload();
    final Duration timeToLive = notification.getTimeToLive();

    Builder builder = new Builder().addData(KEY_TYPE, notification.getType());
    if (pushMessage != null) {
        builder = builder.addData(KEY_MESSAGE, pushMessage);
    }

    if (jsonPayload != null) {
        builder = builder.addData(KEY_PAYLOAD, jsonPayload.toJson());
    }

    if (timeToLive != null) {
        // The value of this parameter must be a duration from 0 to 2,419,200 seconds.
        final long seconds = timeToLive.getStandardSeconds();
        if ((seconds >= MIN_SECONDS_TO_LIVE) && (seconds <= MAX_SECONDS_TO_LIVE)) {
            //noinspection NumericCastThatLosesPrecision
            builder.timeToLive((int) seconds); // Safe cast.
        }
    }

    final Message message = builder.build();

    // Send the Message.
    final Result result;
    try {
        result = sender.send(message, pushToken.getToken(), gcmProperties.getRetries());
        LOG.debug("push: notification sent, message={}", message.toString());
    } catch (final IOException e) {
        LOG.error("push: unable to send message, pushToken={}", logId(pushToken.getToken()), e);
        throw new PushConnectionException(e);
    }

    if (result.getMessageId() != null) {
        LOG.debug("push: message delivered to GCM, pushToken={}", logId(pushToken.getToken()));
        final String canonicalRegId = result.getCanonicalRegistrationId();
        if (canonicalRegId != null) {

            /**
             * Same device has more than on registration ID: update database with new (canonical) registration id.
             * Make sure to replace the registration ID stored the system with this canonical ID, as eventually the ID you're using will stop working.
             */
            return new PushToken(canonicalRegId);
        } else {
            return pushToken;
        }
    } else {
        final String error = result.getErrorCodeName();
        LOG.error("push: message could not be delivered, pushToken={}, error={}", logId(pushToken.getToken()),
                error);
        if (error.equals(Constants.ERROR_NOT_REGISTERED)) {

            // Application has been removed from device. Invalidate push token.
            throw new InvalidPushTokenException(pushToken,
                    "Push token is invalid, application has been removed from device");
        }

        if (error.equals(Constants.ERROR_INVALID_REGISTRATION)) {

            // Application registered an invalid registration id. Invalidate push token.
            throw new InvalidPushTokenException(pushToken, "Push token is invalid");
        }

        throw new PushConnectionException("Notification could not be sent: " + error);
    }
}

From source file:com.worktoken.engine.TimeExpression.java

License:Apache License

/**
 * Calculates alarm date for time duration elements
 *
 * @return Alarm date or null, if alarm date is in the past
 *///w  w  w . jav a 2s  . c  o m
public Date calculateDurationAlarmDate() {
    DateTime now = new DateTime();
    if (endDate != null) {
        return endDate;
    }
    Date start;
    if (startDate != null) {
        start = startDate;
    } else if (duration != null) {
        start = now.toDate();
    } else {
        throw new IllegalStateException("Invalid duration definition");
    }
    Period period = new Period(duration);
    Duration dur = period.toStandardDuration();
    DateTime alarm;
    if (dur.getStandardSeconds() > 24 * 60 * 60) {
        alarm = new DateTime(start).plus(period);
    } else {
        alarm = new DateTime(start).plus(dur);
    }
    if (alarm.isBefore(now)) {
        return null;
    }
    return alarm.toDate();
}

From source file:data.DataService.java

License:Apache License

public InputStream exportData() {
    final DateTime start = DateTime.now();
    DataSource dataSource = DB.getDataSource(dataSourceName);
    final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    final String dbName = getDBName(dataSource);
    final String catalogName = getCatalogName(dataSource);
    ObjectMapper mapper = getObjectMapper();
    final JsonFactory factory = mapper.getFactory();

    PipedInputStream in = new PipedInputStream();
    try {//from  w w w.  j av  a  2  s  . c  om
        final PipedOutputStream out = new PipedOutputStream(in);
        new Thread(new Runnable() {
            public void run() {
                try {
                    JsonGenerator generator = factory.createGenerator(out, JsonEncoding.UTF8);
                    generator.setPrettyPrinter(new DefaultPrettyPrinter());
                    generator.writeStartObject();

                    for (Exchanger exchanger : exchangers) {
                        exchanger.exportData(dbName, catalogName, generator, jdbcTemplate);
                    }

                    generator.writeEndObject();
                    generator.close();

                    DateTime end = DateTime.now();
                    Duration duration = new Duration(start, end);
                    play.Logger.info("Data export took {{}}", duration.getStandardSeconds());
                } catch (IOException e) {
                    play.Logger.error("Failed to export data");
                }
            }
        }).start();
        return in;
    } catch (IOException e) {
        play.Logger.error("Failed to export data");
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:data.DataService.java

License:Apache License

public void importData(File file) throws IOException {
    DateTime start = DateTime.now();/*www . j  ava  2s . c  o m*/
    ObjectMapper mapper = getObjectMapper();
    JsonFactory factory = mapper.getFactory();
    JsonParser parser = factory.createParser(file);

    JsonToken current = parser.nextToken();
    if (current != JsonToken.START_OBJECT) {
        play.Logger.info("Data import failed cause of root if not an object.");
        return;
    }

    DataSource dataSource = DB.getDataSource(dataSourceName);
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    String dbName = getDBName(dataSource);
    disableReferentialIntegtiry(dbName, jdbcTemplate);
    String message = "";
    try {
        for (Exchanger exchanger : exchangers) {
            exchanger.importData(dbName, parser, jdbcTemplate);
        }
        message = "Data import done. it took {{}}";
    } catch (Exception e) {
        message = "Data import failed. it took {{}}";
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        enableReferentialIntegrity(dbName, jdbcTemplate);
        DateTime end = DateTime.now();
        Duration duration = new Duration(start, end);
        play.Logger.info(message, duration.getStandardSeconds());
    }
}

From source file:de.avanux.livetracker.statistics.TrackingStatistics.java

License:Open Source License

public float getAvgLocationMessagePeriod() {
    Duration duration = getDuration();
    if (duration != null) {
        return new Float(duration.getStandardSeconds()).floatValue()
                / new Float(this.locationMessagesCount - 1).floatValue();
    } else {//from  ww  w  .j  av a 2 s. c om
        return 0;
    }
}

From source file:de.avanux.livetracker.Tracker.java

License:Open Source License

public boolean isExpired() {
    Duration age = new Duration(this.lastSeen, new DateTime());
    if (age.getStandardSeconds() > (EXPIRATION_SECONDS + ADDITIONAL_REFRESH_SECONDS)) {
        return true;
    } else {//from  ww w.j  a  va 2  s  .c om
        return false;
    }
}

From source file:de.avanux.livetracker.Tracking.java

License:Open Source License

public void setLocationMessage(LocationMessage locationMessage) {
    if (this.locationMessage != null) {
        Duration duration = new Duration(this.locationMessage.getDate(), locationMessage.getDate());
        this.updateInterval = duration.getStandardSeconds();
        log.debug(this.trackingID + " updateInterval=" + this.updateInterval);
    }//from www  .  j  a va2  s  .  co  m
    this.statistics.updateLocationMessageStatistics(locationMessage);
    this.locationMessage = locationMessage;
}

From source file:de.avanux.livetracker.Tracking.java

License:Open Source License

public boolean isExpired(int expirationSeconds) {
    DateTime present = new DateTime();
    Duration inactivityPeriod = null;
    if (this.locationMessage != null) {
        inactivityPeriod = new Duration(this.locationMessage.getDate(), present);
    } else {/*w w w.ja  v a 2 s.com*/
        inactivityPeriod = new Duration(this.creationTime, present);
    }
    if (inactivityPeriod.getStandardSeconds() > expirationSeconds) {
        return true;
    } else {
        return false;
    }
}