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: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   w  w  w .  j  ava2  s.c  o  m*/

            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.collabnet.ccf.teamforge.TFAppHandler.java

/**
 * This method retrieves all the comments added to a particular artifact
 * (represented by the ArtifactSoapDO) and adds all the comments that are
 * added after the lastModifiedDate into the ArtifcatSoapDO's flex fields
 * with the field name as "Comment Text" [as this is the name displayed in
 * the TF trackers for the Comments]//w w w . j  a  v  a  2  s .  c  o  m
 * 
 * It calls the private method addComments which can add comments for a list
 * of artifacts by querying the ISourceForgeSoap object for this particular
 * TF system.
 * 
 * The comments added by the connector user are ignored by this method.
 * 
 * @param artifact
 *            - The ArtifactSoapDO object whose comments need to be added
 * @param lastModifiedDate
 *            - The last read time of this tracker
 * @param connectorUser
 *            - The username that is configured to log into the TF to
 *            retrieve the artifact data.
 * @param resyncUser
 *            - The resync user for CCF
 */
public void addComments(ArtifactDO artifact, Date lastModifiedDate, String connectorUser, String resyncUser,
        boolean isPreserveBulkCommentOrder) {
    try {
        CommentList commentList = connection.getTeamForgeClient().getCommentList(artifact.getId());
        CommentRow[] comments = commentList.getDataRows();

        if (comments != null) {
            if (isPreserveBulkCommentOrder && comments.length > 1) {
                Collections.reverse(Arrays.asList(comments));
            }
            for (CommentRow comment : comments) {
                String createdBy = comment.getCreatedBy();
                Date createdDate = comment.getDateCreated();
                if (createdBy.equals(connectorUser) || createdBy.equals(resyncUser)) {
                    continue;
                }
                if (lastModifiedDate.after(createdDate) || lastModifiedDate.equals(createdDate)) {
                    continue;
                }
                String description = comment.getDescription();
                description = "\nOriginal commenter: " + createdBy + "\n" + description;
                this.addComment(TFArtifactMetaData.TFFields.commentText.getFieldName(), artifact, description);
            }
        }
    } catch (RemoteException e) {
        log.error("Could not get comments list for artifact " + artifact.getId() + ": " + e.getMessage());
    }
}

From source file:com.unispezi.cpanelremotebackup.CPanelRemoteBackup.java

/**
 * Polls until size of server file does not change anymore
 *
 * @param timeoutDate max timestamp until this operation may run
 * @param backupName  backup name on server
 * @return file size in bytes/*from w ww  . j a  va2s  .  co  m*/
 * @throws ReadTimeoutException if operation took longer than timeout
 */
private long waitForBackupSizeToBecomeStable(Date timeoutDate, String backupName) throws ReadTimeoutException {
    com.unispezi.cpanelremotebackup.tools.Console.print("Polling for backup file size to become stable");
    long lastFileSize = 0;
    long currentFileSize = 0;
    Date now = new Date();
    while (((currentFileSize < minFileBytes) || (currentFileSize != lastFileSize))
            && (now.before(timeoutDate))) {
        com.unispezi.cpanelremotebackup.tools.Console.print(".");
        FTPFile backupWeStarted = ftp.getFileDetails(backupName);
        lastFileSize = currentFileSize;
        currentFileSize = backupWeStarted.getSize();
        try {
            Thread.sleep(pollIntervalSeconds * 1000);
        } catch (InterruptedException e) {
            //Do nothing
        }
        now = new Date();
    }
    com.unispezi.cpanelremotebackup.tools.Console.println(" " + currentFileSize + " bytes");

    if (now.after(timeoutDate)) {
        throw new ReadTimeoutException("Download of file exceeded timeout");
    }
    return currentFileSize;
}

From source file:net.di2e.ecdr.querylanguage.basic.CDRKeywordQueryLanguage.java

