Example usage for org.joda.time Duration getStandardHours

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

Introduction

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

Prototype

public long getStandardHours() 

Source Link

Document

Gets the length of this duration in hours assuming that there are the standard number of milliseconds in an hour.

Usage

From source file:com.pushinginertia.commons.ui.TimePeriod.java

License:Open Source License

public TimePeriod(final Duration duration) {
    ValidateAs.notNull(duration, "duration");
    final long days = duration.getStandardDays();

    // about 30.4 days in a month
    // N days: if dayCount <= 31
    // N weeks: if 31 < dayCount <= 61 and
    // N months: if 61 < dayCount
    final StringBuilder key = new StringBuilder("TimePeriod.");
    if (days < 1) {
        final long minutes = duration.getStandardMinutes();
        if (minutes < 60) {
            quantity = minutes;/*from w  w  w. j a v a2 s . com*/
            key.append("Minute");
        } else {
            quantity = duration.getStandardHours();
            key.append("Hour");
        }
    } else if (days <= 31) {
        quantity = days;
        key.append("Day");
    } else if (days <= 61) {
        quantity = MathUtils.integerDivisionRound(days, 7);
        key.append("Week");
    } else {
        quantity = MathUtils.integerDivisionRound(days, 30);
        key.append("Month");
    }
    if (quantity != 1)
        key.append('s');
    descriptorResourceKey = key.toString();
}

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 {//from  w  w w.j av a  2s.  co  m
        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  ww w.  j av a  2s . 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:de.appsolve.padelcampus.controller.bookings.BookingsController.java

private void validateBookingCancellation(Booking booking) throws Exception {
    if (booking == null) {
        throw new Exception(msg.get("InvalidBooking"));
    }//  ww  w  . j av  a 2 s . c om
    if (booking.getCancelled()) {
        throw new Exception(msg.get("BookingAlreadyCancelled"));
    }
    if (booking.getOffer() == null) {
        throw new Exception(msg.get("BookingCannotBeCancelled"));
    }
    LocalDateTime now = new LocalDateTime(DEFAULT_TIMEZONE);
    LocalDateTime bookingTime = new LocalDateTime().withDate(booking.getBookingDate().getYear(),
            booking.getBookingDate().getMonthOfYear(), booking.getBookingDate().getDayOfMonth()).withTime(
                    booking.getBookingTime().getHourOfDay(), booking.getBookingTime().getMinuteOfHour(), 0, 0);
    if (now.isAfter(bookingTime)) {
        throw new Exception(msg.get("BookingCancellationDeadlineMissed"));
    }

    Duration duration = new Duration(now.toDateTime(DateTimeZone.UTC),
            bookingTime.toDateTime(DateTimeZone.UTC));
    if (duration.getStandardHours() < CANCELLATION_POLICY_DEADLINE) {
        throw new Exception(msg.get("BookingCancellationDeadlineMissed"));
    }
}

From source file:de.fatalix.bookery.App.java

License:Open Source License

public void userLoggedIn(@Observes(notifyObserver = Reception.IF_EXISTS) UserLoggedInEvent event) {
    AppUser user = userService.updateLastLogin(event.getUsername());

    if (user.getLastLogin() != null) {
        DateTime dtLastLogin = new DateTime(user.getLastLogin());
        DateTime dtCurrentLogin = new DateTime(user.getCurrentLogin());
        Duration duration = new Duration(dtLastLogin, dtCurrentLogin);
        String sinceLastLogin = "";
        if (duration.getStandardDays() > 0) {
            long days = duration.getStandardDays();
            if (days == 1) {
                sinceLastLogin = days + " day";
            } else {
                sinceLastLogin = days + " days";
            }// w  w  w. j  ava2s  .  com
        } else if (duration.getStandardHours() > 0) {
            long hours = duration.getStandardHours();
            if (hours == 1) {
                sinceLastLogin = hours + " hour";
            } else {
                sinceLastLogin = hours + " hours";
            }
        } else if (duration.getStandardMinutes() > 0) {
            long minutes = duration.getStandardMinutes();
            if (minutes == 1) {
                sinceLastLogin = minutes + " minute";
            } else {
                sinceLastLogin = minutes + " minutes";
            }
        } else {
            long seconds = duration.getStandardSeconds();
            if (seconds == 1) {
                sinceLastLogin = seconds + " second";
            } else {
                sinceLastLogin = seconds + " seconds";
            }
        }
        Notification.show("Welcome back " + event.getUsername() + " after " + sinceLastLogin + ".");
    } else {
        Notification.show("Welcome " + event.getUsername());
    }

    logger.info("User " + event.getUsername() + " logged in.");
    getNavigator().navigateTo(HomeView.id);
    appLayout.getAppHeader().setLoginName(SecurityUtils.getSubject().getPrincipal().toString());
    appLayout.getAppHeader().setVisible(isLoggedIn());

}

From source file:de.minecrawler.cache.CacheManager.java

License:Open Source License

/**
 * @param index//w w w  . ja v a 2s  . com
 *            Index to check
 * @return <code>true</code> when the cache is expired, otherwhise
 *         <code>false</code>
 */
private boolean isExpired(CacheIndex index) {

    Duration dur = new Duration(index.creationDate, null);
    return dur.getStandardHours() >= EXPIRE_HOUR;
}

From source file:dk.dma.ais.view.rest.AisStoreResource.java

License:Apache License

/**
 * Search data from AisStore and generate KMZ output.
 * /*from   w ww  . ja va  2  s .c om*/
 * @param area
 *            extract AisPackets from AisStore inside this area.
 * @param interval
 *            extract AisPackets from AisStore inside this time interval.
 * @param title
 *            Stamp this title into the generated KML (optional).
 * @param description
 *            Stamp this description into the generated KML (optional).
 * @param primaryMmsi
 *            Style this MMSI as the primary target in the scenario
 *            (optional).
 * @param secondaryMmsi
 *            Style this MMSI as the secondary target in the scenario
 *            (optional).
 * @param snapshotAt
 *            Generate a KML snapshot folder for exactly this point in time
 *            (optional).
 * @param interpolationStepSecs
 *            Interpolate targets between AisPackets using this time step in
 *            seconds (optional).
 * @return HTTP response carrying KML for Google Earth
 */
@SuppressWarnings("unchecked")
private Response scenarioKmz(final BoundingBox area, final Interval interval, final String title,
        final String description, final boolean createSituationFolder, final boolean createMovementsFolder,
        final boolean createTracksFolder, final Integer primaryMmsi, final Integer secondaryMmsi,
        final DateTime snapshotAt, final Integer interpolationStepSecs) {

    // Pre-check input
    final Duration duration = interval.toDuration();
    final long hours = duration.getStandardHours();
    final long minutes = duration.getStandardMinutes();
    if (hours > 60) {
        throw new IllegalArgumentException("Queries spanning more than 6 hours are not allowed.");
    }

    final float size = area.getArea();
    if (size > 2500.0 * 1e6) {
        throw new IllegalArgumentException(
                "Queries spanning more than 2500 square kilometers are not allowed.");
    }

    LOG.info("Preparing KML for span of " + hours + " hours + " + minutes + " minutes and " + (float) size
            + " square kilometers.");

    // Create the query
    //AisStoreQueryBuilder b = AisStoreQueryBuilder.forTime(); // Cannot use
    // getArea
    // because this
    // removes all
    // type 5
    AisStoreQueryBuilder b = AisStoreQueryBuilder.forArea(area);
    b.setFetchSize(200);

    b.setInterval(interval);

    // Execute the query
    AisStoreQueryResult queryResult = get(CassandraConnection.class).execute(b);

    // Apply filters
    Iterable<AisPacket> filteredQueryResult = Iterables.filter(queryResult,
            AisPacketFilters.filterOnMessageId(1, 2, 3, 5, 18, 19, 24));
    filteredQueryResult = Iterables.filter(filteredQueryResult,
            AisPacketFilters.filterRelaxedOnMessagePositionWithin(area));

    if (!filteredQueryResult.iterator().hasNext()) {
        LOG.warn("No AIS data matching criteria.");
    }

    Predicate<? super AisPacket> isPrimaryMmsi = primaryMmsi == null ? e -> true
            : aisPacket -> aisPacket.tryGetAisMessage().getUserId() == primaryMmsi.intValue();

    Predicate<? super AisPacket> isSecondaryMmsi = secondaryMmsi == null ? e -> true
            : aisPacket -> aisPacket.tryGetAisMessage().getUserId() == secondaryMmsi.intValue();

    Predicate<? super AisPacket> triggerSnapshot = snapshotAt != null ? new Predicate<AisPacket>() {
        private final long snapshotAtMillis = snapshotAt.getMillis();
        private boolean snapshotGenerated;

        @Override
        public boolean test(AisPacket aisPacket) {
            boolean generateSnapshot = false;
            if (!snapshotGenerated) {
                if (aisPacket.getBestTimestamp() >= snapshotAtMillis) {
                    generateSnapshot = true;
                    snapshotGenerated = true;
                }
            }
            return generateSnapshot;
        }
    } : e -> true;

    Supplier<? extends String> supplySnapshotDescription = () -> {
        return "<table width=\"300\"><tr><td><h4>" + title + "</h4></td></tr><tr><td><p>" + description
                + "</p></td></tr></table>";
    };

    Supplier<? extends String> supplyTitle = title != null ? () -> title : null;

    Supplier<? extends String> supplyDescription = description != null ? () -> description : null;

    Supplier<? extends Integer> supplyInterpolationStep = interpolationStepSecs != null
            ? () -> interpolationStepSecs
            : null;

    final OutputStreamSink<AisPacket> kmzSink = AisPacketOutputSinks.newKmzSink(e -> true,
            createSituationFolder, createMovementsFolder, createTracksFolder, isPrimaryMmsi, isSecondaryMmsi,
            triggerSnapshot, supplySnapshotDescription, supplyInterpolationStep, supplyTitle, supplyDescription,
            null);

    return Response.ok().entity(StreamingUtil.createStreamingOutput(filteredQueryResult, kmzSink))
            .type(MEDIA_TYPE_KMZ).header("Content-Disposition", "attachment; filename = \"scenario.kmz\"")
            .build();
}

From source file:julian.lylly.model.Util.java

public static String durationToHourMinuteString(Duration duration) {
    long h = duration.getStandardHours();
    long m = duration.getStandardMinutes() % 60;
    return longTo2DigitString(h) + ":" + longTo2DigitString(m);
}

From source file:julian.lylly.model.Util.java

public static String durationToHourMinuteSecondString(Duration duration) {
    long h = duration.getStandardHours();
    long m = duration.getStandardMinutes() % 60;
    long s = duration.getStandardSeconds() % 60;
    return longTo2DigitString(h) + ":" + longTo2DigitString(m) + ":" + longTo2DigitString(s);
}

From source file:org.graylog2.utilities.SearchUtils.java

License:Open Source License

public static Searches.DateHistogramInterval buildInterval(@Nullable final String intervalParam,
        final TimeRange timeRange) {
    if (!isNullOrEmpty(intervalParam)) {
        final String interval = intervalParam.toUpperCase(Locale.ENGLISH);
        if (!validateInterval(interval)) {
            throw new IllegalArgumentException("Invalid interval: \"" + interval + "\"");
        }//  w  ww.  jav a  2  s  .c  om

        return Searches.DateHistogramInterval.valueOf(interval);
    }

    final Duration duration = Duration.millis(timeRange.getTo().getMillis() - timeRange.getFrom().getMillis());

    // This is the same as SearchPage#_determineHistogramResolution() in the UI code
    if (duration.getStandardHours() < 12) {
        return Searches.DateHistogramInterval.MINUTE;
    } else if (duration.getStandardDays() < 3) {
        return Searches.DateHistogramInterval.HOUR;
    } else if (duration.getStandardDays() < 30) {
        return Searches.DateHistogramInterval.DAY;
    } else if (duration.getStandardDays() < (30 * 2)) {
        return Searches.DateHistogramInterval.WEEK;
    } else if (duration.getStandardDays() < (30 * 18)) {
        return Searches.DateHistogramInterval.MONTH;
    } else if (duration.getStandardDays() < (365 * 3)) {
        return Searches.DateHistogramInterval.QUARTER;
    } else {
        return Searches.DateHistogramInterval.YEAR;
    }
}