Example usage for java.util Date compareTo

List of usage examples for java.util Date compareTo

Introduction

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

Prototype

public int compareTo(Date anotherDate) 

Source Link

Document

Compares two Dates for ordering.

Usage

From source file:org.apache.falcon.workflow.engine.OozieWorkflowEngine.java

private void updateCoords(String cluster, BundleJob bundle, int concurrency, Date endTime)
        throws FalconException {
    if (endTime.compareTo(now()) <= 0) {
        throw new FalconException("End time " + SchemaHelper.formatDateUTC(endTime) + " can't be in the past");
    }/* w w w  . jav a2  s  . com*/

    if (bundle.getCoordinators() == null || bundle.getCoordinators().isEmpty()) {
        throw new FalconException("Invalid state. Oozie coords are still not created. Try again later");
    }

    // change coords
    for (CoordinatorJob coord : bundle.getCoordinators()) {
        LOG.debug("Updating endtime of coord {} to {} on cluster {}", coord.getId(),
                SchemaHelper.formatDateUTC(endTime), cluster);
        Date lastActionTime = getCoordLastActionTime(coord);
        if (lastActionTime == null) { // nothing is materialized
            LOG.info("Nothing is materialized for this coord: {}", coord.getId());
            if (endTime.compareTo(coord.getStartTime()) <= 0) {
                LOG.info("Setting end time to START TIME {}", SchemaHelper.formatDateUTC(coord.getStartTime()));
                change(cluster, coord.getId(), concurrency, coord.getStartTime(), null);
            } else {
                LOG.info("Setting end time to START TIME {}", SchemaHelper.formatDateUTC(endTime));
                change(cluster, coord.getId(), concurrency, endTime, null);
            }
        } else {
            LOG.info("Actions have materialized for this coord: {}, last action {}", coord.getId(),
                    SchemaHelper.formatDateUTC(lastActionTime));
            if (!endTime.after(lastActionTime)) {
                Date pauseTime = offsetTime(endTime, -1);
                // set pause time which deletes future actions
                LOG.info("Setting pause time on coord: {} to {}", coord.getId(),
                        SchemaHelper.formatDateUTC(pauseTime));
                change(cluster, coord.getId(), concurrency, null, SchemaHelper.formatDateUTC(pauseTime));
            }
            change(cluster, coord.getId(), concurrency, endTime, "");
        }
    }
}

From source file:com.mg.merp.planning.support.MPSProcessorServiceBean.java

/**
 *       , .. ?? ?   /*from w  ww. j av a 2s  .c  om*/
 *  .
 */
private boolean checkDemandFenceDate(ForecastMethod forecastMethod, Date requiredDate, short demandFenceDays,
        short bucketOffset) {
    Date fenceDate = DateTimeUtils.incDay(mps.getDemandFenceDate(), demandFenceDays);
    switch (forecastMethod) {
    case BY_PERIOD:
        short pdfBucketOffset = MfUtils.determineBucketOffset(mps.getPlanningLevel().getId(), fenceDate);
        if (pdfBucketOffset != -1 && bucketOffset >= pdfBucketOffset)
            return true;
        break;
    case BY_DATE:
        if (requiredDate.compareTo(fenceDate) >= 0)
            return true;
        break;
    }
    return false;
}

From source file:self.philbrown.droidQuery.Ajax.java

