Example usage for org.joda.time MutableDateTime getMillis

List of usage examples for org.joda.time MutableDateTime getMillis

Introduction

In this page you can find the example usage for org.joda.time MutableDateTime getMillis.

Prototype

public long getMillis() 

Source Link

Document

Gets the milliseconds of the datetime instant from the Java epoch of 1970-01-01T00:00:00Z.

Usage

From source file:org.graylog2.indexer.results.FieldHistogramResult.java

License:Open Source License

public Map<Long, Map<String, Number>> getResults() {
    if (result.getBuckets().isEmpty()) {
        return Collections.emptyMap();
    }/*from ww  w.j a v  a  2 s.c  o m*/

    final Map<Long, Map<String, Number>> results = Maps.newTreeMap();
    for (DateHistogram.Bucket b : result.getBuckets()) {
        final ImmutableMap.Builder<String, Number> resultMap = ImmutableMap.builder();
        resultMap.put("total_count", b.getDocCount());

        final Stats stats = b.getAggregations().get(Searches.AGG_STATS);
        resultMap.put("count", stats.getCount());
        resultMap.put("min", stats.getMin());
        resultMap.put("max", stats.getMax());
        resultMap.put("total", stats.getSum());
        resultMap.put("mean", stats.getAvg());

        // cardinality is only calculated if it was explicitly requested, so this might be null
        final Cardinality cardinality = b.getAggregations().get(Searches.AGG_CARDINALITY);
        resultMap.put("cardinality", cardinality == null ? 0 : cardinality.getValue());

        final long timestamp = b.getKeyAsDate().getMillis() / 1000L;
        results.put(timestamp, resultMap.build());
    }

    final long minTimestamp = Collections.min(results.keySet());
    final long maxTimestamp = Collections.max(results.keySet());
    final MutableDateTime currentTime = new MutableDateTime(minTimestamp, DateTimeZone.UTC);

    while (currentTime.getMillis() < maxTimestamp) {
        final Map<String, Number> entry = results.get(currentTime.getMillis());

        // advance timestamp by the interval's seconds value
        currentTime.add(interval.getPeriod());

        if (entry == null) {
            // synthesize a 0 value for this timestamp
            results.put(currentTime.getMillis(), EMPTY_RESULT);
        }
    }
    return results;
}

From source file:org.n52.sos.cache.quartz.QuartzCacheScheduler.java

License:Apache License

public QuartzCacheScheduler(AccessGDB geoDB, boolean updateCacheOnStartup, LocalTime cacheUpdateTime) {
    super(geoDB, updateCacheOnStartup, cacheUpdateTime);

    try {//from  www.j  a  va  2s  .com
        this.quartz = new StdSchedulerFactory().getScheduler();
        this.quartzFactory = new LocalJobFactory();
        this.quartz.setJobFactory(this.quartzFactory);
        this.quartz.start();
    } catch (SchedulerException e) {
        LOGGER.warn("Could not initialize cache scheduling", e);
        return;
    }

    if (!updateCacheOnStartup) {
        LOGGER.info("Update cache on startup disabled!");
    } else {
        try {
            schedule(new UpdateCacheTask(getCandidates()), 0);
            //            List<AbstractEntityCache<?>> requiresUpdates = cacheUpdateRequired();
            //            if (!requiresUpdates.isEmpty()) {
            //               LOGGER.info(String.format("Cache update required for: %s", requiresUpdates.toString()));
            //               /*
            //                * now
            //                */
            //               schedule(new UpdateCacheTask(requiresUpdates), 0);   
            //            }
            //            else {
            //               LOGGER.info("No cache update required. Last update not longer ago than minutes "+FIFTEEN_MINS_MS/(1000*60));
            //            }
        } catch (SchedulerException e) {
            LOGGER.warn(e.getMessage(), e);
            LOGGER.warn("could not initialize cache. disabling scheduled updates.");
            return;
        }
    }

    MutableDateTime mdt = resolveNextScheduleDate(this.getCacheUpdateTime(), new DateTime());
    DateTime now = new DateTime();

    try {
        //         schedule(new UpdateCacheTask(getCandidates()), ONE_HOUR_MS,
        //               ONE_HOUR_MS);
        schedule(new UpdateCacheTask(getCandidates()), mdt.getMillis() - now.getMillis(), ONE_HOUR_MS * 24);
    } catch (SchedulerException e) {
        LOGGER.warn(e.getMessage(), e);
    }

    LOGGER.severe("Next scheduled cache update: " + mdt.toString());

    /*
     * start ONE monitoring after 1 minute and check if the .lock file
     * is older than 30 minutes -> an artifact .lock file!!
     */
    try {
        schedule(new MonitorCacheTask(ONE_HOUR_MS / 2), ONE_HOUR_MS / 60);
    } catch (SchedulerException e) {
        LOGGER.warn(e.getMessage(), e);
    }
}

