LogMessageComparator implements Comparator<LogMessageSearchItem>, Serializable { @Override public int compare(final LogMessageSearchItem message1, final LogMessageSearchItem message2) { final long revision1 = message1.getRevision(); final long revision2 = message2.getRevision(); if (sortType == ASCENDING) { return revision1 < revision2 ? -1 : 1; } else { return revision2 < revision1 ? -1 : 1; } } LogMessageComparator(final int sortType); @Override int compare(final LogMessageSearchItem message1, final LogMessageSearchItem message2); static final int ASCENDING; static final int DESCENDING; }
@Test public void testCompare() throws Exception { List<LogMessageSearchItem> entries = new ArrayList<LogMessageSearchItem>(); LogMessageSearchItem c1 = new LogMessageSearchItem(TestUtils.createLogEntry(1, "jesper", new Date(), "Message 1")); LogMessageSearchItem c2 = new LogMessageSearchItem(TestUtils.createLogEntry(12, "jesper", new Date(), "Message 2")); LogMessageSearchItem c3 = new LogMessageSearchItem(TestUtils.createLogEntry(123, "jesper", new Date(), "Message 3")); entries.add(c3); entries.add(c2); entries.add(c1); assertSame(c3, entries.get(0)); Collections.sort(entries, new LogMessageComparator(LogMessageComparator.ASCENDING)); assertSame(c1, entries.get(0)); assertSame(c2, entries.get(1)); assertSame(c3, entries.get(2)); Collections.sort(entries, new LogMessageComparator(LogMessageComparator.DESCENDING)); assertSame(c1, entries.get(2)); assertSame(c2, entries.get(1)); assertSame(c3, entries.get(0)); try { new LogMessageComparator(6); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException iae) { } LogMessageComparator comparator = new LogMessageComparator(LogMessageComparator.ASCENDING); try { comparator.compare(null, null); fail("NullPointerException expected"); } catch (NullPointerException npe) { } }