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:org.kuali.kfs.module.endow.document.service.impl.PooledFundValueServiceImpl.java

public boolean isValuationDateTheLatest(String pooledSecurityID, Date theValuationDate) {
    boolean isLatest = true;

    Map<String, String> fieldValues = new HashMap<String, String>();
    fieldValues.put(EndowPropertyConstants.POOL_SECURITY_ID, pooledSecurityID);

    BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
    Collection<PooledFundValue> pooledFundValues = businessObjectService.findMatching(PooledFundValue.class,
            fieldValues);//from  w  w w.j  ava  2  s  . c  om

    if (pooledFundValues.isEmpty())
        return true;

    Calendar calendar = Calendar.getInstance();
    Calendar theCalendar = Calendar.getInstance();
    theCalendar.setTime(theValuationDate);

    for (PooledFundValue pooledFundValue : pooledFundValues) {
        Date valuationDate = pooledFundValue.getValuationDate();
        calendar.setTime(valuationDate);
        if (theCalendar.before(calendar)) {
            isLatest = false;
            break;
        }
    }

    return isLatest;
}

From source file:org.betaconceptframework.astroboa.portal.utility.CalendarUtils.java

public List<Calendar> getDiscreteDatesInPeriod(Calendar fromCalendarInclusive, Calendar toCalendarInclusive) {
    List<Calendar> discreteDatesInPeriod = new ArrayList<Calendar>();
    if (fromCalendarInclusive != null && toCalendarInclusive != null) {

        if (fromCalendarInclusive.before(toCalendarInclusive)) {

            // when we process discrete dates we reset the hour.
            clearTimeFromCalendar(fromCalendarInclusive);

            while (fromCalendarInclusive.before(toCalendarInclusive)
                    || fromCalendarInclusive.equals(toCalendarInclusive)) {
                Calendar discreteDate = (GregorianCalendar) fromCalendarInclusive.clone();
                discreteDatesInPeriod.add(discreteDate);
                fromCalendarInclusive.add(Calendar.DAY_OF_MONTH, 1);
            }/*  w w  w  .  j  av a2s.  co m*/
        } else { // check if both dates are equal and return one date only
            clearTimeFromCalendar(fromCalendarInclusive);
            clearTimeFromCalendar(toCalendarInclusive);
            if (fromCalendarInclusive.equals(toCalendarInclusive)) {
                Calendar discreteDate = (GregorianCalendar) fromCalendarInclusive.clone();
                discreteDatesInPeriod.add(discreteDate);
            }
        }
    } else if (fromCalendarInclusive != null && toCalendarInclusive == null) { // we are looking for a specific date
        // when we process discrete dates we reset the hour. we assume that the date field for which we set the criteria contains date(s) without hour data. 
        clearTimeFromCalendar(fromCalendarInclusive);
        Calendar discreteDate = (GregorianCalendar) fromCalendarInclusive.clone();
        discreteDatesInPeriod.add(discreteDate);
    } else if (fromCalendarInclusive == null && toCalendarInclusive != null) { // we are looking for a specific date
        // when we process discrete dates we reset the hour. we assume that the date field for which we set the criteria contains date(s) without hour data. 
        clearTimeFromCalendar(toCalendarInclusive);
        Calendar discreteDate = (GregorianCalendar) toCalendarInclusive.clone();
        discreteDatesInPeriod.add(discreteDate);
    }

    return discreteDatesInPeriod;

}

From source file:org.eclipse.skalli.services.scheduler.Schedule.java

