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:it.jnrpe.plugin.CheckTime.java

/**
 * Analizes the data and produces the metrics.
 * // w  ww .j av  a  2  s.  com
 * @param metrics
 *            produced metrics
 * @param elapsed
 *            elapsed time
 * @param now
 *            date as of now
 * @param date
 */
private void analyze(final List<Metric> metrics, final long elapsed, final Date now, final Date date) {
    long diff = 0;

    boolean behind = false;
    if (now.before(date)) {
        behind = true;
        diff = date.getTime() - now.getTime();
    } else if (now.after(date)) {
        diff = now.getTime() - date.getTime();
    }

    Elapsed elapsedTime = new Elapsed(diff, TimeUnit.MILLISECOND);

    String msg = getMessage(elapsedTime);
    if (diff > TimeUnit.SECOND.convert(1)) {
        if (behind) {
            msg += "behind";
        } else {
            msg += "ahead";
        }
    }
    metrics.add(new Metric("offset", msg, new BigDecimal(TimeUnit.MILLISECOND.convert(diff, TimeUnit.SECOND)),
            null, null));
    metrics.add(new Metric("time", "", new BigDecimal(TimeUnit.MILLISECOND.convert(elapsed, TimeUnit.SECOND)),
            null, null));
}

From source file:com.znsx.cms.service.impl.LicenseManagerImpl.java

/**
 * //w ww  . jav  a 2 s  . co m
 * 
 * @param license
 *            ?License
 * @throws BusinessException
 * @author huangbuji
 *         <p />
 *         Create at 2013 ?7:26:05
 */
private void expireTimeCheck(License license) throws BusinessException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    try {
        Date expire = sdf.parse(license.getExpireTime());
        Date now = new Date();
        if (now.after(expire)) {
            throw new BusinessException(ErrorCode.LICENSE_EXPIRED, "Platform license is expired !");
        }
        // ??
        long time = userSessionDAO.getLatestSession();
        long hisTime = userSessionHistoryDAO.getLatestSession();
        if (hisTime > time) {
            time = hisTime;
        }
        if ((time - now.getTime()) > 7 * 24 * 3600000) {
            throw new BusinessException(ErrorCode.SYSTEM_BAD_CHANGED, "System time has been bad changed !");
        }

    } catch (ParseException e) {
        e.printStackTrace();
        throw new BusinessException(ErrorCode.LICENSE_EXPIRED_FORMAT_INVALID,
                "License value expire_time[" + license.getExpireTime() + "] invaild !");
    }
}

From source file:ispok.converter.BirthDateConverter.java

@Override
public Object getAsObject(FacesContext fc, UIComponent uic, String string) {

    logger.trace("Entering getAsObject()");

    Locale locale = fc.getViewRoot().getLocale();

    ResourceBundle rb = ResourceBundle.getBundle("ispok/pres/inter/ispok", locale);

    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    SimpleDateFormat sdf = (SimpleDateFormat) df;

    String pattern = sdf.toPattern();
    String localPattern = sdf.toLocalizedPattern();

    logger.debug("pattern: {}", pattern);
    logger.debug("localized pattern: {}", localPattern);

    Date date;

    try {// ww w. j a va2s. c  o m
        date = new SimpleDateFormat(pattern).parse(string);
    } catch (ParseException ex) {
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "invalid date", pattern);
        throw new ConverterException(msg);
    }

    if (date.after(new Date())) {
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, rb.getString("birthdate_invalid"),
                rb.getString("birthdate_valid_future"));
        throw new ConverterException(msg);
    }

    Calendar c = Calendar.getInstance();
    c.set(1850, 1, 1);

    if (date.before(c.getTime())) {
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, rb.getString("birthdate_invalid"),
                rb.getString("birthdate_valid_past"));
        throw new ConverterException(msg);
    }

    return date;
}

From source file:org.motechproject.server.service.OPVScheduleTest.java