protected TaskResponse doInBackground(Void... arg0) {
    if (this.isCancelled)
        return null;

    //if synchronous, block on the background thread until ready. Then call beforeSend, etc, before resuming.
    if (!beforeSendIsAsync) {
        try {// ww  w  . j  a  v  a 2 s .co m
            mutex.acquire();
        } catch (InterruptedException e) {
            Log.w("AjaxTask", "Synchronization Error. Running Task Async");
        }
        final Thread asyncThread = Thread.currentThread();
        isLocked = true;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (options.beforeSend() != null) {
                    if (options.context() != null)
                        options.beforeSend().invoke($.with(options.context()), options);
                    else
                        options.beforeSend().invoke(null, options);
                }

                if (options.isAborted()) {
                    cancel(true);
                    return;
                }

                if (options.global()) {
                    synchronized (globalTasks) {
                        if (globalTasks.isEmpty()) {
                            $.ajaxStart();
                        }
                        globalTasks.add(Ajax.this);
                    }
                    $.ajaxSend();
                } else {
                    synchronized (localTasks) {
                        localTasks.add(Ajax.this);
                    }
                }
                isLocked = false;
                LockSupport.unpark(asyncThread);
            }
        });
        if (isLocked)
            LockSupport.park();
    }

    //here is where to use the mutex

    //handle cached responses
    Object cachedResponse = AjaxCache.sharedCache().getCachedResponse(options);
    //handle ajax caching option
    if (cachedResponse != null && options.cache()) {
        Success s = new Success(cachedResponse);
        s.reason = "cached response";
        s.allHeaders = null;
        return s;

    }

    if (connection == null) {
        try {
            String type = options.type();
            URL url = new URL(options.url());
            if (type == null) {
                type = "GET";
            }
            if (type.equalsIgnoreCase("CUSTOM")) {

                try {
                    connection = options.customConnection();
                } catch (Exception e) {
                    connection = null;
                }

                if (connection == null) {
                    Log.w("droidQuery.ajax",
                            "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET.");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                }
            } else {
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod(type);
                if (type.equalsIgnoreCase("POST") || type.equalsIgnoreCase("PUT")) {
                    connection.setDoOutput(true);
                }
            }
        } catch (Throwable t) {
            if (options.debug())
                t.printStackTrace();
            Error e = new Error(null);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = 0;
            e.reason = "Bad Configuration";
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = new Headers();
            e.error = error;
            return e;
        }

    }

    Map<String, Object> args = new HashMap<String, Object>();
    args.put("options", options);
    args.put("request", null);
    args.put("connection", connection);
    EventCenter.trigger("ajaxPrefilter", args, null);

    if (options.headers() != null) {
        if (options.headers().authorization() != null) {
            options.headers()
                    .authorization(options.headers().authorization() + " " + options.getEncodedCredentials());
        } else if (options.username() != null) {
            //guessing that authentication is basic
            options.headers().authorization("Basic " + options.getEncodedCredentials());
        }

        for (Entry<String, String> entry : options.headers().map().entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }

    if (options.data() != null) {
        try {
            OutputStream os = connection.getOutputStream();
            os.write(options.data().toString().getBytes());
            os.close();
        } catch (Throwable t) {
            Log.w("Ajax", "Could not post data");
        }
    }

    if (options.timeout() != 0) {
        connection.setConnectTimeout(options.timeout());
        connection.setReadTimeout(options.timeout());
    }

    if (options.trustedCertificate() != null) {

        Certificate ca = options.trustedCertificate();

        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = null;
        try {
            keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);
        } catch (KeyStoreException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (CertificateException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (IOException e) {
            if (options.debug())
                e.printStackTrace();
        }

        if (keyStore == null) {
            Log.w("Ajax", "Could not configure trusted certificate");
        } else {
            try {
                //Create a TrustManager that trusts the CAs in our KeyStore
                String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
                tmf.init(keyStore);

                //Create an SSLContext that uses our TrustManager
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, tmf.getTrustManagers(), null);
                ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
            } catch (KeyManagementException e) {
                if (options.debug())
                    e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                if (options.debug())
                    e.printStackTrace();
            } catch (KeyStoreException e) {
                if (options.debug())
                    e.printStackTrace();
            }
        }
    }

    try {

        if (options.cookies() != null) {
            CookieManager cm = new CookieManager();
            CookieStore cookies = cm.getCookieStore();
            URI uri = URI.create(options.url());
            for (Entry<String, String> entry : options.cookies().entrySet()) {
                HttpCookie cookie = new HttpCookie(entry.getKey(), entry.getValue());
                cookies.add(uri, cookie);
            }
            connection.setRequestProperty("Cookie", TextUtils.join(",", cookies.getCookies()));
        }

        connection.connect();
        final int statusCode = connection.getResponseCode();
        final String message = connection.getResponseMessage();

        if (options.dataFilter() != null) {
            if (options.context() != null)
                options.dataFilter().invoke($.with(options.context()), connection, options.dataType());
            else
                options.dataFilter().invoke(null, connection, options.dataType());
        }

        final Function function = options.statusCode().get(statusCode);
        if (function != null) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (options.context() != null)
                        function.invoke($.with(options.context()), statusCode, options.clone());
                    else
                        function.invoke(null, statusCode, options.clone());
                }

            });

        }

        //handle dataType
        String dataType = options.dataType();
        if (dataType == null)
            dataType = "text";
        if (options.debug())
            Log.i("Ajax", "dataType = " + dataType);
        Object parsedResponse = null;
        InputStream stream = null;
        try {
            if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) {
                if (options.debug())
                    Log.i("Ajax", "parsing text");
                stream = AjaxUtil.getInputStream(connection);
                parsedResponse = parseText(stream);
            } else if (dataType.equalsIgnoreCase("xml")) {
                if (options.debug())
                    Log.i("Ajax", "parsing xml");
                if (options.customXMLParser() != null) {
                    stream = AjaxUtil.getInputStream(connection);
                    if (options.SAXContentHandler() != null)
                        options.customXMLParser().parse(stream, options.SAXContentHandler());
                    else
                        options.customXMLParser().parse(stream, new DefaultHandler());
                    parsedResponse = "Response handled by custom SAX parser";
                } else if (options.SAXContentHandler() != null) {
                    stream = AjaxUtil.getInputStream(connection);
                    SAXParserFactory factory = SAXParserFactory.newInstance();

                    factory.setFeature("http://xml.org/sax/features/namespaces", false);
                    factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

                    SAXParser parser = factory.newSAXParser();

                    XMLReader reader = parser.getXMLReader();
                    reader.setContentHandler(options.SAXContentHandler());
                    reader.parse(new InputSource(stream));
                    parsedResponse = "Response handled by custom SAX content handler";
                } else {
                    parsedResponse = parseXML(connection);
                }
            } else if (dataType.equalsIgnoreCase("json")) {
                if (options.debug())
                    Log.i("Ajax", "parsing json");
                parsedResponse = parseJSON(connection);
            } else if (dataType.equalsIgnoreCase("script")) {
                if (options.debug())
                    Log.i("Ajax", "parsing script");
                parsedResponse = parseScript(connection);
            } else if (dataType.equalsIgnoreCase("image")) {
                if (options.debug())
                    Log.i("Ajax", "parsing image");
                stream = AjaxUtil.getInputStream(connection);
                parsedResponse = parseImage(stream);
            } else if (dataType.equalsIgnoreCase("raw")) {
                if (options.debug())
                    Log.i("Ajax", "parsing raw data");
                parsedResponse = parseRawContent(connection);
            }
        } catch (ClientProtocolException cpe) {
            if (options.debug())
                cpe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = statusCode;
            e.reason = message;
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            e.error = error;
            return e;
        } catch (Exception ioe) {
            if (options.debug())
                ioe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = statusCode;
            e.reason = message;
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            e.error = error;
            return e;
        } finally {
            connection.disconnect();
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
            }
        }

        if (statusCode >= 300) {
            //an error occurred
            Error e = new Error(parsedResponse);
            Log.e("Ajax Test", parsedResponse.toString());
            //AjaxError error = new AjaxError();
            //error.request = request;
            //error.options = options;
            e.status = e.status;
            e.reason = e.reason;
            //error.status = e.status;
            //error.reason = e.reason;
            //error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            //e.error = error;
            if (options.debug())
                Log.i("Ajax", "Error " + e.status + ": " + e.reason);
            return e;
        } else {
            //handle ajax ifModified option
            List<String> lastModifiedHeaders = connection.getHeaderFields().get("last-modified");
            if (lastModifiedHeaders.size() >= 1) {
                try {
                    String h = lastModifiedHeaders.get(0);
                    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
                    Date lastModified = format.parse(h);
                    if (options.ifModified() && lastModified != null) {
                        Date lastModifiedDate;
                        synchronized (lastModifiedUrls) {
                            lastModifiedDate = lastModifiedUrls.get(options.url());
                        }

                        if (lastModifiedDate != null && lastModifiedDate.compareTo(lastModified) == 0) {
                            //request response has not been modified. 
                            //Causes an error instead of a success.
                            Error e = new Error(parsedResponse);
                            AjaxError error = new AjaxError();
                            error.connection = connection;
                            error.options = options;
                            e.status = e.status;
                            e.reason = e.reason;
                            error.status = e.status;
                            error.reason = e.reason;
                            error.response = e.response;
                            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
                            e.error = error;
                            Function func = options.statusCode().get(304);
                            if (func != null) {
                                if (options.context() != null)
                                    func.invoke($.with(options.context()));
                                else
                                    func.invoke(null);
                            }
                            return e;
                        } else {
                            synchronized (lastModifiedUrls) {
                                lastModifiedUrls.put(options.url(), lastModified);
                            }
                        }
                    }
                } catch (Throwable t) {
                    Log.e("Ajax", "Could not parse Last-Modified Header", t);
                }

            }

            //Now handle a successful request

            Success s = new Success(parsedResponse);
            s.reason = message;
            s.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            return s;
        }

    } catch (Throwable t) {
        if (options.debug())
            t.printStackTrace();
        if (t instanceof java.net.SocketTimeoutException) {
            Error e = new Error(null);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            error.response = e.response;
            e.status = 0;
            String reason = t.getMessage();
            if (reason == null)
                reason = "Socket Timeout";
            e.reason = reason;
            error.status = e.status;
            error.reason = e.reason;
            if (connection != null)
                e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            else
                e.allHeaders = new Headers();
            e.error = error;
            return e;
        }
        return null;
    }
}

