1 package org.apache.velocity.site.news;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.text.DateFormat;
23 import java.text.ParseException;
24 import java.text.SimpleDateFormat;
25 import java.util.ArrayList;
26 import java.util.Collections;
27 import java.util.Comparator;
28 import java.util.Date;
29 import java.util.List;
30
31 import org.apache.velocity.site.news.model.Item;
32
33
34
35
36
37
38
39
40 public abstract class VelocityNewsUtils
41 {
42
43 private static final DateFormat itemDateFormat = new SimpleDateFormat("yyyy-MM-dd");
44
45 private VelocityNewsUtils()
46 {
47 }
48
49 public static final List sortItemsByReverseDate(final List items)
50 {
51 List result = new ArrayList(items);
52 Collections.sort(result, new Comparator()
53 {
54 public int compare(final Object o1, final Object o2)
55 {
56 Item i1 = (Item) o1;
57 Item i2 = (Item) o2;
58
59 if (i1 == null)
60 {
61 return (i2 == null) ? 0 : -1;
62 }
63
64 if (i2 == null)
65 {
66 return 1;
67 }
68
69 Date d1 = null;
70 Date d2 = null;
71 try
72 {
73 d1 = VelocityNewsUtils.parseItemDate(i1.getDate());
74 d2 = VelocityNewsUtils.parseItemDate(i2.getDate());
75 }
76 catch (VelocityNewsException mee)
77 {
78 throw new ClassCastException("While parsing date:" + mee.getMessage());
79 }
80
81 if (d1 == null)
82 {
83 return (d2 == null) ? 0 : -1;
84 }
85
86 if (d2 == null)
87 {
88 return 1;
89 }
90
91 return -(d1.compareTo(d2));
92 }
93 });
94 return result;
95 }
96
97 public static final Date parseItemDate(final String dateString) throws VelocityNewsException
98 {
99 Date date = null;
100 try
101 {
102 date = itemDateFormat.parse(dateString);
103 }
104 catch (ParseException pe)
105 {
106 throw new VelocityNewsException(dateString + " is not a valid yyyy-MM-dd date!");
107 }
108 return date;
109 }
110 }