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:org.jasig.schedassist.web.visitor.CreateAppointmentFormController.java

/**
 * Verify the startTime argument is within the window; throws a {@link ScheduleException} if not.
 * /*  ww w  .java 2  s .  co  m*/
 * @param window
 * @param startTime
 * @throws SchedulingException
 */
protected void validateChosenStartTime(VisibleWindow window, Date startTime) throws SchedulingException {
    final Date currentWindowStart = window.calculateCurrentWindowStart();
    final Date currentWindowEnd = window.calculateCurrentWindowEnd();
    if (startTime.before(currentWindowStart) || startTime.equals(currentWindowEnd)
            || startTime.after(currentWindowEnd)) {
        throw new SchedulingException("requested time is no longer within visible window");
    }
}

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

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

    Patient patient = new Patient(1);

    Capture<Date> minDateCapture = new Capture<Date>();
    Capture<Date> dueDateCapture = new Capture<Date>();
    Capture<Date> lateDateCapture = new Capture<Date>();

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

    Date pregnancyDate = new Date();

    expect(registrarBean.getActivePregnancyDueDate(patient.getPatientId())).andReturn(pregnancyDate);
    expect(registrarBean.getObs(eq(patient), eq(iptSchedule.getConceptName()),
            eq(iptSchedule.getValueConceptName()), (Date) anyObject())).andReturn(obsList);
    expect(registrarBean.getExpectedObs(patient, iptSchedule.getName())).andReturn(expectedObsList);
    expect(registrarBean.createExpectedObs(eq(patient), eq(iptSchedule.getConceptName()),
            eq(iptSchedule.getValueConceptName()), eq(ipt1Event.getNumber()), capture(minDateCapture),
            capture(dueDateCapture), capture(lateDateCapture), (Date) anyObject(), eq(ipt1Event.getName()),
            eq(iptSchedule.getName()))).andReturn(new ExpectedObs());

    replay(registrarBean);//from  www .  j  a v  a 2 s  .  c  o m

    iptSchedule.updateSchedule(patient, date);

    verify(registrarBean);

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

    assertNotNull("Min date is null", minDate);
    assertNotNull("Due date is null", dueDate);
    assertNotNull("Late date is null", lateDate);

    assertTrue("Min date is not before due date", minDate.before(dueDate));
    assertTrue("Late date is not after due date", lateDate.after(dueDate));
}

From source file:ch.bfh.uniboard.accesscontrolled.AccessControlledService.java