From source file:org.talend.components.netsuite.avro.converter.XMLGregorianCalendarToDateTimeConverter.java

License:Open Source License

@Override
public XMLGregorianCalendar convertToDatum(Object timestamp) {
    if (timestamp == null) {
        return null;
    }//  ww w . j  av  a 2 s  .c om

    long timestampMillis;
    if (timestamp instanceof Long) {
        timestampMillis = ((Long) timestamp).longValue();
    } else if (timestamp instanceof Date) {
        timestampMillis = ((Date) timestamp).getTime();
    } else {
        throw new IllegalArgumentException("Unsupported Avro timestamp value: " + timestamp);
    }

    MutableDateTime dateTime = new MutableDateTime();
    dateTime.setMillis(timestampMillis);

    XMLGregorianCalendar xts = datatypeFactory.newXMLGregorianCalendar();
    xts.setYear(dateTime.getYear());
    xts.setMonth(dateTime.getMonthOfYear());
    xts.setDay(dateTime.getDayOfMonth());
    xts.setHour(dateTime.getHourOfDay());
    xts.setMinute(dateTime.getMinuteOfHour());
    xts.setSecond(dateTime.getSecondOfMinute());
    xts.setMillisecond(dateTime.getMillisOfSecond());
    xts.setTimezone(dateTime.getZone().toTimeZone().getOffset(dateTime.getMillis()) / 60000);

    return xts;
}

From source file:org.talend.components.netsuite.avro.converter.XMLGregorianCalendarToDateTimeConverter.java

License:Open Source License

@Override
public Object convertToAvro(XMLGregorianCalendar xts) {
    if (xts == null) {
        return null;
    }//w  w w.  jav  a 2 s  . co m

    MutableDateTime dateTime = new MutableDateTime();
    try {
        dateTime.setYear(xts.getYear());
        dateTime.setMonthOfYear(xts.getMonth());
        dateTime.setDayOfMonth(xts.getDay());
        dateTime.setHourOfDay(xts.getHour());
        dateTime.setMinuteOfHour(xts.getMinute());
        dateTime.setSecondOfMinute(xts.getSecond());
        dateTime.setMillisOfSecond(xts.getMillisecond());

        DateTimeZone tz = DateTimeZone.forOffsetMillis(xts.getTimezone() * 60000);
        if (tz != null) {
            dateTime.setZoneRetainFields(tz);
        }

        return Long.valueOf(dateTime.getMillis());
    } catch (IllegalArgumentException e) {
        throw new ComponentException(e);
    }
}

From source file:org.wicketstuff.datetime.extensions.yui.calendar.DateTimeField.java

License:Apache License