/**
 * Returns <code>true</code> if the recurring task that this schedule describes
 * was due somewhen between <code>first</code> and <code>last</code> (including the
 * interval boundaries)./*from  w ww.  j av a 2  s  .c o m*/
 *
 * @param first  the begin of the interval to check, or <code>null</code>. In that case
 * the method is equivalent to {@link #isDue(Calendar)}.
 * @param last  the end of the interval to check
 *
 * @return  <code>true</code>, if the task is due.
 */
public boolean isDue(Calendar first, Calendar last) {
    if (isDue(last)) {
        return true;
    }

    if (first == null) {
        return false;
    }

    Calendar i = new GregorianCalendar(first.getTimeZone());
    i.setTime(first.getTime());
    i.add(Calendar.MINUTE, 1);
    while (i.before(last)) {
        if (isDue(i)) {
            return true;
        }
        i.add(Calendar.MINUTE, 1);
    }

    return false;
}

From source file:org.bibsonomy.webapp.controller.actions.UserActivationController.java

@Override
public View workOn(UserActivationCommand command) {
    final RequestWrapperContext context = command.getContext();
    command.setPageTitle("activation");

    /*/* ww  w. j a v a 2  s .  c  o m*/
     * user must not be logged in
     */
    if (context.isUserLoggedIn()) {
        throw new AccessDeniedException("error.logged.in.user.activate");
    }

    final String activationCode = command.getActivationCode();

    final List<User> list = logic.getUsers(null, GroupingEntity.PENDING, null, null, null, null, null,
            activationCode, 0, 1);
    User pendingUser = null;
    if (list.size() == 0 || !present(activationCode)) {
        errors.reject("error.illegal_activation_code");
    } else {
        log.debug("trying to activate user with code '" + activationCode + "'");

        pendingUser = list.get(0);

        /* 
         * FIXME: this check should be done by the userdatabasemanager in
         * the activate user method
         * 
         * check, if activation code is invalid.
         * 
         * now < registration_date + 24h
         */
        final Calendar now = Calendar.getInstance();
        final Calendar activationCodeExpirationDate = Calendar.getInstance();
        activationCodeExpirationDate.setTime(pendingUser.getRegistrationDate());
        activationCodeExpirationDate.add(Calendar.HOUR, 24);
        if (!now.before(activationCodeExpirationDate)) {
            errors.reject("error.activation_code_expired");
        }
    }

    /*
     * if there are errors, show them
     */
    if (errors.hasErrors()) {
        return Views.ERROR;
    }

    /*
     * activate user
     */
    logic.updateUser(pendingUser, UserUpdateOperation.ACTIVATE);

    /*
     * send activation confirmation mail
     */
    try {
        mailUtils.sendActivationMail(pendingUser.getName(), pendingUser.getEmail(),
                requestLogic.getInetAddress(), requestLogic.getLocale());
    } catch (final Exception e) {
        log.error("Could not send activation confirmation mail for user " + pendingUser.getName(), e);
    }

    /*
     * log the user into the system, e.g., authenticate the user
     * (luckily, getUsers() includes the password of the user - if not, this
     * would not work and we would have to call getUserDetails() first). See
     * also the next comment.
     */
    final UserDetails userDetails = new UserAdapter(pendingUser);
    final Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails,
            pendingUser.getPassword());

    /*
     * In principle we could directly call SecurityContextHolder.getContext().setAuthentication()
     * with the constructed authentication. However, the pendingUser 
     * returned by getUsers() does not include the user's settings - which 
     * are retrieved from the database by calling authenticate() on the 
     * authenticationManager.
     */
    final Authentication authenticated = authenticationManager.authenticate(authentication);

    SecurityContextHolder.getContext().setAuthentication(authenticated);

    /*
     * TODO: ask user if "remember me" cookie shall be added
     */

    return new ExtendedRedirectView(successRedirect);
}

From source file:jobs.WarningMonitorJob.java

/**
 * All checks done on specific plants under the GardenDroid's care will be managed from here.
 * @param options// www.  j av a2s .c o m
 * @throws EmailException 
 */
