Example usage for java.util Date after

List of usage examples for java.util Date after

Introduction

In this page you can find the example usage for java.util Date after.

Prototype

public boolean after(Date when) 

Source Link

Document

Tests if this date is after the specified date.

Usage

From source file:com.thoughtworks.go.domain.AgentInstanceTest.java

@Test
public void shouldUpdateTheLastHeardTime() throws Exception {
    AgentInstance agentInstance = AgentInstance.createFromConfig(agentConfig, systemEnvironment,
            mock(AgentStatusChangeListener.class));
    agentInstance.update(new AgentRuntimeInfo(agentConfig.getAgentIdentifier(), AgentRuntimeStatus.Idle,
            currentWorkingDirectory(), "cookie", false));
    Date time = agentInstance.getLastHeardTime();
    Thread.sleep(1000);//from  w w  w  . jav  a  2  s.  c o m
    agentInstance.update(new AgentRuntimeInfo(agentConfig.getAgentIdentifier(), AgentRuntimeStatus.Idle,
            currentWorkingDirectory(), "cookie", false));
    Date newtime = agentInstance.getLastHeardTime();
    assertThat(newtime.after(time), is(true));
}

From source file:com.dotosoft.dotoquiz.tools.thirdparty.PicasawebClient.java

public void setAlbumDateFromFolder(File folder, AlbumEntry albumEntry) {
    // Can't do this for autobackup albums
    if (isAlbumOfType(AUTO_UPLOAD_TYPE, albumEntry))
        return;//from  w  w  w .  j  a v a  2  s. c o m

    File[] files = folder.listFiles();
    Date newestDate = null;

    if (files != null) {
        for (File file : files) {
            ImageInformation info = safeReadImageInformation(file);

            if (info != null) {
                Date imageDate = info.getDateTaken();
                if (imageDate != null) {
                    if (newestDate == null || imageDate.after(newestDate))
                        newestDate = imageDate;
                }
            }
        }

        if (newestDate != null) {
            log.info("Setting remote album date based on newest photo in " + folder + ": " + newestDate);

            try {
                albumEntry.setDate(newestDate);
                albumEntry.setEtag("*");
                albumEntry.update();
            } catch (Exception ex) {
                log.error("Unable to set album date for " + albumEntry, ex);
            }
        }
    }
}

From source file:jp.terasoluna.fw.validation.ValidationUtil.java

/**
 * ???????????/*from ww w.  j a v  a2 s .c o m*/
 *
 * <code>null</code> ???????
 *
 * @param value 
 * @param startDateStr
 *            ????
 *            <code>datePattern</code>?????
 *            <code>datePatternStrict</code>????????
 * @param endDateStr
 *            ????
 *            <code>datePattern</code>?????
 *            <code>datePatternStrict</code>????????
 * @param datePattern ?
 * @param datePatternStrict ?
 * @return
 *            ??????????
 *            <code>true</code>?
 *            ?????<code>false</code>?
 */
public static boolean isDateInRange(String value, String startDateStr, String endDateStr, String datePattern,
        String datePatternStrict) {

    // ?null?????true?
    if (StringUtils.isEmpty(value)) {
        return true;
    }

    // ??
    Date result = toDate(value, datePattern, datePatternStrict);
    if (result == null) {
        return false;
    }

    if (GenericValidator.isBlankOrNull(startDateStr) && GenericValidator.isBlankOrNull(endDateStr)) {
        // ????????????
        return true;
    }

    // ??????
    if (!GenericValidator.isBlankOrNull(startDateStr)) {
        Date startDate = toDate(startDateStr, datePattern, datePatternStrict);

        if (startDate == null) {
            throw new IllegalArgumentException("startDate is unparseable[" + startDateStr + "]");
        }

        if (result.before(startDate)) {
            return false;
        }
    }

    // ??????
    if (!GenericValidator.isBlankOrNull(endDateStr)) {
        Date endDate = toDate(endDateStr, datePattern, datePatternStrict);

        if (endDate == null) {
            throw new IllegalArgumentException("endDate is unparseable[" + endDateStr + "]");
        }

        if (result.after(endDate)) {
            return false;
        }
    }

    return true;
}

From source file:edu.mayo.cts2.framework.plugin.service.bioportal.rest.BioportalRestService.java

/**
 * Gets the last update from feed.//w w  w.  j a v  a  2 s. com
 *
 * @param feed the feed
 * @return the last update from feed
 */