/**
 * Sets the converted input, which is an instance of {@link Date}, possibly null. It combines
 * the inputs of the nested date, hours, minutes and am/pm fields and constructs a date from it.
 * <p>/* w  w w  . j a  va2  s.c om*/
 * Note that overriding this method is a better option than overriding {@link #updateModel()}
 * like the first versions of this class did. The reason for that is that this method can be
 * used by form validators without having to depend on the actual model being updated, and this
 * method is called by the default implementation of {@link #updateModel()} anyway (so we don't
 * have to override that anymore).
 */
@Override
public void convertInput() {
    try {
        // Get the converted input values
        Date dateFieldInput = dateField.getConvertedInput();
        Integer hoursInput = hoursField.getConvertedInput();
        Integer minutesInput = minutesField.getConvertedInput();
        AM_PM amOrPmInput = amOrPmChoice.getConvertedInput();

        if (dateFieldInput == null) {
            return;
        }

        // Get year, month and day ignoring any timezone of the Date object
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateFieldInput);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hours = (hoursInput == null ? 0 : hoursInput % 24);
        int minutes = (minutesInput == null ? 0 : minutesInput);

        // Use the input to create a date object with proper timezone
        MutableDateTime date = new MutableDateTime(year, month, day, hours, minutes, 0, 0,
                DateTimeZone.forTimeZone(getClientTimeZone()));

        // Adjust for halfday if needed
        if (use12HourFormat()) {
            int halfday = (amOrPmInput == AM_PM.PM ? 1 : 0);
            date.set(DateTimeFieldType.halfdayOfDay(), halfday);
            date.set(DateTimeFieldType.hourOfHalfday(), hours % 12);
        }

        // The date will be in the server's timezone
        setConvertedInput(newDateInstance(date.getMillis()));
    } catch (RuntimeException e) {
        DateTimeField.this.error(e.getMessage());
        invalid();
    }
}

From source file:org.wso2.analytics.esb.util.TimeRangeUtils.java

License:Open Source License