@Override
protected Attributes beforePost(byte[] message, Attributes alpha, Attributes beta) {

    //TODO Check if ATTRIBUTE_NAME_PUBLICKEY and ATTRIBUTE_NAME_SIG are set in alpha
    if (!alpha.containsKey(ATTRIBUTE_NAME_PUBLICKEY)) {
        logger.log(Level.INFO, "Publickey missing in alpha.");
        beta.add(Attributes.REJECTED, new StringValue("BAC-001 Publickey missing in alpha."));
        return beta;
    }/*  w w w.  jav a 2  s .com*/
    //Get the latest authorization with key and group in the current section in the authorization group
    //Contraint for the publickey
    List<Constraint> constraints = new ArrayList<>();
    List<String> sListKey = new ArrayList<>();
    sListKey.add(ATTRIBUTE_NAME_CRYPTO);
    sListKey.add(ATTRIBUTE_NAME_PUBLICKEY);
    Constraint cKey = new Equal(new MessageIdentifier(sListKey), alpha.getValue(ATTRIBUTE_NAME_PUBLICKEY));
    constraints.add(cKey);

    //Contraint of the group in the message
    List<String> sListGroup = new ArrayList<>();
    sListGroup.add(GROUPED);
    Constraint cGroup = new Equal(new MessageIdentifier(sListGroup), alpha.getValue(GROUPED));
    constraints.add(cGroup);

    //Constraint of the section
    List<String> sListSection = new ArrayList<>();
    sListSection.add(SECTIONED);
    Constraint cSection = new Equal(new AlphaIdentifier(sListSection), alpha.getValue(SECTIONED));
    constraints.add(cSection);

    //Constraint of the group
    List<String> sListGroup2 = new ArrayList<>();
    sListGroup2.add(GROUPED);
    Constraint cGroup2 = new Equal(new AlphaIdentifier(sListGroup2), new StringValue(AUTH));
    constraints.add(cGroup2);

    //Sort by time of posting desc
    List<Order> orderBy = new ArrayList<>();
    Order byTime = new Order(new BetaIdentifier(CHRONOLOGICAL), false);
    orderBy.add(byTime);

    //Limit to one result
    Query q = new Query(constraints, orderBy, 1);

    ResultContainer rc = this.getService.get(q);
    if (rc.getResult().isEmpty() || rc.getResult().size() != 1) {
        logger.log(Level.INFO, "No authorization for publickey {0}" + " section {1}" + " group {2}",
                new Object[] { alpha.getValue(ATTRIBUTE_NAME_PUBLICKEY), alpha.getValue(SECTIONED),
                        alpha.getValue(GROUPED) });
        beta.add(Attributes.REJECTED, new StringValue("BAC-002 No authorization for this publickey."));
        return beta;
    }
    Post authPost = rc.getResult().get(0);

    DateValue currentPostTime = (DateValue) beta.getValue(CHRONOLOGICAL);
    try {
        JsonNode data = JsonLoader.fromString(new String(authPost.getMessage(), Charset.forName("UTF-8")));
        ObjectMapper mapper = new ObjectMapper();

        //Check the signature
        JsonNode key = data.get(ATTRIBUTE_NAME_CRYPTO);

        String type = key.get("type").textValue();

        boolean signature = false;

        switch (type) {
        case "RSA":
            signature = this.checkRSASignature(key, message, alpha);
            break;
        case "DL":
            signature = this.checkDLSignature(key, message, alpha);
            break;
        case "ECDL":
            signature = this.checkECDLSignature(key, message, alpha);
            break;
        default:
            break;
        }

        if (!signature) {
            logger.log(Level.INFO, "Signature for group {0} and key  {1} is not valid.",
                    new Object[] { alpha.getValue(GROUPED), key.get("publickey").asText() });
            beta.add(Attributes.REJECTED, new StringValue("BAC-003 Signature is not valid."));
            return beta;
        }

        //Check if startTime and endTime are set and if the post time is in between.
        if (data.has(STARTTIME)) {
            Date startDate = mapper.readValue(data.get(STARTTIME).traverse(), Date.class);
            if (startDate.after(currentPostTime.getValue())) {
                logger.log(Level.INFO,
                        "Authorization for key {0}" + " section {1}"
                                + " group {2} is not active yet. Start at {3}",
                        new Object[] { alpha.getValue(ATTRIBUTE_NAME_CRYPTO), alpha.getValue(SECTIONED),
                                alpha.getValue(GROUPED), startDate });
                beta.add(Attributes.REJECTED, new StringValue("BAC-004 Authorization is not active yet."));
                return beta;
            }
        }
        if (data.has(ENDTIME)) {
            Date endDate = mapper.readValue(data.get(ENDTIME).traverse(), Date.class);
            if (endDate.before(currentPostTime.getValue())) {
                logger.log(Level.INFO,
                        "Authorization for key {0}" + " section {1}" + " group {2} has expired at {3}.",
                        new Object[] { alpha.getValue(ATTRIBUTE_NAME_CRYPTO), alpha.getValue(SECTIONED),
                                alpha.getValue(GROUPED), endDate });
                beta.add(Attributes.REJECTED, new StringValue("BAC-005 Authorization expired."));
                return beta;
            }
        }
        //Check if the amount of allowed posts is not exceeded
        if (data.has(AMOUNT)) {
            //If check the group for the amount of existing posts
            List<Constraint> constraintsAmount = new ArrayList<>();

            Constraint cASection = new Equal(new AlphaIdentifier(SECTIONED), alpha.getValue(SECTIONED));
            constraintsAmount.add(cASection);

            Constraint cAGroup = new Equal(new AlphaIdentifier(GROUPED), alpha.getValue(GROUPED));
            constraintsAmount.add(cAGroup);

            Constraint cAKey = new Equal(new AlphaIdentifier(ATTRIBUTE_NAME_PUBLICKEY),
                    alpha.getValue(ATTRIBUTE_NAME_PUBLICKEY));
            constraintsAmount.add(cAKey);

            Query qAmount = new Query(constraintsAmount);
            ResultContainer rcAmount = this.getService.get(qAmount);

            if (rcAmount.getResult().size() >= data.get(AMOUNT).asInt()) {
                logger.log(Level.INFO,
                        "Authorization for key {0}" + " section {1}"
                                + " group {2} has used the allowed posts {3}.",
                        new Object[] { alpha.getValue(ATTRIBUTE_NAME_CRYPTO), alpha.getValue(SECTIONED),
                                alpha.getValue(GROUPED), data.get("amount").asInt() });
                beta.add(Attributes.REJECTED, new StringValue("BAC-007 Amount of allowed posts used up."));
                return beta;
            }
        }

    } catch (IOException ex) {
        logger.log(Level.SEVERE, "Error occoured while parsing authorization {0}", ex.getMessage());
        beta.add(Attributes.ERROR, new StringValue("BAC-006 Internal server error."));
        return beta;
    }

    //accept message
    return beta;
}