public boolean checkActivePlantings(Options options) {
    boolean alertDetected = false;
    if (options.enablePlantedWarnings) {
        StringBuilder sb = new StringBuilder();

        List<Plant> plantings = Plant.getActivePlantings();
        for (Plant plant : plantings) {
            //Check Temp Thresholds
            logger.warn("### Checking on plant: " + plant);
            int tempWarn = checkForTempThresholdsAlert(plant.plantData);
            if (tempWarn == 1) {
                sb.append("\n ").append(plant.name)
                        .append(": Tempratures have exceeded the Plants indicated tolerance range.");
            } else if (tempWarn == -1) {
                sb.append("\n ").append(plant.name)
                        .append(": Tempratures have dropped below the Plants indicated tolerance range.");
            }
            //check watering
            HashMap<SensorType, SensorData> latest = SensorData.retrieveLatestSensorData();
            boolean sensorState = false;
            boolean observationState = false;
            int waterDays = plant.plantData.waterFreqDays;
            if (latest.containsKey(SensorType.WATER_IRRIGATION)
                    && latest.get(SensorType.WATER_IRRIGATION) != null) {

                SensorData water = latest.get(SensorType.WATER_IRRIGATION);
                logger.warn("### latest water data== " + water);
                Calendar waterDate = Calendar.getInstance();
                waterDate.setTime(water.dateTime);

                Calendar nextWaterDate = Calendar.getInstance();
                nextWaterDate.add(Calendar.DATE, waterDays);

                if (waterDate.before(nextWaterDate)) {
                    sensorState = true;
                }
            }

            if (!sensorState) { //check observation entries.
                ObservationData mostRecent = ObservationData
                        .find("plant = ? AND dataType = ? order by dateCreated desc",
                                new Object[] { plant, UserDataType.DEFAULT_PLANT_IRRIGATION })
                        .first();
                if (mostRecent != null) {
                    Calendar obsWaterDate = Calendar.getInstance();
                    obsWaterDate.setTime(mostRecent.dateCreated);

                    Calendar nextWaterDate = Calendar.getInstance();
                    nextWaterDate.add(Calendar.DATE, waterDays);
                    if (obsWaterDate.before(nextWaterDate)) {
                        observationState = true;
                    }
                }
            }
            logger.warn(" sensorState=" + sensorState + "  ObsState=" + observationState);
            if (!sensorState & !observationState) {
                sb.append("\n ").append(plant.name).append(": is due for irrigation.");
            }

        }

        if (sb.length() > 0) {
            try {
                alertDetected = true;
                if (options.enableWarningNotification) {
                    sendNotification(options, "", sb.toString());
                }
                logger.info("Plant Alert Message Sent: " + sb.toString());
            } catch (EmailException e) {
                logger.error("Email Alert failed.", e);
                new LogData(new Date(), "Failed to send email address to email address: " + options.email)
                        .save();
            }
        }

    }
    return alertDetected;
}

From source file:org.kuali.kpme.core.kfs.coa.businessobject.Account.java

/**
 * This method determines whether the account is expired or not. Note that if Expiration Date is the same date as testDate, then
 * this will return false. It will only return true if the account expiration date is one day earlier than testDate or earlier.
 * Note that this logic ignores all time components when doing the comparison. It only does the before/after comparison based on
 * date values, not time-values./* w  ww  .j  a  v  a  2 s .c o  m*/
 * 
 * @param testDate - Calendar instance with the date to test the Account's Expiration Date against. This is most commonly set to
 *        today's date.
 * @return true or false based on the logic outlined above
 */
public boolean isExpired(Calendar testDate) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("entering isExpired(" + testDate + ")");
    }

    // dont even bother trying to test if the accountExpirationDate is null
    if (this.accountExpirationDate == null) {
        return false;
    }

    // remove any time-components from the testDate
    testDate = DateUtils.truncate(testDate, Calendar.DAY_OF_MONTH);

    // get a calendar reference to the Account Expiration
    // date, and remove any time components
    Calendar acctDate = Calendar.getInstance();
    acctDate.setTime(this.accountExpirationDate);
    acctDate = DateUtils.truncate(acctDate, Calendar.DAY_OF_MONTH);

    // if the Account Expiration Date is before the testDate
    if (acctDate.before(testDate)) {
        return true;
    } else {
        return false;
    }
}

From source file:nl.strohalm.cyclos.services.accounts.guarantees.PaymentObligationServiceImpl.java

