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.api.web.gwt.client.webservices;
021    
022    import java.util.Date;
023    
024    import com.google.gwt.core.client.JavaScriptException;
025    import com.google.gwt.core.client.JavaScriptObject;
026    import com.google.gwt.http.client.URL;
027    import com.google.gwt.i18n.client.DateTimeFormat;
028    import com.google.gwt.json.client.JSONArray;
029    import com.google.gwt.json.client.JSONBoolean;
030    import com.google.gwt.json.client.JSONNumber;
031    import com.google.gwt.json.client.JSONObject;
032    import com.google.gwt.json.client.JSONString;
033    import com.google.gwt.json.client.JSONValue;
034    
035    public final class JsonUtils {
036      private static int requestId = 0;
037    
038      private JsonUtils() {
039    
040      }
041    
042      public interface JSONHandler {
043        void onResponse(JavaScriptObject obj);
044    
045        void onTimeout();
046    
047        void onError(int errorCode, String errorMessage);
048      }
049    
050      public static void requestJson(String url, JSONHandler handler) {
051        if (!url.endsWith("&") && !url.endsWith("?")) {
052          url += "&";
053        }
054        if (!url.contains("format=json")) {
055          url += "format=json&";
056        }
057        if (!url.contains("callback=")) {
058          //IMPORTANT : the url should ended with ?callback= or &callback= for JSONP calls
059          url += "callback=";
060        }
061        makeJSONRequest(requestId++, URL.encode(url), handler);
062      }
063    
064      public static native void makeJSONRequest(int requestId, String url, JSONHandler handler) /*-{
065          var callback = "callback" + requestId;
066    
067          // create SCRIPT tag, and set SRC attribute equal to JSON feed URL + callback function name
068          var script = document.createElement("script");
069          script.setAttribute("src", url+callback);
070          script.setAttribute("type", "text/javascript");
071    
072          window[callback] = function(jsonObj) {
073            @org.sonar.api.web.gwt.client.webservices.JsonUtils::dispatchJSON(Lcom/google/gwt/core/client/JavaScriptObject;Lorg/sonar/api/web/gwt/client/webservices/JsonUtils$JSONHandler;)(jsonObj, handler);
074            window[callback + "done"] = true;
075          }
076    
077          setTimeout(function() {
078            if (!window[callback + "done"]) {
079              handler.@org.sonar.api.web.gwt.client.webservices.JsonUtils.JSONHandler::onTimeout();
080            }
081    
082            // cleanup
083            document.body.removeChild(script);
084            if (window[callback]) {
085              delete window[callback];
086            }
087            if (window[callback + "done"]) {
088              delete window[callback + "done"];
089            }
090          }, 120000);
091    
092          document.body.appendChild(script);
093        }-*/;
094    
095      public static void dispatchJSON(JavaScriptObject jsonObj, JSONHandler handler) {
096        JSONObject obj = new JSONObject(jsonObj);
097        if (obj.isObject() != null) {
098          if (obj.containsKey("err_code")) {
099            handler.onError(new Double(obj.get("err_code").isNumber().doubleValue()).intValue(),
100                obj.get("err_msg").isString().stringValue());
101            return;
102          }
103        }
104        handler.onResponse(jsonObj);
105      }
106    
107      public static String getString(JSONObject json, String field) {
108        JSONValue jsonValue;
109        JSONString jsonString;
110        if ((jsonValue = json.get(field)) == null) {
111          return null;
112        }
113        if ((jsonString = jsonValue.isString()) == null) {
114          JSONNumber jsonNumber = jsonValue.isNumber();
115          return jsonNumber != null ? jsonNumber.toString() : null;
116        }
117        return jsonString.stringValue();
118      }
119      
120      public static Date getDate(JSONObject json, String field) {
121        DateTimeFormat frmt = DateTimeFormat.getFormat("yyyy-MM-dd'T'HH:mm:ssZ");
122        String date = getString(json, field);
123        if (date!=null && date.endsWith("Z") && date.length()>2) {
124          // see SONAR-1182
125          date = date.substring(0, date.length()-2) + "+00:00";
126        }
127        return frmt.parse(date);
128      }
129      
130      public static Boolean getBoolean(JSONObject json, String field) {
131        JSONValue jsonValue;
132        JSONBoolean jsonBoolean;
133        if ((jsonValue = json.get(field)) == null) {
134          return null;
135        }
136        if ((jsonBoolean = jsonValue.isBoolean()) == null) {
137          return null;
138        }
139        return jsonBoolean.booleanValue();
140      }
141    
142      public static Double getDouble(JSONObject json, String field) {
143        JSONValue jsonValue;
144        JSONNumber jsonNumber;
145        if ((jsonValue = json.get(field)) == null) {
146          return null;
147        }
148        if ((jsonNumber = jsonValue.isNumber()) == null) {
149          return null;
150        }
151        return jsonNumber.doubleValue();
152      }
153    
154      public static Integer getInteger(JSONObject json, String field) {
155        final Double d = getDouble(json, field);
156        if (d != null) {
157          return d.intValue();
158        }
159        return null;
160      }
161    
162      public static JSONObject getArray(JSONValue json, int i) {
163        if (json instanceof JSONArray) {
164          return ((JSONArray) json).get(i).isObject();
165        }
166        if (json instanceof JSONObject) {
167          return ((JSONObject) json).get(Integer.toString(i)).isObject();
168        }
169        throw new JavaScriptException("Not implemented");
170      }
171    
172      public static int getArraySize(JSONValue array) {
173        if (array instanceof JSONArray) {
174          return ((JSONArray) array).size();
175        }
176        if (array instanceof JSONObject) {
177          return ((JSONObject) array).size();
178        }
179        throw new JavaScriptException("Not implemented");
180      }
181    
182    }