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.globus.workspace.service.impls.WorkspaceHomeImpl.java

public InstanceResource find(String id)

        throws ManageException, DoesNotExistException {

    if (id == null) {
        throw new ManageException("id may not be null");
    }//from  w  w  w. j ava 2  s.  c  o m

    final InstanceResource resource;

    final Lock lock = this.lockManager.getLock(id);
    try {
        lock.lockInterruptibly();
    } catch (InterruptedException e) {
        throw new ManageException(e.getMessage(), e);
    }

    try {

        final Element el = this.cache.get(id);
        if (el == null) {
            resource = this.newInstance(id);
            resource.load(id); // throws DoesNotExistException if not in db

            final Calendar currTime = Calendar.getInstance();
            final Calendar termTime = resource.getTerminationTime();
            if (termTime != null && termTime.before(currTime)) {
                boolean destroyed = this.destroy(id);
                if (destroyed) {
                    throw new DoesNotExistException(Lager.id(id) + " expired");
                }
            }

        } else {
            resource = (InstanceResource) el.getObjectValue();
        }

    } catch (DoesNotExistException e) {
        this.cache.remove(id);
        throw e;
    } catch (CreationException e) {
        throw new ManageException(e.getMessage(), e); // ...
    } finally {
        lock.unlock();
    }

    return resource;
}

From source file:nkarasch.repeatingreminder.scheduling.AlertBroadcastReceiver.java

private DAY_POSITION isLegalTime(Calendar calendar, Alert alert) {

    Calendar startTime = Calendar.getInstance();
    startTime.set(Calendar.DAY_OF_WEEK, calendar.get(Calendar.DAY_OF_WEEK));
    startTime.set(Calendar.HOUR_OF_DAY, alert.getStartHour());
    startTime.set(Calendar.MINUTE, alert.getStartMinute());
    startTime.set(Calendar.SECOND, 0);
    startTime.add(Calendar.SECOND, -1);

    Calendar endTime = Calendar.getInstance();
    endTime.set(Calendar.DAY_OF_WEEK, calendar.get(Calendar.DAY_OF_WEEK));
    endTime.set(Calendar.HOUR_OF_DAY, alert.getEndHour());
    endTime.set(Calendar.MINUTE, alert.getEndMinute());
    endTime.set(Calendar.SECOND, 0);
    endTime.add(Calendar.SECOND, 61);

    if (calendar.after(startTime) && calendar.before(endTime)) {
        return DAY_POSITION.BETWEEN;
    } else if (calendar.after(endTime)) {
        return DAY_POSITION.AFTER_END;
    } else if (calendar.before(startTime)) {
        return DAY_POSITION.BEFORE_START;
    } else {/*from  w ww  .j a  va 2 s . c o m*/
        return DAY_POSITION.BETWEEN;
    }
}

From source file:com.intuit.wasabi.tests.service.IntegrationExperiment.java

/**
 * Checks if the date change behaviour is correct for several cases.
 *
 * @param identifier the identifier of the test
 * @param start      the start time/*from   www  . jav  a 2  s  .c o  m*/
 * @param end        the end time
 * @throws ParseException when parse date time failed
 */
