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:views.Student_Home.java

public Student_Home() {
    initComponents();//from  w w w.ja v  a2s.co m
    userLoggedIn.setText("User: " + projectManagementSystem.ProjectManagementGlobalSession.user_id);
    studentActions = new StudentActions();
    taskModel = (DefaultTableModel) taskListTable.getModel();
    ArrayList projectsList = studentActions.fetchProjets();
    Date date = new Date();
    projectModel = (DefaultTableModel) projectListTable.getModel();

    for (int i = 0; i < projectsList.size(); i++) {
        Project project = (Project) projectsList.get(i);
        if (date.after(project.getEndDate())) {
            String[] str = { project.getProjectId(), project.getProjectDescription(), "Completed" };
            projectModel.insertRow(projectModel.getRowCount(), str);
        }
        if (date.before(project.getStartDate())) {
            String[] str = { project.getProjectId(), project.getProjectDescription(), "Up coming Project" };
            projectModel.insertRow(projectModel.getRowCount(), str);
        } else if (date.before(project.getEndDate())) {
            String[] str = { project.getProjectId(), project.getProjectDescription(), "In progress" };
            projectModel.insertRow(projectModel.getRowCount(), str);
        }

    }

    populateTasks();

}

From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.MyCompanyPageController.java

protected boolean checkEndDateIsBeforeStartDateForBudget(final B2BBudgetForm b2BBudgetForm) {
    final Date startDate = b2BBudgetForm.getStartDate();
    final Date endDate = b2BBudgetForm.getEndDate();
    return endDate.before(startDate);
}

From source file:de.cismet.cids.custom.utils.berechtigungspruefung.BerechtigungspruefungHandler.java

/**
 * DOCUMENT ME!//from w  ww  .  j a  v  a2 s  .c o  m
 *
 * @param  user  DOCUMENT ME!
 */
public void deleteOldDateianhangFiles(final User user) {
    final File directory = new File(BerechtigungspruefungProperties.getInstance().getAnhangAbsPath());
    final Date thresholdDate = getThresholdAnhangDate();

    // look for all anhang files
    for (final File file : directory.listFiles()) {
        if (file.isFile()) {
            try {
                final String fileName = file.getName();
                final BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
                final Date creationDate = new Date(attr.creationTime().toMillis());

                // file older then threshold date (1 month) ?
                if (creationDate.before(thresholdDate)) {
                    final CidsBean anfrageBean = loadAnfrageBean(user, fileName);
                    // assuring, that the file corresponds to an existing bean This prevents accidental deletion of
                    // non-anhang files (i.e. if AnhangAbsPath was set to a path that contains also other files)
                    if (anfrageBean != null) {
                        final Timestamp anfrageTs = (Timestamp) anfrageBean.getProperty("anfrage_timestamp");
                        // timestamp filed in the bean agrees with the file creation date ?
                        if (anfrageTs.before(thresholdDate)) {
                            LOG.info("deleting old Anhang file: " + file.getName() + " (date: "
                                    + creationDate.toString() + ")");
                            // now we can delete (hopefully)
                            file.delete();
                        }
                    }
                }
            } catch (final IOException ex) {
                LOG.warn("could not delete Anhang file: " + file.getName(), ex);
            }
        }
    }
}

From source file:net.phase.wallet.Currency.java

protected static Date latest(Transaction[] transactions) {
    Date result = null;

    if (transactions != null && transactions.length > 0) {
        for (Transaction t : transactions) {
            if (result == null || result.before(t.date)) {
                result = t.date;//from  ww  w. j  a v a 2s . c  om
            }
        }
    }

    return result;
}

From source file:edu.stanford.muse.index.IndexUtils.java

