Example usage for java.util Calendar before

List of usage examples for java.util Calendar before

Introduction

In this page you can find the example usage for java.util Calendar before.

Prototype

public boolean before(Object when) 

Source Link

Document

Returns whether this Calendar represents a time before the time represented by the specified Object.

Usage

From source file:de.lemo.apps.application.DateWorkerImpl.java

public int daysBetween(final Calendar startDate, final Calendar endDate) {
    // TODO a loop seems inefficient for this. Maybe use joda time, it has a `daysBetween` method.
    // Is the the result correct? - We get '1 day' even if the dates are only seconds apart.
    final Calendar date = (Calendar) startDate.clone();
    int daysBetween = 0;
    while (date.before(endDate)) {
        date.add(Calendar.DAY_OF_MONTH, 1);
        daysBetween++;//from  w  w w .j a  v a2  s.com
    }
    return daysBetween;
}

From source file:de.knurt.fam.core.util.time.CalendarUtil.java

/**
 * return the number of days between the given to calendar instances. the
 * result is always a positive long value.
 * /*w  w w  .  ja  v a 2 s. c o m*/
 * @param c1
 *            first calendar instance
 * @param c2
 *            second calendar instance
 * @return the number of days between the given to calendar instances
 */
public long daysBetween(Calendar c1, Calendar c2) {
    long result = 0l;
    while (!DateUtils.isSameDay(c1, c2)) {
        result++;
        if (c1.before(c2)) {
            c1.add(Calendar.DAY_OF_YEAR, 1);
        } else {
            c2.add(Calendar.DAY_OF_YEAR, 1);
        }
    }
    return result;
}

From source file:com.epam.dlab.configuration.SchedulerConfiguration.java

/** Adjust the time in schedule for current time.
 *///from  w  ww .ja  v  a2  s.  c  o  m
public void adjustStartTime() {
    Calendar now = Calendar.getInstance();
    for (String key : realSchedule.keySet()) {
        Calendar time = realSchedule.get(key);
        if (time.before(now)) {
            time.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH),
                    time.get(Calendar.HOUR_OF_DAY), time.get(Calendar.MINUTE), time.get(Calendar.SECOND));
            if (time.before(now)) {
                time.add(Calendar.DAY_OF_MONTH, 1);
            }
            realSchedule.put(key, time);
        }
    }
}

From source file:felixwiemuth.lincal.NotificationService.java

@Override
protected void onHandleIntent(Intent intent) {
    calendars = Calendars.getInstance(this);
    Calendar now = Calendar.getInstance();
    Calendar nextAlarm = null;// w  w w  .j  a v  a  2s  .c o  m
    for (int i = 0; i < calendars.getCalendarCount(); i++) {
        LinCalConfig config = calendars.getConfigByPos(i);
        if (config.isNotificationsEnabled()) { // only load calendar if notifications are enabled
            LinCal cal = calendars.getCalendarByPos(this, i);
            if (cal != null) { // if the calendar could not be loaded, skip it (this will also skip scheduling of next notifications for this calendar)
                Calendar nextTime = processCalendar(cal, config, now);
                if (nextAlarm == null || (nextTime != null && nextTime.before(nextAlarm))) {
                    nextAlarm = nextTime;
                }
            }
        }
    }
    calendars.save(this);
    // Schedule next processing if there are further entries
    if (nextAlarm != null) {
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent processIntent = new Intent(this, NotificationService.class);
        PendingIntent alarmIntent = PendingIntent.getService(this, 0, processIntent, 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextAlarm.getTimeInMillis(), alarmIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, nextAlarm.getTimeInMillis(), alarmIntent);
        }
    }
    stopSelf();
}

From source file:org.apache.ws.security.processor.TimestampProcessor.java

public void handleTimestamp(Timestamp timestamp) throws WSSecurityException {
    if (log.isDebugEnabled()) {
        log.debug("Preparing to verify the timestamp");

        DateFormat zulu = new XmlSchemaDateFormat();

        log.debug("Current time: " + zulu.format(Calendar.getInstance().getTime()));
        if (timestamp.getCreated() != null) {
            log.debug("Timestamp created: " + zulu.format(timestamp.getCreated().getTime()));
        }/*w  w w  .  j  ava  2s .co m*/
        if (timestamp.getExpires() != null) {
            log.debug("Timestamp expires: " + zulu.format(timestamp.getExpires().getTime()));
        }
    }

    // Validate whether the security semantics have expired
    Calendar exp = timestamp.getExpires();
    if (exp != null && wssConfig.isTimeStampStrict()) {
        Calendar rightNow = Calendar.getInstance();
        if (exp.before(rightNow)) {
            throw new WSSecurityException(WSSecurityException.MESSAGE_EXPIRED, "invalidTimestamp",
                    new Object[] { "The security semantics of the message have expired" });
        }
    }
}