@Test(dependsOnMethods = { "t_remainingTransitionTests" }, dataProvider = "dates")
public void t_validDateBehaviourOnTransitions(String identifier, String start, String end)
        throws ParseException {
    LOGGER.info("Testing " + identifier + " behaviour.");

    // use a start time in the near future to make sure nothing goes wrong unexpectedly
    String defaultStart = TestUtils.relativeTimeString(2);
    Calendar now = Calendar.getInstance();
    Calendar startCal = TestUtils.parseTime(start);
    Calendar endCal = TestUtils.parseTime(end);
    boolean invalid = startCal.before(now) || startCal.after(endCal);

    // Try to change in draft state
    Experiment experimentDraftState = postExperiment(
            ExperimentFactory.createExperiment().setStartTime(defaultStart));
    experimentDraftState.setStartTime(start).setEndTime(end);
    Experiment updatedDraftState = putExperiment(experimentDraftState,
            // FIXME: jwtodd
            //                startCal.after(endCal)? HttpStatus.SC_BAD_REQUEST : HttpStatus.SC_OK);
            startCal.after(endCal) ? HttpStatus.SC_BAD_REQUEST : HttpStatus.SC_OK);
    if (startCal.after(endCal)) {
        // FIXME: jwtodd
        //            Assert.assertEquals(lastError(), "Invalid input");
        Assert.assertTrue(lastError().startsWith("Invalid "));
    } else {
        assertEqualModelItems(updatedDraftState, experimentDraftState,
                new DefaultNameExclusionStrategy("modificationTime"));
    }
    toCleanUp.add(updatedDraftState);

    // Try to change in running state
    Experiment experimentRunningState = postExperiment(
            ExperimentFactory.createExperiment().setStartTime(defaultStart));
    postBucket(BucketFactory.createBucket(experimentRunningState).setAllocationPercent(1));
    experimentRunningState.setState(Constants.EXPERIMENT_STATE_RUNNING);
    putExperiment(experimentRunningState);
    experimentRunningState.setStartTime(start).setEndTime(end);
    Experiment updatedRunningState = putExperiment(experimentRunningState,
            // FIXME: jwtodd
            //                invalid ? HttpStatus.SC_BAD_REQUEST : HttpStatus.SC_OK);
            invalid ? HttpStatus.SC_BAD_REQUEST : HttpStatus.SC_OK);
    if (invalid) {
        // FIXME: jwtodd
        //            Assert.assertEquals(lastError(), "Invalid input");
        Assert.assertTrue(lastError().startsWith("Invalid "));
    } else {
        assertEqualModelItems(updatedRunningState, experimentRunningState,
                new DefaultNameExclusionStrategy("modificationTime"));
    }
    toCleanUp.add(updatedRunningState);

    // Try to change in paused state
    Experiment experimentPausedState = postExperiment(
            ExperimentFactory.createExperiment().setStartTime(defaultStart));
    postBucket(BucketFactory.createBucket(experimentPausedState).setAllocationPercent(1));
    experimentPausedState.setState(Constants.EXPERIMENT_STATE_PAUSED);
    putExperiment(experimentPausedState);
    experimentPausedState.setStartTime(start).setEndTime(end);
    Experiment updatedPausedState = putExperiment(experimentPausedState,
            // FIXME: jwtodd
            //                invalid ? HttpStatus.SC_BAD_REQUEST : HttpStatus.SC_OK);
            invalid ? HttpStatus.SC_BAD_REQUEST : HttpStatus.SC_OK);
    if (invalid) {
        // FIXME: jwtodd
        //            Assert.assertEquals(lastError(), "Invalid input");
        Assert.assertTrue(lastError().startsWith("Invalid "));
    } else {
        assertEqualModelItems(updatedPausedState, experimentPausedState,
                new DefaultNameExclusionStrategy("modificationTime"));
    }
    toCleanUp.add(updatedPausedState);

    // Try to change in terminated state: is never allowed
    Experiment experimentTerminatedState = postExperiment(
            ExperimentFactory.createExperiment().setStartTime(defaultStart));
    postBucket(BucketFactory.createBucket(experimentTerminatedState).setAllocationPercent(1));
    experimentTerminatedState.setState(Constants.EXPERIMENT_STATE_PAUSED);
    putExperiment(experimentTerminatedState);
    experimentTerminatedState.setState(Constants.EXPERIMENT_STATE_TERMINATED);
    putExperiment(experimentTerminatedState);
    experimentTerminatedState.setStartTime(start).setEndTime(end);
    // FIXME: jwtodd
    //        putExperiment(experimentTerminatedState, HttpStatus.SC_BAD_REQUEST);
    putExperiment(experimentTerminatedState, HttpStatus.SC_BAD_REQUEST);
    // FIXME: jwtodd
    //        Assert.assertEquals(lastError(), "Invalid input");
    Assert.assertTrue(lastError().startsWith("Invalid "));
    toCleanUp.add(experimentTerminatedState);
}

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