protected Date getLastUpdateFromFeed(SyndFeed feed) {
    Date latestDate = null;

    for (Object entry : feed.getEntries()) {
        SyndEntry syndEntry = (SyndEntry) entry;
        DateModule date = (DateModule) syndEntry.getModule(DateModule.URI);
        Date foundDate = date.getDate();
        if (latestDate == null || foundDate.after(latestDate)) {
            latestDate = foundDate;
        }
    }

    return latestDate;
}

From source file:com.intel.xdk.cache.Cache.java

private String getCookies() {
    Map<String, ?> valueMap = activity.getSharedPreferences(cookies, 0).getAll();
    SharedPreferences.Editor valueEditor = activity.getSharedPreferences(cookies, 0).edit();
    Map<String, ?> expiresMap = activity.getSharedPreferences(cookiesExpires, 0).getAll();
    SharedPreferences.Editor expiresEditor = activity.getSharedPreferences(cookiesExpires, 0).edit();

    StringBuffer cookies = new StringBuffer("{");
    Iterator<String> keys = valueMap.keySet().iterator();
    while (keys.hasNext()) {
        String key = keys.next();
        String value = (String) valueMap.get(key);
        String expires = (String) expiresMap.get(key);
        Date expiresDate = null, now = new Date();
        if (!expires.equals(DONOTEXPIRE)) {
            try {
                expiresDate = sdf.parse(expires);
            } catch (ParseException e) {
                e.printStackTrace();/*  w ww  . j  a  v a 2s . c o m*/
            }
        }
        if (expiresDate == null || expiresDate.after(now)) {
            value = value.replaceAll("'", "\\\\'");
            cookies.append(key + ":{value:'" + value + "'}");
            if (keys.hasNext()) {
                cookies.append(", ");
            }
        } else {
            //coookie is expired - remove it from prefs
            valueEditor.remove(key);
            expiresEditor.remove(key);
        }
    }
    valueEditor.commit();
    expiresEditor.commit();
    cookies.append("}");
    if (Debug.isDebuggerConnected())
        Log.i(tag, "intel.xdk.cookies: " + cookies.toString());
    return cookies.toString();
}

From source file:com.celements.blog.plugin.BlogPlugin.java

private void filterTimespan(List<Article> articles, String language, boolean withArchive, boolean archiveOnly,
        boolean withFutur, boolean futurOnly, XWikiContext context) {
    Date now = new Date();
    List<Article> deleteArticles = new ArrayList<Article>();
    for (Iterator<Article> artIter = articles.iterator(); artIter.hasNext();) {
        Article article = (Article) artIter.next();
        Date archivedate = article.getArchiveDate(language);
        Date publishdate = article.getPublishDate(language);
        if (((archivedate != null) && archivedate.before(now))
                && ((!withArchive && !archiveOnly) || futurOnly)) {
            deleteArticles.add(article);
        }/*from   w  ww  . j av  a  2  s . co m*/
        if (((publishdate != null) && publishdate.after(now))
                && ((!withFutur && !futurOnly) || (archiveOnly && (!withFutur || (archivedate == null)
                        || ((archivedate != null) && archivedate.after(now)))))) {
            deleteArticles.add(article);
        }
        if (((publishdate == null) || publishdate.before(now))
                && ((archivedate == null) || archivedate.after(now)) && (archiveOnly || futurOnly)) {
            deleteArticles.add(article);
        }
    }
    for (Iterator<Article> delIter = deleteArticles.iterator(); delIter.hasNext();) {
        articles.remove(delIter.next());
    }
}

From source file:org.openehealth.coala.beans.PatientBean.java

/**
 * Method to validate search parameters patientID, givenName, lastName and
 * dateOfBirth as a group. This is needed to have proper error notification
 * on failed search field input at search view, if user provides non
 * matching (invalid) input./*  w w w .ja v a  2  s .  c o m*/
 * 
 * @param event
 */
