]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-3051 support POST, PUT and DELETE queries in GWT API.
authorSimon Brandhof <simon.brandhof@gmail.com>
Tue, 17 Jan 2012 14:54:01 +0000 (15:54 +0100)
committerSimon Brandhof <simon.brandhof@gmail.com>
Wed, 18 Jan 2012 16:22:26 +0000 (17:22 +0100)
This patch is gracefully provided by Eugene Zadyra.

sonar-gwt-api/src/main/java/org/sonar/gwt/JsonUtils.java
sonar-gwt-api/src/main/java/org/sonar/wsclient/gwt/AbstractSimpleCallback.java [new file with mode: 0644]
sonar-gwt-api/src/main/java/org/sonar/wsclient/gwt/SimpleCallback.java [new file with mode: 0644]
sonar-gwt-api/src/main/java/org/sonar/wsclient/gwt/Sonar.java

index ca64c74ca81c49dbd33810e118d30a70ee04cc3d..020209e3eaa66e8fe32e599316d87e8962fea216 100644 (file)
  * License along with Sonar; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
  */
+
 package org.sonar.gwt;
 
 import com.google.gwt.core.client.JavaScriptException;
 import com.google.gwt.core.client.JavaScriptObject;
-import com.google.gwt.http.client.URL;
+import com.google.gwt.http.client.*;
 import com.google.gwt.i18n.client.DateTimeFormat;
 import com.google.gwt.json.client.*;
+import org.sonar.wsclient.services.WSUtils;
 
 import java.util.Date;
 
@@ -34,70 +36,107 @@ public final class JsonUtils {
     // only static methods
   }
 