@Override
public View workOn(final PasswordReminderCommand command) {

    /*//from  w w  w.  j a  v  a2  s.  c  o  m
     * check if internal authentication is supported
     */
    if (!authConfig.containsAuthMethod(AuthMethod.INTERNAL)) {
        errors.reject("error.method_not_allowed");
        return Views.ERROR;
    }

    // get locale
    final Locale locale = requestLogic.getLocale();

    final User user = new User();
    user.setName(command.getUserName());
    user.setEmail(command.getUserEmail());

    /*
     * Get the hosts IP address.
     */
    final String inetAddress = requestLogic.getInetAddress();
    final String hostInetAddress = requestLogic.getHostInetAddress();

    /*
     * check captcha
     */
    this.checkCaptcha(command.getRecaptcha_challenge_field(), command.getRecaptcha_response_field(),
            hostInetAddress);

    /*
     * If the user name is null, we get an exception on getUserDetails.
     * Hence, we send the user back to the form.
     */
    if (errors.hasErrors()) {
        /*
         * Generate HTML to show captcha.
         */
        command.setCaptchaHTML(captcha.createCaptchaHtml(locale));
        return Views.PASSWORD_REMINDER;
    }

    /*
     * check, if user name exists
     */
    final User existingUser = adminLogic.getUserDetails(user.getName());

    if (existingUser == null || existingUser.getName() == null || Role.DELETED.equals(existingUser.getRole())) {
        /*
         * user does not exist or has been deleted (we should not sent 
         * reminders to deleted users!)
         */
        errors.rejectValue("userName", "error.field.valid.user.name");
    } else if (!user.getEmail().equalsIgnoreCase(existingUser.getEmail())) {
        /*
         * user exists but email address does not match
         */
        errors.rejectValue("userEmail", "error.field.valid.user.email");
    } else if (present(existingUser.getLdapId())) {
        /*
         * user exists and e-mail-address is fine but user has an LDAP ID
         * and thus shall not use the reminder
         */
        errors.reject("error.passReminder.ldap",
                "You are registered using LDAP and thus don't have a password we could send you a reminder for.");
    } else if (present(existingUser.getOpenID())) {
        /*
         * user exists and e-mail-address is fine but user has an OpenID
         * and thus shall not use the reminder
         */
        errors.reject("error.passReminder.openid",
                "You are registered using OpenID and thus don't have a password we could send you a reminder for.");
    }

    /*
     * If the user does not exist, getReminderPasswordRequestDate() returns null.
     * Hence, we send the user back to the form.
     */
    if (errors.hasErrors()) {
        /*
         * Generate HTML to show captcha.
         */
        command.setCaptchaHTML(captcha.createCaptchaHtml(locale));
        return Views.PASSWORD_REMINDER;
    }

    /*
     * check, if user has requested a password reminder not so long ago
     */
    final Calendar now = Calendar.getInstance();
    /*
     * set expiration date by adding the max number of minutes a password
     * reminder is valid to the time where the user requested the reminder
     */
    final Calendar reminderExpirationDate = Calendar.getInstance();
    reminderExpirationDate.setTime(existingUser.getReminderPasswordRequestDate());
    reminderExpirationDate.add(Calendar.MINUTE, maxMinutesPasswordReminderValid);
    if (now.before(reminderExpirationDate)) {
        /*
         * existing reminder still valid
         */
        final int waitingMinutes = (int) (reminderExpirationDate.getTimeInMillis() - now.getTimeInMillis())
                / 1000 / 60;
        errors.reject("error.passReminder.time",
                new Object[] { maxMinutesPasswordReminderValid, waitingMinutes },
                "You already requested a password in the last " + maxMinutesPasswordReminderValid
                        + " minutes. Please wait " + waitingMinutes
                        + " minutes before you can request a new password");
    }

    /*
     * Password reminder still valid -> send user back.
     */
    if (errors.hasErrors()) {
        /*
         * Generate HTML to show captcha.
         */
        command.setCaptchaHTML(captcha.createCaptchaHtml(locale));
        return Views.PASSWORD_REMINDER;
    }

    /*
     * at this point the given information like email and username are correct, and now we
     * need to create a new pass and put it into the DB and send it per mail.
     */

    /*
     * create the random pw and set it to the user object
     */
    final String tempPassword = getRandomString();
    user.setReminderPassword(tempPassword);
    user.setReminderPasswordRequestDate(new Date());

    // create reminder hash
    final String reminderHash = this.encryptReminderHash(user.getName(), tempPassword);

    // update db
    adminLogic.updateUser(user, UserUpdateOperation.UPDATE_ALL);

    // send mail
    mailUtils.sendPasswordReminderMail(user.getName(), user.getEmail(), inetAddress, locale,
            maxMinutesPasswordReminderValid, UrlUtils.safeURIEncode(reminderHash));

    command.setSuccess(true);
    return Views.PASSWORD_REMINDER;
}