protected Filter getTemporalFilter(Date startDate, Date endDate, String type,
        StringBuilder humanReadableQueryBuilder) throws UnsupportedQueryException {
    Filter filter = null;//  ww w. java2  s . com
    if (startDate != null || endDate != null) {
        if (startDate != null && endDate != null) {
            if (startDate.after(endDate)) {
                throw new UnsupportedQueryException(
                        "Start date value [" + startDate + "] cannot be after endDate [" + endDate + "]");
            }
            filter = filterBuilder.attribute(type).during().dates(startDate, endDate);
            humanReadableQueryBuilder.append(" " + SearchConstants.STARTDATE_PARAMETER + "=[" + startDate + "] "
                    + SearchConstants.ENDDATE_PARAMETER + "=[" + endDate + "] "
                    + SearchConstants.DATETYPE_PARAMETER + "=[" + type + "]");
        } else if (startDate != null) {
            filter = filterBuilder.attribute(type).after().date(startDate);
            humanReadableQueryBuilder.append(" " + SearchConstants.STARTDATE_PARAMETER + "=[" + startDate + "] "
                    + SearchConstants.DATETYPE_PARAMETER + "=[" + type + "]");
        } else if (endDate != null) {
            filter = filterBuilder.attribute(type).before().date(endDate);
            humanReadableQueryBuilder.append(" " + SearchConstants.ENDDATE_PARAMETER + "=[" + endDate + "] "
                    + SearchConstants.DATETYPE_PARAMETER + "=[" + type + "]");
        }
    }

    return filter;
}

From source file:com.aurel.track.report.dashboard.StatusOverTimeGraph.java

/**
* Create a map of hierarchical data with TWorkItemBeans in the periods
* -   key: year//  w  ww .j av a  2s . c  o m
* -   value: map
*          -   key: period
*          -   Set of TStateChangeBeans, one for each workItem
* @param timeInterval
* @return
*/
private static SortedMap<Integer, SortedMap<Integer, List<TWorkItemBean>>> getNewWorkItemsMap(List workItemList,
        int timeInterval, Date dateFrom, Date dateTo) {
    SortedMap<Integer, SortedMap<Integer, List<TWorkItemBean>>> yearToIntervalToWorkItemBeans = new TreeMap();
    int yearValue;
    int intervalValue;
    if (workItemList != null) {
        Calendar calendarCreated = Calendar.getInstance();
        Iterator iterator = workItemList.iterator();
        int calendarInterval = getCalendarInterval(timeInterval);
        while (iterator.hasNext()) {
            TWorkItemBean workItemBean = (TWorkItemBean) iterator.next();
            Date createDate = workItemBean.getCreated();
            if (createDate == null) {
                continue;
            }
            if (dateFrom != null && dateFrom.after(createDate) || dateTo != null && dateTo.before(createDate)) {
                continue;
            }
            calendarCreated.setTime(workItemBean.getCreated());
            yearValue = calendarCreated.get(Calendar.YEAR);
            intervalValue = calendarCreated.get(calendarInterval);
            if (Calendar.WEEK_OF_YEAR == calendarInterval) {
                //avoid adding the first week of the new year as the first week of the old year,
                //because it can be that the year is the old one but the last days of the year belong to the first week of the next year
                //and that would add an entry with the first week of the old year
                int monthValue = calendarCreated.get(Calendar.MONTH);
                if (monthValue >= 11 && intervalValue == 1) {
                    yearValue = yearValue + 1;
                }
            }
            SortedMap<Integer, List<TWorkItemBean>> intervalToWorkItemBeans = yearToIntervalToWorkItemBeans
                    .get(new Integer(yearValue));
            if (intervalToWorkItemBeans == null) {
                yearToIntervalToWorkItemBeans.put(new Integer(yearValue), new TreeMap());
                intervalToWorkItemBeans = yearToIntervalToWorkItemBeans.get(new Integer(yearValue));
            }
            List<TWorkItemBean> workItemBeansForInterval = intervalToWorkItemBeans
                    .get(new Integer(intervalValue));
            if (workItemBeansForInterval == null) {
                intervalToWorkItemBeans.put(new Integer(intervalValue), new ArrayList());
                workItemBeansForInterval = intervalToWorkItemBeans.get(new Integer(intervalValue));
            }
            workItemBeansForInterval.add(workItemBean);
        }
    }
    return yearToIntervalToWorkItemBeans;
}

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

/**
 * Check for updates./* w ww .j a v  a 2  s .  c o  m*/
 *
 * @param feed the feed
 */