public void testSkipExpired() {
    Date date = new Date();

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);//from   www  . j  a v  a2  s .co m
    calendar.add(Calendar.DATE, -28); // age is 4 weeks

    Patient patient = new Patient();
    patient.setBirthdate(calendar.getTime());
    patient.setDateCreated(calendar.getTime());
    Capture<Date> minDateCapture = new Capture<Date>();
    Capture<Date> dueDateCapture = new Capture<Date>();
    Capture<Date> lateDateCapture = new Capture<Date>();
    Capture<Date> maxDateCapture = new Capture<Date>();

    List<Obs> obsList = new ArrayList<Obs>();
    List<ExpectedObs> expectedObsList = new ArrayList<ExpectedObs>();

    expect(registrarBean.getObs(patient, opvSchedule.getConceptName(), opvSchedule.getValueConceptName(),
            patient.getBirthdate())).andReturn(obsList);
    expect(registrarBean.getExpectedObs(patient, opvSchedule.getName())).andReturn(expectedObsList);
    expect(registrarBean.createExpectedObs(eq(patient), eq(opvSchedule.getConceptName()),
            eq(opvSchedule.getValueConceptName()), eq(opv1Event.getNumber()), capture(minDateCapture),
            capture(dueDateCapture), capture(lateDateCapture), capture(maxDateCapture), eq(opv1Event.getName()),
            eq(opvSchedule.getName()))).andReturn(new ExpectedObs());
    calendar.set(2010, 03, 10);
    expect(registrarBean.getChildRegistrationDate()).andReturn(calendar.getTime());

    calendar.set(2011, 03, 10);
    Encounter encounter = new Encounter();
    encounter.setEncounterDatetime(calendar.getTime());
    expect(registrarBean.getEncounters(patient, MotechConstants.ENCOUNTER_TYPE_PATIENTREGVISIT,
            patient.getBirthdate())).andReturn(Arrays.asList(encounter));

    replay(registrarBean);

    opvSchedule.updateSchedule(patient, date);

    verify(registrarBean);

    Date dueDate = dueDateCapture.getValue();
    Date lateDate = lateDateCapture.getValue();

    assertNotNull("Due date is null", dueDate);
    assertNotNull("Late date is null", lateDate);
    assertTrue("Late date is not after due date", lateDate.after(dueDate));

}

From source file:org.openmrs.module.OT.web.ajax.AjaxController.java

@RequestMapping(value = "/module/OT/ajax/validateRescheduleDate.htm", method = RequestMethod.GET)
public void validateRescheduleDate(@RequestParam("rescheduleDate") String rescheduleDateStr,
        @RequestParam("rescheduledTime") String rescheduledTimeStr, HttpServletResponse response)
        throws IOException, ParseException {

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter writer = response.getWriter();

    Date rescheduleDate = OperationTheatreUtil.parseDate(rescheduleDateStr + " " + rescheduledTimeStr);
    Date now = new Date();
    String currentDateStr = OperationTheatreUtil.formatDate(now) + " 12:00 AM";
    Date currentDate = OperationTheatreUtil.parseDate(currentDateStr);
    if (rescheduleDate.after(currentDate))
        writer.print("success");
    else/*w w w. j a v a2 s  .co m*/
        writer.print("fail");
}

From source file:com.webbfontaine.valuewebb.model.validators.tt.TTDateValidator.java

@Override
public boolean isValid(Object value) {
    int range = Utils.getAppCountry().equals(Constants.GH) ? -3 : -2;

    if (Utils.currentPage().contains("TtGenList")) {
        return true;
    }/*from   w ww  . j a v  a 2  s . co m*/

    boolean notFuture;

    if (value != null && value instanceof Date) {
        Date dateValue = (Date) value;
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.YEAR, range);

        notFuture = !DateUtils.truncate(dateValue, Calendar.DAY_OF_MONTH)
                .after(DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH)); // value must not be in future
        return notFuture && dateValue.after(cal.getTime());
    }

    return true;
}

From source file:eu.europa.ec.fisheries.uvms.reporting.service.bean.impl.ReportExecutionServiceBean.java

private void updateTripWithVmsPositionCount(TripDTO trip, Collection<MovementMapResponseType> movementMap) {
    Integer count = 0;/*  w  w  w. j a  v a 2  s . c  om*/

    if (trip != null
            && (trip.getRelativeFirstFaDateTime() != null && trip.getRelativeLastFaDateTime() != null)) {
        for (MovementMapResponseType map : movementMap) {
            for (MovementType movement : map.getMovements()) {
                if (movement.getPositionTime() != null) {
                    Date movementDate = movement.getPositionTime();
                    if (movementDate.after(trip.getRelativeFirstFaDateTime())
                            && movementDate.before(trip.getRelativeLastFaDateTime())) {
                        count++;
                    }
                }
            }
        }
        trip.setVmsPositionCount(count);
    }
}

From source file:eu.europa.esig.dss.client.ocsp.OnlineOCSPSource.java