From source file:net.sourceforge.eclipsetrader.yahoo.HistoryFeed.java

public void updateHistory(Security security, int interval) {
    if (interval == IHistoryFeed.INTERVAL_DAILY) {
        Calendar from = Calendar.getInstance();
        Calendar to = Calendar.getInstance();

        History history = security.getHistory();
        if (history.size() == 0)
            from.add(Calendar.YEAR, -CorePlugin.getDefault().getPreferenceStore()
                    .getInt(CorePlugin.PREFS_HISTORICAL_PRICE_RANGE));
        else {/* ww  w.  j  a v  a  2 s. c o m*/
            Bar cd = history.getLast();
            if (cd != null) {
                from.setTime(cd.getDate());
                from.add(Calendar.DATE, 1);
            }
        }

        try {
            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            String host = "ichart.finance.yahoo.com"; //$NON-NLS-1$
            BundleContext context = YahooPlugin.getDefault().getBundle().getBundleContext();
            ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
            if (reference != null) {
                IProxyService proxy = (IProxyService) context.getService(reference);
                IProxyData data = proxy.getProxyDataForHost(host, IProxyData.HTTP_PROXY_TYPE);
                if (data != null) {
                    if (data.getHost() != null)
                        client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                    if (data.isRequiresAuthentication())
                        client.getState().setProxyCredentials(AuthScope.ANY,
                                new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
                }
            }

            String symbol = null;
            if (security.getHistoryFeed() != null)
                symbol = security.getHistoryFeed().getSymbol();
            if (symbol == null || symbol.length() == 0)
                symbol = security.getCode();

            // If the last bar from the data is from a date before today, then
            // download the historical data, otherwise it's enough to download the data for today.
            to.add(Calendar.DAY_OF_MONTH, -1);
            to.set(Calendar.HOUR, 0);
            to.set(Calendar.MINUTE, 0);
            to.set(Calendar.SECOND, 0);
            to.set(Calendar.MILLISECOND, 0);
            Bar lastHistoryBar = history.getLast();
            Date lastDate;
            if (lastHistoryBar == null)
                lastDate = from.getTime();
            else
                lastDate = lastHistoryBar.getDate();
            if (lastDate.before(to.getTime())) {
                log.info("Updating historical data for " + security.getCode() + " - " //$NON-NLS-1$//$NON-NLS-2$
                        + security.getDescription());

                StringBuffer url = new StringBuffer("http://" + host + "/table.csv" + "?s="); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                url.append(symbol);
                url.append("&d=" + to.get(Calendar.MONTH) + "&e=" + to.get(Calendar.DAY_OF_MONTH) + "&f=" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                        + to.get(Calendar.YEAR));
                url.append("&g=d"); //$NON-NLS-1$
                url.append("&a=" + from.get(Calendar.MONTH) + "&b=" + from.get(Calendar.DAY_OF_MONTH) + "&c=" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                        + from.get(Calendar.YEAR));
                url.append("&ignore=.csv"); //$NON-NLS-1$
                log.debug(url);

                HttpMethod method = new GetMethod(url.toString());
                method.setFollowRedirects(true);
                client.executeMethod(method);

                BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));

                // The first line is the header, ignoring
                String inputLine = in.readLine();
                log.trace(inputLine);

                while ((inputLine = in.readLine()) != null) {
                    log.trace(inputLine);
                    if (inputLine.startsWith("<")) //$NON-NLS-1$
                        continue;
                    String[] item = inputLine.split(","); //$NON-NLS-1$
                    if (item.length < 6)
                        continue;

                    Calendar day = Calendar.getInstance();
                    try {
                        day.setTime(df.parse(item[0]));
                    } catch (Exception e) {
                        try {
                            day.setTime(dfAlt.parse(item[0]));
                        } catch (Exception e1) {
                            log.error(e1, e1);
                        }
                    }
                    day.set(Calendar.HOUR, 0);
                    day.set(Calendar.MINUTE, 0);
                    day.set(Calendar.SECOND, 0);
                    day.set(Calendar.MILLISECOND, 0);

                    Bar bar = new Bar();
                    bar.setDate(day.getTime());
                    bar.setOpen(Double.parseDouble(item[1].replace(',', '.')));
                    bar.setHigh(Double.parseDouble(item[2].replace(',', '.')));
                    bar.setLow(Double.parseDouble(item[3].replace(',', '.')));
                    bar.setClose(Double.parseDouble(item[4].replace(',', '.')));
                    bar.setVolume(Long.parseLong(item[5]));

                    // Remove the old bar, if exists
                    int index = history.indexOf(bar.getDate());
                    if (index != -1)
                        history.remove(index);

                    history.add(bar);
                }
                in.close();
            }

            // Get the data for today (to-date) using a different URL at Yahoo!
            //Bar lastbar = history.getLast
            log.debug("Get data for today using a separate URL..."); //$NON-NLS-1$
            StringBuffer url = new StringBuffer(
                    "http://finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=sl1d1t1c1ohgv&e=.csv"); //$NON-NLS-1$ //$NON-NLS-2$
            log.debug(url);

            HttpMethod method = new GetMethod(url.toString());
            method.setFollowRedirects(true);
            client.executeMethod(method);

            BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            String inputLine = in.readLine();
            log.trace(inputLine);
            String[] item = inputLine.split(","); //$NON-NLS-1$
            item[2] = item[2].replace("\"", ""); //$NON-NLS-1$ //$NON-NLS-2$

            SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy", Locale.US); //$NON-NLS-1$
            Calendar day = Calendar.getInstance();

            // Transfer the data from the string array to the Bar
            day.setTime(df.parse(item[2]));
            Bar bar = new Bar();
            bar.setDate(day.getTime());
            bar.setOpen(Double.parseDouble(item[5]));
            bar.setClose(Double.parseDouble(item[1]));
            bar.setHigh(Double.parseDouble(item[6]));
            bar.setLow(Double.parseDouble(item[7]));
            bar.setVolume(Long.parseLong(item[8]));

            // Remove the old bar, if exists
            int index = history.indexOf(bar.getDate());
            if (index != -1)
                history.remove(index);
            history.add(bar);

            in.close();

        } catch (Exception e) {
            log.error(e, e);
        }

        CorePlugin.getRepository().save(history);
    } else
        log.warn("Intraday data not supported for " + security.getCode() + " - " + security.getDescription()); //$NON-NLS-1$ //$NON-NLS-2$
}