public static List<TimeRange> getDateTimeRanges(long from, long to) {
    List<TimeRange> ranges = new ArrayList<>(10);
    MutableDateTime fromDate = new MutableDateTime(from);
    fromDate.set(DateTimeFieldType.millisOfSecond(), 0);
    MutableDateTime toDate = new MutableDateTime(to);
    toDate.set(DateTimeFieldType.millisOfSecond(), 0);
    MutableDateTime tempFromTime = fromDate.copy();
    MutableDateTime tempToTime = toDate.copy();

    if (log.isDebugEnabled()) {
        log.debug("Time range: " + formatter.format(fromDate.toDate()) + " -> "
                + formatter.format(toDate.toDate()));
    }// w  w  w  . j  a  va  2s . co  m

    if (toDate.getMillis() - fromDate.getMillis() < DateTimeConstants.MILLIS_PER_MINUTE) {
        ranges.add(new TimeRange(RangeUnit.SECOND.name(),
                new long[] { fromDate.getMillis(), toDate.getMillis() }));
    } else {
        if (tempFromTime.getSecondOfMinute() != 0
                && (toDate.getMillis() - fromDate.getMillis() > DateTimeConstants.MILLIS_PER_MINUTE)) {
            tempFromTime = tempFromTime.minuteOfHour().roundCeiling();
            ranges.add(new TimeRange(RangeUnit.SECOND.name(),
                    new long[] { fromDate.getMillis(), tempFromTime.getMillis() }));
        }
        if (tempFromTime.getMinuteOfHour() != 0
                && ((toDate.getMillis() - tempFromTime.getMillis()) >= DateTimeConstants.MILLIS_PER_MINUTE)) {
            fromDate = tempFromTime.copy();
            if (((toDate.getMillis() - tempFromTime.getMillis()) / DateTimeConstants.MILLIS_PER_MINUTE) < 60) {
                tempFromTime = tempFromTime.minuteOfHour().add(
                        (toDate.getMillis() - tempFromTime.getMillis()) / DateTimeConstants.MILLIS_PER_MINUTE);
            } else {
                tempFromTime = tempFromTime.hourOfDay().roundCeiling();
            }
            ranges.add(new TimeRange(RangeUnit.MINUTE.name(),
                    new long[] { fromDate.getMillis(), tempFromTime.getMillis() }));
        }
        if (tempFromTime.getHourOfDay() != 0
                && ((toDate.getMillis() - tempFromTime.getMillis()) >= DateTimeConstants.MILLIS_PER_HOUR)) {
            fromDate = tempFromTime.copy();
            if (((toDate.getMillis() - tempFromTime.getMillis()) / DateTimeConstants.MILLIS_PER_HOUR) < 24) {
                tempFromTime = tempFromTime.hourOfDay().add(
                        (toDate.getMillis() - tempFromTime.getMillis()) / DateTimeConstants.MILLIS_PER_HOUR);
            } else {
                tempFromTime = tempFromTime.dayOfMonth().roundCeiling();
            }
            ranges.add(new TimeRange(RangeUnit.HOUR.name(),
                    new long[] { fromDate.getMillis(), tempFromTime.getMillis() }));
        }
        if (tempFromTime.getDayOfMonth() != 1
                && ((toDate.getMillis() - tempFromTime.getMillis()) >= DateTimeConstants.MILLIS_PER_DAY)) {
            fromDate = tempFromTime.copy();
            if ((((toDate.getMillis() - tempFromTime.getMillis())
                    / DateTimeConstants.MILLIS_PER_DAY)) < tempFromTime.dayOfMonth().getMaximumValue()) {
                tempFromTime = tempFromTime.dayOfMonth().add(((toDate.getMillis() - tempFromTime.getMillis())
                        / ((long) DateTimeConstants.MILLIS_PER_DAY)));
            } else {
                tempFromTime = tempFromTime.monthOfYear().roundCeiling();
            }
            ranges.add(new TimeRange(RangeUnit.DAY.name(),
                    new long[] { fromDate.getMillis(), tempFromTime.getMillis() }));
        }
        if (tempToTime.getSecondOfMinute() != 0
                && (tempToTime.getMillis() - tempFromTime.getMillis()) >= DateTimeConstants.MILLIS_PER_SECOND) {
            toDate = tempToTime.copy();
            long remainingSeconds = ((toDate.getMillis() - tempFromTime.getMillis())
                    % DateTimeConstants.MILLIS_PER_MINUTE) / DateTimeConstants.MILLIS_PER_SECOND;
            if (remainingSeconds < 60) {
                tempToTime = tempToTime.secondOfMinute().add(-1 * remainingSeconds);

            } else {
                tempToTime = tempToTime.secondOfMinute().roundFloor();
            }
            ranges.add(new TimeRange(RangeUnit.SECOND.name(),
                    new long[] { tempToTime.getMillis(), toDate.getMillis() }));
        }
        if (tempToTime.getMinuteOfHour() != 0 && ((tempToTime.getMillis()
                - tempFromTime.getMillis()) >= DateTimeConstants.MILLIS_PER_MINUTE)) {
            toDate = tempToTime.copy();
            long remainingMinutes = ((toDate.getMillis() - tempFromTime.getMillis())
                    % DateTimeConstants.MILLIS_PER_HOUR) / DateTimeConstants.MILLIS_PER_MINUTE;
            if (remainingMinutes < 60) {
                tempToTime = tempToTime.minuteOfHour().add(-1 * remainingMinutes);
            } else {
                tempToTime = tempToTime.hourOfDay().roundFloor();
            }
            ranges.add(new TimeRange(RangeUnit.MINUTE.name(),
                    new long[] { tempToTime.getMillis(), toDate.getMillis() }));
        }
        if (tempToTime.getHourOfDay() != 0
                && ((tempToTime.getMillis() - tempFromTime.getMillis()) >= DateTimeConstants.MILLIS_PER_HOUR)) {
            toDate = tempToTime.copy();
            long remainingHours = ((toDate.getMillis() - tempFromTime.getMillis())
                    % DateTimeConstants.MILLIS_PER_DAY) / DateTimeConstants.MILLIS_PER_HOUR;
            if (remainingHours < 24) {
                tempToTime = tempToTime.hourOfDay().add(-1 * remainingHours);
            } else {
                tempToTime = tempToTime.dayOfMonth().roundFloor();
            }
            ranges.add(new TimeRange(RangeUnit.HOUR.name(),
                    new long[] { tempToTime.getMillis(), toDate.getMillis() }));
        }
        if (tempToTime.getDayOfMonth() != 1
                && ((tempToTime.getMillis() - tempFromTime.getMillis()) >= DateTimeConstants.MILLIS_PER_DAY)) {
            toDate = tempToTime.copy();
            tempToTime = tempToTime.monthOfYear().roundFloor();
            ranges.add(new TimeRange(RangeUnit.DAY.name(),
                    new long[] { tempToTime.getMillis(), toDate.getMillis() }));
        }
        if (tempToTime.isAfter(tempFromTime)) {
            ranges.add(new TimeRange(RangeUnit.MONTH.name(),
                    new long[] { tempFromTime.getMillis(), tempToTime.getMillis() }));
        }
    }
    if (log.isDebugEnabled()) {
        for (TimeRange timeRange : ranges) {
            log.debug("Unit: " + timeRange.getUnit() + " Range: "
                    + formatter.format(new Date(timeRange.getRange()[0])) + "(" + timeRange.getRange()[0]
                    + ")->" + formatter.format(new Date(timeRange.getRange()[1])) + "("
                    + timeRange.getRange()[1] + ")");
        }
    }
    return ranges;
}

