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:onl.netfishers.netshot.RestService.java

/**
 * Gets the device last 20 tasks./*from w  ww .j  a va 2 s .c om*/
 *
 * @param request the request
 * @param id the id
 * @return the device tasks
 * @throws WebApplicationException the web application exception
 */
@SuppressWarnings("unchecked")
@GET
@Path("devices/{id}/tasks")
@RolesAllowed("readonly")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Task> getDeviceTasks(@PathParam("id") Long id) throws WebApplicationException {
    logger.debug("REST request, get device {} tasks.", id);
    Session session = Database.getSession();
    try {
        final int max = 20;
        final Class<?>[] taskTypes = new Class<?>[] { CheckComplianceTask.class, DiscoverDeviceTypeTask.class,
                TakeSnapshotTask.class, RunDeviceScriptTask.class };
        final Criterion[] restrictions = new Criterion[] { Restrictions.eq("t.device.id", id),
                Restrictions.eq("t.deviceId", id), Restrictions.eq("t.device.id", id),
                Restrictions.eq("t.device.id", id) };
        List<Task> tasks = new ArrayList<Task>();
        for (int i = 0; i < taskTypes.length; i++) {
            List<Task> typeTasks = session.createCriteria(taskTypes[i], "t").add(restrictions[i]).list();
            tasks.addAll(typeTasks);
        }
        Collections.sort(tasks, new Comparator<Task>() {
            private int getPriority(Task.Status status) {
                switch (status) {
                case RUNNING:
                    return 1;
                case WAITING:
                    return 2;
                case SCHEDULED:
                    return 3;
                case NEW:
                    return 4;
                default:
                    return 10;
                }
            }

            private Date getSignificantDate(Task t) {
                if (t.getExecutionDate() == null) {
                    return t.getChangeDate();
                } else {
                    return t.getExecutionDate();
                }
            }

            @Override
            public int compare(Task o1, Task o2) {
                int statusDiff = Integer.compare(this.getPriority(o1.getStatus()),
                        this.getPriority(o2.getStatus()));
                if (statusDiff == 0) {
                    Date d1 = this.getSignificantDate(o1);
                    Date d2 = this.getSignificantDate(o2);
                    if (d1 == null) {
                        if (d2 == null) {
                            return 0;
                        } else {
                            return -1;
                        }
                    } else {
                        if (d2 == null) {
                            return 1;
                        } else {
                            return d2.compareTo(d1);
                        }
                    }
                }
                return statusDiff;
            }
        });
        return tasks.subList(0, (max > tasks.size() ? tasks.size() : max));
    } catch (Exception e) {
        logger.error("Unable to fetch the tasks.", e);
        throw new NetshotBadRequestException("Unable to fetch the tasks",
                NetshotBadRequestException.NETSHOT_DATABASE_ACCESS_ERROR);
    } finally {
        session.close();
    }
}

From source file:com.openbravo.pos.sales.JRetailPanelTakeAway.java

