Example usage for java.util Date before

List of usage examples for java.util Date before

Introduction

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

Prototype

public boolean before(Date when) 

Source Link

Document

Tests if this date is before the specified date.

Usage

From source file:eu.europa.esig.dss.validation.process.ltv.ControlTimeSliding.java

/**
 * @param params//from  ww w  .ja  v a 2s  .  com
 * @param certificateChain
 * @return
 */
private ControlTimeSlidingConclusion process(final ProcessParameters params, final XmlDom certificateChain) {

    final ControlTimeSlidingConclusion conclusion = new ControlTimeSlidingConclusion();

    final String signingCertificateId = certificateChain.getValue("./ChainCertificate[1]/@Id");

    final List<XmlDom> chainCertificates = certificateChain.getElements("./ChainCertificate");

    Collections.reverse(chainCertificates);

    /**
     * 2) For each certificate in the chain starting from the first certificate (the certificate issued by the trust
     * anchor), do the following:<br>
     */
    for (final XmlDom chainCertificate : chainCertificates) {

        final String certificateId = getCertificateId(chainCertificate);
        final XmlNode certificateNode = controlTimeSlidingData.addChild(AttributeValue.CERTIFICATE,
                StringUtils.EMPTY);
        certificateNode.setAttribute(AttributeValue.CERTIFICATE_ID, String.valueOf(certificateId));

        final XmlDom certificate = params.getCertificate(certificateId);

        final boolean isTrusted = certificate.getBoolValue("./Trusted/text()");
        if (isTrusted) {

            continue;
        }

        if (StringUtils.equals(signingCertificateId, certificateId)) {

            /**
             * (See NOTE 1) Concerning the trust anchor, it must be checked if it is still trusted at the current
             * date/time. Other checks are not necessary.<br>
             */
            final XmlNode constraintNode = addConstraint(MessageTag.CTS_WITSS);

            final String status = InvolvedServiceInfo.getStatus(certificate);
            constraintNode.addChild(NodeName.STATUS, NodeValue.OK);
            constraintNode.addChild(NodeName.INFO).setAttribute(AttributeValue.TRUSTED_SERVICE_STATUS, status);

            final boolean underSupervision = InvolvedServiceInfo.isSERVICE_STATUS_UNDERSUPERVISION(status);
            final boolean supervisionInCessation = InvolvedServiceInfo
                    .isSERVICE_STATUS_SUPERVISIONINCESSATION(status);
            final boolean accredited = InvolvedServiceInfo.isSERVICE_STATUS_ACCREDITED(status);

            if (!underSupervision && !supervisionInCessation && !accredited) {

                /**
                 * ...where the trust anchor is broken at a known date by initialising control-time to this date/time.<br>
                 */
                if (status.isEmpty()) {

                    // Trusted service is unknown
                    final String serviceName = InvolvedServiceInfo.getServiceName(certificate);
                    LOG.warn("The status of the service is unknown: (serviceName: " + serviceName + ")");
                } else {

                    final Date statusEndDate = InvolvedServiceInfo.getEndDate(certificate);
                    controlTime = statusEndDate;
                    addControlTime(constraintNode);
                }
            }
        }
        /**
         * - a) Find revocation status information satisfying the following:<br>
         * - -  The revocation status information is consistent with the rules conditioning its use to check the
         * revocation status of the considered certificate. For instance, in the case of a CRL, it shall satisfy the
         * checks described in (see clause 6.3).<br>
         *
         * TODO: 20130704 by bielecro: To notify ETSI --> (see clause 6.3) is not the right clause.<br>
         */

        XmlNode constraintNode = addConstraint(MessageTag.CTS_DRIE);

        final boolean revocationExists = certificate.exists("./Revocation");
        if (!revocationExists) {

            constraintNode.addChild(NodeName.STATUS, NodeValue.KO);
            conclusion.setIndication(Indication.INDETERMINATE);
            conclusion.setSubIndication(SubIndication.NO_POE);
            return conclusion;
        }

        final Date revocationIssuingTime = certificate.getTimeValue("./Revocation/IssuingTime/text()");
        final String formatedRevocationIssuingTime = DSSUtils.formatDate(revocationIssuingTime);

        constraintNode.addChild(NodeName.STATUS, NodeValue.OK);
        constraintNode.addChild(NodeName.INFO).setAttribute(AttributeName.REVOCATION_ISSUING_TIME,
                formatedRevocationIssuingTime);

        final Date notAfterTime = certificate.getTimeValue("./NotAfter/text()");
        final Date notBeforeTime = certificate.getTimeValue("./NotBefore/text()");

        /**
         * (See NOTE 2)<br>
         * TODO: ...(for instance, using the CRL extension expiredCertOnCRL (OID: 2.5.29.60)) This check need to be
         * added to the revocation information retrieval.
         */
        constraintNode = addConstraint(MessageTag.CTS_ICNEAIDORSI);

        if (revocationIssuingTime.before(notBeforeTime) || revocationIssuingTime.after(notAfterTime)) {

            constraintNode.addChild(NodeName.STATUS, NodeValue.KO);

            conclusion.setIndication(Indication.INDETERMINATE);
            conclusion.setSubIndication(SubIndication.NO_POE);
            return conclusion;
        }
        constraintNode.addChild(NodeName.STATUS, NodeValue.OK);

        /**
         * - -  The issuance date of the revocation status information is before control-time. If more than one
         * revocation status is found, consider the most recent one and go to the next step. If there is no such
         * information, terminate with INDETERMINATE/NO_POE:<br>
         */

        constraintNode = addConstraint(MessageTag.CTS_IIDORSIBCT);

        if (!revocationIssuingTime.before(controlTime)) {

            constraintNode.addChild(NodeName.STATUS, NodeValue.KO);
            addControlTime(constraintNode);

            conclusion.setIndication(Indication.INDETERMINATE);
            conclusion.setSubIndication(SubIndication.NO_POE);
            return conclusion;
        }
        constraintNode.addChild(NodeName.STATUS, NodeValue.OK);

        /**
         * - b) If the set of POEs contains a proof of existence of the certificate and the revocation status
         * information at (or before) control-time, go to step c). Otherwise, terminate with INDETERMINATE/NO_POE.
         */

        constraintNode = addConstraint(MessageTag.CTS_DSOPCPOEOC);

        final boolean poeExists = poe.getCertificatePOE(certificateId, controlTime);
        if (!poeExists || (revocationIssuingTime.compareTo(controlTime) > 0)) {

            constraintNode.addChild(NodeName.STATUS, NodeValue.KO);
            conclusion.setIndication(Indication.INDETERMINATE);
            conclusion.setSubIndication(SubIndication.NO_POE);
            return conclusion;
        }
        constraintNode.addChild(NodeName.STATUS, NodeValue.OK);

        /**
         * - c) Update the value of control-time as follows:<br>
         */

        constraintNode = addConstraint(MessageTag.CTS_SCT);
        addControlTime(constraintNode);

        final boolean revoked = !certificate.getBoolValue("./Revocation/Status/text()");
        /**
         * - -  If the certificate is marked as revoked in the revocation status information, set control-time to the
         * revocation date.<br>
         */
        if (revoked) {

            final Date revocationDate = certificate.getTimeValue("./Revocation/DateTime/text()");
            controlTime = revocationDate;

            final String formatedRevocationDate = DSSUtils.formatDate(revocationDate);
            constraintNode.addChild(NodeName.INFO, NodeValue.CTS_CTSTRT_LABEL);
            constraintNode.addChild(NodeName.INFO).setAttribute(AttributeName.REVOCATION_TIME,
                    formatedRevocationDate);
        } else {

            /**
             * - -  If the certificate is not marked as revoked.<br>
             * - - - - If the revocation status information is not considered "fresh", set control-time to the issuance
             * date of the revocation status information.<br>
             */
            final long revocationDeltaTime = controlTime.getTime() - revocationIssuingTime.getTime();
            if (revocationDeltaTime > constraintData.getMaxRevocationFreshness()) {

                controlTime = revocationIssuingTime;
                constraintNode.addChild(NodeName.INFO, NodeValue.CTS_CTSTRIT_LABEL);
                final XmlNode xmlNode = constraintNode.addChild(NodeName.INFO, MessageTag.BBB_XCV_IRIF_ANS);
                xmlNode.setAttribute(AttributeValue.CERTIFICATE_ID, String.valueOf(certificateId))
                        .setAttribute(AttributeName.REVOCATION_ISSUING_TIME, formatedRevocationIssuingTime);
            }

            /**
             * - - - - Otherwise, the value of control-time is not changed.<br>
             */
        }
        /**
         * - d) Apply the cryptographic constraints to the certificate and the revocation status information. If the
         * certificate (or the revocation status information) does not match these constraints, set control-time to the
         * lowest time up to which the listed algorithms were considered reliable.<br>
         */

        checkDigestAlgoExpirationDate(certificate, constraintNode, NodeValue.CTS_CTSTETOCSA_LABEL);
        checkEncryptionAlgoExpirationDate(certificate, constraintNode, NodeValue.CTS_CTSTETOCSA_LABEL);

        final XmlDom revocation = certificate.getElement("./Revocation");
        checkDigestAlgoExpirationDate(revocation, constraintNode, NodeValue.CTS_CTSTETORSA_LABEL);
        checkEncryptionAlgoExpirationDate(revocation, constraintNode, NodeValue.CTS_CTSTETORSA_LABEL);

        /**
         * 3) Continue with the next certificate in the chain or, if no further certificate exists, terminate with
         * VALID and the calculated control-time.<br>
         */
    }
    /**
     * NOTE 1: In step 1, initialising control-time with current date/time assumes that the trust anchor is still
     * trusted at the current date/time. The algorithm can capture the very exotic case where the trust anchor is
     * broken (or becomes untrusted for any other reason) at a known date by initialising control-time to this
     * date/time.<br>
     *
     * NOTE 2: The rational of step 2-a) is to check that the revocation status information is "in-scope" for the
     * given certificate. In other words, the rationale is to check that the revocation status information is reliable
     * to be used to ascertain the revocation status of the given certificate. For instance, this includes the fact
     * the certificate is not expired at the issuance date of the revocation status information, unless the issuing CA
     * states that its issues revocation information status for expired certificates (for instance, using the CRL
     * extension expiredCertOnCRL).<br>
     *
     * NOTE 3: If the certificate (or the revocation status information) was authentic, but the signature has been
     * faked exploiting weaknesses of the algorithms used, this is assumed only to be possible after the date the
     * algorithms are declared to be no longer acceptable. Therefore, the owner of the original key pair is assumed to
     * having been under control of his key up to that date. This is the rational of sliding control-time in step
     * 2-d).<br>
     *
     * NOTE 4: For more readability, the algorithm above implicitly assumes that the revocation information status is
     * signed by the certificate's issuer which is the most traditional revocation setting but not the only one. The
     * same algorithm can be adapted to the cases where the revocation information status has its own certificate
     * chain by applying the control-time sliding process to this chain which would output a control-time that has to
     * be compared to the control-time associated to the certificate.
     */

    conclusion.setIndication(Indication.VALID);
    conclusion.addInfo().setAttribute(AttributeValue.CONTROL_TIME, DSSUtils.formatDate(controlTime));

    return conclusion;
}