@Override
public OCSPToken getOCSPToken(CertificateToken certificateToken, CertificateToken issuerCertificateToken) {
    if (dataLoader == null) {
        throw new NullPointerException("DataLoad is not provided !");
    }/*from  ww w . j  av a  2  s  . c  o m*/

    try {
        final String dssIdAsString = certificateToken.getDSSIdAsString();
        if (logger.isTraceEnabled()) {
            logger.trace("--> OnlineOCSPSource queried for " + dssIdAsString);
        }
        final X509Certificate x509Certificate = certificateToken.getCertificate();
        final String ocspAccessLocation = getAccessLocation(x509Certificate);
        if (StringUtils.isEmpty(ocspAccessLocation)) {
            if (logger.isDebugEnabled()) {
                logger.info("No OCSP location found for " + dssIdAsString);
            }
            certificateToken.extraInfo().infoNoOcspUriFoundInCertificate();
            return null;
        }

        final X509Certificate issuerX509Certificate = issuerCertificateToken.getCertificate();
        final byte[] content = buildOCSPRequest(x509Certificate, issuerX509Certificate);

        final byte[] ocspRespBytes = dataLoader.post(ocspAccessLocation, content);

        final OCSPResp ocspResp = new OCSPResp(ocspRespBytes);

        final BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject();

        if (nonceSource != null) {
            Extension extension = basicOCSPResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
            DEROctetString derReceivedNonce = (DEROctetString) extension.getExtnValue();
            BigInteger receivedNonce = new BigInteger(derReceivedNonce.getOctets());
            if (!receivedNonce.equals(nonceSource.getNonce())) {
                throw new DSSException("The OCSP request for " + dssIdAsString
                        + " was the victim of replay attack: nonce [sent:" + nonceSource.getNonce()
                        + ", received:" + receivedNonce + "]");
            }
        }

        Date bestUpdate = null;
        SingleResp bestSingleResp = null;
        final CertificateID certId = DSSRevocationUtils.getOCSPCertificateID(x509Certificate,
                issuerX509Certificate);
        for (final SingleResp singleResp : basicOCSPResp.getResponses()) {
            if (DSSRevocationUtils.matches(certId, singleResp)) {
                final Date thisUpdate = singleResp.getThisUpdate();
                if ((bestUpdate == null) || thisUpdate.after(bestUpdate)) {
                    bestSingleResp = singleResp;
                    bestUpdate = thisUpdate;
                }
            }
        }

        if (bestSingleResp != null) {
            final OCSPToken ocspToken = new OCSPToken(basicOCSPResp, bestSingleResp);
            ocspToken.setSourceURI(ocspAccessLocation);
            certificateToken.setRevocationToken(ocspToken);
            return ocspToken;
        }
    } catch (NullPointerException e) {
        throw new DSSException(
                "OCSPResp is initialised with a null OCSP response... (and there is no nullity check in the OCSPResp implementation)",
                e);
    } catch (OCSPException e) {
        throw new DSSException(e);
    } catch (IOException e) {
        throw new DSSException(e);
    }
    return null;
}

From source file:org.mitre.openid.connect.assertion.JWTBearerAuthenticationProvider.java