From source file:com.adobe.acs.commons.wcm.impl.FileImporter.java

@Override
@SuppressWarnings("squid:S3776")
public void importData(String schemeValue, String dataSource, Resource target) {
    if (scheme.equals(schemeValue)) {
        final File file = new File(dataSource);
        if (file.exists()) {
            Calendar fileLastMod = Calendar.getInstance();
            fileLastMod.setTimeInMillis(file.lastModified());
            String fileName = file.getName();
            String mimeType = mimeTypeService.getMimeType(fileName);

            final Node targetParent;
            final String targetName;

            Node node = target.adaptTo(Node.class);
            if (node != null) {
                try (FileInputStream stream = new FileInputStream(file)) {
                    if (node.isNodeType(JcrConstants.NT_FILE)) {
                        // assume that we are intending to replace this file
                        targetParent = node.getParent();
                        targetName = node.getName();
                        Calendar nodeLastMod = JcrUtils.getLastModified(node);
                        if (!nodeLastMod.before(fileLastMod)) {
                            log.info("File '{}' does not have a newer timestamp than '{}'. Skipping import.",
                                    dataSource, target);
                            return;
                        }/*  w w  w .  j  a  v  a2  s.c o  m*/
                    } else {
                        // assume that we are creating a new file under the current node
                        targetParent = node;
                        targetName = fileName;
                        if (targetParent.hasNode(targetName)) {
                            Node targetNode = targetParent.getNode(targetName);
                            Calendar nodeLastMod = JcrUtils.getLastModified(targetNode);
                            if (!nodeLastMod.before(fileLastMod)) {
                                log.info(
                                        "File '{}' does not have a newer timestamp than '{}'. Skipping import.",
                                        dataSource, targetNode.getPath());
                                return;
                            }
                        }
                    }

                    JcrUtils.putFile(targetParent, targetName, mimeType, stream);
                    node.getSession().save();
                } catch (RepositoryException e) {
                    throw new ImportException(
                            "Unable to import from file '" + dataSource + "' to '" + target.getPath() + "'", e);
                } catch (IOException e) {
                    throw new ImportException("Unexpected IOException while importing", e);
                }
            } else {
                log.warn("Target '{}' is not a JCR node. Skipping import from '{}'.", target.getPath(),
                        dataSource);
            }
        } else {
            log.warn("File at '{}' does not exist. Skipping import.", dataSource);
        }
    } else {
        log.warn("Unrecognized scheme '{}' passed to importData()", schemeValue);
    }
}

From source file:org.wso2.carbon.event.ws.internal.builders.RenewCommandBuilder.java

/**
 * (01) <s12:Envelope//w  w w  . j a va 2  s . com
 * (02)     xmlns:s12="http://www.w3.org/2003/05/soap-envelope"
 * (03)     xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
 * (04)     xmlns:wse="http://schemas.xmlsoap.org/ws/2004/08/eventing"
 * (05)     xmlns:ow="http://www.example.org/oceanwatch" >
 * (06)   <s12:Header>
 * (07)     <wsa:Action>
 * (08)       http://schemas.xmlsoap.org/ws/2004/08/eventing/Renew
 * (09)     </wsa:Action>
 * (10)     <wsa:MessageID>
 * (11)       uuid:bd88b3df-5db4-4392-9621-aee9160721f6
 * (12)     </wsa:MessageID>
 * (13)     <wsa:ReplyTo>
 * (14)      <wsa:Address>http://www.example.com/MyEventSink</wsa:Address>
 * (15)     </wsa:ReplyTo>
 * (16)     <wsa:To>
 * (17)       http://www.example.org/oceanwatch/SubscriptionManager
 * (18)     </wsa:To>
 * (19)     <wse:Identifier>
 * (20)       uuid:22e8a584-0d18-4228-b2a8-3716fa2097fa
 * (21)     </wse:Identifier>
 * (22)   </s12:Header>
 * (23)   <s12:Body>
 * (24)     <wse:Renew>
 * (25)       <wse:Expires>2004-06-26T21:07:00.000-08:00</wse:Expires>
 * (26)     </wse:Renew>
 * (27)   </s12:Body>
 * (28) </s12:Envelope>
 *
 * @param envelope The soap envelope containing the renew subscription request
 * @return The subscription to renew
 * @throws InvalidMessageException
 * @throws InvalidExpirationTimeException
 */