public void validateSearchParameters(ComponentSystemEvent event) {
    searchString.delete(0, searchString.length());
    FacesContext fc = FacesContext.getCurrentInstance();
    String messages = fc.getApplication().getMessageBundle();
    Locale locale = new Locale(localeHandler.getLocale());
    ResourceBundle bundle = ResourceBundle.getBundle(messages, locale);

    UIComponent components = event.getComponent();

    UIInput patientIDInput = (UIInput) components.findComponent("patientID");
    String patientID = patientIDInput.getLocalValue().toString();
    UIInput givenNameInput = (UIInput) components.findComponent("givenName");
    String givenName = givenNameInput.getLocalValue().toString();
    UIInput lastNameInput = (UIInput) components.findComponent("lastName");
    String lastName = lastNameInput.getLocalValue().toString();
    UIInput dateOfBirthInput = (UIInput) components.findComponent("dateOfBirth");

    boolean patientIDEmpty = false;
    boolean givenNameEmpty = false;
    boolean lastNameEmpty = false;
    boolean dateOfBirthEmpty = false;
    if (patientIDInput.getLocalValue() == null || patientIDInput.getLocalValue().toString().trim().isEmpty()) {
        patientIDEmpty = true;
    }
    if (givenNameInput.getLocalValue() == null || givenNameInput.getLocalValue().toString().trim().isEmpty()) {
        givenNameEmpty = true;
    }
    if (lastNameInput.getLocalValue() == null || lastNameInput.getLocalValue().toString().trim().isEmpty()) {
        lastNameEmpty = true;
    }
    if (dateOfBirthInput.getLocalValue() == null
            || dateOfBirthInput.getLocalValue().toString().trim().isEmpty()) {
        dateOfBirthEmpty = true;
    }

    if (patientIDEmpty && givenNameEmpty && lastNameEmpty && dateOfBirthEmpty) {
        FacesMessage msg = new FacesMessage(bundle.getString("errors.nonEmptySearchKey"), "");
        msg.setSeverity(FacesMessage.SEVERITY_WARN);
        fc.addMessage(components.getClientId(), msg);
        // passed to the Render Response phase
        fc.renderResponse();
        cleanOutdatedViewState();
        setPatients(new ListDataModel<Patient>());

    } else {
        boolean validationErrorOccured = false;
        // validating correctness of patientID value if it is set
        if (!patientIDEmpty) {
            if (!StringUtils.isNumeric(patientID)) {
                FacesMessage msg = new FacesMessage(bundle.getString("errors.numericPatientID"), "");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                fc.addMessage(patientIDInput.getClientId(), msg);
                validationErrorOccured = true;
            } else { // ok here -> no actions required, move on now :)
            }
            searchString.append(bundle.getString("search.patient_id") + ": " + patientID + " ");
        }
        // validating correctness of givenName value if it is set
        if (!givenNameEmpty) {

            //            String givenNameChecked = checkAndFixWrongCharset(givenName);
            boolean patternOK = Pattern.matches("[a-zA-Z]*[*]?", givenName);
            if (!patternOK) {
                FacesMessage msg = new FacesMessage(bundle.getString("errors.nonNumericGivenName"), "");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                fc.addMessage(givenNameInput.getClientId(), msg);
                validationErrorOccured = true;
            } else { // ok here -> no actions required, move on now :)
            }
            searchString.append(bundle.getString("search.patient_givenName") + ": " + givenName + " ");
        }
        // validating correctness of lastname value if it is set
        if (!lastNameEmpty) {

            //            String lastNameChecked = checkAndFixWrongCharset(lastName);
            boolean patternOK = Pattern.matches("[a-zA-Z]*[*]?", lastName);
            if (!patternOK) {
                FacesMessage msg = new FacesMessage(bundle.getString("errors.nonNumericLastName"), "");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                fc.addMessage(lastNameInput.getClientId(), msg);
                validationErrorOccured = true;
            } else { // ok here -> no actions required, move on now :)
            }
            searchString.append(bundle.getString("search.patient_lastname") + ": " + lastName + " ");
        }
        // validating correctness of dateOfBirth value if it is set
        if (!dateOfBirthEmpty) {
            try {
                // check for a valid date format by casting into a date
                Date dateOfBirth = (Date) dateOfBirthInput.getLocalValue();
                // if we have real Date object -> check for future date
                // value which make no sense here!
                if (dateOfBirth.after(new Date())) {
                    FacesMessage msg = new FacesMessage("Date of birth must not be in the future!", "");
                    msg.setSeverity(FacesMessage.SEVERITY_WARN);
                    fc.addMessage(dateOfBirthInput.getClientId(), msg);
                    validationErrorOccured = true;
                } else { // ok here -> no actions required, move on now :)
                }
            } catch (RuntimeException rt) {
                // occurs if no valid Date object was in the input field
                // given by the user input
                FacesMessage msg = new FacesMessage(
                        "Please provide a valid date of birth in a useful format. Hint: 'Calendar'!", "");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                fc.addMessage(dateOfBirthInput.getClientId(), msg);
                validationErrorOccured = true;
            }
        }
        /*
         * FINALLY CHECK IF ANY ERRORS HAVE OCCURED WHICH CAUSE THE EARLY
         * RENDER RESPONSE... -> STOP ANY SEARCH!
         */
        if (validationErrorOccured) {
            // passed to the Render Response phase
            fc.renderResponse();
            cleanOutdatedViewState();
            setPatients(new ListDataModel<Patient>());
        }
    }
}

