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:de.atomfrede.tools.evalutation.util.EntryComparator.java

@Override
public int compare(String[] line, String[] lineToCompare) {
    try {/*from w  ww  . j av  a2s  .  c  o  m*/
        Date lineDate = dateFormat.parse(line[CommonConstants.DATE] + " " + line[CommonConstants.TIME]);
        Date compareDate = dateFormat
                .parse(lineToCompare[CommonConstants.DATE] + " " + lineToCompare[CommonConstants.TIME]);
        return lineDate.compareTo(compareDate);
    } catch (ParseException pe) {
        log.error("Parse Exception in comparator..." + pe);
    }
    return 0;
}

From source file:nl.isaac.dotcms.minify.servlet.MinifyServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Check if the "uris" parameter is valid
    String urisAsString = request.getParameter("uris");
    ParamValidationUtil.validateParamNotNull(urisAsString, "uris");

    // Define variables whos content will be determined during the for loop.
    StringBuilder fileContentOfUris = new StringBuilder();
    boolean isContentModified = false;
    ContentType overAllContentType = null;

    // Retrieve data that is used in the for loop only once for speed
    boolean isDebugMode = UtilMethods.isSet(request.getParameter("debug"));
    boolean isLiveMode = HostTools.isLiveMode(request);
    Date ifModifiedSince = new Date(request.getDateHeader("If-Modified-Since"));
    Host defaultHost = HostTools.getCurrentHost(request);

    try {//from w w w . j a  va  2s . c  o m
        for (String uriAsString : StringListUtil.getCleanStringList(urisAsString)) {

            URI uri = new URI(uriAsString);

            ContentType currentContentType = ContentType.getContentType(uri);
            overAllContentType = overAllContentType == null ? currentContentType : overAllContentType;

            if (currentContentType == overAllContentType) {
                Host host = getHostOfUri(uri, defaultHost);

                if (isDebugMode) {

                    fileContentOfUris.append(getOriginalFile(uri, host, isLiveMode));
                    isContentModified = true;

                } else {
                    MinifyCacheKey key = new MinifyCacheKey(uri.getPath(), host.getHostname(), isLiveMode);

                    MinifyCacheFile file = MinifyCacheHandler.INSTANCE.get(key);
                    fileContentOfUris.append(file.getFileData());

                    Date modDate = file.getModDate();
                    isContentModified |= modDate.compareTo(ifModifiedSince) >= 0;
                }
            } else {
                Logger.warn(MinifyServlet.class,
                        "Encountered uri with different contentType than the others, skipping file. Expected "
                                + overAllContentType.extension + ", found: " + currentContentType.extension);
            }
        }

        response.setContentType(overAllContentType.contentTypeString);

        response.addHeader("Cache-Control", "public, max-age=" + BROWSER_CACHE_MAX_AGE);
        response.setDateHeader("Expires", new Date().getTime() + (BROWSER_CACHE_MAX_AGE * 1000));

        if (isContentModified) {
            response.setDateHeader("Last-Modified", new Date().getTime());
            response.getWriter().write(fileContentOfUris.toString());

        } else {
            // No files are modified since the browser cached it, so send
            // status 304. Browser will then use the file from his cache
            response.setStatus(304);
        }

    } catch (DotCMSFileNotFoundException e) {
        Logger.error(MinifyServlet.class, "One or more files can't be found in dotCMS, sending 404 response",
                e);
        response.sendError(404);

    } catch (URISyntaxException e) {
        Logger.error(MinifyServlet.class, "Cannot parse one or more URIs", e);
        response.sendError(404);

    }
}

From source file:org.remus.marketplace.scheduling.GenerateStatisticsJob.java