public Subscription toSubscription(SOAPEnvelope envelope)
        throws InvalidMessageException, InvalidExpirationTimeException {
    if (envelope == null) {
        log.error("No SOAP envelope was provided.");
        throw new BuilderException("No SOAP envelope was provided.");
    }
    Subscription subscription = new Subscription();
    OMElement elem = null;
    if (envelope.getHeader() != null) {
        elem = envelope.getHeader().getFirstChildWithName(IDENTIFIER);
    }
    if (elem == null) {
        log.error("Subscription Identifier is required as a header of the subscription message.");
        throw new InvalidMessageException(
                "Subscription Identifier is required as a header of the subscription message.");
    }
    String id = elem.getText().trim();
    subscription.setId(id);

    OMElement renewElem = envelope.getBody().getFirstChildWithName(RENEW);
    if (renewElem != null) {
        OMElement expiryElem = renewElem.getFirstChildWithName(EXPIRES);
        if (expiryElem != null) {
            Calendar calendarExpires;
            try {
                String expiryText = expiryElem.getText().trim();
                if (expiryText.startsWith("P")) {
                    calendarExpires = Calendar.getInstance();
                    Duration duration = ConverterUtil.convertToDuration(expiryText);
                    calendarExpires.add(Calendar.YEAR, duration.getYears());
                    calendarExpires.add(Calendar.MONTH, duration.getMonths());
                    calendarExpires.add(Calendar.DAY_OF_MONTH, duration.getDays());
                    calendarExpires.add(Calendar.HOUR_OF_DAY, duration.getHours());
                    calendarExpires.add(Calendar.MINUTE, duration.getMinutes());
                    calendarExpires.add(Calendar.SECOND, (int) duration.getSeconds());
                } else {
                    calendarExpires = ConverterUtil.convertToDateTime(expiryText);
                }
            } catch (Exception e) {
                log.error("Error converting the expiration date", e);
                throw new InvalidExpirationTimeException("Error converting the expiration date", e);
            }
            Calendar calendarNow = Calendar.getInstance();
            if (calendarNow.before(calendarExpires)) {
                subscription.setExpires(calendarExpires);
            } else {
                log.error("The expiration time has passed");
                throw new InvalidExpirationTimeException("The expiration time has passed");
            }

            subscription.setExpires(calendarExpires);
        } else {
            log.error("The expiration time was not given");
            throw new InvalidExpirationTimeException("The expiration time was not given");
        }
    }
    return subscription;
}

From source file:de.knurt.fam.news.NewsSourceForYourBookings.java