public void processPaymentObligations(final Calendar taskTime) {
    final Calendar time = DateHelper.truncate(taskTime);

    final PaymentObligationQuery query = new PaymentObligationQuery();
    time.add(Calendar.DATE, -1); // this is to discard the POs expiring today
    query.setExpiration(Period.endingAt(time));
    query.setResultType(ResultType.ITERATOR);
    query.setApplyExpirationToMaxPublishDate(true);
    final Set<Relationship> fetch = new HashSet<Relationship>();
    fetch.add(PaymentObligation.Relationships.LOGS);
    query.setFetch(fetch);/*from ww w . ja  v  a2 s  . co m*/
    query.setStatusList(Arrays.asList(PaymentObligation.Status.PUBLISHED));
    final List<PaymentObligation> paymentObligations = paymentObligationDao.search(query);
    for (final PaymentObligation paymentObligation : paymentObligations) {
        final Calendar expirationDate = DateHelper.truncate(paymentObligation.getExpirationDate());
        // the expiration date or the max publication date are before task's time
        final PaymentObligation.Status newStatus = expirationDate.before(taskTime)
                ? PaymentObligation.Status.EXPIRED
                : PaymentObligation.Status.REGISTERED;

        paymentObligation.setStatus(newStatus);
        final PaymentObligationLog log = paymentObligation.changeStatus(newStatus, null);
        saveLog(log);
        save(paymentObligation, false);
    }
}

From source file:org.sakaiproject.evaluation.tool.locators.EmailSettingsWBL.java

protected Date calculateNextReminderDate() {
    Integer reminderInterval = ((Integer) evalSettings.get(EvalSettings.SINGLE_EMAIL_REMINDER_DAYS));
    String nextReminderStr = (String) evalSettings.get(EvalSettings.NEXT_REMINDER_DATE);

    Date nextReminder;//from w  w w  . j av  a 2 s  . c  o m
    if (nextReminderStr == null || nextReminderStr.trim().equals("")) {
        nextReminder = new Date();
    } else {
        DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy"); //DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL);
        try {
            nextReminder = df.parse(nextReminderStr);
        } catch (ParseException e) {
            // Use current date
            nextReminder = new Date();
        }
    }
    Integer startTime = (Integer) this.evalSettings.get(EvalSettings.CONSOLIDATED_EMAIL_DAILY_START_TIME);
    Integer startMinute = (Integer) this.evalSettings.get(EvalSettings.CONSOLIDATED_EMAIL_DAILY_START_MINUTES);

    Calendar cal = Calendar.getInstance();

    if (nextReminder != null) {
        cal.setTime(nextReminder);
    }

    if (reminderInterval != null && reminderInterval > 0) {
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, startMinute);
        cal.set(Calendar.HOUR_OF_DAY, startTime);

        Calendar now = Calendar.getInstance();
        if (cal.before(now)) {
            cal.add(Calendar.DAY_OF_MONTH, reminderInterval);
        }
        if (cal.before(now)) {
            cal.set(Calendar.YEAR, now.get(Calendar.YEAR));
            cal.set(Calendar.MONTH, now.get(Calendar.MONTH));
            cal.set(Calendar.DAY_OF_MONTH, now.get(Calendar.DAY_OF_MONTH) + 1);
        }

    }
    return cal.getTime();
}

From source file:org.kuali.kfs.module.endow.document.service.impl.PooledFundValueServiceImpl.java