protected void checkForUpdates(SyndFeed feed) {
    try {
        Date lastUpdate = this.getLastUpdate();

        Date lastUpdateFromFeed = this.getLastUpdateFromFeed(feed);

        //account for a null feed coming back from bioportal
        if (lastUpdateFromFeed != null && (lastUpdate == null || lastUpdateFromFeed.after(lastUpdate))) {
            List<String> ontologyIds = this.getUpdatedOntologies(feed, lastUpdateFromFeed);

            for (String ontologyId : ontologyIds) {
                this.purgeGetLatestOntologyVersions();
                this.purgeGetLatestOntologyVersionByOntologyId(ontologyId);
                this.purgeGetOntologyVersionsByOntologyId(ontologyId);
            }

            this.writeUpdateLog(lastUpdateFromFeed);

            this.fireOnCodeSystemsChangeEvent(ontologyIds);
        }
    } catch (Exception e) {
        log.warn("Error reading RSS feed.", e);
    }
}

From source file:com.ibm.watson.developer_cloud.dialog.v1.DialogService.java

/**
 * Returns chat session data dump for a given date rage.
 *
 * @param params the params/* ww  w . ja  v a  2  s .co  m*/
 * @return A list of {@link ConversationData}
 * @throws UnsupportedEncodingException 
 */
