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.client.rest; 020 021import java.text.ParseException; 022import java.text.SimpleDateFormat; 023import java.util.ArrayList; 024import java.util.Date; 025import java.util.List; 026import java.util.Locale; 027import java.util.TimeZone; 028 029import org.json.simple.JSONArray; 030import org.json.simple.JSONObject; 031 032 033/** 034 * Json utils methods. 035 */ 036public class JsonUtils { 037 038 /* 039 * GMT is the most commonly used timezone; we can save on parsing and 040 * creating a TimeZone by creating a GMT TimeZone once 041 */ 042 private static TimeZone GMT_TZ = TimeZone.getTimeZone("GMT"); 043 /** 044 * Format a Date in RFC822 with the given time zone. 045 * 046 * @param date date to format. 047 * @param timeZoneId the time zone to use 048 * @return RFC822 for the date, <code>null</code> if the date was <code>null</code>. 049 */ 050 public static String formatDateRfc822(Date date, String timeZoneId) { 051 if (date != null) { 052 TimeZone tZone = "GMT".equals(timeZoneId) ? GMT_TZ : TimeZone.getTimeZone(timeZoneId); 053 SimpleDateFormat dateFormater = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); 054 dateFormater.setTimeZone(tZone); 055 return dateFormater.format(date); 056 } 057 return null; 058 } 059 060 /** 061 * Format a Date in RFC822 GMT. 062 * 063 * @param date date to format. 064 * @return RFC822 GMT for the date, <code>null</code> if the date was <code>null</code>. 065 */ 066 public static String formatDateRfc822(Date date) { 067 return formatDateRfc822(date, "GMT"); 068 } 069 070 /** 071 * Parse a string in RFC822 GMT format. 072 * 073 * @param str string to parse. 074 * @return parsed date, <code>null</code> if the string was <code>null</code> or in an invalid format. 075 */ 076 static Date parseDateRfc822(String str) { 077 if (str != null) { 078 try { 079 SimpleDateFormat dateFormater = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US); 080 dateFormater.setTimeZone(GMT_TZ); 081 return dateFormater.parse(str); 082 } 083 catch (ParseException ex) { 084 return null; 085 } 086 } 087 return null; 088 } 089 090}