From source file:de.hybris.platform.integration.cis.payment.cronjob.DefaultCisFraudReportJob.java

@Override
public PerformResult perform(final CisFraudReportCronJobModel cronJob) {
    try {//from w w  w.  ja  v a  2 s  . c  o  m
        final CisFraudReportRequest request = new CisFraudReportRequest();
        final Date requestStartTime = getLastCronJobEndTime();
        final Date requestEndTime = new Date();
        final Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, -24);

        if (requestStartTime.before(calendar.getTime())) {
            LOG.error("CyberSource report time range is only valid for the past 24 hours");
            return new PerformResult(CronJobResult.ERROR, CronJobStatus.ABORTED);
        }

        request.setStartDateTime(requestStartTime);
        request.setEndDateTime(requestEndTime);
        final RestResponse<CisFraudReportResult> response = getOndemandHystrixCommandFactory().newCommand(
                getHystrixCommandConfig(), new HystrixExecutable<RestResponse<CisFraudReportResult>>() {
                    @Override
                    public RestResponse<CisFraudReportResult> runEvent() {
                        return getFraudClient().generateFraudReport(cronJob.getCode(), request);
                    }

                    @Override
                    public RestResponse<CisFraudReportResult> fallbackEvent() {
                        return null;
                    }

                    @Override
                    public RestResponse<CisFraudReportResult> defaultEvent() {
                        return null;
                    }
                }).execute();

        if (response != null) {
            final List<CisFraudTransactionResult> transactionResults = response.getResult().getTransactions();

            if (CollectionUtils.isNotEmpty(transactionResults)) {
                //Retrieve all the transactionIds from each of the transaction results
                final List<String> transactionIds = (List<String>) CollectionUtils.collect(transactionResults,
                        new Transformer() {
                            @Override
                            public Object transform(final Object o) {
                                final CisFraudTransactionResult result = (CisFraudTransactionResult) o;

                                return result.getClientAuthorizationId();
                            }
                        });

                final List<PaymentTransactionEntryModel> transactionEntries = getPaymentTransactionEntryModels(
                        transactionIds);

                //For each transaction result, set the transaction from it's corresponding order and fire the business process event
                for (final CisFraudTransactionResult transactionResult : transactionResults) {
                    final PaymentTransactionEntryModel transactionEntry = (PaymentTransactionEntryModel) CollectionUtils
                            .find(transactionEntries, new Predicate() {
                                @Override
                                public boolean evaluate(final Object o) {
                                    return ((PaymentTransactionEntryModel) o).getCode()
                                            .equalsIgnoreCase(transactionResult.getClientAuthorizationId());
                                }
                            });

                    if (transactionEntry != null && transactionEntry.getPaymentTransaction() != null
                            && transactionEntry.getPaymentTransaction().getOrder() != null) {
                        final PaymentTransactionModel transaction = transactionEntry.getPaymentTransaction();
                        final String guid = transaction.getOrder().getGuid();

                        final PaymentTransactionEntryModel newTransactionEntry = getTransactionResultConverter()
                                .convert(transactionResult);
                        getPaymentService().setPaymentTransactionReviewResult(newTransactionEntry, guid);
                    }
                }
            }

            //Set the LastFraudReportEndTime for use the next time this cron job runs
            cronJob.setLastFraudReportEndTime(requestEndTime);
            getModelService().save(cronJob);

            return new PerformResult(CronJobResult.SUCCESS, CronJobStatus.FINISHED);
        }

        return new PerformResult(CronJobResult.ERROR, CronJobStatus.ABORTED);
    } catch (final Exception e) {
        LOG.warn(String.format("Error occurred while processing the fraud reports [%s]",
                e.getLocalizedMessage()));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error occurred while processing the fraud reports", e);
        }
        return new PerformResult(CronJobResult.ERROR, CronJobStatus.ABORTED);
    }
}