public Date getLatestValueEffectiveDate(String pooledSecurityID) {
    Map<String, String> fieldValues = new HashMap<String, String>();
    fieldValues.put(EndowPropertyConstants.POOL_SECURITY_ID, pooledSecurityID);

    BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
    Collection<PooledFundValue> pooledFundValues = businessObjectService.findMatching(PooledFundValue.class,
            fieldValues);// w ww  .j  a va  2 s .co  m

    if (pooledFundValues.isEmpty())
        return null;

    PooledFundValue thePooledFundValue = pooledFundValues.iterator().next();
    Date theLastestValueEffectiveDate = thePooledFundValue.getValueEffectiveDate();

    Calendar calendar = Calendar.getInstance();
    Calendar theLatestCalendar = Calendar.getInstance();
    theLatestCalendar.setTime(theLastestValueEffectiveDate);
    Date valueEffectiveDate = null;
    for (PooledFundValue pooledFundValue : pooledFundValues) {
        valueEffectiveDate = pooledFundValue.getValueEffectiveDate();
        calendar.setTime(valueEffectiveDate);
        if (theLatestCalendar.before(calendar)) {
            theLatestCalendar = calendar;
        }
    }

    return new java.sql.Date(theLatestCalendar.getTime().getTime());

}

From source file:org.apache.cocoon.generation.CalendarGenerator.java

/**
 * Generate XML data./*from w ww.  jav a 2 s .  c  o m*/
 *
 * @throws  SAXException if an error occurs while outputting the document
 */