-  public interface JSONHandler {
-    void onResponse(JavaScriptObject obj);
+  public interface SimpleHandler extends Handler {
+    void onSuccess();
+  }
+
+  public interface JSONHandler extends Handler {
+    void onResponse(JavaScriptObject json);
+  }
 
+  public interface Handler {
     void onTimeout();
 
     void onError(int errorCode, String errorMessage);
   }
 
-  public static void requestJson(String url, JSONHandler handler) {
-    if (!url.endsWith("&") && !url.endsWith("?")) {
-      url += "&";
-    }
-    if (!url.contains("format=json")) {
-      url += "format=json&";
-    }
-    if (!url.contains("callback=")) {
-      // IMPORTANT : the url should ended with ?callback= or &callback= for JSONP calls
-      url += "callback=";
+  public static void request(String url, final SimpleHandler handler, RequestBuilder.Method method, String body) {
+    RequestBuilder requestBuilder = new RequestBuilder(method, URL.encode(formatURL(url)));
+    requestBuilder.setRequestData(body);
+    requestBuilder.setTimeoutMillis(120000);
+    requestBuilder.setCallback(new RequestCallback() {
+      public void onResponseReceived(Request request, Response response) {
+        if (!errorsHandled(response.getText(), handler)) {
+          handler.onSuccess();
+        }
+      }
+
+      public void onError(Request request, Throwable throwable) {
+        handler.onError(-1, throwable.getMessage());
+      }
+    });
+    try {
+      requestBuilder.send();
+    } catch (RequestException e) {
+      handler.onError(-1, e.getMessage());
     }
-    makeJSONRequest(requestId++, URL.encode(url), handler);
   }
 
-  public static native void makeJSONRequest(int requestId, String url, JSONHandler handler)
-  /*-{
-    var callback = "callback" + requestId;
+  public static void requestJson(String url, final JSONHandler handler, RequestBuilder.Method method, String body) {
+    RequestBuilder requestBuilder = new RequestBuilder(method, URL.encode(formatURL(url)));
+    requestBuilder.setRequestData(body);
+    requestBuilder.setCallback(new RequestCallback() {
+      public void onResponseReceived(Request request, Response response) {
+        if (!errorsHandled(response.getText(), handler)) {
+          dispatchJSON(response.getText(), handler);
+        }
+      }
+
+      public void onError(Request request, Throwable throwable) {
+        handler.onError(-1, throwable.getMessage());
+      }
+    });
+    requestBuilder.setTimeoutMillis(120000);
+    try {
+      requestBuilder.send();
+    } catch (RequestException e) {
+      handler.onError(-1, e.getMessage());
+    }
+  }
 
-    // create SCRIPT tag, and set SRC attribute equal to JSON feed URL + callback function name
-    var script = document.createElement("script");
-    script.setAttribute("src", url + callback);
-    script.setAttribute("type", "text/javascript");
+  public static void requestJson(String url, final JSONHandler handler) {
+    requestJson(url, handler, RequestBuilder.GET, null);
+  }
 
-    window[callback] = function(jsonObj) {
-      @org.sonar.gwt.JsonUtils::dispatchJSON(Lcom/google/gwt/core/client/JavaScriptObject;Lorg/sonar/gwt/JsonUtils$JSONHandler;)(jsonObj, handler);
-      window[callback + "done"] = true;
+  private static JavaScriptObject parseJSON(String json) {
+    JSONValue value = JSONParser.parse(json);
+    if (value.isObject() != null) {
+      return value.isObject().getJavaScriptObject();
     }
+    return value.isArray().getJavaScriptObject();
+  }
 
-    setTimeout(function() {
-      if (!window[callback + "done"]) {
-        handler.@org.sonar.gwt.JsonUtils.JSONHandler::onTimeout();
-      }
+  private static String formatURL(String url) {
+    if (!url.endsWith("&") && !url.endsWith("?")) {
+      url += "&";
+    }
+    if (!url.contains("format=json")) {
+      url += "format=json&";
+    }
+    return url;
+  }
 
-      // cleanup
-      document.body.removeChild(script);
-      if (window[callback]) {
-        delete window[callback];
-      }
-      if (window[callback + "done"]) {
-        delete window[callback + "done"];
-      }
-    }, 120000);
-
-    document.body.appendChild(script);
-  }-*/;
-
-  public static void dispatchJSON(JavaScriptObject jsonObj, JSONHandler handler) {
-    JSONObject obj = new JSONObject(jsonObj);
-    if (obj.isObject() != null) {
-      if (obj.containsKey("err_code")) {
-        handler.onError(new Double(obj.get("err_code").isNumber().doubleValue()).intValue(),
-            obj.get("err_msg").isString().stringValue());
-        return;
+  public static native void log(String str)
+    /*-{
+      console.log(str);
+    }-*/;
+
+  private static boolean errorsHandled(String text, Handler handler) {
+    if (text != null && !text.matches("^.*$")) {
+      JSONObject obj = new JSONObject(parseJSON(text));
+      if (obj.isObject() != null) {
+        if (obj.containsKey("err_code")) {
+          handler.onError(new Double(obj.get("err_code").isNumber().doubleValue()).intValue(),
+              obj.get("err_msg").isString().stringValue());
+          return true;
+        }
       }
     }
-    handler.onResponse(jsonObj);
+    return false;
+  }
+
+  public static void dispatchJSON(String text, JSONHandler handler) {
+    handler.onResponse(parseJSON(text));
   }
 
   public static String getString(JSONObject json, String field) {
diff --git a/sonar-gwt-api/src/main/java/org/sonar/wsclient/gwt/AbstractSimpleCallback.java b/sonar-gwt-api/src/main/java/org/sonar/wsclient/gwt/AbstractSimpleCallback.java
new file mode 100644 (file)
index 0000000..74bbd79
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2012 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
+ */
+package org.sonar.wsclient.gwt;
+
+import com.google.gwt.user.client.ui.Widget;
+
+public abstract class AbstractSimpleCallback implements SimpleCallback {
+
+  private Widget loadingWidget = null;
+
+  protected AbstractSimpleCallback(Widget loadingWidget) {
+    this.loadingWidget = loadingWidget;
+  }
+
+  protected AbstractSimpleCallback() {
+  }
+
+  public void onSuccess() {
+    hideLoadingWidget();
+    doOnSuccess();
+  }
+
+  protected abstract void doOnSuccess();
+
+  public final void onTimeout() {
+    doOnTimeout();
+    hideLoadingWidget();
+  }
+
+  public final void onError(int errorCode, String errorMessage) {
+    doOnError(errorCode, errorMessage);
+    hideLoadingWidget();
+  }
+
+  protected void doOnError(int errorCode, String errorMessage) {
+
+  }
+
+  protected void doOnTimeout() {
+
+  }
+
+  private void hideLoadingWidget() {
+    if (loadingWidget != null) {
+      loadingWidget.removeFromParent();
+    }
+  }
+}
diff --git a/sonar-gwt-api/src/main/java/org/sonar/wsclient/gwt/SimpleCallback.java b/sonar-gwt-api/src/main/java/org/sonar/wsclient/gwt/SimpleCallback.java
new file mode 100644 (file)
index 0000000..abb6e88
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2012 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
+ */
+package org.sonar.wsclient.gwt;
+
+public interface SimpleCallback {
+  void onSuccess();
+
+  void onTimeout();
+
+  void onError(int errorCode, String errorMessage);
+}
index ee439203d2d93f91371e9b0da30a73ff3e8caede..046a4a6b91ecd0063e0e5dd13f8b1c9aecc6f4c7 100644 (file)
  * License along with Sonar; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
  */
+
 package org.sonar.wsclient.gwt;
 
 import com.google.gwt.core.client.JavaScriptObject;
+import com.google.gwt.http.client.RequestBuilder;
 import com.google.gwt.i18n.client.Dictionary;
 import com.google.gwt.json.client.JSONObject;
 import org.sonar.gwt.JsonUtils;
-import org.sonar.wsclient.services.Model;
-import org.sonar.wsclient.services.Query;
-import org.sonar.wsclient.services.WSUtils;
+import org.sonar.wsclient.services.*;
 import org.sonar.wsclient.unmarshallers.Unmarshaller;
 import org.sonar.wsclient.unmarshallers.Unmarshallers;
 
@@ -89,7 +89,35 @@ public class Sonar {
     });
   }
 
-  private String getUrl(Query query) {
+  public void delete(final DeleteQuery query, final SimpleCallback callback) {
+    createUpdate(query, callback, RequestBuilder.DELETE);
+  }
+
+  public <MODEL extends Model> void create(final CreateQuery<MODEL> query, final SimpleCallback callback) {
+    createUpdate(query, callback, RequestBuilder.POST);
+  }
+
+  public <MODEL extends Model> void update(final UpdateQuery<MODEL> query, final SimpleCallback callback) {
+    createUpdate(query, callback, RequestBuilder.PUT);
+  }
+
+  private void createUpdate(final AbstractQuery query, final SimpleCallback callback, RequestBuilder.Method method) {
+    JsonUtils.request(getUrl(query), new JsonUtils.SimpleHandler() {
+      public void onSuccess() {
+        callback.onSuccess();
+      }
+
+      public void onTimeout() {
+        callback.onTimeout();
+      }
+
+      public void onError(int errorCode, String errorMessage) {
+        callback.onError(errorCode, errorMessage);
+      }
+    }, method, query.getBody());
+  }
+
+  private String getUrl(AbstractQuery query) {
     return host + query.getUrl();
   }
 }