001 /*
002 * Sonar, open source software quality management tool.
003 * Copyright (C) 2009 SonarSource SA
004 * mailto:contact AT sonarsource DOT com
005 *
006 * Sonar is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * Sonar is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public
017 * License along with Sonar; if not, write to the Free Software
018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
019 */
020 package org.sonar.wsclient.unmarshallers;
021
022 import java.text.ParseException;
023 import java.text.SimpleDateFormat;
024 import java.util.Date;
025 import java.util.Map;
026
027 public final class JsonUtils {
028
029 private JsonUtils() {
030 // only static methods
031 }
032
033 public static String getString(Map obj, String field) {
034 Object value = obj.get(field);
035 if (value != null) {
036 return (String) value;
037 }
038 return null;
039 }
040
041 public static Integer getInteger(Map obj, String field) {
042 Object value = obj.get(field);
043 if (value != null) {
044 return ((Long) value).intValue();
045 }
046 return null;
047 }
048
049 public static Boolean getBoolean(Map obj, String field) {
050 Object value = obj.get(field);
051 if (value != null) {
052 return (Boolean)value;
053 }
054 return null;
055 }
056
057 public static Long getLong(Map obj, String field) {
058 Object value = obj.get(field);
059 if (value != null) {
060 return (Long) value;
061 }
062 return null;
063 }
064
065 public static Double getDouble(Map obj, String field) {
066 Object value = obj.get(field);
067 if (value != null) {
068 return (Double) value;
069 }
070 return null;
071 }
072
073 public static Date getDateTime(Map obj, String field) {
074 return parseDate(obj, field, "yyyy-MM-dd'T'HH:mm:ssZ");
075 }
076
077 public static Date getDate(Map obj, String field) {
078 return parseDate(obj, field, "yyyy-MM-dd");
079 }
080
081 private static Date parseDate(Map obj, String field, String format) {
082 String value = getString(obj, field);
083 if (value != null) {
084 try {
085 SimpleDateFormat dateFormat = new SimpleDateFormat(format);
086 return dateFormat.parse(value);
087
088 } catch (ParseException e) {
089 throw new RuntimeException(e);
090 }
091 }
092 return null;
093 }
094 }