public List<ConversationData> getConversationData(final Map<String, Object> params)
        throws UnsupportedEncodingException {
    final String dialogId = (String) params.get(DIALOG_ID);

    final Date from = (Date) params.get(DATE_FROM);
    final Date to = (Date) params.get(DATE_TO);

    final Integer offset = (Integer) params.get(OFFSET);
    final Integer limit = (Integer) params.get(LIMIT);

    if (dialogId == null || dialogId.isEmpty())
        throw new IllegalArgumentException(DIALOG_ID + " can not be null or empty");

    if (from == null)
        throw new IllegalArgumentException(DATE_FROM + " can not be null");

    if (to == null)
        throw new IllegalArgumentException(DATE_TO + " can not be null");

    if (from.after(to))
        throw new IllegalArgumentException("'" + DATE_FROM + "' is greater than '" + DATE_TO + "'");

    String fromString = sdfDate.format(from);
    String toString = sdfDate.format(to);

    String path = String.format("/v1/dialogs/%s/conversation", dialogId);

    Request requestBuilder = Request.Get(path).withQuery(DATE_FROM, fromString, DATE_TO, toString);

    if (offset != null)
        requestBuilder.withQuery(OFFSET, offset);
    if (limit != null)
        requestBuilder.withQuery(LIMIT, limit);

    HttpRequestBase request = requestBuilder.build();
    /*HttpHost proxy=new HttpHost("10.100.1.124",3128);
    ConnRouteParams.setDefaultProxy(request.getParams(),proxy);*/
    try {
        HttpResponse response = execute(request);
        JsonObject jsonObject = ResponseUtil.getJsonObject(response);
        List<ConversationData> conversationDataList = GsonSingleton.getGson()
                .fromJson(jsonObject.get("conversations"), listConversationDataType);
        return conversationDataList;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.gst.accounting.journalentry.service.JournalEntryWritePlatformServiceJpaRepositoryImpl.java

private void validateBusinessRulesForJournalEntries(final JournalEntryCommand command) {
    /** check if date of Journal entry is valid ***/
    final LocalDate entryLocalDate = command.getTransactionDate();
    final Date transactionDate = entryLocalDate.toDateTimeAtStartOfDay().toDate();
    // shouldn't be in the future
    final Date todaysDate = new Date();
    if (transactionDate.after(todaysDate)) {
        throw new JournalEntryInvalidException(GL_JOURNAL_ENTRY_INVALID_REASON.FUTURE_DATE, transactionDate,
                null, null);/* w  ww  .  ja  v  a  2  s  .co m*/
    }
    // shouldn't be before an accounting closure
    final GLClosure latestGLClosure = this.glClosureRepository
            .getLatestGLClosureByBranch(command.getOfficeId());
    if (latestGLClosure != null) {
        if (latestGLClosure.getClosingDate().after(transactionDate)
                || latestGLClosure.getClosingDate().equals(transactionDate)) {
            throw new JournalEntryInvalidException(GL_JOURNAL_ENTRY_INVALID_REASON.ACCOUNTING_CLOSED,
                    latestGLClosure.getClosingDate(), null, null);
        }
    }

    /*** check if credits and debits are valid **/
    final SingleDebitOrCreditEntryCommand[] credits = command.getCredits();
    final SingleDebitOrCreditEntryCommand[] debits = command.getDebits();

    // atleast one debit or credit must be present
    if (credits == null || credits.length <= 0 || debits == null || debits.length <= 0) {
        throw new JournalEntryInvalidException(GL_JOURNAL_ENTRY_INVALID_REASON.NO_DEBITS_OR_CREDITS, null, null,
                null);
    }

    checkDebitAndCreditAmounts(credits, debits);
}

From source file:com.intuit.it.billing.data.BillingFileReader.java

/**
 * getAllocationsList//from  w  w  w . jav  a 2  s .  c  o  m
 * 
 * To be used in a caching method where we are pulling all of the allocations at once.  The way we can do this
 * is to merge a date range based set of billing history records with a date range set of allocations.
 * <p/>
 * <p/>
 * <b>DATABASE PROCEDURE:</b>
 *  
 * @code
 *     FUNCTION fn_get_allocations(
 *           customer IN VARCHAR2,
 *           start_date IN DATE,
 *           end_date   IN DATE )
 *        RETURN ref_cursor;
 * @endcode
 * <p/>
 * <b>DATABASE RESULT SET:</b>
 * <ul>
 *    <li>ALLOCATION_DATE,</li>
 *    <li>ALLOCATION_T, </li>
 *    <li>ALLOCATION_AMT,</li>
 *    <li>AR_ITEM_NO, </li>
 *    <li>BILL_ITEM_NO, </li>
 *    <li>ITEM_DESCRIPTION, </li>
 *    <li>ITEM_CODE,</li> 
 *    <li>AR_ITEM_DATE, </li>
 *    <li>BILL_ITEM_DATE </li>
 *    <li>LICENSE</li>
 *  </ul>
 *  
 * @param customer  :  The Customer.accountNo account number of the customer who's allocations we need
 * @param startDate : The starting date of the allocation - to be merged with a billing history record set
 * @param endDate  :  The ending date of the allocation - to be merged with a billing history record set
 * 
 * @return A list of Allocation objects. 
 * 
 */
@Override
public List<Allocation> getAllocationsList(String customer, Date startDate, Date endDate) throws JSONException {

    List<Allocation> allocs = new ArrayList<Allocation>();

    try {
        //csv file containing data
        String strFile = directory + "ac_" + customer + ".csv";
        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy h:mm");

        //create BufferedReader to read csv file
        BufferedReader br = new BufferedReader(new FileReader(strFile));
        String strLine = "";
        int lineNumber = 0, tokenNumber = 0;

        //read comma separated file line by line
        while ((strLine = br.readLine()) != null) {

            if (strLine.startsWith("$")) {
                continue;
            }

            lineNumber++;

            tokenNumber = 0;

            //break comma separated line using ","
            String[] splitted = strLine.split(",");

            Allocation l = new Allocation();

            l.setLicense(splitted[tokenNumber]);
            tokenNumber++;
            l.setAllocationDate(formatter.parse(splitted[tokenNumber]));
            tokenNumber++;

            Date d = l.getAllocationDate();
            if (d != null && d.after(formatter.parse("01/01/1990 00:00"))
                    && startDate.after(formatter.parse("01/01/1990 00:00"))
                    && endDate.after(formatter.parse("01/01/1990 00:00"))) {
                if (d.before(startDate) || d.after(endDate)) {
                    lineNumber--;
                    continue;
                }
            }

            l.setAllocationAmount(new BigDecimal(splitted[tokenNumber]));
            tokenNumber++;
            l.setAllocatedFromItem(splitted[tokenNumber]);
            tokenNumber++;
            l.setAllocatedToItem(splitted[tokenNumber]);
            tokenNumber++;
            l.setItemDescription(splitted[tokenNumber]);
            tokenNumber++;
            l.setItemCode(splitted[tokenNumber]);
            tokenNumber++;
            allocs.add(l);
        }

        br.close();

    } catch (Exception e) {
        System.out.println("Exception while reading csv file:  " + e);
        throw JSONException.noDataFound("Bad file read " + e.getMessage());

    }

    if (allocs == null || allocs.isEmpty()) {
        throw JSONException.noDataFound("Null set returned - no data found");
    }

    return allocs;
}