private void m_jSettleBillActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jSettleBillActionPerformed
    logger.info("m_jSettleBillActionPerformed");
    logger.info(//from  w  ww .  j a  va 2 s.c o  m
            "Start Settle Bill Button :" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(new Date()));
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date sysDate = new Date();
    m_RootApp = (JRootApp) m_App;
    String closeTime = m_App.getProperties().getProperty("machine.closetime");
    String currentDate = format.format(sysDate).toString() + " " + closeTime;
    String closeDayDate = sdf.format(m_RootApp.getActiveDayDateStart());
    Date closeDate = null;
    Date activeDayDate = null;
    try {
        closeDate = sdf.parse(currentDate);
        activeDayDate = sdf.parse(closeDayDate);
    } catch (ParseException ex) {
        Logger.getLogger(JRetailPanelTakeAway.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (closeDate.compareTo(activeDayDate) >= 0) {
        m_RootApp.closeDay();
        m_oTicket.setActiveCash(m_App.getActiveCashIndex());
        m_oTicket.setActiveDay(m_App.getActiveDayIndex());
        m_oTicket.setDate(new Date()); // Set the edition date.
        String accDate = new SimpleDateFormat("yyyy-MM-dd").format(m_App.getActiveDayDateStart());
        Date dateValue = java.sql.Date.valueOf(accDate);
        m_oTicket.setAccountDate(dateValue);
    }
    if (m_oTicket.getLinesCount() == 0) {
        return;
    }
    printBill();
    JPaymentEditor.showMessage(JRetailPanelTakeAway.this, dlReceipts, m_oTicket, this, "TakeAway");
    //  logger.info("settled successfully");
    logger.info("End Settle Bill Button :" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(new Date()));
}

From source file:org.alfresco.repo.search.impl.lucene.ADMLuceneTest.java

/**
 * @throws Exception/*from  ww  w.  j  a v a2s  .  com*/
 */
public void testSort() throws Exception {
    Collator collator = Collator.getInstance(I18NUtil.getLocale());

    luceneFTS.pause();
    buildBaseIndex();
    runBaseTests();

    ADMLuceneSearcherImpl searcher = buildSearcher();

    SearchParameters sp = new SearchParameters();
    sp.addStore(rootNodeRef.getStoreRef());
    sp.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp.setQuery("PATH:\"//.\"");
    sp.addSort("ID", true);
    ResultSet results = searcher.query(sp);

    String current = null;
    for (ResultSetRow row : results) {
        String id = row.getNodeRef().getId();

        if (current != null) {
            if (collator.compare(current, id) > 0) {
                fail();
            }
        }
        current = id;
    }
    results.close();

    SearchParameters sp2 = new SearchParameters();
    sp2.addStore(rootNodeRef.getStoreRef());
    sp2.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp2.setQuery("PATH:\"//.\"");
    sp2.addSort("ID", false);
    results = searcher.query(sp2);

    current = null;
    for (ResultSetRow row : results) {
        String id = row.getNodeRef().getId();
        if (current != null) {
            if (collator.compare(current, id) < 0) {
                fail();
            }
        }
        current = id;
    }
    results.close();

    luceneFTS.resume();

    SearchParameters sp3 = new SearchParameters();
    sp3.addStore(rootNodeRef.getStoreRef());
    sp3.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp3.setQuery("PATH:\"//.\"");
    sp3.addSort(SearchParameters.SORT_IN_DOCUMENT_ORDER_ASCENDING);
    results = searcher.query(sp3);

    int count = 0;
    for (ResultSetRow row : results) {
        assertEquals(documentOrder[count++], row.getNodeRef());
    }
    results.close();

    SearchParameters sp4 = new SearchParameters();
    sp4.addStore(rootNodeRef.getStoreRef());
    sp4.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp4.setQuery("PATH:\"//.\"");
    sp4.addSort(SearchParameters.SORT_IN_DOCUMENT_ORDER_DESCENDING);
    results = searcher.query(sp4);

    count = 1;
    for (ResultSetRow row : results) {
        assertEquals(documentOrder[documentOrder.length - (count++)], row.getNodeRef());
    }
    results.close();

    SearchParameters sp5 = new SearchParameters();
    sp5.addStore(rootNodeRef.getStoreRef());
    sp5.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp5.setQuery("PATH:\"//.\"");
    sp5.addSort(SearchParameters.SORT_IN_SCORE_ORDER_ASCENDING);
    results = searcher.query(sp5);

    float score = 0;
    for (ResultSetRow row : results) {
        assertTrue(score <= row.getScore());
        score = row.getScore();
    }
    results.close();

    SearchParameters sp6 = new SearchParameters();
    sp6.addStore(rootNodeRef.getStoreRef());
    sp6.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp6.setQuery("PATH:\"//.\"");
    sp6.addSort(SearchParameters.SORT_IN_SCORE_ORDER_DESCENDING);
    results = searcher.query(sp6);

    score = 1.0f;
    for (ResultSetRow row : results) {
        assertTrue(score >= row.getScore());
        score = row.getScore();
    }
    results.close();

    // sort by created date

    SearchParameters sp7 = new SearchParameters();
    sp7.addStore(rootNodeRef.getStoreRef());
    sp7.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp7.setQuery("PATH:\"//.\"");
    sp7.addSort("@" + createdDate.getPrefixedQName(namespacePrefixResolver), true);
    results = searcher.query(sp7);

    Date date = null;
    for (ResultSetRow row : results) {
        Date currentBun = DefaultTypeConverter.INSTANCE.convert(Date.class,
                nodeService.getProperty(row.getNodeRef(), createdDate));
        // System.out.println(currentBun);
        if (date != null) {
            assertTrue(date.compareTo(currentBun) <= 0);
        }
        date = currentBun;
    }
    results.close();

    SearchParameters sp8 = new SearchParameters();
    sp8.addStore(rootNodeRef.getStoreRef());
    sp8.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp8.setQuery("PATH:\"//.\"");
    sp8.addSort("@" + createdDate, false);
    results = searcher.query(sp8);

    date = null;
    for (ResultSetRow row : results) {
        Date currentBun = DefaultTypeConverter.INSTANCE.convert(Date.class,
                nodeService.getProperty(row.getNodeRef(), createdDate));
        // System.out.println(currentBun);
        if ((date != null) && (currentBun != null)) {
            assertTrue(date.compareTo(currentBun) >= 0);
        }
        date = currentBun;
    }
    results.close();

    SearchParameters sp_7 = new SearchParameters();
    sp_7.addStore(rootNodeRef.getStoreRef());
    sp_7.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp_7.setQuery("PATH:\"//.\"");
    sp_7.addSort("@" + ContentModel.PROP_MODIFIED, true);
    results = searcher.query(sp_7);

    date = null;
    for (ResultSetRow row : results) {
        Date currentBun = DefaultTypeConverter.INSTANCE.convert(Date.class,
                nodeService.getProperty(row.getNodeRef(), ContentModel.PROP_MODIFIED));
        if (currentBun != null) {
            Calendar c = new GregorianCalendar();
            c.setTime(currentBun);
            c.set(Calendar.MILLISECOND, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.HOUR_OF_DAY, 0);
            currentBun = c.getTime();
        }
        if ((date != null) && (currentBun != null)) {
            assertTrue(date.compareTo(currentBun) <= 0);
        }
        date = currentBun;
    }
    results.close();

    SearchParameters sp_8 = new SearchParameters();
    sp_8.addStore(rootNodeRef.getStoreRef());
    sp_8.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp_8.setQuery("PATH:\"//.\"");
    sp_8.addSort("@" + ContentModel.PROP_MODIFIED, false);
    results = searcher.query(sp_8);

    date = null;
    for (ResultSetRow row : results) {
        Date currentBun = DefaultTypeConverter.INSTANCE.convert(Date.class,
                nodeService.getProperty(row.getNodeRef(), ContentModel.PROP_MODIFIED));
        // System.out.println(currentBun);
        if (currentBun != null) {
            Calendar c = new GregorianCalendar();
            c.setTime(currentBun);
            c.set(Calendar.MILLISECOND, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.HOUR_OF_DAY, 0);
            currentBun = c.getTime();
        }

        if ((date != null) && (currentBun != null)) {
            assertTrue(date.compareTo(currentBun) >= 0);
        }
        date = currentBun;
    }
    results.close();

    // sort by double

    SearchParameters sp9 = new SearchParameters();
    sp9.addStore(rootNodeRef.getStoreRef());
    sp9.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp9.setQuery("PATH:\"//.\"");
    sp9.addSort("@" + orderDouble, true);
    results = searcher.query(sp9);

    Double d = null;
    for (ResultSetRow row : results) {
        Double currentBun = DefaultTypeConverter.INSTANCE.convert(Double.class,
                nodeService.getProperty(row.getNodeRef(), orderDouble));
        // System.out.println( (currentBun == null ? "null" : NumericEncoder.encode(currentBun))+ " "+currentBun);
        if (d != null) {
            assertTrue(d.compareTo(currentBun) <= 0);
        }
        d = currentBun;
    }
    results.close();

    SearchParameters sp10 = new SearchParameters();
    sp10.addStore(rootNodeRef.getStoreRef());
    sp10.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp10.setQuery("PATH:\"//.\"");
    sp10.addSort("@" + orderDouble, false);
    results = searcher.query(sp10);

    d = null;
    for (ResultSetRow row : results) {
        Double currentBun = DefaultTypeConverter.INSTANCE.convert(Double.class,
                nodeService.getProperty(row.getNodeRef(), orderDouble));
        // System.out.println(currentBun);
        if ((d != null) && (currentBun != null)) {
            assertTrue(d.compareTo(currentBun) >= 0);
        }
        d = currentBun;
    }
    results.close();

    // sort by float

    SearchParameters sp11 = new SearchParameters();
    sp11.addStore(rootNodeRef.getStoreRef());
    sp11.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp11.setQuery("PATH:\"//.\"");
    sp11.addSort("@" + orderFloat, true);
    results = searcher.query(sp11);

    Float f = null;
    for (ResultSetRow row : results) {
        Float currentBun = DefaultTypeConverter.INSTANCE.convert(Float.class,
                nodeService.getProperty(row.getNodeRef(), orderFloat));
        // System.out.println( (currentBun == null ? "null" : NumericEncoder.encode(currentBun))+ " "+currentBun);
        if (f != null) {
            assertTrue(f.compareTo(currentBun) <= 0);
        }
        f = currentBun;
    }
    results.close();

    SearchParameters sp12 = new SearchParameters();
    sp12.addStore(rootNodeRef.getStoreRef());
    sp12.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp12.setQuery("PATH:\"//.\"");
    sp12.addSort("@" + orderFloat, false);
    results = searcher.query(sp12);

    f = null;
    for (ResultSetRow row : results) {
        Float currentBun = DefaultTypeConverter.INSTANCE.convert(Float.class,
                nodeService.getProperty(row.getNodeRef(), orderFloat));
        // System.out.println(currentBun);
        if ((f != null) && (currentBun != null)) {
            assertTrue(f.compareTo(currentBun) >= 0);
        }
        f = currentBun;
    }
    results.close();

    // sort by long

    SearchParameters sp13 = new SearchParameters();
    sp13.addStore(rootNodeRef.getStoreRef());
    sp13.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp13.setQuery("PATH:\"//.\"");
    sp13.addSort("@" + orderLong, true);
    results = searcher.query(sp13);

    Long l = null;
    for (ResultSetRow row : results) {
        Long currentBun = DefaultTypeConverter.INSTANCE.convert(Long.class,
                nodeService.getProperty(row.getNodeRef(), orderLong));
        // System.out.println( (currentBun == null ? "null" : NumericEncoder.encode(currentBun))+ " "+currentBun);
        if (l != null) {
            assertTrue(l.compareTo(currentBun) <= 0);
        }
        l = currentBun;
    }
    results.close();

    SearchParameters sp14 = new SearchParameters();
    sp14.addStore(rootNodeRef.getStoreRef());
    sp14.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp14.setQuery("PATH:\"//.\"");
    sp14.addSort("@" + orderLong, false);
    results = searcher.query(sp14);

    l = null;
    for (ResultSetRow row : results) {
        Long currentBun = DefaultTypeConverter.INSTANCE.convert(Long.class,
                nodeService.getProperty(row.getNodeRef(), orderLong));
        // System.out.println(currentBun);
        if ((l != null) && (currentBun != null)) {
            assertTrue(l.compareTo(currentBun) >= 0);
        }
        l = currentBun;
    }
    results.close();

    // sort by int

    SearchParameters sp15 = new SearchParameters();
    sp15.addStore(rootNodeRef.getStoreRef());
    sp15.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp15.setQuery("PATH:\"//.\"");
    sp15.addSort("@" + orderInt, true);
    results = searcher.query(sp15);

    Integer i = null;
    for (ResultSetRow row : results) {
        Integer currentBun = DefaultTypeConverter.INSTANCE.convert(Integer.class,
                nodeService.getProperty(row.getNodeRef(), orderInt));
        // System.out.println( (currentBun == null ? "null" : NumericEncoder.encode(currentBun))+ " "+currentBun);
        if (i != null) {
            assertTrue(i.compareTo(currentBun) <= 0);
        }
        i = currentBun;
    }
    results.close();

    SearchParameters sp16 = new SearchParameters();
    sp16.addStore(rootNodeRef.getStoreRef());
    sp16.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp16.setQuery("PATH:\"//.\"");
    sp16.addSort("@" + orderInt, false);
    results = searcher.query(sp16);

    i = null;
    for (ResultSetRow row : results) {
        Integer currentBun = DefaultTypeConverter.INSTANCE.convert(Integer.class,
                nodeService.getProperty(row.getNodeRef(), orderInt));
        // System.out.println(currentBun);
        if ((i != null) && (currentBun != null)) {
            assertTrue(i.compareTo(currentBun) >= 0);
        }
        i = currentBun;
    }
    results.close();

    // sort by text

    SearchParameters sp17 = new SearchParameters();
    sp17.addStore(rootNodeRef.getStoreRef());
    sp17.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp17.setQuery("PATH:\"//.\"");
    sp17.addSort("@" + orderText, true);
    results = searcher.query(sp17);

    String text = null;
    for (ResultSetRow row : results) {
        String currentBun = DefaultTypeConverter.INSTANCE.convert(String.class,
                nodeService.getProperty(row.getNodeRef(), orderText));
        // System.out.println( (currentBun == null ? "null" : NumericEncoder.encode(currentBun))+ " "+currentBun);
        if ((text != null) && (currentBun != null)) {
            assertTrue(collator.compare(text, currentBun) <= 0);
        }
        text = currentBun;
    }
    results.close();

    SearchParameters sp18 = new SearchParameters();
    sp18.addStore(rootNodeRef.getStoreRef());
    sp18.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp18.setQuery("PATH:\"//.\"");
    sp18.addSort("@" + orderText, false);
    results = searcher.query(sp18);

    text = null;
    for (ResultSetRow row : results) {
        String currentBun = DefaultTypeConverter.INSTANCE.convert(String.class,
                nodeService.getProperty(row.getNodeRef(), orderText));
        // System.out.println(currentBun);
        if ((text != null) && (currentBun != null)) {
            assertTrue(collator.compare(text, currentBun) >= 0);
        }
        text = currentBun;
    }
    results.close();

    // sort by content size

    // sort by ML text

    // Locale[] testLocales = new Locale[] { I18NUtil.getLocale(), Locale.ENGLISH, Locale.FRENCH, Locale.CHINESE };
    Locale[] testLocales = new Locale[] { I18NUtil.getLocale(), Locale.ENGLISH, Locale.FRENCH };
    for (Locale testLocale : testLocales) {
        Collator localisedCollator = Collator.getInstance(testLocale);

        SearchParameters sp19 = new SearchParameters();
        sp19.addStore(rootNodeRef.getStoreRef());
        sp19.setLanguage(SearchService.LANGUAGE_LUCENE);
        sp19.setQuery("PATH:\"//.\"");
        sp19.addSort("@" + orderMLText, true);
        sp19.addLocale(testLocale);
        results = searcher.query(sp19);

        text = null;
        for (ResultSetRow row : results) {
            MLText mltext = DefaultTypeConverter.INSTANCE.convert(MLText.class,
                    nodeService.getProperty(row.getNodeRef(), orderMLText));
            if (mltext != null) {
                String currentBun = mltext.getValue(testLocale);
                // System.out.println( (currentBun == null ? "null" : NumericEncoder.encode(currentBun))+ "
                // "+currentBun);
                if ((text != null) && (currentBun != null)) {
                    assertTrue(localisedCollator.compare(text, currentBun) <= 0);
                }
                text = currentBun;
            }
        }
        results.close();

        SearchParameters sp20 = new SearchParameters();
        sp20.addStore(rootNodeRef.getStoreRef());
        sp20.setLanguage(SearchService.LANGUAGE_LUCENE);
        sp20.setQuery("PATH:\"//.\"");
        sp20.addSort("@" + orderMLText, false);
        sp20.addLocale(testLocale);
        results = searcher.query(sp20);

        text = null;
        for (ResultSetRow row : results) {
            MLText mltext = DefaultTypeConverter.INSTANCE.convert(MLText.class,
                    nodeService.getProperty(row.getNodeRef(), orderMLText));
            if (mltext != null) {
                String currentBun = mltext.getValue(testLocale);
                if ((text != null) && (currentBun != null)) {
                    assertTrue(localisedCollator.compare(text, currentBun) >= 0);
                }
                text = currentBun;
            }
        }
        results.close();

    }

    luceneFTS.resume();

    SearchParameters spN = new SearchParameters();
    spN.addStore(rootNodeRef.getStoreRef());
    spN.setLanguage(SearchService.LANGUAGE_LUCENE);
    spN.setQuery("PATH:\"//.\"");
    spN.addSort("cabbage", false);
    results = searcher.query(spN);
    results.close();

    // test sort on unkown properties ALF-4193

    spN = new SearchParameters();
    spN.addStore(rootNodeRef.getStoreRef());
    spN.setLanguage(SearchService.LANGUAGE_LUCENE);
    spN.setQuery("PATH:\"//.\"");
    spN.addSort("PARENT", false);
    results = searcher.query(spN);
    results.close();

    spN = new SearchParameters();
    spN.addStore(rootNodeRef.getStoreRef());
    spN.setLanguage(SearchService.LANGUAGE_LUCENE);
    spN.setQuery("PATH:\"//.\"");
    spN.addSort("@PARENT:PARENT", false);
    results = searcher.query(spN);
    results.close();

    luceneFTS.resume();

    // sort by content size

    SearchParameters sp20 = new SearchParameters();
    sp20.addStore(rootNodeRef.getStoreRef());
    sp20.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp20.setQuery("PATH:\"//.\"");
    sp20.addSort("@" + ContentModel.PROP_CONTENT + ".size", false);
    results = searcher.query(sp20);

    Long size = null;
    for (ResultSetRow row : results) {
        ContentData currentBun = DefaultTypeConverter.INSTANCE.convert(ContentData.class,
                nodeService.getProperty(row.getNodeRef(), ContentModel.PROP_CONTENT));
        // System.out.println(currentBun);
        if ((size != null) && (currentBun != null)) {
            assertTrue(size.compareTo(currentBun.getSize()) >= 0);
        }
        if (currentBun != null) {
            size = currentBun.getSize();
        }
    }
    results.close();

    // sort by content mimetype

    SearchParameters sp21 = new SearchParameters();
    sp21.addStore(rootNodeRef.getStoreRef());
    sp21.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp21.setQuery("PATH:\"//.\"");
    sp21.addSort("@" + ContentModel.PROP_CONTENT + ".mimetype", false);
    results = searcher.query(sp21);

    String mimetype = null;
    for (ResultSetRow row : results) {
        ContentData currentBun = DefaultTypeConverter.INSTANCE.convert(ContentData.class,
                nodeService.getProperty(row.getNodeRef(), ContentModel.PROP_CONTENT));
        // System.out.println(currentBun);
        if ((mimetype != null) && (currentBun != null)) {
            assertTrue(mimetype.compareTo(currentBun.getMimetype()) >= 0);
        }
        if (currentBun != null) {
            mimetype = currentBun.getMimetype();
        }
    }
    results.close();

}

From source file:org.openmrs.logic.db.hibernate.HibernateLogicObsDAO.java

public Criterion getCriterion(LogicExpression logicExpression, Date indexDate, Criteria criteria) {
    Operator operator = logicExpression.getOperator();
    Operand rightOperand = logicExpression.getRightOperand();
    Operand leftOperand = null;//  ww  w .  ja va 2  s  .c  o m
    if (logicExpression instanceof LogicExpressionBinary) {
        leftOperand = ((LogicExpressionBinary) logicExpression).getLeftOperand();
    }
    List<Criterion> criterion = new ArrayList<Criterion>();

    //the root token can be a concept name for the obs datasource
    String rootToken = logicExpression.getRootToken();

    Concept concept = getConceptForToken(rootToken);
    if (concept != null) {
        criterion.add(Restrictions.eq("concept", concept));
    } else {
        if (rootToken != null && (rootToken.equalsIgnoreCase(COMPONENT_ENCOUNTER_ID)
                || rootToken.equalsIgnoreCase(COMPONENT_OBS_DATETIME))) {
            //this is a component not a concept so it is fine
        } else {
            throw new LogicException("Concept: " + rootToken + " does not exist");
        }
    }

    if (operator == Operator.BEFORE) {
        criterion.add(Restrictions.lt("obsDatetime", rightOperand));

    } else if (operator == Operator.AFTER) {
        criterion.add(Restrictions.gt("obsDatetime", rightOperand));

    } else if (operator == Operator.AND || operator == Operator.OR) {

        Criterion leftCriteria = null;
        Criterion rightCriteria = null;

        if (leftOperand instanceof LogicExpression) {
            leftCriteria = this.getCriterion((LogicExpression) leftOperand, indexDate, criteria);
        }
        if (rightOperand instanceof LogicExpression) {
            rightCriteria = this.getCriterion((LogicExpression) rightOperand, indexDate, criteria);
        }

        if (leftCriteria != null && rightCriteria != null) {
            if (operator == Operator.AND) {
                criterion.add(Restrictions.and(leftCriteria, rightCriteria));
            }
            if (operator == Operator.OR) {
                criterion.add(Restrictions.or(leftCriteria, rightCriteria));
            }
        }
    } else if (operator == Operator.NOT) {

        Criterion rightCriteria = null;

        if (rightOperand instanceof LogicExpression) {
            rightCriteria = this.getCriterion((LogicExpression) rightOperand, indexDate, criteria);
        }

        if (rightCriteria != null) {
            criterion.add(Restrictions.not(rightCriteria));
        }

    } else if (operator == Operator.CONTAINS) {
        // used with PROBLEM ADDED concept, to retrieve the "ANSWERED
        // BY" concept, stashed inside the concept's valueCoded member
        // variable. for example:
        // new LogicCriteria("PROBLEM ADDED").contains("HIV INFECTED");
        if (rightOperand instanceof OperandNumeric) {
            concept = Context.getConceptService().getConcept(((OperandNumeric) rightOperand).asInteger());
            criterion.add(Restrictions.eq("valueCoded", concept));
        } else if (rightOperand instanceof OperandText) {
            concept = Context.getConceptService().getConcept((String) ((OperandText) rightOperand).asString());
            criterion.add(Restrictions.eq("valueCoded", concept));

        } else if (rightOperand instanceof OperandConcept) {
            criterion.add(Restrictions.eq("valueCoded", ((OperandConcept) rightOperand).asConcept()));

        } else
            log.error("Invalid operand value for CONTAINS operation");
    } else if (operator == Operator.IN) {
        log.error("Invalid operand value for IN operation");
    } else if (operator == Operator.EQUALS) {
        if (rightOperand instanceof OperandNumeric) {
            if (rootToken.equalsIgnoreCase(COMPONENT_ENCOUNTER_ID)) {
                EncounterService encounterService = Context.getEncounterService();
                Encounter encounter = encounterService
                        .getEncounter(((OperandNumeric) rightOperand).asInteger());
                criterion.add(Restrictions.eq("encounter", encounter));
            } else
                criterion.add(Restrictions.eq("valueNumeric", ((OperandNumeric) rightOperand).asDouble()));
        } else if (rightOperand instanceof OperandText)
            criterion.add(Restrictions.eq("valueText", ((OperandText) rightOperand).asString()));
        else if (rightOperand instanceof OperandDate)
            if (leftOperand instanceof OperandText
                    && ((OperandText) leftOperand).asString().equals(COMPONENT_OBS_DATETIME)) {
                criterion.add(Restrictions.eq(COMPONENT_OBS_DATETIME, rightOperand));
            } else {
                criterion.add(Restrictions.eq("valueDatetime", rightOperand));
            }
        else if (rightOperand instanceof OperandConcept)
            criterion.add(Restrictions.eq("valueCoded", ((OperandConcept) rightOperand).asConcept()));
        else
            log.error("Invalid operand value for EQUALS operation");

    } else if (operator == Operator.LTE) {
        if (rightOperand instanceof OperandNumeric)
            criterion.add(Restrictions.le("valueNumeric", ((OperandNumeric) rightOperand).asDouble()));
        else if (rightOperand instanceof OperandDate)
            if (leftOperand instanceof OperandText
                    && ((OperandText) leftOperand).asString().equals(COMPONENT_OBS_DATETIME)) {
                criterion.add(Restrictions.le(COMPONENT_OBS_DATETIME, rightOperand));
            } else {
                criterion.add(Restrictions.le("valueDatetime", rightOperand));
            }
        else
            log.error("Invalid operand value for LESS THAN EQUAL operation");

    } else if (operator == Operator.GTE) {
        if (rightOperand instanceof OperandNumeric)
            criterion.add(Restrictions.ge("valueNumeric", ((OperandNumeric) rightOperand).asDouble()));
        else if (rightOperand instanceof OperandDate)
            if (leftOperand instanceof OperandText
                    && ((OperandText) leftOperand).asString().equals(COMPONENT_OBS_DATETIME)) {
                criterion.add(Restrictions.ge(COMPONENT_OBS_DATETIME, rightOperand));
            } else {
                criterion.add(Restrictions.ge("valueDatetime", rightOperand));
            }
        else
            log.error("Invalid operand value for GREATER THAN EQUAL operation");

    } else if (operator == Operator.LT) {
        if (rightOperand instanceof OperandNumeric)
            criterion.add(Restrictions.lt("valueNumeric", ((OperandNumeric) rightOperand).asDouble()));
        else if (rightOperand instanceof OperandDate)
            if (leftOperand instanceof OperandText
                    && ((OperandText) leftOperand).asString().equals(COMPONENT_OBS_DATETIME)) {
                criterion.add(Restrictions.lt(COMPONENT_OBS_DATETIME, rightOperand));
            } else {
                criterion.add(Restrictions.lt("valueDatetime", rightOperand));
            }
        else
            log.error("Invalid operand value for LESS THAN operation");

    } else if (operator == Operator.GT) {
        if (rightOperand instanceof OperandNumeric)
            criterion.add(Restrictions.gt("valueNumeric", ((OperandNumeric) rightOperand).asDouble()));
        else if (rightOperand instanceof OperandDate)
            if (leftOperand instanceof OperandText
                    && ((OperandText) leftOperand).asString().equals(COMPONENT_OBS_DATETIME)) {
                criterion.add(Restrictions.gt(COMPONENT_OBS_DATETIME, rightOperand));
            } else {
                criterion.add(Restrictions.gt("valueDatetime", rightOperand));
            }
        else
            log.error("Invalid operand value for GREATER THAN operation");

    } else if (operator == Operator.EXISTS) {
        // EXISTS can be handled on the higher level (above
        // LogicService, even) by coercing the Result into a Boolean for
        // each patient
    } else if (operator == Operator.ASOF && rightOperand instanceof OperandDate) {
        indexDate = (Date) rightOperand;
        criterion.add(Restrictions.le("obsDatetime", indexDate));

    } else if (operator == Operator.WITHIN && rightOperand instanceof Duration) {

        Duration duration = (Duration) rightOperand;
        Calendar within = Calendar.getInstance();
        within.setTime(indexDate);

        if (duration.getUnits() == Duration.Units.YEARS) {
            within.add(Calendar.YEAR, duration.getDuration().intValue());
        } else if (duration.getUnits() == Duration.Units.MONTHS) {
            within.add(Calendar.MONTH, duration.getDuration().intValue());
        } else if (duration.getUnits() == Duration.Units.WEEKS) {
            within.add(Calendar.WEEK_OF_YEAR, duration.getDuration().intValue());
        } else if (duration.getUnits() == Duration.Units.DAYS) {
            within.add(Calendar.DAY_OF_YEAR, duration.getDuration().intValue());
        } else if (duration.getUnits() == Duration.Units.HOURS) {
            within.add(Calendar.HOUR_OF_DAY, duration.getDuration().intValue());
        } else if (duration.getUnits() == Duration.Units.MINUTES) {
            within.add(Calendar.MINUTE, duration.getDuration().intValue());
        } else if (duration.getUnits() == Duration.Units.SECONDS) {
            within.add(Calendar.SECOND, duration.getDuration().intValue());
        }

        if (indexDate.compareTo(within.getTime()) > 0) {
            criterion.add(Restrictions.between("obsDatetime", within.getTime(), indexDate));
        } else {
            criterion.add(Restrictions.between("obsDatetime", indexDate, within.getTime()));
        }
    }

    Criterion c = null;

    for (Criterion crit : criterion) {
        if (c == null) {
            c = crit;
        } else {
            c = Restrictions.and(c, crit);
        }
    }
    return c;
}

From source file:org.openmrs.logic.db.hibernate.HibernateLogicEncounterDAO.java

/**
 * Convenience method to get the list of hibernate queries for this expression
 * /*from w w  w .ja v  a2  s.  c  o  m*/
 * @param logicExpression
 * @param indexDate
 * @param criteria Criteria object so that certain expressions can add aliases, etc
 * @return Criterion to be added to the Criteria
 */
public Criterion getCriterion(LogicExpression logicExpression, Date indexDate, Criteria criteria) {
    Operator operator = logicExpression.getOperator();
    Object rightOperand = logicExpression.getRightOperand();
    Object leftOperand = null;
    if (logicExpression instanceof LogicExpressionBinary) {
        leftOperand = ((LogicExpressionBinary) logicExpression).getLeftOperand();
    }
    List<Criterion> criterion = new ArrayList<Criterion>();

    //if the leftOperand is a String and does not match any components,
    //see if it is a concept name and restrict accordingly
    //a null operator implies a concept restriction
    if (leftOperand instanceof LogicExpression) {
        // no restrictions if there is no operator
        // TODO restrict on provider != null for encounterProvider token?
    }

    String token = logicExpression.getRootToken();

    if (operator == null) {
        // no restrictions if there is no operator
        // TODO restrict on provider != null for encounterProvider token?
    } else if (operator == Operator.BEFORE || operator == Operator.LT) {
        if (ENCOUNTER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandDate) {
            criterion.add(Restrictions.lt("encounterDatetime", rightOperand));
        } else {
            throw new LogicException("'before' is not a valid operator on " + token + " and " + rightOperand);
        }
    } else if (operator == Operator.AFTER || operator == Operator.GT) {
        if (ENCOUNTER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandDate) {
            criterion.add(Restrictions.gt("encounterDatetime", rightOperand));
        } else {
            throw new LogicException("'after' is not a valid operator on " + token + " and " + rightOperand);
        }
    } else if (operator == Operator.AND || operator == Operator.OR) {
        if (ENCOUNTER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandDate) {
            Criterion leftCriteria = null;
            Criterion rightCriteria = null;
            if (leftOperand instanceof LogicExpression) {
                leftCriteria = this.getCriterion((LogicExpression) leftOperand, indexDate, criteria);
            }
            if (rightOperand instanceof LogicExpression) {
                rightCriteria = this.getCriterion((LogicExpression) rightOperand, indexDate, criteria);
            }

            if (leftCriteria != null && rightCriteria != null) {
                if (operator == Operator.AND) {
                    criterion.add(Restrictions.and(leftCriteria, rightCriteria));
                }
                if (operator == Operator.OR) {
                    criterion.add(Restrictions.or(leftCriteria, rightCriteria));
                }
            }
        } else {
            throw new LogicException("'and/or' are not valid operators on " + token + " and " + rightOperand);
        }
    } else if (operator == Operator.NOT) {

        Criterion rightCriteria = null;

        if (rightOperand instanceof LogicExpression) {
            rightCriteria = this.getCriterion((LogicExpression) rightOperand, indexDate, criteria);
        }

        if (rightCriteria != null) {
            criterion.add(Restrictions.not(rightCriteria));
        }

    } else if (operator == Operator.CONTAINS) {
        if (ENCOUNTER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandText) {
            criteria.createAlias("encounterType", "encounterType");
            criterion.add(Expression.eq("encounterType.name", ((OperandText) rightOperand).asString()));
        } else if (LOCATION_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandText) {
            criteria.createAlias("location", "location");
            criterion.add(Restrictions.eq("location.name", ((OperandText) rightOperand).asString()));
        } else if (PROVIDER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandNumeric) {
            criteria.createAlias("provider", "provider");
            criterion.add(Restrictions.eq("provider.personId", ((OperandNumeric) rightOperand).asInteger()));
        } else {
            throw new LogicException("'contains' is not a valid operator on " + token + " and " + rightOperand);
        }
    } else if (operator == Operator.IN) {
        if (ENCOUNTER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandCollection) {
            criteria.createAlias("encounterType", "encounterType");
            criterion.add(
                    Expression.in("encounterType.name", ((OperandCollection) rightOperand).asCollection()));
        } else if (LOCATION_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandCollection) {
            criteria.createAlias("location", "location");
            criterion.add(Restrictions.in("location.name", ((OperandCollection) rightOperand).asCollection()));
        } else if (PROVIDER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandCollection) {
            criteria.createAlias("provider", "provider");
            criterion.add(
                    Restrictions.in("provider.systemId", ((OperandCollection) rightOperand).asCollection()));
        } else {
            throw new LogicException("'in' is not a valid operator on " + token + " and " + rightOperand);
        }
    } else if (operator == Operator.EQUALS) {
        if (ENCOUNTER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandDate) {
            criterion.add(Restrictions.eq("encounterDatetime", rightOperand));
        } else if (ENCOUNTER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandText) {
            criteria.createAlias("encounterType", "encounterType");
            criterion.add(Restrictions.eq("encounterType.name", ((OperandText) rightOperand).asString()));
        } else if (LOCATION_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandText) {
            criteria.createAlias("location", "location");
            criterion.add(Restrictions.eq("location.name", ((OperandText) rightOperand).asString()));
        } else if (PROVIDER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandText) {
            criteria.createAlias("provider", "provider");
            criterion.add(Restrictions.eq("provider.systemId", ((OperandText) rightOperand).asString()));
        } else {
            throw new LogicException("'equals' is not a valid operator on " + token + " and " + rightOperand);
        }
    } else if (operator == Operator.LTE) {
        if (rightOperand instanceof OperandDate)
            criterion.add(Restrictions.le("encounterDatetime", rightOperand));
        else
            throw new LogicException(
                    "'less than or equals' is not a valid operator on " + token + " and " + rightOperand);
    } else if (operator == Operator.GTE) {
        if (rightOperand instanceof OperandDate)
            criterion.add(Restrictions.ge("encounterDatetime", rightOperand));
        else
            throw new LogicException(
                    "'greater than or equals' is not a valid operator on " + token + " and " + rightOperand);
    } else if (operator == Operator.LT) {
        if (rightOperand instanceof OperandDate)
            criterion.add(Restrictions.lt("encounterDatetime", rightOperand));
        else
            throw new LogicException(
                    "'less than' is not a valid operator on " + token + " and " + rightOperand);

    } else if (operator == Operator.GT) {
        if (rightOperand instanceof OperandDate)
            criterion.add(Restrictions.gt("encounterDatetime", rightOperand));
        else
            throw new LogicException(
                    "'greater than' is not a valid operator on " + token + " and " + rightOperand);

    } else if (operator == Operator.EXISTS) {
        // EXISTS can be handled on the higher level (above
        // LogicService, even) by coercing the Result into a Boolean for
        // each patient
    } else if (operator == Operator.ASOF && rightOperand instanceof Date) {
        indexDate = (Date) rightOperand;
        criterion.add(Restrictions.le("encounterDatetime", indexDate));

    } else if (operator == Operator.WITHIN) {
        if (rightOperand instanceof Duration) {
            Duration duration = (Duration) rightOperand;
            Calendar within = Calendar.getInstance();
            within.setTime(indexDate);

            if (duration.getUnits() == Duration.Units.YEARS) {
                within.add(Calendar.YEAR, duration.getDuration().intValue());
            } else if (duration.getUnits() == Duration.Units.MONTHS) {
                within.add(Calendar.MONTH, duration.getDuration().intValue());
            } else if (duration.getUnits() == Duration.Units.WEEKS) {
                within.add(Calendar.WEEK_OF_YEAR, duration.getDuration().intValue());
            } else if (duration.getUnits() == Duration.Units.DAYS) {
                within.add(Calendar.DAY_OF_YEAR, duration.getDuration().intValue());
            } else if (duration.getUnits() == Duration.Units.HOURS) {
                within.add(Calendar.HOUR_OF_DAY, duration.getDuration().intValue());
            } else if (duration.getUnits() == Duration.Units.MINUTES) {
                within.add(Calendar.MINUTE, duration.getDuration().intValue());
            } else if (duration.getUnits() == Duration.Units.SECONDS) {
                within.add(Calendar.SECOND, duration.getDuration().intValue());
            }

            if (indexDate.compareTo(within.getTime()) > 0) {
                criterion.add(Restrictions.between("encounterDatetime", within.getTime(), indexDate));
            } else {
                criterion.add(Restrictions.between("encounterDatetime", indexDate, within.getTime()));
            }
        } else {
            throw new LogicException("'within' is not a valid operator on " + token + " and " + rightOperand);
        }
    }

    Criterion c = null;

    for (Criterion crit : criterion) {
        if (c == null) {
            c = crit;
        } else {
            c = Restrictions.and(c, crit);
        }
    }
    return c;
}

From source file:org.fsl.roms.service.action.RoadCheckServiceAction.java

private boolean validateInitiateRequiredFields(RequestContext context, boolean checkMVFields) {
    RoadCheckInitiateView roadCheckInitiateView = (RoadCheckInitiateView) context.getFlowScope()
            .get("initiateView");
    boolean error = false;
    Calendar calendar = Calendar.getInstance();
    Date currentDate = calendar.getTime();

    if (StringUtils.isBlank(roadCheckInitiateView.getActivityType())) {
        addErrorMessageWithParameter(context, "RequiredFields", "Road Check Activity");
        error = true;//from www  .j ava  2 s. c  om
    }

    // if(StringUtils.isBlank(roadCheckInitiateView.getOperationName())){
    if (roadCheckInitiateView.getActivityType().equalsIgnoreCase("S")
            && (roadCheckInitiateView.getRoadOperationBO() == null
                    || roadCheckInitiateView.getRoadOperationBO().getRoadOperationId() == null)) {
        addErrorMessageWithParameter(context, "RequiredFields", "Operation Name");
        error = true;
    }

    // if(StringUtils.isBlank(roadCheckInitiateView.getOffencePlace())){
    if (roadCheckInitiateView.getOffencePlace() == null
            || roadCheckInitiateView.getOffencePlace().getArteryId() == null) {
        addErrorMessageWithParameter(context, "RequiredFields", "Place of Offence");
        error = true;
    }
    if (roadCheckInitiateView.getOffenceDate() == null) {
        addErrorMessageWithParameter(context, "RequiredFields", "Offence Date");
        error = true;
    } else {

        XMLGregorianCalendar today = null;
        // Date convertedDate = null;

        // SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
        /* try { convertedDate = dateFormat.parse(StringUtil.getCurrentDateString()); } catch (ParseException e1) {
         * // TODO Auto-generated catch block e1.printStackTrace(); } */
        // convertedDate = dateFormat.getCalendar().getTime();

        try {
            today = DateUtils.getXMLGregorianCalendar(currentDate);
        } catch (DatatypeConfigurationException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // System.err.println("The date " + offDate);

        if (roadCheckInitiateView.getOffenceDate().after(currentDate)) {
            addErrorMessageText(context, "Offence Date cannot be after Today's Date and Time");
            error = true;
        }
        boolean offDateError = false;
        Date startDate = null;
        Date endDate = null;

        if (roadCheckInitiateView.getActivityType().equalsIgnoreCase("S")) {

            if (roadCheckInitiateView.getRoadOperationBO() != null
                    && roadCheckInitiateView.getRoadOperationBO().getRoadOperationId() != null) {

                Date offDate = roadCheckInitiateView.getRoadOperationBO().getStatusId()
                        .equalsIgnoreCase(Constants.Status.ROAD_OPERATION_STARTED)
                                ? returnDateTimeInMinutesOnlyDateType(roadCheckInitiateView.getOffenceDate())
                                : returnDateTimeInMinutesOnlyDateType(roadCheckInitiateView.getOffenceDate());

                if (roadCheckInitiateView.getRoadOperationBO().getActualStartDate() != null) {

                    startDate = roadCheckInitiateView.getRoadOperationBO().getStatusId()
                            .equalsIgnoreCase(Constants.Status.ROAD_OPERATION_STARTED)
                                    ? returnDateTimeInMinutesOnlyDateType(
                                            roadCheckInitiateView.getRoadOperationBO().getActualStartDate())
                                    : returnDateTimeInMinutesOnlyDateType(
                                            roadCheckInitiateView.getRoadOperationBO().getActualStartDate());

                    if (offDate.compareTo(startDate) < 0) {
                        offDateError = true;
                    }
                } else {
                    if (startDate == null) {
                        startDate = roadCheckInitiateView.getRoadOperationBO().getStatusId()
                                .equalsIgnoreCase(Constants.Status.ROAD_OPERATION_STARTED)
                                        ? returnDateOnlyDateType(roadCheckInitiateView.getRoadOperationBO()
                                                .getScheduledStartDate())
                                        : returnDateTimeInMinutesOnlyDateType(roadCheckInitiateView
                                                .getRoadOperationBO().getScheduledStartDate());
                    }
                    if (offDate.compareTo(startDate) < 0) {
                        offDateError = true;
                    }
                }

                if (roadCheckInitiateView.getRoadOperationBO().getActualEndDate() != null) {
                    endDate = roadCheckInitiateView.getRoadOperationBO().getStatusId()
                            .equalsIgnoreCase(Constants.Status.ROAD_OPERATION_STARTED)
                                    ? returnDateOnlyDateType(
                                            roadCheckInitiateView.getRoadOperationBO().getActualEndDate())
                                    : returnDateTimeInMinutesOnlyDateType(
                                            roadCheckInitiateView.getRoadOperationBO().getActualEndDate());

                    if (offDate.compareTo(endDate) > 0) {
                        offDateError = true;
                    }
                } else {
                    if (endDate == null) {

                        Calendar calRoadEndDate = Calendar.getInstance();
                        calRoadEndDate
                                .setTime(roadCheckInitiateView.getRoadOperationBO().getScheduledEndDate());
                        calRoadEndDate.set(Calendar.HOUR_OF_DAY, 23);
                        calRoadEndDate.set(Calendar.MINUTE, 59);
                        calRoadEndDate.set(Calendar.SECOND, 59);
                        endDate = roadCheckInitiateView.getRoadOperationBO().getStatusId()
                                .equalsIgnoreCase(Constants.Status.ROAD_OPERATION_STARTED)
                                        ? returnDateTimeInMinutesOnlyDateType(calRoadEndDate.getTime())
                                        : returnDateTimeInMinutesOnlyDateType(roadCheckInitiateView
                                                .getRoadOperationBO().getScheduledEndDate());
                    }
                    if (offDate.compareTo(endDate) > 0) {
                        offDateError = true;
                    }
                }
            }

            if (offDateError == true) {
                try {
                    error = true;
                    if (startDate.compareTo(endDate) == 0) {
                        addErrorMessageText(context,
                                "Offence Date must be " + DateUtils.getFormattedUtilDate(startDate) + " for "
                                        + roadCheckInitiateView.getRoadOperationBO().getOperationName());
                    } else {
                        //addErrorMessageText(context, "Offence Date must be between " + DateUtils.getFormattedUtilDate(startDate) + " and " + DateUtils.getFormattedUtilDate(endDate) + " for " + roadCheckInitiateView.getRoadOperationBO().getOperationName());
                        addErrorMessageText(context,
                                "Offence Date must be between "
                                        + (roadCheckInitiateView.getRoadOperationBO().getStatusId()
                                                .equalsIgnoreCase(Constants.Status.ROAD_OPERATION_STARTED)
                                                        ? DateUtils.getFormattedUtilLongDate(startDate)
                                                        : DateUtils.getFormattedUtilLongDate(startDate))
                                        + " and "
                                        + (roadCheckInitiateView.getRoadOperationBO().getStatusId()
                                                .equalsIgnoreCase(Constants.Status.ROAD_OPERATION_STARTED)
                                                        ? DateUtils.getFormattedUtilLongDate(endDate)
                                                        : DateUtils.getFormattedUtilLongDate(endDate))
                                        + " for "
                                        + roadCheckInitiateView.getRoadOperationBO().getOperationName());
                    }
                } catch (Exception e) {
                    logger.error("Road Check", e);
                }
            }
        }

    }

    // if(StringUtils.isBlank(roadCheckInitiateView.getInspector())){
    if (roadCheckInitiateView.getTaStaffBO() == null
            || StringUtils.isBlank(roadCheckInitiateView.getTaStaffBO().getStaffId())) {
        addErrorMessageWithParameter(context, "RequiredFields", "Inspector");
        error = true;
    }

    if (StringUtils.isBlank(roadCheckInitiateView.getRoleObserved())) {
        addErrorMessageWithParameter(context, "RequiredFields", "Role Observed");
        error = true;
    } else if ("T".equalsIgnoreCase(roadCheckInitiateView.getRoleObserved())
            && StringUtils.isBlank(roadCheckInitiateView.getOtherRoleId())) {
        addErrorMessageWithParameter(context, "RequiredFields", "Other Role Observed");
        error = true;

    }

    //global address validation - kpowell

    boolean errorFoundInAddress = validateAddress(context, roadCheckInitiateView.getAddressView());

    if (errorFoundInAddress) {
        error = true;
    }

    /* if(StringUtils.isBlank(roadCheckInitiateView.getMobilePhoneNo()) &&
     * StringUtils.isBlank(roadCheckInitiateView.getHomePhoneNo()) &&
     * StringUtils.isBlank(roadCheckInitiateView.getWorkPhoneNo())){ addErrorMessageWithParameter(context,
     * "RequiredFields", "At least one Contact Number"); error=true; } */

    // Validate Phone numbers
    logger.info("Mobile Phone " + roadCheckInitiateView.getMobilePhoneNo());
    if (!StringUtils.isBlank(roadCheckInitiateView.getMobilePhoneNo())
            && !roadCheckInitiateView.getMobilePhoneNo().equals("(___)___-____")) {
        if (!PhoneNumberUtil.validateAllPhoneNumbers(roadCheckInitiateView.getMobilePhoneNo())) {
            addErrorMessageText(context, "Mobile Contact Number is not valid. E.g.(555)555-5555");
            error = true;
        }
    }
    if (!StringUtils.isBlank(roadCheckInitiateView.getHomePhoneNo())
            && !roadCheckInitiateView.getHomePhoneNo().equals("(___)___-____")) {
        if (!PhoneNumberUtil.validateAllPhoneNumbers(roadCheckInitiateView.getHomePhoneNo())) {
            addErrorMessageText(context, "Home Contact Number is not valid. E.g.(555)555-5555");
            error = true;
        }
    }
    if (!StringUtils.isBlank(roadCheckInitiateView.getWorkPhoneNo())
            && !roadCheckInitiateView.getWorkPhoneNo().equals("(___)___-____")) {
        if (!PhoneNumberUtil.validateAllPhoneNumbers(roadCheckInitiateView.getWorkPhoneNo())) {
            addErrorMessageText(context, "Work Contact Number is not valid. E.g.(555)555-5555");
            error = true;
        }
    }

    if (StringUtils.isBlank(roadCheckInitiateView.getPlateRegNo())) {
        addErrorMessageWithParameter(context, "RequiredFields", "Plate No.");
        error = true;
    }

    if (roadCheckInitiateView.isDisableMotorVehicleFields() == false && checkMVFields == true) {

        //         if (StringUtils.isBlank(roadCheckInitiateView.getChassisNo())) {
        //            addErrorMessageWithParameter(context, "RequiredFields", "Chassis No.");
        //            error = true;
        //         }

        //         if (StringUtils.isBlank(roadCheckInitiateView.getEngineNo())) {
        //            addErrorMessageWithParameter(context, "RequiredFields", "Engine No.");
        //            error = true;
        //         }

        if (StringUtils.isBlank(roadCheckInitiateView.getMakeDescription())) {
            addErrorMessageWithParameter(context, "RequiredFields", "Make");
            error = true;
        }

        if (StringUtils.isBlank(roadCheckInitiateView.getModel())) {
            addErrorMessageWithParameter(context, "RequiredFields", "Model");
            error = true;
        }

        if (StringUtils.isBlank(roadCheckInitiateView.getType())) {
            addErrorMessageWithParameter(context, "RequiredFields", "Type");
            error = true;
        }

        if (StringUtils.isBlank(roadCheckInitiateView.getColour())) {
            addErrorMessageWithParameter(context, "RequiredFields", "Colour");
            error = true;
        }

        if (roadCheckInitiateView.getYear() == null) {
            addErrorMessageWithParameter(context, "RequiredFields", "Year");
            error = true;
        } else {
            // validate MV year
            int firstYear = 1800;
            int lastYear = Calendar.getInstance().get(Calendar.YEAR) + 1;
            // System.err.println("lastYear: " + lastYear);
            if (roadCheckInitiateView.getYear().intValue() < firstYear
                    || roadCheckInitiateView.getYear().intValue() > lastYear) {
                addErrorMessage(context, "InvalidYear");
                error = true;
            }
        }

    }

    if (checkMVFields == true) {
        if (roadCheckInitiateView.isBadgeQuery()) {
            if (StringUtils.isBlank(roadCheckInitiateView.getBadgeNo())) {
                addErrorMessageWithParameter(context, "RequiredFields", "Badge #");
                error = true;
            }
        }

        if (roadCheckInitiateView.isDlQuery()) {
            if (StringUtils.isBlank(roadCheckInitiateView.getDlNo())) {
                addErrorMessageWithParameter(context, "RequiredFields", "Driver Licence #");
                error = true;
            }
        }

        //         if (roadCheckInitiateView.isRoadLicQuery()) {
        //            if (StringUtils.isBlank(roadCheckInitiateView.getRoadLicNo())) {
        //               addErrorMessageWithParameter(context, "RequiredFields", "Road Licence #");
        //               error = true;
        //            }
        //         }
    }
    return error;
}

From source file:it.webappcommon.lib.jsf.AbstractPageBase.java

/**
 * Metodo che permette di ordinare, in ordine crescente o decrescente in
 * base ad ascending, un arraylist di oggetti di qualsiasi tipo in base al
 * parametro column. In particolare, con la reflection, viene gestito
 * l'ordinamento per column se essa e' int, long, double, float, boolean,
 * String, Date, Integer. Se non e' di uno di questi tipi, l'ordinamento non
 * fa niente in quanto il compareTo del comparator definito all'interno del
 * metodo ritorna sempre 0. La column, va indicata, come sempre del resto,
 * senza il get o l'is davanti.//from w  ww. ja v a 2  s.  c  o m
 * 
 * @param list
 *            ArrayList da ordinare
 * @param column
 *            Nome della colonna/propriet dell'oggetto in base alla quale
 *            effettuare l'ordinamento
 * @param ascending
 *            Booleano che specifica se l'ordinamento deve essere ascendente
 *            o meno
 */
public void sort(List list, final String column, final boolean ascending) {
    // TODO: Gestione di property a pi livelli: ad esempio
    // ElementBL.element.nome
    Comparator comparator = null;

    if ((column != null) && (!column.equals("")) && (list != null) && (list.size() > 0)) {

        final Class item_class = list.get(0).getClass();

        comparator = new Comparator() {

            public int compare(Object o1, Object o2) {

                PropertyDescriptor column_descriptor = null;
                Method read_method = null;
                Object obj1 = null;
                Object obj2 = null;
                Object resInvoke1 = null;
                Object resInvoke2 = null;
                Date date1 = null;
                Date date2 = null;
                String str1 = null;
                String str2 = null;
                Integer Int1 = null;
                Integer Int2 = null;
                Double Double1 = null;
                Double Double2 = null;
                Float Float1 = null;
                Float Float2 = null;
                int returnValue = 0;

                try {

                    if ((column == null) || (o1 == null) || (o2 == null)) {

                        /*
                         * In caso di non specificazione della colonna o di
                         * uno dei due oggetti ritorna 0, facendo in modo
                         * che l'ordinamento non ha alcun effetto
                         */
                        returnValue = 0;

                    } else {

                        /*
                         * Tenta di ottenere un property descriptor a
                         * partire dalla colonna
                         */
                        try {

                            column_descriptor = new PropertyDescriptor(column, item_class);
                            read_method = column_descriptor.getReadMethod();

                        } catch (Exception e) {

                            read_method = null;

                        }

                        if (read_method != null) {

                            obj1 = item_class.cast(o1);
                            obj2 = item_class.cast(o2);

                            /*
                             * Viene gestito l'ordinamento per String,
                             * Boolean, int
                             */
                            if (read_method.getReturnType() == int.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo primitivo int">
                                /*
                                 * Variabili di tipo primitivo e'
                                 * impossibile che siano NULL
                                 */
                                str1 = read_method.invoke(obj1).toString();
                                str2 = read_method.invoke(obj2).toString();

                                int int1 = Integer.parseInt(str1);
                                int int2 = Integer.parseInt(str2);

                                if (ascending) {

                                    if (int1 < int2) {
                                        returnValue = -1;
                                    } else if (int1 > int2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                } else {

                                    if (int1 > int2) {
                                        returnValue = -1;
                                    } else if (int1 < int2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == long.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo primitivo long">
                                /*
                                 * Variabili di tipo primitivo e'
                                 * impossibile che siano NULL
                                 */
                                str1 = read_method.invoke(obj1).toString();
                                str2 = read_method.invoke(obj2).toString();

                                long lng1 = Long.parseLong(str1);
                                long lng2 = Long.parseLong(str2);

                                if (ascending) {

                                    if (lng1 < lng2) {
                                        returnValue = -1;
                                    } else if (lng1 > lng2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                } else {

                                    if (lng1 > lng2) {
                                        returnValue = -1;
                                    } else if (lng1 < lng2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == double.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo primitivo double">
                                /*
                                 * Variabili di tipo primitivo e'
                                 * impossibile che siano NULL
                                 */
                                str1 = read_method.invoke(obj1).toString();
                                str2 = read_method.invoke(obj2).toString();

                                double dbl1 = Double.parseDouble(str1);
                                double dbl2 = Double.parseDouble(str2);

                                if (ascending) {

                                    if (dbl1 < dbl2) {
                                        returnValue = -1;
                                    } else if (dbl1 > dbl2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                } else {

                                    if (dbl1 > dbl2) {
                                        returnValue = -1;
                                    } else if (dbl1 < dbl2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == float.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo primitivo float">
                                /*
                                 * Variabili di tipo primitivo e'
                                 * impossibile che siano NULL
                                 */
                                str1 = read_method.invoke(obj1).toString();
                                str2 = read_method.invoke(obj2).toString();

                                float flt1 = Float.parseFloat(str1);
                                float flt2 = Float.parseFloat(str2);

                                if (ascending) {

                                    if (flt1 < flt2) {
                                        returnValue = -1;
                                    } else if (flt1 > flt2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                } else {

                                    if (flt1 > flt2) {
                                        returnValue = -1;
                                    } else if (flt1 < flt2) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == Float.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo object Float">
                                /*
                                 * Variabili di tipo object e' impossibile
                                 * che siano NULL
                                 */
                                /*
                                 * Pu essere che la propriet degli
                                 * oggetti sia NULL. In quel caso il
                                 * toString() genera errore se non gestito.
                                 * Se resInvoke1 oppure resInvoke2 sono
                                 * NULL, anche le rispettive conversioni in
                                 * interi lo devono essere
                                 */
                                resInvoke1 = read_method.invoke(obj1);
                                resInvoke2 = read_method.invoke(obj2);
                                if (resInvoke1 != null) {
                                    Float1 = (Float) resInvoke1;
                                }
                                if (resInvoke2 != null) {
                                    Float2 = (Float) resInvoke2;
                                }

                                if (ascending) {

                                    if ((Float1 != null) && (Float2 != null)) {
                                        returnValue = Float1.compareTo(Float2);
                                    } else if ((Float1 == null) && (Float2 != null)) {
                                        returnValue = -1;
                                    } else if ((Float1 != null) && (Float2 == null)) {
                                        returnValue = 1;
                                    } else if ((Float1 == null) && (Float2 == null)) {
                                        returnValue = 0;
                                    }

                                } else {

                                    if ((Float1 != null) && (Float2 != null)) {
                                        returnValue = Float2.compareTo(Float1);
                                    } else if ((Float1 != null) && (Float2 == null)) {
                                        returnValue = -1;
                                    } else if ((Float1 == null) && (Float2 != null)) {
                                        returnValue = 1;
                                    } else if ((Float1 == null) && (Float2 == null)) {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == boolean.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo primitivo boolean">
                                /*
                                 * Variabili di tipo primitivo e'
                                 * impossibile che siano NULL
                                 */
                                str1 = read_method.invoke(obj1).toString();
                                str2 = read_method.invoke(obj2).toString();

                                boolean bool1 = Boolean.parseBoolean(str1);
                                boolean bool2 = Boolean.parseBoolean(str2);

                                if (ascending) {

                                    if ((!bool1) && (bool2)) {
                                        returnValue = -1;
                                    } else if ((bool1) && (!bool2)) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                } else {

                                    if ((bool1) && (!bool2)) {
                                        returnValue = -1;
                                    } else if ((!bool1) && (bool2)) {
                                        returnValue = 1;
                                    } else {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == String.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo object String">
                                /*
                                 * Pu essere che la propriet degli
                                 * oggetti sia NULL. In quel caso il
                                 * toString() genera errore se non gestito.
                                 * Se resInvoke1
                                 * 
                                 * oppure resInvoke2 sono NULL, anche le
                                 * rispettive conversioni in stringa lo
                                 * devono essere
                                 */
                                resInvoke1 = read_method.invoke(obj1);
                                resInvoke2 = read_method.invoke(obj2);
                                if (resInvoke1 != null) {
                                    str1 = resInvoke1.toString().toUpperCase();
                                }
                                if (resInvoke2 != null) {
                                    str2 = resInvoke2.toString().toUpperCase();
                                }

                                if (ascending) {

                                    if ((str1 != null) && (str2 != null)) {
                                        returnValue = str1.compareTo(str2);
                                    } else if ((str1 == null) && (str2 != null)) {
                                        returnValue = -1;
                                    } else if ((str1 != null) && (str2 == null)) {
                                        returnValue = 1;
                                    } else if ((str1 == null) && (str2 == null)) {
                                        returnValue = 0;
                                    }

                                } else {

                                    if ((str1 != null) && (str2 != null)) {
                                        returnValue = str2.compareTo(str1);
                                    } else if ((str1 != null) && (str2 == null)) {
                                        returnValue = -1;
                                    } else if ((str1 == null) && (str2 != null)) {
                                        returnValue = 1;
                                    } else if ((str1 == null) && (str2 == null)) {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == Date.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo object Date">
                                /*
                                 * Pu essere che la propriet degli
                                 * oggetti sia NULL. In quel caso il
                                 * toString() genera errore se non gestito.
                                 * Se resInvoke1 oppure resInvoke2 sono
                                 * NULL, anche le rispettive conversioni in
                                 * date lo devono essere
                                 */
                                resInvoke1 = read_method.invoke(obj1);
                                resInvoke2 = read_method.invoke(obj2);
                                if (resInvoke1 != null) {
                                    date1 = (Date) resInvoke1;
                                }
                                if (resInvoke2 != null) {
                                    date2 = (Date) resInvoke2;
                                }

                                if (ascending) {

                                    if ((date1 != null) && (date2 != null)) {
                                        returnValue = date1.compareTo(date2);
                                    } else if ((date1 == null) && (date2 != null)) {
                                        returnValue = -1;
                                    } else if ((date1 != null) && (date2 == null)) {
                                        returnValue = 1;
                                    } else if ((date1 == null) && (date2 == null)) {
                                        returnValue = 0;
                                    }

                                } else {

                                    if ((date1 != null) && (date2 != null)) {
                                        returnValue = date2.compareTo(date1);
                                    } else if ((date1 != null) && (date2 == null)) {
                                        returnValue = -1;
                                    } else if ((date1 == null) && (date2 != null)) {
                                        returnValue = 1;
                                    } else if ((date1 == null) && (date2 == null)) {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == Integer.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo object Integer">
                                /*
                                 * Pu essere che la propriet degli
                                 * oggetti sia NULL. In quel caso il
                                 * toString() genera errore se non gestito.
                                 * Se resInvoke1 oppure resInvoke2 sono
                                 * NULL, anche le rispettive conversioni in
                                 * interi lo devono essere
                                 */
                                resInvoke1 = read_method.invoke(obj1);
                                resInvoke2 = read_method.invoke(obj2);
                                if (resInvoke1 != null) {
                                    Int1 = (Integer) resInvoke1;
                                }
                                if (resInvoke2 != null) {
                                    Int2 = (Integer) resInvoke2;
                                }

                                if (ascending) {

                                    if ((Int1 != null) && (Int2 != null)) {
                                        returnValue = Int1.compareTo(Int2);
                                    } else if ((Int1 == null) && (Int2 != null)) {
                                        returnValue = -1;
                                    } else if ((Int1 != null) && (Int2 == null)) {
                                        returnValue = 1;
                                    } else if ((Int1 == null) && (Int2 == null)) {
                                        returnValue = 0;
                                    }

                                } else {

                                    if ((Int1 != null) && (Int2 != null)) {
                                        returnValue = Int2.compareTo(Int1);
                                    } else if ((Int1 != null) && (Int2 == null)) {
                                        returnValue = -1;
                                    } else if ((Int1 == null) && (Int2 != null)) {
                                        returnValue = 1;
                                    } else if ((Int1 == null) && (Int2 == null)) {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            } else if (read_method.getReturnType() == Double.class) {

                                // <editor-fold defaultstate="collapsed"
                                // desc="Gestione tipo object Double">
                                /*
                                 * Pu essere che la propriet degli
                                 * oggetti sia NULL. In quel caso il
                                 * toString() genera errore se non gestito.
                                 * Se resInvoke1 oppure resInvoke2 sono
                                 * NULL, anche le rispettive conversioni in
                                 * interi lo devono essere
                                 */
                                resInvoke1 = read_method.invoke(obj1);
                                resInvoke2 = read_method.invoke(obj2);
                                if (resInvoke1 != null) {
                                    Double1 = (Double) resInvoke1;
                                }
                                if (resInvoke2 != null) {
                                    Double2 = (Double) resInvoke2;
                                }

                                if (ascending) {

                                    if ((Double1 != null) && (Double2 != null)) {
                                        returnValue = Double1.compareTo(Double2);
                                    } else if ((Double1 == null) && (Double2 != null)) {
                                        returnValue = -1;
                                    } else if ((Double1 != null) && (Double2 == null)) {
                                        returnValue = 1;
                                    } else if ((Double1 == null) && (Double2 == null)) {
                                        returnValue = 0;
                                    }

                                } else {

                                    if ((Double1 != null) && (Double2 != null)) {
                                        returnValue = Double2.compareTo(Double1);
                                    } else if ((Double1 != null) && (Double2 == null)) {
                                        returnValue = -1;
                                    } else if ((Double1 == null) && (Double2 != null)) {
                                        returnValue = 1;
                                    } else if ((Double1 == null) && (Double2 == null)) {
                                        returnValue = 0;
                                    }

                                }
                                // </editor-fold>

                            }

                        } else {

                            /*
                             * Nel caso in cui non ci sia il metodo get
                             * della colonna passata, ritorna 0, facendo in
                             * modo che l'ordinamento non ha alcun effetto
                             */
                            returnValue = 0;

                        }

                    }

                } catch (Exception e) {

                    /*
                     * In caso d'errore in Comparator ritorna 0, facendo in
                     * modo che l'ordinamento non ha alcun effetto
                     */

                    returnValue = 0;

                } finally {

                    /* Clean-up oggetti */
                    column_descriptor = null;
                    read_method = null;
                    obj1 = null;
                    obj2 = null;
                    resInvoke1 = null;
                    resInvoke2 = null;
                    date1 = null;
                    date2 = null;
                    str1 = null;
                    str2 = null;
                    Int1 = null;
                    Int2 = null;
                    Float1 = null;
                    Float2 = null;

                }

                return returnValue;

            }
        };

        if (comparator != null) {
            Collections.sort(list, comparator);
        }

    }

    comparator = null;

}

From source file:org.openmrs.module.tracnetreporting.impl.TracNetIndicatorServiceImpl.java

@SuppressWarnings({ "static-access", "unused" })
private List<Patient> listOfPatients(List<Integer> patientIds, String startDate) throws ParseException {

    List<Patient> patients = new ArrayList<Patient>();

    try {/* w  w  w . j  a  v  a 2 s . c  o  m*/
        DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        Date startingDate = sdf.parse(startDate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(startingDate);

        // subtracting 3 months to the given date.
        cal.add(2, -2);

        String realDate = cal.get(cal.YEAR) + "/" + cal.get(cal.MONTH) + "/" + cal.get(cal.DATE);
        startingDate = sdf.parse(realDate);

        for (Integer patientId : patientIds) {

            if (!maxDateForNextVisit(patientId).equals("")) {
                Date maxDate = sdf.parse(maxDateForNextVisit(patientId));

                if (maxDate.compareTo(startingDate) < 0) {

                    Patient patient = Context.getPatientService().getPatient(patientId);

                    if (!patient.getPersonVoided()) {

                        patients.add(patient);
                    }
                }
            }
        }
    } catch (Exception e) {
        // TODO: handle exception
    }

    return patients;
}

From source file:com.clark.func.Functions.java

/**
 * Determines how two dates compare up to no more than the specified most
 * significant field.//from w  w w  . j  a va2s.  c  om
 * 
 * @param date1
 *            the first date, not <code>null</code>
 * @param date2
 *            the second date, not <code>null</code>
 * @param field
 *            the field from <code>Calendar</code>
 * @return a negative integer, zero, or a positive integer as the first date
 *         is less than, equal to, or greater than the second.
 * @throws IllegalArgumentException
 *             if any argument is <code>null</code>
 * @see #truncateCalendar(Calendar, int)
 * @see #truncatedCompareTo(Date, Date, int)
 * @since 3.0
 */
public static int truncatedCompareTo(Date date1, Date date2, int field) {
    Date truncatedDate1 = truncateDate(date1, field);
    Date truncatedDate2 = truncateDate(date2, field);
    return truncatedDate1.compareTo(truncatedDate2);
}