/** returns list of list of docs organized by a series of time windows */
public static List<Window> docsBySlidingWindow(Collection<EmailDocument> allDocs, int windowSizeInMonths,
        int stepSizeInMonths) {
    List<Window> result = new ArrayList<Window>();
    if (allDocs.size() == 0)
        return result;

    // compute the begin and end date of the corpus
    Date first = null;//w w w .j ava  2 s . c o  m
    Date last = null;
    for (EmailDocument ed : allDocs) {
        Date d = ed.date;
        if (d == null) { // drop this ed
            log.warn("Warning: null date on email: " + ed.getHeader());
            continue;
        }
        if (first == null || d.before(first))
            first = d;
        if (last == null || d.after(last))
            last = d;
    }

    // compute the monthly intervals
    List<Pair<Date, Date>> intervals = Util.getSlidingMonthlyIntervalsBackward(first, last, windowSizeInMonths,
            stepSizeInMonths);

    int nIntervals = intervals.size();
    for (int i = 0; i < nIntervals; i++) {
        Window w = new Window();
        w.start = intervals.get(i).getFirst();
        w.end = intervals.get(i).getSecond();
        w.docs = new ArrayList<EmailDocument>();
        result.add(w);
    }

    // for each message, add it to all intervals it belongs to
    // can be made more efficient by first sorting allDocs by date etc
    // but may not be needed except for a very large # of intervals and
    // a large # of docs
    for (EmailDocument ed : allDocs) {
        Date d = ed.date;
        if (d == null)
            continue;

        // add ed to all intervals that c falls in
        for (int i = 0; i < nIntervals; i++) {
            Pair<Date, Date> interval = intervals.get(i);
            Date intervalStart = interval.getFirst();
            Date intervalEnd = interval.getSecond();
            if (d.equals(intervalStart) || d.equals(intervalEnd)
                    || (d.after(intervalStart) && d.before(intervalEnd))) {
                result.get(i).docs.add(ed);
                break;
            }
        }
    }

    return result;
}

From source file:gda.data.metadata.icat.XMLIcat.java

@Override
protected String getValue(String visitIDFilter, String userNameFilter, String accessName) throws Exception {

    String filepath = "file:" + LocalProperties.get(URL_PROP);
    Resource xmlfile = new FileSystemResourceLoader().getResource(filepath);
    XmlBeanFactory bf = new XmlBeanFactory(xmlfile);

    long tolerance = LocalProperties.getAsInt(SHIFT_TOL_PROP, 1440);

    // if not filtering on visit ID
    if (visitIDFilter == null || visitIDFilter.isEmpty()) {

        //loop over all the beans
        String values = "";
        Map<String, XMLIcatEntry> beans = bf.getBeansOfType(XMLIcatEntry.class);
        for (XMLIcatEntry bean : beans.values()) {
            // filter on username
            String names[] = bean.getUsernames().split(",");
            if (ArrayUtils.contains(names, userNameFilter)) {

                // filter on date
                Date now;
                if (operatingDate != null) {
                    now = operatingDate;
                } else {
                    now = new Date();
                }/*from   w w  w.j a v  a2  s  .co  m*/

                Date start = formatter.parse(bean.getExperimentStart());
                Date end = formatter.parse(bean.getExperimentStart());
                start.setTime(start.getTime() - tolerance * 60000);// tolerance is in minutes but getTime returns in
                // ms
                end.setTime(end.getTime() + tolerance * 60000); // tolerance is in minutes but getTime returns in ms

                if (now.after(start) && now.before(end)) {

                    // add to return string
                    try {
                        if (values.isEmpty()) {
                            values = BeanUtils.getProperty(bean, accessName);
                        } else {
                            values += "," + BeanUtils.getProperty(bean, accessName);
                        }
                    } catch (Exception e) {
                        logger.warn("Exception trying to get property " + accessName + " from bean.", e);
                    }
                }
            }
        }

        // return the values string
        if (values.isEmpty()) {
            return null;
        }
        return values;
    }

    // else find the experiment for that visit and get its property
    XMLIcatEntry visit = bf.getBean(visitIDFilter, XMLIcatEntry.class);
    String names[] = visit.getUsernames().split(",");
    if (ArrayUtils.contains(names, userNameFilter)) {
        try {
            return BeanUtils.getProperty(visit, accessName);
        } catch (Exception e) {
            logger.warn("Exception trying to get property " + accessName + " from bean.", e);
        }
    }

    // else 
    return null;

}

From source file:com.pearson.dashboard.util.Util.java