From source file:com.hypersocket.session.SessionServiceImpl.java

@Override
public synchronized boolean isLoggedOn(Session session, boolean touch) {
    if (session == null)
        return false;

    repository.refresh(session);/* w w  w. j  av  a 2 s.  c  o  m*/

    if (session.getSignedOut() == null) {

        Calendar currentTime = Calendar.getInstance();
        Calendar c = Calendar.getInstance();
        c.setTime(session.getLastUpdated());
        c.add(Calendar.MINUTE, session.getTimeout());

        if (log.isDebugEnabled()) {
            log.debug("Checking session timeout currentTime=" + currentTime.getTime() + " lastUpdated="
                    + session.getLastUpdated() + " timeoutThreshold=" + c.getTime());
        }

        if (c.before(currentTime)) {
            if (log.isDebugEnabled()) {
                log.debug("Session has timed out");
            }
            closeSession(session);

            if (log.isDebugEnabled()) {
                log.debug("Session " + session.getPrincipal().getPrincipalName() + "/" + session.getId()
                        + " is now closed");
            }

            return false;
        }

        if (touch) {
            session.touch();
            if (session.isReadyForUpdate()) {
                repository.updateSession(session);
                if (log.isDebugEnabled()) {
                    log.debug("Session " + session.getPrincipal().getPrincipalName() + "/" + session.getId()
                            + " state has been updated");
                }
            }

        }
        return true;
    } else {
        return false;
    }

}

From source file:gov.utah.dts.sdc.actions.CommercialStudentCreateAction.java

private boolean isValidCompletionDate(Date date1) {

    Calendar today = Calendar.getInstance();
    Calendar date1Cal = Calendar.getInstance();
    date1Cal.setTime(date1);//from  w  w  w. ja va  2 s.c  om

    // set hour, minute, and secod to 0
    today.set(Calendar.HOUR_OF_DAY, 0);
    today.set(Calendar.MINUTE, 0);
    today.set(Calendar.SECOND, 0);
    today.set(Calendar.MILLISECOND, 0);
    date1Cal.set(Calendar.HOUR_OF_DAY, 0);
    date1Cal.set(Calendar.MINUTE, 0);
    date1Cal.set(Calendar.SECOND, 0);
    date1Cal.set(Calendar.MILLISECOND, 0);

    if (date1Cal.before(today) || date1Cal.equals(today)) {
        return true;
    }

    return false;
}

From source file:org.kuali.kfs.pdp.service.impl.PaymentFileValidationServiceImpl.java

/**
 * Checks the payment date is not more than 30 days past or 30 days coming
 *
 * @param paymentGroup <code>PaymentGroup</code> being checked
 * @param warnings <code>List</code> list of accumulated warning messages
 *///from   w ww . j  a v a2  s. c o m
protected void checkGroupPaymentDate(PaymentGroup paymentGroup, List<String> warnings) {
    Timestamp now = dateTimeService.getCurrentTimestamp();

    Calendar nowPlus30 = Calendar.getInstance();
    nowPlus30.setTime(now);
    nowPlus30.add(Calendar.DATE, 30);

    Calendar nowMinus30 = Calendar.getInstance();
    nowMinus30.setTime(now);
    nowMinus30.add(Calendar.DATE, -30);

    if (paymentGroup.getPaymentDate() != null) {
        Calendar payDate = Calendar.getInstance();
        payDate.setTime(paymentGroup.getPaymentDate());

        if (payDate.before(nowMinus30)) {
            addWarningMessage(warnings, PdpKeyConstants.MESSAGE_PAYMENT_LOAD_PAYDATE_OVER_30_DAYS_PAST,
                    dateTimeService.toDateString(paymentGroup.getPaymentDate()));
        }

        if (payDate.after(nowPlus30)) {
            addWarningMessage(warnings, PdpKeyConstants.MESSAGE_PAYMENT_LOAD_PAYDATE_OVER_30_DAYS_OUT,
                    dateTimeService.toDateString(paymentGroup.getPaymentDate()));
        }
    } else {
        // KFSMI-9997
        // Calculate tomorrow's date to set as payment date rather than null
        Calendar tomorrow = Calendar.getInstance();
        tomorrow.setTime(now);
        tomorrow.add(Calendar.DATE, 1);
        tomorrow.getTime();

        Date paymentDate = new Date(tomorrow.getTime().getTime());
        paymentGroup.setPaymentDate(paymentDate);
    }
}

