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