From source file:org.openmrs.module.emrapi.adt.AdtServiceImpl.java

@Override
@Transactional/*from   w w w  .  j a v a2s.c om*/
public VisitDomainWrapper createRetrospectiveVisit(Patient patient, Location location, Date startDatetime,
        Date stopDatetime) throws ExistingVisitDuringTimePeriodException {

    if (startDatetime.after(new Date())) {
        throw new IllegalArgumentException("emrapi.retrospectiveVisit.startDateCannotBeInFuture");
    }

    if (stopDatetime.after(new Date())) {
        throw new IllegalArgumentException("emrapi.retrospectiveVisit.stopDateCannotBeInFuture");
    }

    if (startDatetime.after(stopDatetime)) {
        throw new IllegalArgumentException("emrapi.retrospectiveVisit.endDateBeforeStartDateMessage");
    }

    if (hasVisitDuring(patient, location, startDatetime, stopDatetime)) {
        throw new ExistingVisitDuringTimePeriodException("emrapi.retrospectiveVisit.patientAlreadyHasVisit");
    }

    Visit visit = buildVisit(patient, location, startDatetime);
    visit.setStopDatetime(stopDatetime);

    return wrap(visitService.saveVisit(visit));
}

From source file:com.jpeterson.littles3.bo.S3Authenticator.java

/**
 * Authenticate the request using the prescribed Amazon S3 authentication
 * mechanisms.//from   w  ww .  ja  v  a  2 s .co m
 * 
 * @param req
 *            The original HTTP request.
 * @param s3Request
 *            The S3 specific information for authenticating the request.
 * @return The authenticated <code>CanonicalUser</code> making the request.
 * @throws RequestTimeTooSkewedException
 *             Thrown if the request timestamp is outside of the allotted
 *             timeframe.
 */
public CanonicalUser authenticate(HttpServletRequest req, S3ObjectRequest s3Request)
        throws AuthenticatorException {
    // check to see if anonymous request
    String authorization = req.getHeader(HEADER_AUTHORIZATION);

    if (authorization == null) {
        return new CanonicalUser(CanonicalUser.ID_ANONYMOUS);
    }

    // attempting to be authenticated request

    if (false) {
        // check timestamp of request
        Date timestamp = s3Request.getTimestamp();
        if (timestamp == null) {
            throw new RequestTimeTooSkewedException("No timestamp provided");
        }

        GregorianCalendar calendar = new GregorianCalendar();
        Date now = calendar.getTime();
        calendar.add(Calendar.MINUTE, 15);
        Date maximumDate = calendar.getTime();
        calendar.add(Calendar.MINUTE, -30);
        Date minimumDate = calendar.getTime();

        if (timestamp.before(minimumDate)) {
            throw new RequestTimeTooSkewedException(
                    "Timestamp [" + timestamp + "] too old. System time: " + now);
        }

        if (timestamp.after(maximumDate)) {
            throw new RequestTimeTooSkewedException(
                    "Timestamp [" + timestamp + "] too new. System time: " + now);
        }
    }

    // authenticate request
    String[] fields = authorization.split(" ");

    if (fields.length != 2) {
        throw new InvalidSecurityException("Unsupported authorization format");
    }

    if (!fields[0].equals(AUTHORIZATION_TYPE)) {
        throw new InvalidSecurityException("Unsupported authorization type: " + fields[0]);
    }

    String[] keys = fields[1].split(":");

    if (keys.length != 2) {
        throw new InvalidSecurityException("Invalid AWSAccesskeyId:Signature");
    }

    String accessKeyId = keys[0];
    String signature = keys[1];
    String secretAccessKey = userDirectory.getAwsSecretAccessKey(accessKeyId);
    String calculatedSignature;

    try {
        SecretKey key = new SecretKeySpec(secretAccessKey.getBytes(), "HmacSHA1");
        Mac m = Mac.getInstance("HmacSHA1");
        m.init(key);
        m.update(s3Request.getStringToSign().getBytes());
        byte[] mac = m.doFinal();
        calculatedSignature = new String(Base64.encodeBase64(mac));
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidSecurityException(e);
    } catch (InvalidKeyException e) {
        throw new InvalidSecurityException(e);
    }

    System.out.println("-----------------");
    System.out.println("signature: " + signature);
    System.out.println("calculatedSignature: " + calculatedSignature);
    System.out.println("-----------------");

    if (calculatedSignature.equals(signature)) {
        // authenticated!
        return userDirectory.getCanonicalUser(secretAccessKey);
    } else {
        throw new SignatureDoesNotMatchException("Provided signature doesn't match calculated value");
    }
}