private NewsItem getNewsItemOf(Booking booking, TimeFrame from) {
    NewsItem result = null;//from www.j  a v a 2s . c  o m
    if ((booking.isCanceled() && from.contains(booking.getCancelation().getDateCanceled()))
            || (!booking.isCanceled() && !booking.sessionAlreadyMade())) {
        result = new NewsItemDefault();
        String facilityLabel = booking.getFacility().getLabel();
        String bOrA = booking.isApplication() ? "application" : "booking"; // INTLANG
        String desc = "";
        if (booking.isCanceled()) {
            String reason = booking.getCancelation().getReason();
            desc = String.format("Your %s for %s was canceled.", bOrA, facilityLabel); // INTLANG
            if (reason != null && !reason.isEmpty()) {
                desc += " Reason: " + reason;
            }
            result.setEventStarts(booking.getCancelation().getDateCanceled());
        } else { // uncanceled booking
            if (booking.isQueueBased() && !booking.sessionAlreadyMade()) {
                //  booking in queue and not made
                desc = String.format("Expected start of your session on %s. Your position in queue: %s.",
                        facilityLabel, ((QueueBooking) booking).getCurrentQueuePosition()); // INTLANG
                result.setEventStarts(((QueueBooking) booking).getExpectedSessionStart().getTime());
                if (booking.sessionAlreadyBegun()) {
                    result.setLinkToFurtherInformation(
                            TemplateHtml.href("viewrequest") + QueryStringBuilder.getQueryString(booking));
                } else {
                    result.setLinkToFurtherInformation(
                            TemplateHtml.href("editrequest") + QueryStringBuilder.getQueryString(booking));
                }
            } else { // booking has session start time
                Calendar today = Calendar.getInstance();
                if (DateUtils.isSameDay(today.getTime(), booking.getSessionTimeFrame().getDateStart())) {
                    // session is today
                    if (DateUtils.isSameDay(today.getTime(), booking.getSessionTimeFrame().getDateEnd())) {
                        desc = String.format("Your session on %s.", facilityLabel); // INTLANG
                        result.setEventStarts(booking.getSessionTimeFrame().getDateStart());
                        result.setEventEnds(booking.getSessionTimeFrame().getDateEnd());
                    } else {
                        desc = String.format("Your session on %s (ends on %s).", facilityLabel,
                                FamDateFormat.getDateAndTimeShort(booking.getSessionTimeFrame().getDateEnd())); // INTLANG
                        result.setEventStarts(booking.getSessionTimeFrame().getDateStart());
                    }
                    if (booking.sessionAlreadyBegun()) {
                        result.setLinkToFurtherInformation(
                                TemplateHtml.href("viewrequest") + QueryStringBuilder.getQueryString(booking));
                    } else {
                        result.setLinkToFurtherInformation(
                                TemplateHtml.href("editrequest") + QueryStringBuilder.getQueryString(booking));
                    }
                } else { // session starts in future
                    Calendar booking_c = booking.getSessionTimeFrame().getCalendarStart();
                    if (booking_c.before(today)) {
                        desc = String.format("your session on %s.", facilityLabel); // INTLANG
                    } else {
                        long days = CalendarUtil.me().daysBetween(today, booking_c);
                        desc = String.format("%s %s to your session on %s.", days, days == 1 ? "day" : "days",
                                facilityLabel); // INTLANG
                    }
                    result.setEventStarts(booking_c.getTime());
                    if (booking.getSessionTimeFrame().getCalendarEnd() != null) {
                        result.setEventEnds(booking.getSessionTimeFrame().getCalendarEnd().getTime());
                    }
                    result.setLinkToFurtherInformation(
                            TemplateHtml.href("editrequest") + QueryStringBuilder.getQueryString(booking));
                }
            }
            if (booking.getNotice() != null && !booking.getNotice().isEmpty()) {
                desc += " Notice: " + booking.getNotice();
            }
        }
        if (result != null && desc != null) {
            result.setDescription(desc);
        }
    }
    return result;
}

From source file:solarrecorder.SolarRecorder.java

SolarRecorder(long interval) {
    SolarEventCalculator sec = new SolarEventCalculator(new Location(latitude, longitude), "Europe/London");
    Calendar sunRise = sec.computeSunriseCalendar(zen, new GregorianCalendar());
    Calendar sunSet = sec.computeSunsetCalendar(zen, new GregorianCalendar());

    printCalendar("sunRise ", sunRise);
    printCalendar("sunSet ", sunSet);

    Calendar now = Calendar.getInstance();
    printCalendar("Now ", now);

    if (now.before(sunRise)) {
        Calendar startOfDay = Calendar.getInstance();
        startOfDay.set(Calendar.HOUR_OF_DAY, 0);
        startOfDay.set(Calendar.MINUTE, 0);
        startOfDay.set(Calendar.SECOND, 0);
        printCalendar("Start of Day ", startOfDay);

        printCalendar(now, " Before sunrise");
        if (diffInMins(sunRise, now) < interval) {
            printCalendar("Sun will rise at ", sunRise);
        } else if (diffInMins(now, startOfDay) < interval + intervalError) {
            sendSolarUpdate();/*from  w w  w.  j a  v  a2 s  . co m*/
        }
    } else if (now.after(sunSet)) {
        Calendar midnight = Calendar.getInstance();
        midnight.set(Calendar.HOUR_OF_DAY, 23);
        midnight.set(Calendar.MINUTE, 59);
        midnight.set(Calendar.SECOND, 59);
        printCalendar("End of Day ", midnight);

        printCalendar(now, " After sunset");
        if (diffInMins(now, sunSet) < interval) {
            printCalendar("Sun set at ", sunSet);
            sendSolarUpdate();
        } else if (diffInMins(midnight, now) < interval + intervalError) {
            sendSolarUpdate();
        }
    } else {
        printCalendar(now, " Sun is up");
        sendSolarUpdate();
    }
}

From source file:hu.petabyte.redflags.engine.gear.filter.PublicationDateFilter.java

@Override
public boolean accept(Notice notice) throws Exception {
    if (null == notice.getData().getPublicationDate()) {
        return false;
    }//w w  w.  j  a  va 2  s. c  om

    Calendar noticeDateCal = Calendar.getInstance();
    noticeDateCal.setTime(notice.getData().getPublicationDate());

    Calendar minDateCal = Calendar.getInstance();
    minDateCal.setTime(minDate);

    return !noticeDateCal.before(minDateCal);
}