From source file:org.wso2.analytics.shared.util.time.TimeRangeUtils.java

License:Open Source License

public static List<TimeRange> getDateTimeRanges(long from, long to) {
    List<TimeRange> ranges = new ArrayList<>(10);
    MutableDateTime fromDate = new MutableDateTime(from);
    fromDate.set(DateTimeFieldType.millisOfSecond(), 0);
    MutableDateTime toDate = new MutableDateTime(to);
    toDate.set(DateTimeFieldType.millisOfSecond(), 0);
    MutableDateTime tempFromTime = fromDate.copy();
    MutableDateTime tempToTime = toDate.copy();

    if (log.isDebugEnabled()) {
        log.debug("Time range: " + formatter.format(fromDate.toDate()) + "->"
                + formatter.format(toDate.toDate()));
    }/*  w  ww.  j a va  2  s .  co  m*/

    if (toDate.getMillis() - fromDate.getMillis() < DateTimeConstants.MILLIS_PER_MINUTE) {
        ranges.add(new TimeRange(RangeUnit.SECOND.name(),
                new long[] { fromDate.getMillis(), toDate.getMillis() }));
    } else {
        if (tempFromTime.getSecondOfMinute() != 0
                && (toDate.getMillis() - fromDate.getMillis() > DateTimeConstants.MILLIS_PER_MINUTE)) {
            tempFromTime = tempFromTime.minuteOfHour().roundCeiling();
            ranges.add(new TimeRange(RangeUnit.SECOND.name(),
                    new long[] { fromDate.getMillis(), tempFromTime.getMillis() }));
        }
        if (tempFromTime.getMinuteOfHour() != 0
                && ((toDate.getMillis() - tempFromTime.getMillis()) >= DateTimeConstants.MILLIS_PER_MINUTE)) {
            fromDate = tempFromTime.copy();
            if (((toDate.getMillis() - tempFromTime.getMillis()) / DateTimeConstants.MILLIS_PER_MINUTE) < 60) {
                tempFromTime = tempFromTime.minuteOfHour().add(
                        (toDate.getMillis() - tempFromTime.getMillis()) / DateTimeConstants.MILLIS_PER_MINUTE);
            } else {
                tempFromTime = tempFromTime.hourOfDay().roundCeiling();
            }
            ranges.add(new TimeRange(RangeUnit.MINUTE.name(),
                    new long[] { fromDate.getMillis(), tempFromTime.getMillis() }));
        }
        if (tempFromTime.getHourOfDay() != 0
                && ((toDate.getMillis() - tempFromTime.getMillis()) >= DateTimeConstants.MILLIS_PER_HOUR)) {
            fromDate = tempFromTime.copy();
            if (((toDate.getMillis() - tempFromTime.getMillis()) / DateTimeConstants.MILLIS_PER_HOUR) < 24) {
                tempFromTime = tempFromTime.hourOfDay().add(
                        (toDate.getMillis() - tempFromTime.getMillis()) / DateTimeConstants.MILLIS_PER_HOUR);
            } else {
                tempFromTime = tempFromTime.dayOfMonth().roundCeiling();
            }
            ranges.add(new TimeRange(RangeUnit.HOUR.name(),
                    new long[] { fromDate.getMillis(), tempFromTime.getMillis() }));
        }
        if (tempFromTime.getDayOfMonth() != 1
                && ((toDate.getMillis() - tempFromTime.getMillis()) >= DateTimeConstants.MILLIS_PER_DAY)) {
            fromDate = tempFromTime.copy();
            if ((((toDate.getMillis() - tempFromTime.getMillis())
                    / DateTimeConstants.MILLIS_PER_DAY)) < tempFromTime.dayOfMonth().getMaximumValue()) {
                tempFromTime = tempFromTime.dayOfMonth().add(((toDate.getMillis() - tempFromTime.getMillis())
                        / ((long) DateTimeConstants.MILLIS_PER_DAY)));
            } else {
                tempFromTime = tempFromTime.monthOfYear().roundCeiling();
            }
            ranges.add(new TimeRange(RangeUnit.DAY.name(),
                    new long[] { fromDate.getMillis(), tempFromTime.getMillis() }));
        }
        if (tempToTime.getSecondOfMinute() != 0
                && (tempToTime.getMillis() - tempFromTime.getMillis()) >= DateTimeConstants.MILLIS_PER_SECOND) {
            toDate = tempToTime.copy();
            long remainingSeconds = ((toDate.getMillis() - tempFromTime.getMillis())
                    % DateTimeConstants.MILLIS_PER_MINUTE) / DateTimeConstants.MILLIS_PER_SECOND;
            if (remainingSeconds < 60) {
                tempToTime = tempToTime.secondOfMinute().add(-1 * remainingSeconds);

            } else {
                tempToTime = tempToTime.secondOfMinute().roundFloor();
            }
            ranges.add(new TimeRange(RangeUnit.SECOND.name(),
                    new long[] { tempToTime.getMillis(), toDate.getMillis() }));
        }
        if (tempToTime.getMinuteOfHour() != 0 && ((tempToTime.getMillis()
                - tempFromTime.getMillis()) >= DateTimeConstants.MILLIS_PER_MINUTE)) {
            toDate = tempToTime.copy();
            long remainingMinutes = ((toDate.getMillis() - tempFromTime.getMillis())
                    % DateTimeConstants.MILLIS_PER_HOUR) / DateTimeConstants.MILLIS_PER_MINUTE;
            if (remainingMinutes < 60) {
                tempToTime = tempToTime.minuteOfHour().add(-1 * remainingMinutes);
            } else {
                tempToTime = tempToTime.hourOfDay().roundFloor();
            }
            ranges.add(new TimeRange(RangeUnit.MINUTE.name(),
                    new long[] { tempToTime.getMillis(), toDate.getMillis() }));
        }
        if (tempToTime.getHourOfDay() != 0
                && ((tempToTime.getMillis() - tempFromTime.getMillis()) >= DateTimeConstants.MILLIS_PER_HOUR)) {
            toDate = tempToTime.copy();
            long remainingHours = ((toDate.getMillis() - tempFromTime.getMillis())
                    % DateTimeConstants.MILLIS_PER_DAY) / DateTimeConstants.MILLIS_PER_HOUR;
            if (remainingHours < 24) {
                tempToTime = tempToTime.hourOfDay().add(-1 * remainingHours);
            } else {
                tempToTime = tempToTime.dayOfMonth().roundFloor();
            }
            ranges.add(new TimeRange(RangeUnit.HOUR.name(),
                    new long[] { tempToTime.getMillis(), toDate.getMillis() }));
        }
        if (tempToTime.getDayOfMonth() != 1
                && ((tempToTime.getMillis() - tempFromTime.getMillis()) >= DateTimeConstants.MILLIS_PER_DAY)) {
            toDate = tempToTime.copy();
            tempToTime = tempToTime.monthOfYear().roundFloor();
            ranges.add(new TimeRange(RangeUnit.DAY.name(),
                    new long[] { tempToTime.getMillis(), toDate.getMillis() }));
        }
        if (tempToTime.isAfter(tempFromTime)) {
            ranges.add(new TimeRange(RangeUnit.MONTH.name(),
                    new long[] { tempFromTime.getMillis(), tempToTime.getMillis() }));
        }
    }
    if (log.isDebugEnabled()) {
        for (TimeRange timeRange : ranges) {
            log.debug("Unit: " + timeRange.getUnit() + " Range: "
                    + formatter.format(new Date(timeRange.getRange()[0])) + "(" + timeRange.getRange()[0]
                    + ")->" + formatter.format(new Date(timeRange.getRange()[1])) + "("
                    + timeRange.getRange()[1] + ")");
        }
    }
    return ranges;
}