From source file:org.jasig.schedassist.portlet.webflow.FlowHelper.java

/**
 * Verify the startTime argument is within the window; return {@link #NO} if not.
 * //from w  ww.  j  a  v a2  s.com
 * @param window
 * @param startTime
 * @return {@link #YES} for valid, {@link #NO} for invalid
 */
public String validateChosenStartTime(VisibleWindow window, Date startTime) {
    final Date currentWindowEnd = window.calculateCurrentWindowEnd();
    if (startTime.before(window.calculateCurrentWindowStart()) || startTime.equals(currentWindowEnd)
            || startTime.after(currentWindowEnd)) {
        LOG.debug("selected startTime (" + startTime + ") is no longer within window " + window.getKey());
        return NO;
    }

    return YES;
}

From source file:com.hzq.car.CarTest.java

@Test
public void test01() throws IOException, ParseException {

    //        String token = getToken();
    //        logger.warn("getToken: {}", token);
    String token = "932039219c9b5bf0ab65b9b50023ee56";
    String url = DATA_URL_TEST;
    if (isProd)//w w  w  . jav a 2s .  c o m
        url = DATA_URL_PROD;

    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date parse = format.parse("2017-03-07"); //? 
    calendar.setTime(parse);
    //        calendar.add(Calendar.MONTH, -6);
    Date grabDate = calendar.getTime();

    //        Calendar NOW = Calendar.getInstance();
    //        NOW.add(Calendar.DATE, -2);

    while (grabDate.before(new Date())) {
        try {
            sendAndSave(token, grabDate, url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        calendar.add(Calendar.DATE, 1);
        grabDate = calendar.getTime();
    }

}

From source file:fr.paris.lutece.plugins.stock.modules.billetterie.web.StockBilletterieApp.java

/**
 * Calculate if show is open to book./*from   www.  jav a  2s.c  om*/
 *
 * @param show the show
 * @return 0 open, 1 to come, -1 passed
 */
private int caculateBookingOpened(ShowDTO show) {
    Date startDate = DateUtils.getDate(show.getStartDate(), true);
    Date endDate = DateUtils.getDate(show.getEndDate(), false);
    Date today = new Date();
    int seanceOpened;

    if (today.before(startDate)) {
        seanceOpened = BOOKING_TO_COME;
    } else if (today.after(endDate)) {
        seanceOpened = BOOKING_PASSED;
    } else {
        seanceOpened = BOOKING_OPENED;
    }

    return seanceOpened;
}

From source file:com.appleframework.monitor.model.MetricDog.java

protected boolean inWorkTime(Date current) {
    Date now = null;
    try {/* w w w.  j av  a2 s . c  o  m*/
        now = sdf.parse(sdf.format(current));

        Date start = sdf.parse(startTime);
        Date end = sdf.parse(endTime);
        //"?"?
        if (excludeTimeMode) {
            return !(now.after(start) && now.before(end));
        } else {
            return now.after(start) && now.before(end);
        }
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.phenotips.data.internal.MonarchPatientScorerTest.java

@Test
public void getSpecificityWithNoFeaturesReturns0() throws ComponentLookupException {
    Mockito.doReturn(Collections.emptySet()).when(this.patient).getFeatures();
    CapturingMatcher<PatientSpecificity> specCapture = new CapturingMatcher<>();
    Mockito.doNothing().when(this.cache).set(Matchers.eq(""), Matchers.argThat(specCapture));
    Date d1 = new Date();
    this.mocker.getComponentUnderTest().getSpecificity(this.patient);
    Date d2 = new Date();
    PatientSpecificity spec = specCapture.getLastValue();
    Assert.assertEquals(0.0, spec.getScore(), 0.0);
    Assert.assertEquals("monarchinitiative.org", spec.getComputingMethod());
    Assert.assertFalse(d1.after(spec.getComputationDate()));
    Assert.assertFalse(d2.before(spec.getComputationDate()));
}