public static Map<String, List<String>> getIteration(Configuration configuration, String projectId)
        throws IOException, ParseException, URISyntaxException {
    RallyRestApi restApi = loginRally(configuration);
    Map<String, List<String>> testSetsInformation = new HashMap<String, List<String>>();
    QueryRequest iterationRequest = new QueryRequest("Iteration");
    iterationRequest.setProject("/project/" + projectId);
    iterationRequest.setLimit(2000);/*from  w  ww  .j  ava 2 s  .c  om*/
    QueryResponse iterationResponse = restApi.query(iterationRequest);
    JsonArray iterationArray = iterationResponse.getResults();
    QueryFilter queryFilter = null;
    for (int i = 0; i < iterationArray.size(); i++) {
        JsonElement elements = iterationArray.get(i);
        JsonObject object = elements.getAsJsonObject();
        String ref = object.get("_ref").getAsString();
        ref = ref.substring(ref.indexOf("/iteration/"));
        ref = ref.replace(".js", "");
        DateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
        String strStartDate = object.get("StartDate").getAsString().substring(0, 10);
        Date startDate = (Date) formatter1.parse(strStartDate);
        String strEndDate = object.get("EndDate").getAsString().substring(0, 10);
        Date endDate = (Date) formatter1.parse(strEndDate);
        Date dateNow = new Date();
        if (dateNow.after(startDate) && dateNow.before(endDate)) {
            if (queryFilter == null) {
                queryFilter = new QueryFilter("Iteration", "=", ref);
            } else {
                queryFilter = queryFilter.or(new QueryFilter("Iteration", "=", ref));
            }
        }
    }
    if (queryFilter != null) {
        QueryRequest testSetRequest = new QueryRequest("TestSet");
        testSetRequest.setQueryFilter(queryFilter);
        String wsapiVersion = "1.43";
        restApi.setWsapiVersion(wsapiVersion);
        testSetRequest.setProject("/project/" + projectId);
        testSetRequest.setScopedDown(true);
        QueryResponse testSetQueryResponse = restApi.query(testSetRequest);
        List<String> iosTestSetList = new ArrayList<String>();
        List<String> winTestSetList = new ArrayList<String>();
        for (int i = 0; i < testSetQueryResponse.getResults().size(); i++) {
            JsonObject testSetJsonObject = testSetQueryResponse.getResults().get(i).getAsJsonObject();
            String testSetId = testSetJsonObject.get("FormattedID").getAsString();
            String testSetName = testSetJsonObject.get("Name").getAsString();
            if (testSetName.toUpperCase().contains("EOS")) {
                if (testSetName.toUpperCase().contains("WIN")) {
                    winTestSetList.add(testSetId);
                } else {
                    iosTestSetList.add(testSetId);
                }
            }

        }
        testSetsInformation.put("IOS", iosTestSetList);
        testSetsInformation.put("WIN", winTestSetList);
    }
    return testSetsInformation;
}

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

private boolean alreadyHaveNewerCacheEntry(HttpHost target, HttpRequest request, HttpResponse backendResponse)
        throws IOException {
    HttpCacheEntry existing = null;//  w w w.j a va2s.c o  m
    try {
        existing = responseCache.getCacheEntry(target, request);
    } catch (IOException ioe) {
        // nop
    }
    if (existing == null)
        return false;
    Header entryDateHeader = existing.getFirstHeader("Date");
    if (entryDateHeader == null)
        return false;
    Header responseDateHeader = backendResponse.getFirstHeader("Date");
    if (responseDateHeader == null)
        return false;
    try {
        Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
        Date responseDate = DateUtils.parseDate(responseDateHeader.getValue());
        return responseDate.before(entryDate);
    } catch (DateParseException e) {
    }
    return false;
}

From source file:com.iorga.webappwatcher.analyzer.model.session.DurationPerPrincipalStats.java

private TimeSlice findOrCreateTimeSlice(final Date date, final long timeSliceDurationMillis) {
    // will binary search the time slice
    int low = 0;//from   w  w  w . java  2 s  . c o m
    int high = timeSlices.size() - 1;
    int mid;
    while (low <= high) {
        mid = (low + high) / 2;
        final TimeSlice midTimeSlice = timeSlices.get(mid);
        if (date.after(midTimeSlice.endDate)) {
            low = mid + 1;
        } else if (date.before(midTimeSlice.startDate)) {
            high = mid - 1;
        } else {
            return midTimeSlice;
        }
    }
    // not found in the existing time slices, must create a new one
    return createNewTimeSlice(date, timeSliceDurationMillis);
}

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

/**
 * Try to validate the client credentials by parsing and validating the JWT.
 *///from  w  ww .ja  v a  2  s  . c  om
@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");
    }
}