From source file:org.wso2.analytics.shared.util.time.TimeRangeUtils.java

License:Open Source License

public static long getFloorValueForTimeStamp(long timestamp, String timeUnit) {
    RangeUnit timeUnitEnum = RangeUnit.valueOf(timeUnit);
    MutableDateTime mutableDateTime = new MutableDateTime(timestamp);
    long newFloorTimestamp = mutableDateTime.getMillis();
    switch (timeUnitEnum) {
    case MONTH:/*w ww .j a  v  a2  s .  co  m*/
        newFloorTimestamp = mutableDateTime.monthOfYear().roundFloor().getMillis();
        break;
    case DAY:
        newFloorTimestamp = mutableDateTime.dayOfMonth().roundFloor().getMillis();
        break;
    case HOUR:
        newFloorTimestamp = mutableDateTime.hourOfDay().roundFloor().getMillis();
        break;
    }
    if (log.isDebugEnabled()) {
        log.debug("Original date: " + formatter.format(new Date(timestamp)) + " -> Rounded date:"
                + formatter.format(new Date(newFloorTimestamp)));
    }
    return newFloorTimestamp;
}

From source file:se.toxbee.sleepfighter.model.Alarm.java

License:Open Source License

/**
 * Returns when this alarm will ring.<br/>
 * If {@link #canHappen()} returns false, -1 will be returned.
 *
 * @param now the current time in unix epoch timestamp.
 * @return the time in unix epoch timestamp when alarm will next ring.
 *///from  w  ww.  j ava  2s  .  c o m