From source file:com.bouncestorage.swiftproxy.v1.ObjectResource.java

private Response conditionalGetSatisified(GetOptions options, String etag, Date mtime) {
    if (options.getIfMatch() != null && !eTagsEqual(etag, options.getIfMatch())) {
        return Response.status(Response.Status.PRECONDITION_FAILED).build();
    }//from   ww  w  . ja  v  a  2s .  c o  m

    if (options.getIfNoneMatch() != null && eTagsEqual(etag, options.getIfNoneMatch())) {
        return Response.notModified().build();
    }

    if (options.getIfModifiedSince() != null && mtime.compareTo(options.getIfModifiedSince()) <= 0) {
        return Response.notModified().build();
    }

    if (options.getIfUnmodifiedSince() != null && mtime.compareTo(options.getIfUnmodifiedSince()) > 0) {
        return Response.status(Response.Status.PRECONDITION_FAILED).build();
    }

    return null;
}

From source file:com.encens.khipus.service.production.RawMaterialPayRollServiceBean.java

private boolean isValidLicence(String license, Date startDate, Date endDate) {
    if (endDate == null)
        return false;
    if (startDate == null)
        return false;
    if (startDate.compareTo(endDate) > 0)
        return false;
    if (StringUtils.isBlank(license))
        return false;
    return true;/*from w  w  w. j av a 2  s . co  m*/
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractProductsController.java

@RequestMapping(value = "/setplandate", method = RequestMethod.POST)
@ResponseBody// w  ww. ja v  a 2s  .  co m
public String setPlanDate(@ModelAttribute("planDateForm") ProductForm form, BindingResult result,
        ModelMap map) {
    logger.debug("### setPlanDate method starting...(POST)");

    Date startDate = form.getStartDate();
    if (channelService.getCurrentRevision(null).getStartDate() == null
            || channelService.getCurrentRevision(null).getStartDate().after(new Date())) {
        if (startDate.compareTo(DateUtils.truncate(DateUtils.minusOneDay(new Date()))) < 0) {
            logger.debug("### Activation not allowed. Plan date should be greater than or equal to today.");
            return "plan_date_should_be_greater_or_equal_to_today";
        }
    } else {
        if (startDate.compareTo(DateUtils.minusOneDay(new Date())) <= 0) {
            logger.debug("### Activation not allowed. Plan date should be greater than today.");
            return "plan_date_should_be_greater_to_today";
        }
    }
    // If we are activating today and there is no product added yet, don't allow activation
    ChannelRevision channelRevision = channelService.getChannelRevision(null,
            channelService.getFutureRevision(null).getStartDate(), false);
    if (startDate.compareTo(DateUtils.truncate(new Date())) == 0
            && channelRevision.getProductRevisions().size() == 0
            && channelRevision.getProductBundleRevisions().size() == 0) {
        logger.debug("### Activation not allowed. No product/product bundle added.");
        return "no_product_added";
    }
    long todayMinTIme = DateUtils.truncate((new Date())).getTime();
    long todayMaxTIme = DateUtils.setMaxTime((new Date())).getTime();

    if (startDate.getTime() >= todayMinTIme && startDate.getTime() <= todayMaxTIme) {
        // current time stamp
        startDate = new Date();
    }
    productService.setReferencePriceBookFutureRevisionDate(startDate);

    logger.debug("### planChargesDate method starting...(POST)");
    return "success";
}

From source file:org.libreplan.web.workreports.WorkReportCRUDController.java

public Constraint checkConstraintStartDate() {
    return (comp, value) -> {
        Date startDate = (Date) value;

        if ((startDate != null) && (filterFinishDate.getValue() != null)
                && (startDate.compareTo(filterFinishDate.getValue()) > 0)) {

            filterStartDate.setValue(null);
            throw new WrongValueException(comp, _("must be before end date"));
        }//from   w  ww . ja v  a2 s  .  co m
    };
}

From source file:org.libreplan.web.workreports.WorkReportCRUDController.java

public Constraint checkConstraintFinishDate() {
    return (comp, value) -> {
        Date finishDate = (Date) value;

        if ((finishDate != null) && (filterStartDate.getValue() != null)
                && (finishDate.compareTo(filterStartDate.getValue()) < 0)) {

            filterFinishDate.setValue(null);
            throw new WrongValueException(comp, _("must be later than start date"));
        }//from www  .j  a  v a2s  . co m
    };
}

From source file:org.openkoala.koala.monitor.service.MonitorDataServiceImpl.java

@Override
public final List<CountVo> getHttpMonitorCount(String nodeId, String statUnit, Date beginTime) {
    List<CountVo> list = new ArrayList<CountVo>();
    String sql = null;/*  w  ww. j a  v  a  2 s.c o m*/
    Date beginDt = KoalaDateUtils.getDayBegin(beginTime);
    Date endDt = null;
    if (Constant.UNIT_HOUR.equals(statUnit)) {
        sql = "select m.HOUR, count(*) from KM_HTTP_DETAILS h left join KM_MAIN_STAT m on h.THREAD_KEY = m.THREAD_KEY and m.FK_NODE_ID=? and (m.BEGIN_TIME between ? and ?) group by m.HOUR order by m.HOUR";
        endDt = KoalaDateUtils.getDayEnd(beginDt);
    } else if (Constant.UNIT_DAY.equals(statUnit)) {
        sql = "select m.DAY, count(*) from KM_HTTP_DETAILS h left join KM_MAIN_STAT m on h.THREAD_KEY = m.THREAD_KEY and m.FK_NODE_ID=? and (m.BEGIN_TIME between ? and ?) group by m.DAY order by m.DAY";
        endDt = KoalaDateUtils.getLastDateOfMonth(beginDt);
    } else {
        throw new RuntimeException("?");
    }

    final Map<Integer, String> tmpMap = new HashMap<Integer, String>();
    Object[] objects = new Object[] { nodeId, beginDt, endDt };
    jdbcTemplate.query(sql, objects, new ResultSetExtractor<Object>() {
        @Override
        public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
            while (rs.next()) {
                if (rs.getObject(1) != null) {
                    tmpMap.put(rs.getInt(1), rs.getObject(2).toString());
                }
            }
            return null;
        }
    });

    int index = Constant.UNIT_HOUR.equals(statUnit) ? 0 : 1;
    for (;;) {
        if (beginDt.compareTo(endDt) > 0)
            break;
        CountVo countVo = new CountVo();
        if (tmpMap.containsKey(index)) {
            countVo.setHttpCount(Integer.parseInt(tmpMap.get(index)));
        } else {
            countVo.setHttpCount(0);
        }
        list.add(countVo);
        if (Constant.UNIT_HOUR.equals(statUnit)) {
            countVo.setDateStr(KoalaDateUtils.format(beginDt, "yyyy-MM-dd HH"));
            beginDt = DateUtils.addHours(beginDt, 1);
        } else if (Constant.UNIT_DAY.equals(statUnit)) {
            countVo.setDateStr(KoalaDateUtils.format(beginDt, "yyyy-MM-dd"));
            beginDt = DateUtils.addDays(beginDt, 1);
        }
        index++;
    }
    return list;
}

From source file:org.libreplan.web.workreports.WorkReportCRUDController.java

public void checkCannotBeHigher(Timebox starting, Timebox ending) {
    starting.clearErrorMessage(true);//from w w w . j  a  va 2  s . c  o m
    ending.clearErrorMessage(true);

    final Date startingDate = starting.getValue();
    final Date endingDate = ending.getValue();

    if (endingDate == null || startingDate == null || startingDate.compareTo(endingDate) > 0) {
        throw new WrongValueException(starting, _("Cannot be higher than finish hour"));
    }
}