/**
 * Try to validate the client credentials by parsing and validating the JWT.
 *///from  w w w. j  a va 2  s.com
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    JWTBearerAssertionAuthenticationToken jwtAuth = (JWTBearerAssertionAuthenticationToken) authentication;

    try {
        ClientDetailsEntity client = clientService.loadClientByClientId(jwtAuth.getClientId());

        JWT jwt = jwtAuth.getJwt();
        JWTClaimsSet jwtClaims = jwt.getJWTClaimsSet();

        // check the signature with nimbus
        if (jwt instanceof SignedJWT) {
            SignedJWT jws = (SignedJWT) jwt;

            JWSAlgorithm alg = jws.getHeader().getAlgorithm();

            if (client.getTokenEndpointAuthSigningAlg() != null
                    && !client.getTokenEndpointAuthSigningAlg().equals(alg)) {
                throw new InvalidClientException("Client's registered request object signing algorithm ("
                        + client.getRequestObjectSigningAlg()
                        + ") does not match request object's actual algorithm (" + alg.getName() + ")");
            }

            if (client.getTokenEndpointAuthMethod() == null
                    || client.getTokenEndpointAuthMethod().equals(AuthMethod.NONE)
                    || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_BASIC)
                    || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_POST)) {

                // this client doesn't support this type of authentication
                throw new AuthenticationServiceException("Client does not support this authentication method.");

            } else if ((client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY)
                    && (alg.equals(JWSAlgorithm.RS256) || alg.equals(JWSAlgorithm.RS384)
                            || alg.equals(JWSAlgorithm.RS512) || alg.equals(JWSAlgorithm.ES256)
                            || alg.equals(JWSAlgorithm.ES384) || alg.equals(JWSAlgorithm.ES512)
                            || alg.equals(JWSAlgorithm.PS256) || alg.equals(JWSAlgorithm.PS384)
                            || alg.equals(JWSAlgorithm.PS512)))
                    || (client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT)
                            && (alg.equals(JWSAlgorithm.HS256) || alg.equals(JWSAlgorithm.HS384)
                                    || alg.equals(JWSAlgorithm.HS512)))) {

                // double-check the method is asymmetrical if we're in HEART mode
                if (config.isHeartMode()
                        && !client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY)) {
                    throw new AuthenticationServiceException("[HEART mode] Invalid authentication method");
                }

                JWTSigningAndValidationService validator = validators.getValidator(client, alg);

                if (validator == null) {
                    throw new AuthenticationServiceException("Unable to create signature validator for client "
                            + client + " and algorithm " + alg);
                }

                if (!validator.validateSignature(jws)) {
                    throw new AuthenticationServiceException(
                            "Signature did not validate for presented JWT authentication.");
                }
            } else {
                throw new AuthenticationServiceException("Unable to create signature validator for method "
                        + client.getTokenEndpointAuthMethod() + " and algorithm " + alg);
            }
        }

        // check the issuer
        if (jwtClaims.getIssuer() == null) {
            throw new AuthenticationServiceException("Assertion Token Issuer is null");
        } else if (!jwtClaims.getIssuer().equals(client.getClientId())) {
            throw new AuthenticationServiceException(
                    "Issuers do not match, expected " + client.getClientId() + " got " + jwtClaims.getIssuer());
        }

        // check expiration
        if (jwtClaims.getExpirationTime() == null) {
            throw new AuthenticationServiceException("Assertion Token does not have required expiration claim");
        } else {
            // it's not null, see if it's expired
            Date now = new Date(System.currentTimeMillis() - (timeSkewAllowance * 1000));
            if (now.after(jwtClaims.getExpirationTime())) {
                throw new AuthenticationServiceException(
                        "Assertion Token is expired: " + jwtClaims.getExpirationTime());
            }
        }

        // check not before
        if (jwtClaims.getNotBeforeTime() != null) {
            Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000));
            if (now.before(jwtClaims.getNotBeforeTime())) {
                throw new AuthenticationServiceException(
                        "Assertion Token not valid untill: " + jwtClaims.getNotBeforeTime());
            }
        }

        // check issued at
        if (jwtClaims.getIssueTime() != null) {
            // since it's not null, see if it was issued in the future
            Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000));
            if (now.before(jwtClaims.getIssueTime())) {
                throw new AuthenticationServiceException(
                        "Assertion Token was issued in the future: " + jwtClaims.getIssueTime());
            }
        }

        // check audience
        if (jwtClaims.getAudience() == null) {
            throw new AuthenticationServiceException("Assertion token audience is null");
        } else if (!(jwtClaims.getAudience().contains(config.getIssuer())
                || jwtClaims.getAudience().contains(config.getIssuer() + "token"))) {
            throw new AuthenticationServiceException("Audience does not match, expected " + config.getIssuer()
                    + " or " + (config.getIssuer() + "token") + " got " + jwtClaims.getAudience());
        }

        // IFF we managed to get all the way down here, the token is valid

        // add in the ROLE_CLIENT authority
        Set<GrantedAuthority> authorities = new HashSet<>(client.getAuthorities());
        authorities.add(ROLE_CLIENT);

        return new JWTBearerAssertionAuthenticationToken(client.getClientId(), jwt, authorities);

    } catch (InvalidClientException e) {
        throw new UsernameNotFoundException("Could not find client: " + jwtAuth.getClientId());
    } catch (ParseException e) {

        logger.error("Failure during authentication, error was: ", e);

        throw new AuthenticationServiceException("Invalid JWT format");
    }
}

From source file:com.apigee.sdk.apm.http.impl.client.cache.CachedResponseSuitabilityChecker.java

/**
 * Check entry against If-Modified-Since, if If-Modified-Since is in the
 * future it is invalid as per//from   ww w. ja  v a2  s  .com
 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
 * 
 * @param request
 * @param entry
 * @param now
 * @return
 */
private boolean lastModifiedValidatorMatches(HttpRequest request, HttpCacheEntry entry, Date now) {
    Header lastModifiedHeader = entry.getFirstHeader(HeaderConstants.LAST_MODIFIED);
    Date lastModified = null;
    try {
        if (lastModifiedHeader != null) {
            lastModified = DateUtils.parseDate(lastModifiedHeader.getValue());
        }
    } catch (DateParseException dpe) {
        // nop
    }

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

    for (Header h : request.getHeaders(HeaderConstants.IF_MODIFIED_SINCE)) {
        try {
            Date ifModifiedSince = DateUtils.parseDate(h.getValue());
            if (ifModifiedSince.after(now) || lastModified.after(ifModifiedSince)) {
                return false;
            }
        } catch (DateParseException dpe) {
            // nop
        }
    }
    return true;
}