private void createClickStatistics(Integer id, File folder, Node node, Calendar instance) {
    Map<Date, Integer> map = new HashMap<Date, Integer>();
    for (int i = 0, n = month; i < n; i++) {
        Calendar instance2 = Calendar.getInstance();
        instance2.setTime(new Date());
        instance2.add(Calendar.MONTH, i * -1);
        map.put(instance2.getTime(), 0);
    }//w  ww  .  ja  v  a 2  s.  co  m
    AdvancedCriteria criteria = new AdvancedCriteria()
            .addRestriction(Restrictions.between(Clickthrough.TIME, instance.getTime(), new Date()))
            .addRestriction(Restrictions.eq(Clickthrough.NODE, node));
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.count(Clickthrough.NODE));

    projectionList
            .add(Projections.sqlGroupProjection("month({alias}.time) as month, year({alias}.time) as year",
                    "month({alias}.time), year({alias}.time)", new String[] { "month", "year" },
                    new Type[] { Hibernate.INTEGER, Hibernate.INTEGER }));
    criteria.setProjection(projectionList);

    List<Object> query = clickthroughDao.query(criteria);
    for (Object object : query) {
        Object[] data = (Object[]) object;
        Integer count = (Integer) data[0];
        Integer month = (Integer) data[1];
        Integer year = (Integer) data[2];
        Set<Date> keySet = map.keySet();
        for (Date date : keySet) {
            Calendar instance2 = Calendar.getInstance();
            instance2.setTime(date);
            if (instance2.get(Calendar.YEAR) == year && instance2.get(Calendar.MONTH) == month - 1) {
                map.put(date, count);
            }
        }

    }

    DefaultCategoryDataset data = new DefaultCategoryDataset();
    List<Date> keySet = new ArrayList<Date>(map.keySet());
    Collections.sort(keySet, new Comparator<Date>() {

        @Override
        public int compare(Date o1, Date o2) {
            return o1.compareTo(o2);
        }
    });
    for (Date date : keySet) {
        Integer integer = map.get(date);
        Calendar instance2 = Calendar.getInstance();
        instance2.setTime(date);
        int year = instance2.get(Calendar.YEAR);
        int month = instance2.get(Calendar.MONTH) + 1;
        data.addValue(integer, "Column1", month + "-" + year);
    }

    JFreeChart createBarChart = ChartFactory.createBarChart("Clicks", "Month", "", data,
            PlotOrientation.VERTICAL, false, false, false);

    File file = new File(folder, "clicks_" + id + ".png");
    if (file.exists()) {
        file.delete();
    }
    try {
        ChartUtilities.saveChartAsPNG(file, createBarChart, 500, 300);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.remus.marketplace.scheduling.GenerateStatisticsJob.java

private void createDownloadStatistics(Integer id, File folder, Node node, Calendar instance) {
    Map<Date, Integer> map = new HashMap<Date, Integer>();
    for (int i = 0, n = month; i < n; i++) {
        Calendar instance2 = Calendar.getInstance();
        instance2.setTime(new Date());
        instance2.add(Calendar.MONTH, i * -1);
        map.put(instance2.getTime(), 0);
    }/* w  w  w.  j  a  v  a  2 s.c o m*/
    AdvancedCriteria criteria = new AdvancedCriteria()
            .addRestriction(Restrictions.between(Download.TIME, instance.getTime(), new Date()))
            .addRestriction(Restrictions.eq(Download.NODE, node));
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.count(Download.NODE));

    projectionList
            .add(Projections.sqlGroupProjection("month({alias}.time) as month, year({alias}.time) as year",
                    "month({alias}.time), year({alias}.time)", new String[] { "month", "year" },
                    new Type[] { Hibernate.INTEGER, Hibernate.INTEGER }));
    criteria.setProjection(projectionList);

    List<Object> query = downloadDao.query(criteria);
    for (Object object : query) {
        Object[] data = (Object[]) object;
        Integer count = (Integer) data[0];
        Integer month = (Integer) data[1];
        Integer year = (Integer) data[2];
        Set<Date> keySet = map.keySet();
        for (Date date : keySet) {
            Calendar instance2 = Calendar.getInstance();
            instance2.setTime(date);
            if (instance2.get(Calendar.YEAR) == year && instance2.get(Calendar.MONTH) == month - 1) {
                map.put(date, count);
            }
        }

    }

    DefaultCategoryDataset data = new DefaultCategoryDataset();
    List<Date> keySet = new ArrayList<Date>(map.keySet());
    Collections.sort(keySet, new Comparator<Date>() {

        @Override
        public int compare(Date o1, Date o2) {
            return o1.compareTo(o2);
        }
    });
    for (Date date : keySet) {
        Integer integer = map.get(date);
        Calendar instance2 = Calendar.getInstance();
        instance2.setTime(date);
        int year = instance2.get(Calendar.YEAR);
        int month = instance2.get(Calendar.MONTH) + 1;
        data.addValue(integer, "Column1", month + "-" + year);
    }

    JFreeChart createBarChart = ChartFactory.createBarChart("Downloads", "Month", "", data,
            PlotOrientation.VERTICAL, false, false, false);

    File file = new File(folder, "download_" + id + ".png");
    if (file.exists()) {
        file.delete();
    }
    try {
        ChartUtilities.saveChartAsPNG(file, createBarChart, 500, 300);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.libreplan.web.orders.OrderElementPredicate.java

private boolean isGreaterToStartDate(Date date, Date startDate) {
    if (startDate == null) {
        return true;
    }/*from  w w  w. j  a v  a2  s.  c  o m*/

    if (date != null && (date.compareTo(startDate) >= 0)) {
        return true;
    }
    return false;
}

From source file:org.libreplan.web.orders.OrderElementPredicate.java

private boolean isLowerToFinishDate(Date date, Date finishDate) {
    if (finishDate == null) {
        return true;
    }//from w  ww.j a v  a 2  s . c om
    if (date != null && (date.compareTo(finishDate) <= 0)) {
        return true;
    }
    return false;
}

From source file:org.openmrs.module.laboratory.web.controller.confidentialtest.AddConfidentialTest.java

private boolean validateDate(String dateStr) throws ParseException {
    Date date = LaboratoryUtil.parseDate(dateStr);
    Date now = new Date();
    Date currentDate = LaboratoryUtil.parseDate(LaboratoryUtil.formatDate(now));
    return date.compareTo(currentDate) >= 0;
}

From source file:it.govpay.model.comparator.EstrattoContoComparator.java

@Override
public int compare(EstrattoConto o1, EstrattoConto o2) {
    //  cod_flusso_rendicontazione, iuv, data_pagamento
    String codFlussoRendicontazione1 = o1.getCodFlussoRendicontazione() != null
            ? o1.getCodFlussoRendicontazione()
            : "";
    String codFlussoRendicontazione2 = o2.getCodFlussoRendicontazione() != null
            ? o2.getCodFlussoRendicontazione()
            : "";

    if (StringUtils.equals(codFlussoRendicontazione1, codFlussoRendicontazione2)) {
        String iuv1 = o1.getIuv() != null ? o1.getIuv() : "";
        String iuv2 = o2.getIuv() != null ? o2.getIuv() : "";

        if (StringUtils.equals(iuv1, iuv2)) {
            Date dataPagamento1 = o1.getDataPagamento();

            if (dataPagamento1 == null)
                return -1;

            Date dataPagamento2 = o2.getDataPagamento();

            if (dataPagamento2 == null)
                return -1;

            dataPagamento1.compareTo(dataPagamento2);
        }/*from ww  w. jav  a2s. c o  m*/

        return iuv1.compareTo(iuv2);
    }

    return codFlussoRendicontazione1.compareTo(codFlussoRendicontazione2);
}

From source file:com.epam.ipodromproject.service.CompetitionService.java

@Transactional
public boolean addCompetition(Date dateOfCompetition, Horse[] horsesToAdd, String[] horseCoefs) {
    if ((dateOfCompetition == null) || (horsesToAdd.length != horseCoefs.length)
            || (dateOfCompetition.compareTo(new Date()) <= 0)) {
        return false;
    }/*  w ww .jav a2  s .com*/

    Map<Horse, HorseInfo> horses = new HashMap<>();
    for (int i = 0; i < horseCoefs.length; i++) {
        HorseInfo horseInfo = null;
        try {
            horseInfo = new HorseInfo(Double.valueOf(horseCoefs[i]));
        } catch (NumberFormatException e) {
        }
        if ((horseInfo != null) && (horsesToAdd[i] != null) && (horseInfo.getCoefficient() >= 1)) {
            if (horses.keySet().contains(horsesToAdd[i])) {
                return false;
            }
            horses.put(horsesToAdd[i], horseInfo);
        }
    }
    if (horses.size() <= 1) {
        return false;
    } else {
        Competition competition = new Competition();
        competition.setState(CompetitionState.NOT_REGISTERED);
        competition.setDateOfStart(dateOfCompetition);
        competition.setHorses(horses);
        competitionRepository.save(competition);
        return true;
    }
}

From source file:com.wifi.brainbreaker.mydemo.http.ModAssetServer.java

public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {
    AbstractHttpEntity body = null;//from w  w  w.j  a va  2 s . co  m

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }

    final String url = URLDecoder.decode(request.getRequestLine().getUri());
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        byte[] entityContent = EntityUtils.toByteArray(entity);
        Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length);
    }

    final String location = "www" + (url.equals("/") ? "/index.htm" : url);
    response.setStatusCode(HttpStatus.SC_OK);

    try {
        Log.i(TAG, "Requested: \"" + url + "\"");

        // Compares the Last-Modified date header (if present) with the If-Modified-Since date
        if (request.containsHeader("If-Modified-Since")) {
            try {
                Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue());
                if (date.compareTo(mServer.mLastModified) <= 0) {
                    // The file has not been modified
                    response.setStatusCode(HttpStatus.SC_NOT_MODIFIED);
                    return;
                }
            } catch (DateParseException e) {
                e.printStackTrace();
            }
        }

        // We determine if the asset is compressed
        try {
            AssetFileDescriptor afd = mAssetManager.openFd(location);

            // The asset is not compressed
            FileInputStream fis = new FileInputStream(afd.getFileDescriptor());
            fis.skip(afd.getStartOffset());
            body = new InputStreamEntity(fis, afd.getDeclaredLength());

            Log.d(TAG, "Serving uncompressed file " + "www" + url);

        } catch (FileNotFoundException e) {

            // The asset may be compressed
            // AAPT compresses assets so first we need to uncompress them to determine their length
            InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000);
            byte[] tmp = new byte[4096];
            int length = 0;
            while ((length = stream.read(tmp)) != -1)
                buffer.write(tmp, 0, length);
            body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size());
            stream.close();

            Log.d(TAG, "Serving compressed file " + "www" + url);

        }

        body.setContentType(getMimeMediaType(url) + "; charset=UTF-8");
        response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified));

    } catch (IOException e) {
        // File does not exist
        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
        body = new EntityTemplate(new ContentProducer() {
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write("<html><body><h1>");
                writer.write("File ");
                writer.write("www" + url);
                writer.write(" not found");
                writer.write("</h1></body></html>");
                writer.flush();
            }
        });
        Log.d(TAG, "File " + "www" + url + " not found");
        body.setContentType("text/html; charset=UTF-8");
    }

    response.setEntity(body);

}