Example usage for java.lang Float compareTo

List of usage examples for java.lang Float compareTo

Introduction

In this page you can find the example usage for java.lang Float compareTo.

Prototype

public int compareTo(Float anotherFloat) 

Source Link

Document

Compares two Float objects numerically.

Usage

From source file:org.etudes.mneme.impl.SubmissionServiceImpl.java

/**
 * Get the submissions to the assessment made by all users.
 * //from   ww  w  .  j av a  2s.  c om
 * @param assessment
 *        The assessment.
 * @param sort
 *        The sort.
 * @param question
 *        An optional question, to use for sort-by-score (the score would be for this question in the submission, not the overall).
 * @param filterByPermission
 *        if true, return submissions only from users who are currently permitted to submit, otherwise return any submissions found.
 * @return A List<Submission> of the submissions for the assessment.
 */
protected List<SubmissionImpl> getAssessmentSubmissions(Assessment assessment,
        final FindAssessmentSubmissionsSort sort, final Question question, boolean filterByPermission) {
    // collect the submissions to this assessment
    List<SubmissionImpl> rv = this.storage.getAssessmentSubmissions(assessment);

    // get all possible users who can submit
    Set<String> userIds = this.securityService.getUsersIsAllowed(MnemeService.SUBMIT_PERMISSION,
            assessment.getContext());

    // filter out any userIds that are not currently defined
    List<User> users = this.userDirectoryService.getUsers(userIds);
    userIds.clear();
    for (User user : users) {
        userIds.add(user.getId());
    }

    // if any user is not represented in the submissions we found, add an empty submission
    for (String userId : userIds) {
        boolean found = false;
        for (Submission s : rv) {
            if (s.getUserId().equals(userId)) {
                found = true;
                break;
            }
        }

        if (!found) {
            SubmissionImpl s = this.getPhantomSubmission(userId, assessment);
            rv.add(s);
        }
    }

    // filter out any submissions found that are not for one of the users in the userIds list (they may have lost permission)
    if (filterByPermission) {
        for (Iterator<SubmissionImpl> i = rv.iterator(); i.hasNext();) {
            SubmissionImpl submission = i.next();

            if (!userIds.contains(submission.getUserId())) {
                i.remove();
            }
        }
    }

    // for all but user name & status sorts, separate out the completed, not-started, in-progress
    List<SubmissionImpl> inProgress = new ArrayList<SubmissionImpl>();
    List<SubmissionImpl> notStarted = new ArrayList<SubmissionImpl>();
    if ((sort != FindAssessmentSubmissionsSort.userName_a) && (sort != FindAssessmentSubmissionsSort.userName_d)
            && (sort != FindAssessmentSubmissionsSort.status_a)
            && (sort != FindAssessmentSubmissionsSort.status_d)) {
        for (Iterator i = rv.iterator(); i.hasNext();) {
            SubmissionImpl submission = (SubmissionImpl) i.next();

            if (!submission.getIsStarted().booleanValue()) {
                notStarted.add(submission);
                i.remove();
            } else if (!submission.getIsComplete().booleanValue()) {
                inProgress.add(submission);
                i.remove();
            }
        }
    }

    // sort - secondary sort of user name, or if primary is title, on submit date
    Collections.sort(rv, new Comparator() {
        public int compare(Object arg0, Object arg1) {
            int rv = 0;
            FindAssessmentSubmissionsSort secondary = null;
            switch (sort) {
            case userName_a:
            case userName_d:
            case status_a:
            case status_d: {
                String id0 = ((Submission) arg0).getUserId();
                try {
                    User u = userDirectoryService.getUser(id0);
                    id0 = u.getSortName();
                } catch (UserNotDefinedException e) {
                }

                String id1 = ((Submission) arg1).getUserId();
                try {
                    User u = userDirectoryService.getUser(id1);
                    id1 = u.getSortName();
                } catch (UserNotDefinedException e) {
                }

                rv = id0.compareToIgnoreCase(id1);

                // Note: leave status sort ascending
                if (sort == FindAssessmentSubmissionsSort.userName_d)
                    rv = -1 * rv;

                secondary = FindAssessmentSubmissionsSort.sdate_a;
                break;
            }
            case final_a:
            case final_d: {
                Float final0 = null;
                Float final1 = null;
                if (question != null) {
                    Answer a0 = ((Submission) arg0).getAnswer(question);
                    Answer a1 = ((Submission) arg1).getAnswer(question);
                    final0 = ((a0 == null) ? Float.valueOf(0f) : a0.getTotalScore());
                    final1 = ((a1 == null) ? Float.valueOf(0f) : a1.getTotalScore());
                } else {
                    final0 = ((Submission) arg0).getTotalScore();
                    final1 = ((Submission) arg1).getTotalScore();
                }

                // null sorts small
                if ((final0 == null) && (final1 == null)) {
                    rv = 0;
                } else if (final0 == null) {
                    rv = -1;
                } else if (final1 == null) {
                    rv = 1;
                } else {
                    rv = final0.compareTo(final1);
                }

                if (sort == FindAssessmentSubmissionsSort.final_d)
                    rv = -1 * rv;

                secondary = FindAssessmentSubmissionsSort.userName_a;
                break;
            }
            case sdate_a:
            case sdate_d: {
                Date date0 = ((Submission) arg0).getSubmittedDate();
                Date date1 = ((Submission) arg1).getSubmittedDate();
                if ((date0 == null) && (date1 == null)) {
                    rv = 0;
                } else if (date0 == null) {
                    rv = -1;
                } else if (date1 == null) {
                    rv = 1;
                } else {
                    rv = date0.compareTo(date1);
                }

                if (sort == FindAssessmentSubmissionsSort.sdate_d)
                    rv = -1 * rv;

                secondary = FindAssessmentSubmissionsSort.userName_a;
                break;
            }
            case evaluated_a:
            case evaluated_d: {
                Boolean evaluated0 = ((Submission) arg0).getEvaluation().getEvaluated();
                Boolean evaluated1 = ((Submission) arg1).getEvaluation().getEvaluated();
                rv = evaluated0.compareTo(evaluated1);

                if (sort == FindAssessmentSubmissionsSort.evaluated_d)
                    rv = -1 * rv;

                secondary = FindAssessmentSubmissionsSort.userName_a;
                break;
            }
            case released_a:
            case released_d: {
                Boolean released0 = ((Submission) arg0).getIsReleased();
                Boolean released1 = ((Submission) arg1).getIsReleased();
                rv = released0.compareTo(released1);

                if (sort == FindAssessmentSubmissionsSort.released_d)
                    rv = -1 * rv;

                secondary = FindAssessmentSubmissionsSort.userName_a;
                break;
            }
            }

            // secondary sort
            FindAssessmentSubmissionsSort third = null;
            if ((rv == 0) && (secondary != null)) {
                switch (secondary) {
                case userName_a: {
                    String id0 = ((Submission) arg0).getUserId();
                    try {
                        User u = userDirectoryService.getUser(id0);
                        id0 = u.getSortName();
                    } catch (UserNotDefinedException e) {
                    }

                    String id1 = ((Submission) arg1).getUserId();
                    try {
                        User u = userDirectoryService.getUser(id1);
                        id1 = u.getSortName();
                    } catch (UserNotDefinedException e) {
                    }

                    rv = id0.compareToIgnoreCase(id1);
                    third = FindAssessmentSubmissionsSort.sdate_a;
                    break;
                }

                case sdate_a: {
                    Date date0 = ((Submission) arg0).getSubmittedDate();
                    Date date1 = ((Submission) arg1).getSubmittedDate();
                    if ((date0 == null) && (date1 == null)) {
                        rv = 0;
                    } else if (date0 == null) {
                        rv = -1;
                    } else if (date1 == null) {
                        rv = 1;
                    } else {
                        rv = ((Submission) arg0).getSubmittedDate()
                                .compareTo(((Submission) arg1).getSubmittedDate());
                    }
                    break;
                }
                }
            }

            // third sort
            if ((rv == 0) && (third != null)) {
                switch (third) {
                case sdate_a: {
                    Date date0 = ((Submission) arg0).getSubmittedDate();
                    Date date1 = ((Submission) arg1).getSubmittedDate();
                    if ((date0 == null) && (date1 == null)) {
                        rv = 0;
                    } else if (date0 == null) {
                        rv = -1;
                    } else if (date1 == null) {
                        rv = 1;
                    } else {
                        rv = ((Submission) arg0).getSubmittedDate()
                                .compareTo(((Submission) arg1).getSubmittedDate());
                    }
                    break;
                }
                }
            }

            return rv;
        }
    });

    // if we have in-progress and not-started to deal with
    if (!inProgress.isEmpty()) {
        // sort them by user name asc
        Collections.sort(inProgress, new Comparator() {
            public int compare(Object arg0, Object arg1) {
                int rv = 0;
                String id0 = ((Submission) arg0).getUserId();
                try {
                    User u = userDirectoryService.getUser(id0);
                    id0 = u.getSortName();
                } catch (UserNotDefinedException e) {
                }

                String id1 = ((Submission) arg1).getUserId();
                try {
                    User u = userDirectoryService.getUser(id1);
                    id1 = u.getSortName();
                } catch (UserNotDefinedException e) {
                }

                rv = id0.compareToIgnoreCase(id1);
                return rv;
            }
        });

        rv.addAll(inProgress);
    }

    if (!notStarted.isEmpty()) {
        // sort them by user name asc
        Collections.sort(notStarted, new Comparator() {
            public int compare(Object arg0, Object arg1) {
                int rv = 0;
                String id0 = ((Submission) arg0).getUserId();
                try {
                    User u = userDirectoryService.getUser(id0);
                    id0 = u.getSortName();
                } catch (UserNotDefinedException e) {
                }

                String id1 = ((Submission) arg1).getUserId();
                try {
                    User u = userDirectoryService.getUser(id1);
                    id1 = u.getSortName();
                } catch (UserNotDefinedException e) {
                }

                rv = id0.compareToIgnoreCase(id1);
                return rv;
            }
        });

        rv.addAll(notStarted);
    }

    return rv;
}

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

/**
 * @throws Exception/*from   w  w w . j a  v  a 2s  . c o  m*/
 */
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:cn.jcenterhome.web.action.CpAction.java

@SuppressWarnings("unchecked")
private Entry<String, Float>[] getSortedHashtableByValue(Map<String, Float> h) {
    Set<Entry<String, Float>> set = h.entrySet();
    Entry<String, Float>[] entries = set.toArray(new Entry[set.size()]);
    Arrays.sort(entries, new Comparator() {
        public int compare(Object arg0, Object arg1) {
            Entry entry1 = (Entry) arg0;
            Entry entry2 = (Entry) arg1;
            Float value1 = (Float) entry1.getValue();
            Float value2 = (Float) entry2.getValue();
            int size = value2.compareTo(value1);
            if (size == 0) {
                String key1 = (String) entry1.getKey();
                String key2 = (String) entry2.getKey();
                return key1.compareTo(key2);
            }//w w w.  j  a  va  2s  .c  o m
            return size;
        }
    });
    return entries;
}

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 . j  a v a2  s. co  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;

}