From source file:View.DialogoEstadisticas.java

private boolean validarIntervalo(String periodo, String opc) {
    String fechaFinI = null;/*from   w w w.  ja v a  2s  .c o m*/
    String fechaFinF = null;
    String fechaInI = null;
    String fechaInF = null;

    SimpleDateFormat dt1 = new SimpleDateFormat("dd-MM-yyyy");
    StringTokenizer st = new StringTokenizer(periodo, "/");
    while (st.hasMoreTokens()) {
        fechaFinI = st.nextToken();
        fechaFinF = st.nextToken();
    }

    switch (opc) {
    case "f":
        st = new StringTokenizer(fechaIntervaloI, "/");
        break;

    case "i":
        st = new StringTokenizer(fechaIntervaloF, "/");
        break;
    }

    fechaInI = st.nextToken();
    fechaInF = st.nextToken();

    try {

        Date dI = dt1.parse(fechaInF);
        Date dF = dt1.parse(fechaFinF);
        switch (opc) {
        case "f":
            System.out.println("Fecha intervalo Inicial: " + fechaInF);
            System.out.println("Fecha que me dan final: " + fechaFinF);
            System.out.println("Resultado: " + dF.after(dI));
            if (!dF.after(dI)) {
                cmbPeriodoF.setSelectedItem(fechaIntervaloF);
            }
            return (dF.after(dI));

        case "i":
            System.out.println("Fecha intervalo Fin: " + fechaInF);
            System.out.println("Fecha que me dan inicial: " + fechaFinF);
            System.out.println("Resultado: " + dF.before(dI));
            if (!dF.before(dI)) {
                cmbPeriodoI.setSelectedItem(fechaIntervaloI);
            }
            return (dF.before(dI));
        }
        return false;
    } catch (ParseException ex) {
        Logger.getLogger(DialogoEstadisticas.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }

}

From source file:com.ibm.xsp.webdav.resource.DAVResourceDominoDocuments.java

private void fetchChildrenForNotesView() {
    // LOGGER.info(getCallingMethod()+":"+"Start fetchChildrenForNotesView; Fetching children for "
    // +/*from w ww  .  ja  va2s  .c  o m*/
    // this.getName()+" with internal address= "+this.getInternalAddress()+"  and public href= "+this.getPublicHref());

    Document curDoc = null;
    this.setMembers(new Vector<IDAVResource>());
    View curView = null;
    Database curDb = null;
    // Vector<IDAVResource> resMembers = null;
    String notesURL = this.getInternalAddress();

    curView = DominoProxy.getView(notesURL);

    if (curView == null) {
        LOGGER.error("Could not retrieve view: " + notesURL);
        return;
    }

    // Read the repository list to get the view
    try {
        // LOGGER.info(getCallingMethod()+":"+"Openend view " +
        // curView.getName());

        // Initialize an empty vector at the right size
        // We might need to enlarge it if we have more attachments
        // LOGGER.info( "View num doc is "+new
        // Integer(curView.getEntryCount()).toString());
        for (int i = 0; i < curView.getEntryCount(); i++) {
            curDoc = curView.getNthDocument(i + 1);
            // LOGGER.info( "Start processing doc no "+ new
            // Integer(i).toString());

            if (curDoc == null) {
                // LOGGER.info(getCallingMethod()+":"+this.getName() +
                // " does not (yet) contain resources");
                return;
            }
            // LOGGER.info(getCallingMethod()+":"+"Start process view ");
            DAVResourceDominoDocuments docRes = null;
            if (curDoc.hasEmbedded()) {
                // LOGGER.info(getCallingMethod()+":"+"Document "+curDoc.getUniversalID()+
                // " has embedded; Start Add Attachments");
                // docRes = this.addAttachmentsFromDocument(curDoc);
                docRes = new DAVResourceDominoDocuments(this.getRepository());
                LOGGER.info("DOCRES from att created ok; start setup");
                docRes.setup(curDoc);
                // docRes.setCollection(false);
                // docRes.setMember(true);
                // LOGGER.info(getCallingMethod()+":"+"Successfully create attachments for "+curDoc.getUniversalID());
            } else {
                // LOGGER.info(getCallingMethod()+":"+"Document "+
                // curDoc.getUniversalID()+
                // " has no attachment; try to get a resource");
                docRes = new DAVResourceDominoDocuments(this.getRepository());
                docRes.setup(curDoc);
                docRes.setCollection(true);
                docRes.setMember(false);
                // LOGGER.info(getCallingMethod()+":"+"Successfully create resource from doc "+docRes.getName());
            }
            // TODO: Fix this!

            if (docRes != null) {

                // LOGGER.info(getCallingMethod()+":"+"Resource "+docRes.getName()+"created OK; Try to add to resMembers");
                this.getMembers().add(docRes);
                // LOGGER.info(getCallingMethod()+":"+"Resources added OK;");

                // Capture last modified based on the latest date of the
                // documents in view
                Date viewDate = this.getLastModified();
                Date docDate = docRes.getLastModified();
                if (viewDate == null || (docDate != null && viewDate.before(docDate))) {
                    this.setLastModified(docDate);
                }
                // LOGGER.info(getCallingMethod()+":"+"Resource processes  OK");

            }
            // //
            // LOGGER.info(getCallingMethod()+":"+"Try recycle and find the next for "+curDoc.getUniversalID()+"....");
            // Document oldDoc=curDoc;
            // curDoc = curView.getNextDocument(curDoc);
            // oldDoc.recycle();
            // // LOGGER.info(getCallingMethod()+":"+"Recycle OK!");
            // //
            // LOGGER.info("Next doc is "+((curDoc!=null)?"Not null":"null"));
        } // end for

    } catch (NotesException ne) {
        LOGGER.error(ne);

    } catch (Exception e) {
        LOGGER.error(e);

    } finally {

        try {
            // LOGGER.info(getCallingMethod()+":"+"Final recycle....");

            if (curDoc != null) {
                // curDoc.recycle();
            }

            if (curView != null) {
                curView.recycle();
            }

            if (curDb != null) {
                curDb.recycle();
            }
            // LOGGER.info(getCallingMethod()+":"+"Final recycle OK!");

        } catch (Exception e) {
            LOGGER.error(e);
        }

        // LOGGER.info(getCallingMethod()+":"+"Completed reading file resources from Domino view");
        // LOGGER.info(getCallingMethod()+":"+"Start to setMembers...");
        // this.setMembers(resMembers);
        // LOGGER.info(getCallingMethod()+":"+"SetMembers OK! Exit fetchChildrenforNotesView");
    }
    // Now save back the members to the main object

}

From source file:org.kuali.ole.service.impl.OleLicenseRequestServiceImpl.java

/**
 * This method will generate the request xml for the delete operation.
 * @param metadata//from   w  w w. j ava 2 s.c  o  m
 * @return  rollBackXml
 */
//    private String buildDeleteAgreementRequestXml(OleAgreementDocumentMetadata metadata){
//        ResponseHandler responseHandler = new ResponseHandler();
//        RequestHandler requestHandler = new RequestHandler();
//        Request request = new Request();
//        request.setUser("khuntley");
//        request.setOperation("delete");
//        RequestDocument requestDocument = new RequestDocument();
//        requestDocument.setId("1");
//        requestDocument.setCategory(OLEConstants.WORK_CATEGORY);
//        requestDocument.setType("license");
//        requestDocument.setUuid(metadata.getAgreementUUID());
//        String agreementFormat = metadata.getAgreementFileName().substring(metadata.getAgreementFileName().indexOf(".")+1
//                ,metadata.getAgreementFileName().length());
//        if((agreementFormat.equals("pdf")) | (agreementFormat.equals("xslt"))) {
//            requestDocument.setFormat(agreementFormat);
//        }
//        else {
//            requestDocument.setFormat("doc");
//        }
//        //requestDocument.setFormat(agreementFormat);
//        List<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
//        requestDocuments.add(requestDocument);
//        request.setRequestDocuments(requestDocuments);
//        String rollBackXml = requestHandler.toXML(request);
//        return rollBackXml;
//    }
@Override
public boolean validateDate(Date documentDate, String fromDate, String toDate) throws Exception {
    boolean isValidDate = false;
    String dateToCompare = "";
    if (documentDate != null) {
        dateToCompare = dateFormat.format(documentDate);
    }
    try {
        if (((toDate == null || toDate.isEmpty()) && fromDate != null && !fromDate.isEmpty())
                && (dateToCompare.equals(fromDate)
                        || (documentDate != null && documentDate.after(dateFormat.parse(fromDate))))) {
            isValidDate = true;
        } else if (((fromDate == null || fromDate.isEmpty()) && toDate != null && !toDate.isEmpty())
                && (dateToCompare.equals(toDate)
                        || (documentDate != null && documentDate.before(dateFormat.parse(toDate))))) {
            isValidDate = true;
        } else if (((fromDate == null || fromDate.isEmpty()) && ((toDate == null) || toDate.isEmpty()))
                || ((fromDate != null && (dateToCompare.equals(fromDate)
                        || (documentDate != null && documentDate.after(dateFormat.parse(fromDate)))))
                        && (toDate != null && (dateToCompare.equals(toDate)
                                || (documentDate != null && documentDate.before(dateFormat.parse(toDate))))))) {
            isValidDate = true;
        }
    } catch (Exception e) {
        LOG.error("Error while comparing the date" + e.getMessage());
        throw new RuntimeException(e);
    }
    return isValidDate;

}

From source file:com.aurel.track.attachment.AttachmentAction.java

/**
 * This method save an attachment as a link.
 * @return/*from   www. ja  v a  2s. co m*/
 */
public String saveLink() {
    HttpServletResponse response = ServletActionContext.getResponse();
    try {

        Date originalLastModifiedDate = null;
        Date lastModifiedDate = DateTimeUtils.getInstance().parseISODateTime(lastModified);
        TWorkItemBean workItemBean = ItemBL.loadWorkItemSystemAttributes(workItemID);
        if (workItemBean != null) {
            originalLastModifiedDate = workItemBean.getLastEdit();
        }

        AttachBL.saveAttachmentAsLink(workItemID, description, theUrl, personID);
        Long urlSize = 0L;
        HistorySaverBL.addAttachment(workItemID, personID, locale, theUrl, description, urlSize, true);

        StringBuilder sb = new StringBuilder();
        sb.append("{");
        JSONUtility.appendBooleanValue(sb, JSONUtility.JSON_FIELDS.SUCCESS, true);
        JSONUtility.appendFieldName(sb, JSONUtility.JSON_FIELDS.DATA).append(":{");
        if (originalLastModifiedDate != null && lastModifiedDate != null) {
            if (!lastModifiedDate.before(originalLastModifiedDate)) {
                workItemBean = ItemBL.loadWorkItemSystemAttributes(workItemID);
                Date lastModified = null;
                if (workItemBean != null) {
                    lastModified = workItemBean.getLastEdit();
                }
                JSONUtility.appendStringValue(sb, "lastModified",
                        DateTimeUtils.getInstance().formatISODateTime(lastModified), true);
            }
        }

        sb.append("}}");
        try {
            JSONUtility.prepareServletResponseJSON(ServletActionContext.getResponse());
            PrintWriter out = ServletActionContext.getResponse().getWriter();
            out.println(sb);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LOGGER.error(ExceptionUtils.getStackTrace(e));
        }

    } catch (AttachBLException ex) {
        LOGGER.error("Can't save attachemnt as a link!!", ex);
        List<LabelValueBean> errors = new ArrayList<LabelValueBean>();
        String error = ex.getMessage();
        errors.add(new LabelValueBean(error, "theFile"));
        JSONUtility.encodeJSONErrorsExtJS(response, errors);
    }

    return null;
}

From source file:com.evolveum.midpoint.gui.api.util.WebComponentUtil.java

public static boolean isSubscriptionIdCorrect(String subscriptionId) {
    if (StringUtils.isEmpty(subscriptionId)) {
        return false;
    }//from  ww  w  .ja va  2  s. c o  m
    if (!NumberUtils.isDigits(subscriptionId)) {
        return false;
    }
    if (subscriptionId.length() < 11) {
        return false;
    }
    String subscriptionType = subscriptionId.substring(0, 2);
    boolean isTypeCorrect = false;
    for (SubscriptionType type : SubscriptionType.values()) {
        if (type.getSubscriptionType().equals(subscriptionType)) {
            isTypeCorrect = true;
            break;
        }
    }
    if (!isTypeCorrect) {
        return false;
    }
    String substring1 = subscriptionId.substring(2, 4);
    String substring2 = subscriptionId.substring(4, 6);
    try {
        if (Integer.parseInt(substring1) < 1 || Integer.parseInt(substring1) > 12) {
            return false;
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yy");
        String currentYear = dateFormat.format(Calendar.getInstance().getTime());
        if (Integer.parseInt(substring2) < Integer.parseInt(currentYear)) {
            return false;
        }

        String expDateStr = subscriptionId.substring(2, 6);
        dateFormat = new SimpleDateFormat("MMyy");
        Date expDate = dateFormat.parse(expDateStr);
        Date currentDate = new Date(System.currentTimeMillis());
        if (expDate.before(currentDate)) {
            return false;
        }
    } catch (Exception ex) {
        return false;
    }
    VerhoeffCheckDigit checkDigit = new VerhoeffCheckDigit();
    if (checkDigit.isValid(subscriptionId)) {
        return true;
    }
    return false;
}

From source file:com.zimbra.cs.mailbox.calendar.ZRecur.java

private Date estimateEndTimeByUntilAndHardLimits(ParsedDateTime dtStart) throws ServiceException {
    boolean forever = false;
    Calendar hardEnd = dtStart.getCalendarCopy();
    Frequency freq = mFreq;//from   w  w  w . ja  va  2s  .com
    if (freq == null)
        freq = Frequency.WEEKLY;
    switch (freq) {
    case WEEKLY:
        int weeks = sExpansionLimits.maxWeeks;
        if (weeks <= 0)
            forever = true;
        else
            hardEnd.add(Calendar.WEEK_OF_YEAR, weeks);
        break;
    case MONTHLY:
        int months = sExpansionLimits.maxMonths;
        if (months <= 0)
            forever = true;
        else
            hardEnd.add(Calendar.MONTH, months);
        break;
    case YEARLY:
        int years = sExpansionLimits.maxYears;
        if (years <= 0)
            forever = true;
        else
            hardEnd.add(Calendar.YEAR, years);
        break;
    case DAILY:
        int days = sExpansionLimits.maxDays;
        if (days <= 0)
            forever = true;
        else
            hardEnd.add(Calendar.DAY_OF_YEAR, days);
        break;
    default:
        int otherFreqYears = Math.max(sExpansionLimits.maxYearsOtherFreqs, 1);
        hardEnd.add(Calendar.YEAR, otherFreqYears);
    }
    Date d;
    if (forever)
        d = new Date(MAX_DATE_MILLIS);
    else
        d = hardEnd.getTime();
    if (mUntil != null) {
        Date until = mUntil.getDateForRecurUntil(dtStart.getTimeZone());
        if (until.before(d))
            d = until;
    }
    return d;
}

From source file:io.jsonwebtoken.impl.DefaultJwtParser.java

@Override
public Jwt parse(String jwt) throws ExpiredJwtException, MalformedJwtException, SignatureException {

    Assert.hasText(jwt, "JWT String argument cannot be null or empty.");

    String base64UrlEncodedHeader = null;
    String base64UrlEncodedPayload = null;
    String base64UrlEncodedDigest = null;

    int delimiterCount = 0;

    StringBuilder sb = new StringBuilder(128);

    for (char c : jwt.toCharArray()) {

        if (c == SEPARATOR_CHAR) {

            String token = Strings.clean(sb.toString());

            if (delimiterCount == 0) {
                base64UrlEncodedHeader = token;
            } else if (delimiterCount == 1) {
                base64UrlEncodedPayload = token;
            }/*from  ww  w .  j  a v  a2  s . c om*/

            delimiterCount++;
            sb = new StringBuilder(128);
        } else {
            sb.append(c);
        }
    }

    if (delimiterCount != 2) {
        String msg = "JWT strings must contain exactly 2 period characters. Found: " + delimiterCount;
        throw new MalformedJwtException(msg);
    }
    if (sb.length() > 0) {
        base64UrlEncodedDigest = sb.toString();
    }

    if (base64UrlEncodedPayload == null) {
        throw new MalformedJwtException("JWT string '" + jwt + "' is missing a body/payload.");
    }

    // =============== Header =================
    Header header = null;

    CompressionCodec compressionCodec = null;

    if (base64UrlEncodedHeader != null) {
        String origValue = TextCodec.BASE64URL.decodeToString(base64UrlEncodedHeader);
        Map<String, Object> m = readValue(origValue);

        if (base64UrlEncodedDigest != null) {
            header = new DefaultJwsHeader(m);
        } else {
            header = new DefaultHeader(m);
        }

        compressionCodec = compressionCodecResolver.resolveCompressionCodec(header);
    }

    // =============== Body =================
    String payload;
    if (compressionCodec != null) {
        byte[] decompressed = compressionCodec.decompress(TextCodec.BASE64URL.decode(base64UrlEncodedPayload));
        payload = new String(decompressed, Strings.UTF_8);
    } else {
        payload = TextCodec.BASE64URL.decodeToString(base64UrlEncodedPayload);
    }

    Claims claims = null;

    if (payload.charAt(0) == '{' && payload.charAt(payload.length() - 1) == '}') { //likely to be json, parse it:
        Map<String, Object> claimsMap = readValue(payload);
        claims = new DefaultClaims(claimsMap);
    }

    // =============== Signature =================
    if (base64UrlEncodedDigest != null) { //it is signed - validate the signature

        JwsHeader jwsHeader = (JwsHeader) header;

        SignatureAlgorithm algorithm = null;

        if (header != null) {
            String alg = jwsHeader.getAlgorithm();
            if (Strings.hasText(alg)) {
                algorithm = SignatureAlgorithm.forName(alg);
            }
        }

        if (algorithm == null || algorithm == SignatureAlgorithm.NONE) {
            //it is plaintext, but it has a signature.  This is invalid:
            String msg = "JWT string has a digest/signature, but the header does not reference a valid signature "
                    + "algorithm.";
            throw new MalformedJwtException(msg);
        }

        if (key != null && keyBytes != null) {
            throw new IllegalStateException(
                    "A key object and key bytes cannot both be specified. Choose either.");
        } else if ((key != null || keyBytes != null) && signingKeyResolver != null) {
            String object = key != null ? "a key object" : "key bytes";
            throw new IllegalStateException(
                    "A signing key resolver and " + object + " cannot both be specified. Choose either.");
        }

        //digitally signed, let's assert the signature:
        Key key = this.key;

        if (key == null) { //fall back to keyBytes

            byte[] keyBytes = this.keyBytes;

            if (Objects.isEmpty(keyBytes) && signingKeyResolver != null) { //use the signingKeyResolver
                if (claims != null) {
                    key = signingKeyResolver.resolveSigningKey(jwsHeader, claims);
                } else {
                    key = signingKeyResolver.resolveSigningKey(jwsHeader, payload);
                }
            }

            if (!Objects.isEmpty(keyBytes)) {

                Assert.isTrue(!algorithm.isRsa(),
                        "Key bytes cannot be specified for RSA signatures.  Please specify a PublicKey or PrivateKey instance.");

                key = new SecretKeySpec(keyBytes, algorithm.getJcaName());
            }
        }

        Assert.notNull(key, "A signing key must be specified if the specified JWT is digitally signed.");

        //re-create the jwt part without the signature.  This is what needs to be signed for verification:
        String jwtWithoutSignature = base64UrlEncodedHeader + SEPARATOR_CHAR + base64UrlEncodedPayload;

        JwtSignatureValidator validator;
        try {
            validator = createSignatureValidator(algorithm, key);
        } catch (IllegalArgumentException e) {
            String algName = algorithm.getValue();
            String msg = "The parsed JWT indicates it was signed with the " + algName + " signature "
                    + "algorithm, but the specified signing key of type " + key.getClass().getName()
                    + " may not be used to validate " + algName + " signatures.  Because the specified "
                    + "signing key reflects a specific and expected algorithm, and the JWT does not reflect "
                    + "this algorithm, it is likely that the JWT was not expected and therefore should not be "
                    + "trusted.  Another possibility is that the parser was configured with the incorrect "
                    + "signing key, but this cannot be assumed for security reasons.";
            throw new UnsupportedJwtException(msg, e);
        }

        if (!validator.isValid(jwtWithoutSignature, base64UrlEncodedDigest)) {
            String msg = "JWT signature does not match locally computed signature. JWT validity cannot be "
                    + "asserted and should not be trusted.";
            throw new SignatureException(msg);
        }
    }

    //since 0.3:
    if (claims != null) {

        SimpleDateFormat sdf;

        final Date now = this.clock.now();

        //https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-30#section-4.1.4
        //token MUST NOT be accepted on or after any specified exp time:
        Date exp = claims.getExpiration();
        if (exp != null) {

            if (now.equals(exp) || now.after(exp)) {
                sdf = new SimpleDateFormat(ISO_8601_FORMAT);
                String expVal = sdf.format(exp);
                String nowVal = sdf.format(now);

                String msg = "JWT expired at " + expVal + ". Current time: " + nowVal;
                throw new ExpiredJwtException(header, claims, msg);
            }
        }

        //https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-30#section-4.1.5
        //token MUST NOT be accepted before any specified nbf time:
        Date nbf = claims.getNotBefore();
        if (nbf != null) {

            if (now.before(nbf)) {
                sdf = new SimpleDateFormat(ISO_8601_FORMAT);
                String nbfVal = sdf.format(nbf);
                String nowVal = sdf.format(now);

                String msg = "JWT must not be accepted before " + nbfVal + ". Current time: " + nowVal;
                throw new PrematureJwtException(header, claims, msg);
            }
        }

        validateExpectedClaims(header, claims);
    }

    Object body = claims != null ? claims : payload;

    if (base64UrlEncodedDigest != null) {
        return new DefaultJws<Object>((JwsHeader) header, body, base64UrlEncodedDigest);
    } else {
        return new DefaultJwt<Object>(header, body);
    }
}

From source file:com.ibm.xsp.webdav.resource.DAVResourceDominoCategorizedDocuments.java

@SuppressWarnings("unchecked")
private void fetchChildrenForNotesDocument() throws NotesException {
    // LOGGER.info(getCallingMethod()+":"+"Start fetchChildrenForNotesDocument; Fetching children for doc with UNID="
    // + this.getDocumentUniqueID());
    Document curDoc = null;//from   w  w  w.  ja v a 2 s. c om
    String docID = null;
    Vector<IDAVResource> resMembers = null;
    this.setMembers(new Vector<IDAVResource>());
    String notesURL = this.getInternalAddress();
    DAVRepositoryDominoCategorizedDocuments repository = (DAVRepositoryDominoCategorizedDocuments) this
            .getRepository();
    // LOGGER.info("Internal Address is "+notesURL);
    // LOGGER.info("PublicHref is "+this.getPublicHref());
    curDoc = DominoProxy.getDocument(notesURL);
    // LOGGER.info(getCallingMethod()+":"+"Currdoc not null ; OK");
    if (curDoc == null) {
        LOGGER.error("Could not retrieve the document");
        return;
    }
    boolean readOnly = this.checkReadOnlyAccess(curDoc);
    Date curCreationDate = curDoc.getCreated().toJavaDate();
    if (curDoc.hasItem("DAVCreated")) {
        @SuppressWarnings("rawtypes")
        Vector times = curDoc.getItemValueDateTimeArray("DAVCreated");
        Object time = times.elementAt(0);
        if (time.getClass().getName().endsWith("DateTime")) {
            curCreationDate = ((DateTime) time).toJavaDate();
        }
    }
    Date curChangeDate = curDoc.getLastModified().toJavaDate();
    if (curDoc.hasItem("DAVModified")) {
        @SuppressWarnings("rawtypes")
        Vector times = curDoc.getItemValueDateTimeArray("DAVModified");
        Object time = times.elementAt(0);
        if (time.getClass().getName().endsWith("DateTime")) {
            curChangeDate = ((DateTime) time).toJavaDate();
        }
    }
    this.setCreationDate(curCreationDate);
    this.setLastModified(curChangeDate);
    this.setReadOnly(readOnly);
    // Read the repository list to get the view
    try {
        LOGGER.info(getCallingMethod() + ":" + "Currdoc not null ; OK; Has UNID=" + curDoc.getUniversalID());
        docID = curDoc.getUniversalID();

        LOGGER.info(getCallingMethod() + ":" + "Openend document " + docID);

        // No children if there are no attachments
        if (!curDoc.hasEmbedded()) { // folder

            ViewEntryCollection responses = repository
                    .getAllEntriesByKey(curDoc.getItemValueString(repository.getPubHrefField()));
            LOGGER.info(getCallingMethod() + ":" + "Get Responses...");
            int numOfResponses = responses.getCount();
            LOGGER.info(getCallingMethod() + ":" + "Current doc has " + String.valueOf(numOfResponses)
                    + " responses");
            if (numOfResponses > 1) {
                resMembers = new Vector<IDAVResource>(numOfResponses - 1);
                LOGGER.info(getCallingMethod() + ":" + "Start Process responses");
                lotus.domino.ViewEntry ve = responses.getFirstEntry();
                ve = responses.getNextEntry();
                Document docResp = null;
                while (ve != null) {
                    docResp = ve.getDocument();
                    // if(docResp.getUniversalID()!=docID){
                    LOGGER.info(getCallingMethod() + ":" + "Doc response has unid=" + docResp.getUniversalID()
                            + "; Try find attachment(s)");
                    Vector<String> allEmbedded = DominoProxy.evaluate("@AttachmentNames", docResp);
                    int numOfAttachments = allEmbedded.isEmpty() ? 0
                            : (allEmbedded.get(0).toString().equals("") ? 0 : allEmbedded.size());
                    LOGGER.info(getCallingMethod() + ":" + "Doc has " + String.valueOf(numOfAttachments)
                            + " attachment(s)");
                    if (numOfAttachments == 0) { // No attachments in here!
                        LOGGER.info(getCallingMethod() + ":" + "Doc " + docResp.getUniversalID()
                                + " response has no attachment; is a directory; Create resource for it");
                        DAVResourceDominoCategorizedDocuments resAtt = new DAVResourceDominoCategorizedDocuments(
                                this.getRepository(),
                                this.getPublicHref() + "/" + docResp.getItemValueString(
                                        ((DAVRepositoryDominoCategorizedDocuments) (this.getRepository()))
                                                .getDirectoryField()),
                                true);
                        resAtt.setup(docResp);
                        if (resAtt != null) {
                            LOGGER.info(getCallingMethod() + ":"
                                    + "Created DavResourceDomino Attachments from getDocumentResource-OK");
                            if (resAtt.filter()) {
                                this.getMembers().add(resAtt);
                            }
                            resMembers.add(resAtt);
                            LOGGER.info(getCallingMethod() + ":" + "Resource successfull added");
                        }
                    } else {
                        LOGGER.info(getCallingMethod() + ":" + "Doc response " + docResp.getUniversalID()
                                + " has attachments >0; ");

                        String curAttName = allEmbedded.get(0).toString();
                        if ((curAttName != null) && (!curAttName.equals(""))) {
                            LOGGER.info(getCallingMethod() + ":" + "Doc response fitrst attachment has name "
                                    + curAttName);
                            DAVResourceDominoCategorizedDocuments resAtt = new DAVResourceDominoCategorizedDocuments(
                                    this.getRepository(), this.getPublicHref() + "/" + curAttName, true);
                            resAtt.setup(docResp);
                            if (resAtt != null) {
                                // Now add it to the Vector
                                LOGGER.info(getCallingMethod() + ":"
                                        + "Created DAVResourceDominoDocuments with getAttachmentResource-OK!\n Start load resource");
                                // resMembers.add(curAttachment);
                                if (resAtt.filter()) {
                                    this.getMembers().add(resAtt);
                                }
                                LOGGER.info(getCallingMethod() + ":" + "Resource successfull added");
                                Date viewDate = this.getLastModified();
                                Date docDate = resAtt.getLastModified();
                                if (viewDate == null || (docDate != null && viewDate.before(docDate))) {
                                    this.setLastModified(docDate);
                                }
                                LOGGER.info(getCallingMethod() + ":"
                                        + "Resource successfull updated last modified");

                                LOGGER.info(getCallingMethod() + ":" + "Processing complete attachment:"
                                        + curAttName);
                            }
                        }
                    }
                    LOGGER.info(getCallingMethod() + ":" + "Start recycling..");
                    // Document docTmp=docResp;
                    // } //end
                    // if(docResp.getUniversalID()!=curDoc.getUniversalID()){
                    ve = responses.getNextEntry();
                    // docTmp.recycle();
                    LOGGER.info(getCallingMethod() + ":" + "Recycling OK!");
                } // end while

            } // end if numresp>0

            try {
                LOGGER.info(getCallingMethod() + ":" + "Final recycling..");
                if (curDoc != null) {
                    curDoc.recycle();
                }
                LOGGER.info(getCallingMethod() + ":" + "End FINAL recycling OK!");

            } catch (Exception e) {
                LOGGER.error(e);
            }
            // Now save back the members to the main object
            LOGGER.info(getCallingMethod() + ":"
                    + "Finish processing current doc as a directory; No more attachment(s) in it; Return!");
            return;
        }

        // Get all attachments
        LOGGER.info(getCallingMethod() + ":" + "Current doc has attachments!");
        @SuppressWarnings("rawtypes")
        Vector allEmbedded = DominoProxy.evaluate("@AttachmentNames", curDoc);
        int numOfAttchments = allEmbedded.size();
        if (numOfAttchments == 0) { // No attachments in here!
            LOGGER.info(getCallingMethod() + ":" + "Something wrong:  Doc + " + docID
                    + " has no attachments (@AttachmentNames)");
            return;
        }
        LOGGER.info(getCallingMethod() + ":" + docID + " has " + new Integer(numOfAttchments).toString()
                + " attachment(s)");
        // Initialize an empty vector at the right size
        // We might need to enlarge it if we have more attachments
        resMembers = new Vector<IDAVResource>(numOfAttchments);
        LOGGER.info(getCallingMethod() + ":" + "Start processing attachment(s)..");
        for (int i = 0; i < numOfAttchments; i++) {

            String curAttName = allEmbedded.get(i).toString();
            DAVResourceDominoCategorizedDocuments curAttachment = getDocumentResource(curDoc);

            if (curAttachment != null) {
                // Now add it to the Vector
                LOGGER.info(getCallingMethod() + ":" + "Resource attachment successfully created!");
                // resMembers.add(curAttachment);
                if (curAttachment.filter()) {
                    this.getMembers().add(curAttachment);
                }
                LOGGER.info("Resource  attachment successfully added: " + curAttName + "; OK!");
            } else {
                LOGGER.error("Could not load attachment#" + curAttName + "#");
            }
        }

    } catch (NotesException ne) {
        LOGGER.error(ne);

    } catch (Exception e) {
        LOGGER.error(e);

    } finally {

        try {
            LOGGER.info(getCallingMethod() + ":" + "Final block; Start Recycling!");

            if (curDoc != null) {
                curDoc.recycle();
            }

        } catch (Exception e) {
            LOGGER.error(e);
        }
        // Now save back the members to the main object
        // this.setMembers(resMembers);
        LOGGER.info("Completed reading attachments resources from Notes document; OK!");
    }

}