From source file:bamboo.trove.rule.RuleChangeUpdateManager.java

/**
 * Calculate the date time of the next run.
 *
 * @return The time of the next run.//from   w  w  w  .  j  ava 2s  . c o  m
 */
private Date nextRunDate() {
    Calendar now = Calendar.getInstance();
    Calendar next = Calendar.getInstance();
    next.set(Calendar.HOUR_OF_DAY, scheduleTimeHour);
    next.set(Calendar.MINUTE, scheduleTimeMinute);
    if (next.before(now)) {
        next.add(Calendar.DATE, 1);
    }
    return next.getTime();
}

From source file:it.geosolutions.geobatch.flow.file.FileBasedFlowManager.java

/**
 * returns an unmodifiable descending ordered by creation time list of all the consumers
 * //from   www. j a  va  2 s  .co m
 * @return
 */
public final Set<BaseEventConsumer> getEventConsumers() {
    TreeSet tree = new TreeSet<BaseEventConsumer<EventObject, EventConsumerConfiguration>>(
            new Comparator<BaseEventConsumer<EventObject, EventConsumerConfiguration>>() {
                @Override
                public int compare(BaseEventConsumer<EventObject, EventConsumerConfiguration> o1,
                        BaseEventConsumer<EventObject, EventConsumerConfiguration> o2) {
                    Calendar cal = o1.getCreationTimestamp();
                    Calendar currentcal = o2.getCreationTimestamp();
                    if (cal.before(currentcal))
                        return 1;
                    else if (cal.after(currentcal))
                        return -1;
                    else
                        return 0;
                }
            });
    tree.addAll(eventConsumers.values());
    return tree;
}

From source file:com.ecofactor.qa.automation.newapp.service.DataServiceImpl.java

/**
 * Gets the current base temp./*from w  w  w. j av a  2s .  c o  m*/
 * 
 * @param thermostatId
 *            the thermostat id
 * @param mode
 *            the mode
 * @return the current base temp
 * @see com.ecofactor.qa.automation.algorithm.service.DataService#getCurrentBaseTemp(java.lang.Integer,
 *      java.lang.String)
 */
public double getCurrentBaseTemp(Integer thermostatId, String mode) {

    double baseTemp = 0;
    List<ThermostatProgramLog> programList = tstatProgLogDao.listUTCCurrentDayLog(thermostatId,
            DateUtil.getUTCDayOfWeek());
    for (ThermostatProgramLog tstatProgramLog : programList) {

        Date startTimeUTC = tstatProgramLog.getStartTimeUTC();
        Date endTimeUTC = tstatProgramLog.getEndTimeUTC();

        DateTime startTimeJoda = new DateTime(startTimeUTC);
        DateTime endTimeJoda = new DateTime(endTimeUTC);

        Calendar startCalendar = DateUtil.convertTimeToUTCCalendar(startTimeJoda);
        Calendar endCalendar = DateUtil.convertTimeToUTCCalendar(endTimeJoda);
        Calendar utcCalendar = DateUtil.getUTCCalendar();

        if (!endCalendar.before(utcCalendar) && !startCalendar.after(utcCalendar)) {

            if (mode.equalsIgnoreCase("Cool")) {
                baseTemp = tstatProgramLog.getCoolSetting();
            } else if (mode.equalsIgnoreCase("Heat")) {
                baseTemp = tstatProgramLog.getHeatSetting();
            }
            break;
        }
    }

    DriverConfig.setLogString("Base Temp from Program Log table : " + baseTemp, true);
    LOGGER.debug("Base Temp from Program Log table : " + baseTemp, true);
    return baseTemp;
}