public synchronized Long getNextMillis(long now) {
    if (!this.canHappen()) {
        return NEXT_NON_REAL;
    }

    MutableDateTime next = new MutableDateTime(now);
    next.setHourOfDay(this.hour);
    next.setMinuteOfHour(this.minute);
    next.setSecondOfMinute(this.second);

    // Check if alarm was earlier today. If so, move to next day
    if (next.isBefore(now)) {
        next.addDays(1);
    }
    // Offset for weekdays
    int offset = 0;

    // first weekday to check (0-6), getDayOfWeek returns (1-7)
    int weekday = next.getDayOfWeek() - 1;

    // Find the weekday the alarm should run, should at most run seven times
    for (int i = 0; i < 7; i++) {
        // Wrap to first weekday
        if (weekday > MAX_WEEK_INDEX) {
            weekday = 0;
        }
        if (this.enabledDays[weekday]) {
            // We've found the closest day the alarm is enabled for
            offset = i;
            break;
        }
        weekday++;
        offset++;
    }

    if (offset > 0) {
        next.addDays(offset);
    }

    return next.getMillis();
}

From source file:se.toxbee.sleepfighter.service.AlarmPlannerService.java

License:Open Source License

/**
 * Reschedule an {@link Alarm}, that has gone of, to some minutes from now,
 * defined by the alarm itself./*from w  w  w.j a  v  a2s  . co m*/
 * 
 * @param alarmId
 *            the alarm's id
 */
private void snooze(int alarmId) {
    Alarm alarm = SFApplication.get().getPersister().fetchAlarmById(alarmId);
    if (alarm == null) {
        throw new IllegalArgumentException("No alarm was found with given id");
    }

    // Determine which time to schedule at by adding offset minutes from alarm to current time
    MutableDateTime dateTime = MutableDateTime.now();

    int mins = alarm.getSnoozeConfig().getSnoozeTime();

    dateTime.addMinutes(mins);

    long scheduleTime = dateTime.getMillis();
    schedule(scheduleTime, alarm);
    showSnoozingNotification(alarm, dateTime.toString("HH:mm"));
}