DateAdjuster.java
3.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* org.apache.sling.commons.json.JSONException
* org.apache.sling.commons.json.JSONObject
*/
package com.day.cq.analytics.sitecatalyst.impl.util;
import com.day.cq.analytics.sitecatalyst.util.RelativeDateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
public class DateAdjuster {
private static final String DEFAULT_FORMAT_PATTERN = "yyyy-MM-dd";
private DateAdjuster() {
}
public static JSONObject adjustDates(JSONObject reportDescription) throws JSONException, ParseException {
if (reportDescription.has("date")) {
DateAdjuster.adjustOneDate(reportDescription, "date", "datePattern");
}
if (reportDescription.has("dateFrom")) {
DateAdjuster.adjustOneDate(reportDescription, "dateFrom", "dateFromPattern");
}
if (reportDescription.has("dateTo")) {
DateAdjuster.adjustOneDate(reportDescription, "dateTo", "dateToPattern");
}
DateAdjuster.checkDates(reportDescription);
return reportDescription;
}
static void adjustOneDate(JSONObject reportDescription, String dateKey, String patternKey) throws ParseException, JSONException {
String formatPattern = "yyyy-MM-dd";
String date = reportDescription.getString(dateKey);
if (reportDescription.has(patternKey)) {
formatPattern = reportDescription.optString(patternKey);
reportDescription.remove(patternKey);
}
Date newDate = null;
RelativeDateFormat format = new RelativeDateFormat(formatPattern);
if (date.equalsIgnoreCase("thisYear")) {
Calendar cal = Calendar.getInstance();
if (dateKey.equalsIgnoreCase("dateFrom")) {
cal.set(6, 1);
}
newDate = cal.getTime();
} else if (date.equalsIgnoreCase("lastYear")) {
Calendar cal = Calendar.getInstance();
cal.add(1, -1);
if (dateKey.equalsIgnoreCase("dateFrom")) {
cal.set(6, 1);
} else {
cal.set(2, 11);
cal.set(5, 31);
}
newDate = cal.getTime();
} else {
newDate = format.parseRelative(date);
}
reportDescription.put(dateKey, (Object)format.format(newDate));
}
static void checkDates(JSONObject reportDescription) throws ParseException, JSONException {
Date to;
Date from;
SimpleDateFormat format;
if (reportDescription.has("dateFrom") && reportDescription.has("dateTo") && !(from = (format = new SimpleDateFormat("yyyy-MM-dd")).parse(reportDescription.optString("dateFrom"))).before(to = format.parse(reportDescription.optString("dateTo")))) {
throw new JSONException("Illegal daterange in report description, 'dateFrom' is after 'dateTo'.");
}
}
}