public void generate() throws SAXException, ProcessingException {
    Calendar start = Calendar.getInstance(locale);
    start.clear();
    start.set(Calendar.YEAR, this.year);
    start.set(Calendar.MONTH, this.month);
    start.set(Calendar.DAY_OF_MONTH, 1);
    Calendar end = (Calendar) start.clone();
    end.add(Calendar.MONTH, 1);

    // Determine previous and next months
    Calendar prevMonth = (Calendar) start.clone();
    prevMonth.add(Calendar.MONTH, -1);

    this.contentHandler.startDocument();
    this.contentHandler.startPrefixMapping(PREFIX, URI);
    attributes.clear();
    attributes.addAttribute("", YEAR_ATTR_NAME, YEAR_ATTR_NAME, "CDATA", String.valueOf(year));
    attributes.addAttribute("", MONTH_ATTR_NAME, MONTH_ATTR_NAME, "CDATA",
            monthFormatter.format(start.getTime()));

    // Add previous and next month
    attributes.addAttribute("", PREV_YEAR_ATTR_NAME, PREV_YEAR_ATTR_NAME, "CDATA",
            String.valueOf(prevMonth.get(Calendar.YEAR)));
    attributes.addAttribute("", PREV_MONTH_ATTR_NAME, PREV_MONTH_ATTR_NAME, "CDATA",
            monthNumberFormatter.format(prevMonth.get(Calendar.MONTH) + 1));
    attributes.addAttribute("", NEXT_YEAR_ATTR_NAME, NEXT_YEAR_ATTR_NAME, "CDATA",
            String.valueOf(end.get(Calendar.YEAR)));
    attributes.addAttribute("", NEXT_MONTH_ATTR_NAME, NEXT_MONTH_ATTR_NAME, "CDATA",
            monthNumberFormatter.format(end.get(Calendar.MONTH) + 1));

    this.contentHandler.startElement(URI, CALENDAR_NODE_NAME, PREFIX + ':' + CALENDAR_NODE_NAME, attributes);
    int weekNo = start.get(Calendar.WEEK_OF_MONTH);
    int firstDay = start.getFirstDayOfWeek();
    if (start.get(Calendar.DAY_OF_WEEK) != firstDay) {
        attributes.clear();
        attributes.addAttribute("", NUMBER_ATTR_NAME, NUMBER_ATTR_NAME, "CDATA", String.valueOf(weekNo));
        this.contentHandler.startElement(URI, WEEK_NODE_NAME, PREFIX + ':' + WEEK_NODE_NAME, attributes);
        if (padWeeks) {
            Calendar previous = (Calendar) start.clone();
            while (previous.get(Calendar.DAY_OF_WEEK) != firstDay) {
                previous.add(Calendar.DAY_OF_MONTH, -1);
            }
            while (previous.before(start)) {
                attributes.clear();
                attributes.addAttribute("", NUMBER_ATTR_NAME, NUMBER_ATTR_NAME, "CDATA",
                        String.valueOf(previous.get(Calendar.DAY_OF_MONTH)));
                attributes.addAttribute("", WEEKDAY_ATTR_NAME, WEEKDAY_ATTR_NAME, "CDATA",
                        weekdays[previous.get(Calendar.DAY_OF_WEEK)]);
                attributes.addAttribute("", DATE_ATTR_NAME, DATE_ATTR_NAME, "CDATA",
                        dateFormatter.format(previous.getTime()));
                this.contentHandler.startElement(URI, DAY_NODE_NAME, PREFIX + ':' + DAY_NODE_NAME, attributes);
                addContent(previous, locale);
                this.contentHandler.endElement(URI, DAY_NODE_NAME, PREFIX + ':' + DAY_NODE_NAME);
                previous.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
    }
    while (start.before(end)) {
        if (start.get(Calendar.DAY_OF_WEEK) == firstDay) {
            weekNo = start.get(Calendar.WEEK_OF_MONTH);
            attributes.clear();
            attributes.addAttribute("", NUMBER_ATTR_NAME, NUMBER_ATTR_NAME, "CDATA", String.valueOf(weekNo));
            this.contentHandler.startElement(URI, WEEK_NODE_NAME, PREFIX + ':' + WEEK_NODE_NAME, attributes);
        }
        attributes.clear();
        attributes.addAttribute("", NUMBER_ATTR_NAME, NUMBER_ATTR_NAME, "CDATA",
                String.valueOf(start.get(Calendar.DAY_OF_MONTH)));
        attributes.addAttribute("", WEEKDAY_ATTR_NAME, WEEKDAY_ATTR_NAME, "CDATA",
                weekdays[start.get(Calendar.DAY_OF_WEEK)]);
        attributes.addAttribute("", DATE_ATTR_NAME, DATE_ATTR_NAME, "CDATA",
                dateFormatter.format(start.getTime()));
        this.contentHandler.startElement(URI, DAY_NODE_NAME, PREFIX + ':' + DAY_NODE_NAME, attributes);
        addContent(start, locale);
        this.contentHandler.endElement(URI, DAY_NODE_NAME, PREFIX + ':' + DAY_NODE_NAME);
        start.add(Calendar.DAY_OF_MONTH, 1);
        if (start.get(Calendar.DAY_OF_WEEK) == firstDay || (!padWeeks && !start.before(end))) {
            this.contentHandler.endElement(URI, WEEK_NODE_NAME, PREFIX + ':' + WEEK_NODE_NAME);
        }
    }

    if (padWeeks) {
        while (firstDay != end.get(Calendar.DAY_OF_WEEK)) {
            attributes.clear();
            attributes.addAttribute("", NUMBER_ATTR_NAME, NUMBER_ATTR_NAME, "CDATA",
                    String.valueOf(end.get(Calendar.DAY_OF_MONTH)));
            attributes.addAttribute("", WEEKDAY_ATTR_NAME, WEEKDAY_ATTR_NAME, "CDATA",
                    weekdays[end.get(Calendar.DAY_OF_WEEK)]);
            attributes.addAttribute("", DATE_ATTR_NAME, DATE_ATTR_NAME, "CDATA",
                    dateFormatter.format(end.getTime()));
            this.contentHandler.startElement(URI, DAY_NODE_NAME, PREFIX + ':' + DAY_NODE_NAME, attributes);
            addContent(end, locale);
            this.contentHandler.endElement(URI, DAY_NODE_NAME, PREFIX + ':' + DAY_NODE_NAME);
            end.add(Calendar.DAY_OF_MONTH, 1);
            if (firstDay == end.get(Calendar.DAY_OF_WEEK)) {
                this.contentHandler.endElement(URI, WEEK_NODE_NAME, PREFIX + ':' + WEEK_NODE_NAME);
            }
        }
    }
    this.contentHandler.endElement(URI, CALENDAR_NODE_NAME, PREFIX + ':' + CALENDAR_NODE_NAME);
    this.contentHandler.endPrefixMapping(PREFIX);
    this.contentHandler.endDocument();
}