001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *      http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.oozie.util;
020
021import com.google.common.annotations.VisibleForTesting;
022import java.sql.Timestamp;
023import java.text.DateFormat;
024import java.text.ParseException;
025import java.text.ParsePosition;
026import java.text.SimpleDateFormat;
027import java.util.Calendar;
028import java.util.Date;
029import java.util.GregorianCalendar;
030import java.util.TimeZone;
031import java.util.regex.Matcher;
032import java.util.regex.Pattern;
033import org.apache.hadoop.conf.Configuration;
034import org.apache.oozie.coord.TimeUnit;
035import org.apache.oozie.service.ConfigurationService;
036
037/**
038 * Date utility classes to parse and format datetimes in Oozie expected datetime formats.
039 */
040public class DateUtils {
041    private static final XLog LOG = XLog.getLog(DateUtils.class);
042    private static final Pattern GMT_OFFSET_COLON_PATTERN = Pattern.compile("^GMT(\\-|\\+)(\\d{2})(\\d{2})$");
043    private static final Pattern THREE_LETTER_ID_PATTERN = Pattern.compile("[A-Z]{3}");
044    public static final TimeZone UTC = getTimeZone("UTC");
045
046    public static final String ISO8601_UTC_MASK = "yyyy-MM-dd'T'HH:mm'Z'";
047    private static final String ISO8601_TZ_MASK_WITHOUT_OFFSET = "yyyy-MM-dd'T'HH:mm";
048
049    private static String ACTIVE_MASK = ISO8601_UTC_MASK;
050    private static TimeZone ACTIVE_TIMEZONE = UTC;
051
052    public static final String OOZIE_PROCESSING_TIMEZONE_KEY = "oozie.processing.timezone";
053
054    public static final String OOZIE_PROCESSING_TIMEZONE_DEFAULT = "UTC";
055
056    private static boolean OOZIE_IN_UTC = true;
057
058    private static final Pattern VALID_TIMEZONE_PATTERN = Pattern.compile("^UTC$|^GMT(\\+|\\-)\\d{4}$");
059
060    /**
061     * Configures the Datetime parsing with Oozie processing timezone.
062     * <p>
063     * The {@link #OOZIE_PROCESSING_TIMEZONE_KEY} property is read and set as the Oozie processing timezone.
064     * Valid values for this property are <code>UTC</code> and <code>GMT(+/-)####</code>
065     *
066     * @param conf Oozie server configuration.
067     */
068    public static void setConf(Configuration conf) {
069        String tz = ConfigurationService.get(conf, OOZIE_PROCESSING_TIMEZONE_KEY);
070        if (!VALID_TIMEZONE_PATTERN.matcher(tz).matches()) {
071            throw new RuntimeException("Invalid Oozie timezone, it must be 'UTC' or 'GMT(+/-)####");
072        }
073        ACTIVE_TIMEZONE = TimeZone.getTimeZone(tz);
074        OOZIE_IN_UTC = ACTIVE_TIMEZONE.equals(UTC);
075        ACTIVE_MASK = (OOZIE_IN_UTC) ? ISO8601_UTC_MASK : ISO8601_TZ_MASK_WITHOUT_OFFSET + tz.substring(3);
076    }
077
078    /**
079     * Returns Oozie processing timezone.
080     *
081     * @return Oozie processing timezone. The returned timezone is <code>UTC</code> or a <code>GMT(+/-)####</code>
082     * timezone.
083     */
084    public static TimeZone getOozieProcessingTimeZone() {
085        return ACTIVE_TIMEZONE;
086    }
087
088    /**
089     * Returns Oozie processing datetime mask.
090     * <p>
091     * This mask is an ISO8601 datetime mask for the Oozie processing timezone.
092     *
093     * @return  Oozie processing datetime mask.
094     */
095    public static String getOozieTimeMask() {
096        return ACTIVE_MASK;
097    }
098
099    private static DateFormat getISO8601DateFormat(TimeZone tz, String mask) {
100        DateFormat dateFormat = new SimpleDateFormat(mask);
101        // Stricter parsing to prevent dates such as 2011-12-50T01:00Z (December 50th) from matching
102        dateFormat.setLenient(false);
103        dateFormat.setTimeZone(tz);
104        return dateFormat;
105    }
106
107    private static DateFormat getSpecificDateFormat(String format) {
108        DateFormat dateFormat = new SimpleDateFormat(format);
109        dateFormat.setTimeZone(ACTIVE_TIMEZONE);
110        return dateFormat;
111    }
112
113    /**
114     * {@link TimeZone#getTimeZone(java.lang.String)} takes the timezone ID as an argument; for invalid IDs it returns the
115     * <code>GMT</code> TimeZone.  A timezone ID formatted like <code>GMT-####</code> is not a valid ID, however, it will actually
116     * map this to the <code>GMT-##:##</code> TimeZone, instead of returning the <code>GMT</code> TimeZone.  We check (later)
117     * check that a timezone ID is valid by calling {@link TimeZone#getTimeZone(java.lang.String)} and seeing if the returned
118     * TimeZone ID is equal to the original; because we want to allow <code>GMT-####</code>, while still disallowing actual
119     * invalid IDs, we have to manually replace <code>GMT-####</code> with <code>GMT-##:##</code> first.
120     *
121     * @param tzId The timezone ID
122     * @return If tzId matches <code>GMT-####</code>, then we return <code>GMT-##:##</code>; otherwise, we return tzId unaltered
123     */
124    private static String handleGMTOffsetTZNames(String tzId) {
125        Matcher m = GMT_OFFSET_COLON_PATTERN.matcher(tzId);
126        if (m.matches() && m.groupCount() == 3) {
127            tzId = "GMT" + m.group(1) + m.group(2) + ":" + m.group(3);
128        }
129        return tzId;
130    }
131
132    /**
133     * Returns the {@link TimeZone} for the given timezone ID.
134     *
135     * @param tzId timezone ID.
136     * @return  the {@link TimeZone} for the given timezone ID.
137     */
138    public static TimeZone getTimeZone(String tzId) {
139        if (tzId == null) {
140            throw new IllegalArgumentException("Invalid TimeZone: " + tzId);
141        }
142        tzId = handleGMTOffsetTZNames(tzId);    // account for GMT-####
143        TimeZone tz = TimeZone.getTimeZone(tzId);
144
145        // Check whether tzID can handle DST shifts
146        if (!isThreeLetterTZName(tzId)) {
147            LOG.warn("GMT, UTC or Region/City Timezone formats are preferred instead of " + tzId);
148        }
149
150        // If these are not equal, it means that the tzId is not valid (invalid tzId's return GMT)
151        if (!tz.getID().equals(tzId)) {
152            throw new IllegalArgumentException("Invalid TimeZone: " + tzId);
153        }
154        return tz;
155    }
156
157    /**
158     * Check whether 3-letter timezone ID is in preferred format,
159     * UTC, GMT or Region/City, the other three-letter codes may not handle
160     * DST shifts properly.
161     * @param tzId
162     * @return true if format is not appropriate for DST shift
163     */
164    @VisibleForTesting
165    static boolean isThreeLetterTZName(String tzId) {
166        Matcher m = THREE_LETTER_ID_PATTERN.matcher(tzId);
167        return m.matches() && !tzId.equalsIgnoreCase("UTC") && !tzId.equalsIgnoreCase("GMT");
168    }
169
170    /**
171     * Parses a datetime in ISO8601 format in UTC timezone
172     *
173     * @param s string with the datetime to parse.
174     * @return the corresponding {@link Date} instance for the parsed date.
175     * @throws ParseException thrown if the given string was not an ISO8601 UTC value.
176     */
177    public static Date parseDateUTC(String s) throws ParseException {
178        return getISO8601DateFormat(UTC, ISO8601_UTC_MASK).parse(s);
179    }
180
181    /**
182     * Parses a datetime in ISO8601 format in the Oozie processing timezone.
183     *
184     * @param s string with the datetime to parse.
185     * @return the corresponding {@link Date} instance for the parsed date.
186     * @throws ParseException thrown if the given string was not an ISO8601 value for the Oozie processing timezon.
187     */
188    public static Date parseDateOozieTZ(String s) throws ParseException {
189        s = s.trim();
190        ParsePosition pos = new ParsePosition(0);
191        Date d = getISO8601DateFormat(ACTIVE_TIMEZONE, ACTIVE_MASK).parse(s, pos);
192        if (d == null) {
193            throw new ParseException("Could not parse [" + s + "] using [" + ACTIVE_MASK + "] mask",
194                                     pos.getErrorIndex());
195        }
196        if (d != null && s.length() > pos.getIndex()) {
197            throw new ParseException("Correct datetime string is followed by invalid characters: " + s, pos.getIndex());
198        }
199        return d;
200    }
201
202    /**
203     * Formats a {@link Date} as a string in ISO8601 format using Oozie processing timezone.
204     *
205     * @param d {@link Date} to format.
206     * @return the ISO8601 string for the given date, <code>NULL</code> if the {@link Date} instance was
207     * <code>NULL</code>
208     */
209    public static String formatDateOozieTZ(Date d) {
210        return (d != null) ? getISO8601DateFormat(ACTIVE_TIMEZONE, ACTIVE_MASK).format(d) : "NULL";
211    }
212
213    /**
214     * Formats a {@link Date} as a string using the specified format mask.
215     * <p>
216     * The format mask must be a {@link SimpleDateFormat} valid format mask.
217     *
218     * @param d {@link Date} to format.
219     * @param format the {@link SimpleDateFormat} format mask to use
220     * @return the string for the given date using the specified format mask,
221     * <code>NULL</code> if the {@link Date} instance was <code>NULL</code>
222     */
223    public static String formatDateCustom(Date d, String format) {
224        return (d != null) ? getSpecificDateFormat(format).format(d) : "NULL";
225    }
226
227    /**
228     * Formats a {@link Date} as a string containing the seconds (or millis) since the Unix epoch (Jan 1, 1970).
229     * <p>
230     * The format mask must be a {@link SimpleDateFormat} valid format mask
231     *
232     * @param d {@link Date} to format.
233     * @param millis true to include milliseconds
234     * @return the number of seconds or millis between the given date and Jan 1, 1970,
235     * <code>NULL</code> if the {@link Date} instance was <code>NULL</code>
236     */
237    public static String formatDateEpoch(Date d, Boolean millis) {
238        if (d == null) {
239            return "NULL";
240        } else {
241            return Long.toString(millis ? d.getTime() : d.getTime() / 1000);
242        }
243    }
244
245    /**
246     * Formats a {@link Calendar} as a string in ISO8601 format using Oozie processing timezone.
247     *
248     * @param c {@link Calendar} to format.
249     * @return the ISO8601 string for the given date, <code>NULL</code> if the {@link Calendar} instance was
250     * <code>NULL</code>
251     */
252    public static String formatDateOozieTZ(Calendar c) {
253        return (c != null) ? formatDateOozieTZ(c.getTime()) : "NULL";
254    }
255
256    /**
257     * Formats a {@link Calendar} as a string in ISO8601 format without adjusting its timezone.  However, the mask will still
258     * ensure that the returned date is in the Oozie processing timezone.
259     *
260     * @param c {@link Calendar} to format.
261     * @return the ISO8601 string for the given date, <code>NULL</code> if the {@link Calendar} instance was
262     * <code>NULL</code>
263     */
264    public static String formatDate(Calendar c) {
265        return (c != null) ? getISO8601DateFormat(c.getTimeZone(), ACTIVE_MASK).format(c.getTime()) : "NULL";
266    }
267
268    /**
269     * This function returns number of hour in a day when given a Calendar with appropriate TZ. It consider DST to find
270     * the number of hours. Generally it is 24. At some tZ, in one day of a year it is 23 and another day it is 25
271     *
272     * @param cal The date for which the number of hours is requested
273     * @return number of hour in that day.
274     */
275    public static int hoursInDay(Calendar cal) {
276        Calendar localCal = new GregorianCalendar(cal.getTimeZone());
277        localCal.set(Calendar.MILLISECOND, 0);
278        localCal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 30, 0);
279        localCal.add(Calendar.HOUR_OF_DAY, 24);
280        switch (localCal.get(Calendar.HOUR_OF_DAY)) {
281            case 1:
282                return 23;
283            case 23:
284                return 25;
285            default: // Case 0
286                return 24;
287        }
288    }
289
290    /**
291     * Determine whether a specific date is on DST change day
292     *
293     * @param cal Date to know if it is DST change day. Appropriate TZ is specified
294     * @return true , if it DST change date otherwise false
295     */
296    public static boolean isDSTChangeDay(Calendar cal) {
297        return hoursInDay(cal) != 24;
298    }
299
300    /**
301     * Move the any date-time to the end of the duration. If endOfFlag == day, move the date to the end of day (24:00 on
302     * the same day or 00:00 on the next day) If endOf Flag = month. move the date to then end of current month
303     * Otherwise do nothing
304     *
305     * @param cal : Date-time needs to be moved to the end
306     * @param endOfFlag : day (for end of day) or month (for end of month) or empty
307     */
308    public static void moveToEnd(Calendar cal, TimeUnit endOfFlag) {
309        // TODO: Both logic needs to be checked
310        if (endOfFlag == TimeUnit.END_OF_DAY) { // 24:00:00
311            cal.add(Calendar.DAY_OF_MONTH, 1);
312            // cal.set(Calendar.HOUR_OF_DAY, cal
313            // .getActualMaximum(Calendar.HOUR_OF_DAY) + 1);// TODO:
314            cal.set(Calendar.HOUR_OF_DAY, 0);
315            cal.set(Calendar.MINUTE, 0);
316            cal.set(Calendar.SECOND, 0);
317        }
318        else if (endOfFlag == TimeUnit.END_OF_MONTH) {
319            cal.add(Calendar.MONTH, 1);
320            cal.set(Calendar.DAY_OF_MONTH, 1);
321            cal.set(Calendar.HOUR_OF_DAY, 0);
322            cal.set(Calendar.MINUTE, 0);
323            cal.set(Calendar.SECOND, 0);
324        }
325        else if (endOfFlag == TimeUnit.END_OF_WEEK) {
326            cal.add(Calendar.WEEK_OF_YEAR, 1);
327            cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
328            cal.set(Calendar.HOUR_OF_DAY, 0);
329            cal.set(Calendar.MINUTE, 0);
330            cal.set(Calendar.SECOND, 0);
331        }
332    }
333
334    /**
335     * Create a Calendar instance using the specified date and Time zone
336     * @param dateString the date
337     * @param tz : TimeZone
338     * @return appropriate Calendar object
339     * @throws Exception if the date can't be parsed
340     */
341    public static Calendar getCalendar(String dateString, TimeZone tz) throws Exception {
342        Date date = DateUtils.parseDateOozieTZ(dateString);
343        Calendar calDate = Calendar.getInstance();
344        calDate.setTime(date);
345        calDate.setTimeZone(tz);
346        return calDate;
347    }
348
349    /**
350     * Create a Calendar instance for UTC time zone using the specified date.
351     * @param dateString the date
352     * @return appropriate Calendar object
353     * @throws Exception if the date can't be parsed
354     */
355    public static Calendar getCalendar(String dateString) throws Exception {
356        return getCalendar(dateString, ACTIVE_TIMEZONE);
357    }
358
359    /**
360     * Convert java.sql.Timestamp to java.util.Date
361     *
362     * @param timestamp java.sql.Timestamp
363     * @return java.util.Date
364     */
365    public static java.util.Date toDate(java.sql.Timestamp timestamp) {
366        if (timestamp != null) {
367            long milliseconds = timestamp.getTime();
368            return new java.util.Date(milliseconds);
369        }
370        return null;
371    }
372
373    /**
374     * Convert java.util.Date to java.sql.Timestamp
375     *
376     * @param d java.util.Date
377     * @return java.sql.Timestamp
378     */
379    public static Timestamp convertDateToTimestamp(Date d) {
380        if (d != null) {
381            return new Timestamp(d.getTime());
382        }
383        return null;
384    }
385
386}