From 8791f8bdfced127ee3222ecf8aafd76bee5c3642 Mon Sep 17 00:00:00 2001 From: Manolo Carrasco Date: Wed, 21 Sep 2011 21:03:20 +0000 Subject: [PATCH] Adding Ajax abilities to Gquery, as a easy way to get and handle data from non gwt servers. Added a generator to convert JSON objects to java builders/pojos --- .../java/com/google/gwt/query/Query.gwt.xml | 5 + .../java/com/google/gwt/query/client/GQ.java | 6 +- .../com/google/gwt/query/client/GQuery.java | 2 - .../google/gwt/query/client/Properties.java | 36 +-- .../query/client/builders/JsonBuilder.java | 45 ++++ .../client/builders/JsonBuilderBase.java | 84 +++++++ .../gwt/query/client/builders/JsonName.java | 29 +++ .../google/gwt/query/client/js/JsCache.java | 22 +- .../google/gwt/query/client/js/JsUtils.java | 7 +- .../gwt/query/client/plugins/ajax/Ajax.java | 209 ++++++++++++++++++ .../query/client/plugins/ajax/AjaxImpl.java | 174 --------------- .../gwt/query/client/GQueryAjaxTest.java | 83 +++++++ 12 files changed, 503 insertions(+), 199 deletions(-) create mode 100644 gwtquery-core/src/main/java/com/google/gwt/query/client/builders/JsonBuilder.java create mode 100644 gwtquery-core/src/main/java/com/google/gwt/query/client/builders/JsonBuilderBase.java create mode 100644 gwtquery-core/src/main/java/com/google/gwt/query/client/builders/JsonName.java create mode 100644 gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/ajax/Ajax.java delete mode 100644 gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/ajax/AjaxImpl.java create mode 100644 gwtquery-core/src/test/java/com/google/gwt/query/client/GQueryAjaxTest.java diff --git a/gwtquery-core/src/main/java/com/google/gwt/query/Query.gwt.xml b/gwtquery-core/src/main/java/com/google/gwt/query/Query.gwt.xml index bf096c37..f451c033 100644 --- a/gwtquery-core/src/main/java/com/google/gwt/query/Query.gwt.xml +++ b/gwtquery-core/src/main/java/com/google/gwt/query/Query.gwt.xml @@ -17,6 +17,11 @@ + + + + + diff --git a/gwtquery-core/src/main/java/com/google/gwt/query/client/GQ.java b/gwtquery-core/src/main/java/com/google/gwt/query/client/GQ.java index 1932df40..a970fefc 100644 --- a/gwtquery-core/src/main/java/com/google/gwt/query/client/GQ.java +++ b/gwtquery-core/src/main/java/com/google/gwt/query/client/GQ.java @@ -5,7 +5,7 @@ import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArrayMixed; -import com.google.gwt.query.client.plugins.ajax.AjaxImpl; +import com.google.gwt.query.client.plugins.ajax.Ajax; import com.google.gwt.dom.client.Element; /** @@ -54,12 +54,12 @@ public abstract class GQ extends GQuery { ajax(null, onSuccess, onError, settings); } - private static AjaxImpl ajaxImpl; + private static Ajax ajaxImpl; public static void ajax(String url, Function onSuccess, Function onError, Properties settings) { if (ajaxImpl == null) { - ajaxImpl = GWT.create(AjaxImpl.class); + ajaxImpl = GWT.create(Ajax.class); } ajaxImpl.ajax(url, onSuccess, onError, settings); } diff --git a/gwtquery-core/src/main/java/com/google/gwt/query/client/GQuery.java b/gwtquery-core/src/main/java/com/google/gwt/query/client/GQuery.java index bd7c218c..b871db88 100644 --- a/gwtquery-core/src/main/java/com/google/gwt/query/client/GQuery.java +++ b/gwtquery-core/src/main/java/com/google/gwt/query/client/GQuery.java @@ -1450,9 +1450,7 @@ public class GQuery implements Lazy { * Stores the value in the named spot with desired return type. */ public GQuery data(String name, Object value) { -// System.out.println("DDD " + size() + " " + elements().length + " " + name + " " + value); for (Element e : elements()) { -// System.out.println("DATAT ....."); data(e, name, value); } return this; diff --git a/gwtquery-core/src/main/java/com/google/gwt/query/client/Properties.java b/gwtquery-core/src/main/java/com/google/gwt/query/client/Properties.java index b9c62e0f..3aefed30 100644 --- a/gwtquery-core/src/main/java/com/google/gwt/query/client/Properties.java +++ b/gwtquery-core/src/main/java/com/google/gwt/query/client/Properties.java @@ -32,7 +32,7 @@ public class Properties extends JavaScriptObject { if (properties != null && !properties.isEmpty()) { String p = wrapPropertiesString(properties); try { - return createImpl(p); + return createImpl("({" + p + "})"); } catch (Exception e) { System.err.println("Error creating Properties: \n> " + properties + "\n< " + p + "\n" + e.getMessage()); } @@ -45,19 +45,19 @@ public class Properties extends JavaScriptObject { }-*/; public static String wrapPropertiesString(String s) { - String ret = "({" + s // + String ret = s // .replaceAll("\\s*/\\*[\\s\\S]*?\\*/\\s*", "") // Remove comments .replaceAll("([:\\)\\(,;}{'\"])\\s+" , "$1") // Remove spaces .replaceAll("\\s+([:\\)\\(,;}{'\"])" , "$1") // Remove spaces .replaceFirst("^[{\\(]+(|.*[^}\\)])[}\\)]+$", "$1") // Remove ({}) - .replaceAll("\\('([^\\)]+)'\\)" , "($1)") // Remove quotes + .replaceAll("\\(\"([^\\)]+)\"\\)" , "($1)") // Remove quotes .replaceAll(",+([\\w-]+:+)" , ";$1") // put semicolon - .replaceAll(":\\s*[\"']?([^'\\]};]*)[\"']?\\s*(;+|$)", ":'$1',") // put quotes to values + .replaceAll(":\\s*[\"']?([^'\"\\]};]*)[\"']?\\s*(;+|$)", ":\"$1\",") // put quotes to all values (even empty) + .replaceAll("(^|[^\\w-$'])([\\w-]+):\"", "$1\"$2\":\"") // quote keys .replaceAll(";([^:]+):", ",$1:") // change semicolon - .replaceAll(":'(-?[\\d\\.]+|null|false|true)',", ":$1,") // numbers do not need quote - .replaceAll("(^|[^\\w-'])([\\w]+[-][\\w-]+):", "$1'$2':") // quote keys with illegal chars - .replaceFirst("[;,]$", "") // remove endings - + "})"; + .replaceAll(":\"(-?[\\d\\.]+|null|false|true)\",", ":$1,") // numbers do not need quote + .replaceFirst("[,]+$", "") // remove endings + ; return ret; } @@ -130,32 +130,32 @@ public class Properties extends JavaScriptObject { } public final String tostring() { - return "(" + toJsonString() + ")"; + return toJsonString(); } public final String toJsonString() { String ret = ""; for (String k : keys()){ + String ky = k.matches("\\d+") ? k : "\"" + k + "\""; JsArrayMixed o = getArray(k); if (o != null) { - ret += k + ":["; + ret += ky + ":["; for (int i = 0, l = o.length(); i < l ; i++) { - ret += "'" + o.getString(i) + "',"; + ret += "\"" + o.getString(i) + "\","; } ret += "],"; } else { Properties p = getJavaScriptObject(k); if (p != null) { - ret += k + ":" + p.toJsonString() + ","; + ret += ky + ":" + p.toJsonString() + ","; } else { - ret += k + ":'" + getStr(k) + "',"; + ret += ky + ":\"" + getStr(k) + "\","; } } } - return "{" + ret.replaceAll(",\\s*([\\]}]|$)","") - .replaceAll("([:,\\[])'(-?[\\d\\.]+|null|false|true)'", "$1$2") - .replaceAll("(^|[^\\w-'])([\\w]+[-][\\w-]+):", "$1'$2':") + return "{" + ret.replaceAll(",\\s*([\\]}]|$)","$1") + .replaceAll("([:,\\[])\"(-?[\\d\\.]+|null|false|true)\"", "$1$2") + "}"; } @@ -179,4 +179,8 @@ public class Properties extends JavaScriptObject { } return ret; } + + public final boolean isEmpty(){ + return c().length() == 0; + } } diff --git a/gwtquery-core/src/main/java/com/google/gwt/query/client/builders/JsonBuilder.java b/gwtquery-core/src/main/java/com/google/gwt/query/client/builders/JsonBuilder.java new file mode 100644 index 00000000..eeb75955 --- /dev/null +++ b/gwtquery-core/src/main/java/com/google/gwt/query/client/builders/JsonBuilder.java @@ -0,0 +1,45 @@ +/* + * Copyright 2011, The gwtquery team. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.google.gwt.query.client.builders; + +import com.google.gwt.query.client.Properties; + +/** + * Tagging interface used to generate JsonBuilder classes. + */ +public interface JsonBuilder { + /** + * load a properties object. + */ + J load(Object prp); + + /** + * parses a json string and loads the resulting properties object. + */ + J parse(String json); + + /** + * parses a json string and loads the resulting properties object, + * if the param 'fix' is true, the syntax of the json string will be + * checked previously and fixed when possible. + */ + J parse(String json, boolean fix); + + /** + * Returns the javascript properties object. + */ + Properties getProperties(); +} diff --git a/gwtquery-core/src/main/java/com/google/gwt/query/client/builders/JsonBuilderBase.java b/gwtquery-core/src/main/java/com/google/gwt/query/client/builders/JsonBuilderBase.java new file mode 100644 index 00000000..ecd8e042 --- /dev/null +++ b/gwtquery-core/src/main/java/com/google/gwt/query/client/builders/JsonBuilderBase.java @@ -0,0 +1,84 @@ +/* + * Copyright 2011, The gwtquery team. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.google.gwt.query.client.builders; + +import com.google.gwt.core.client.JavaScriptObject; +import com.google.gwt.query.client.Properties; +import com.google.gwt.query.client.js.JsObjectArray; +import com.google.gwt.query.client.js.JsUtils; + +public abstract class JsonBuilderBase> implements JsonBuilder { + + protected Properties p = Properties.create(); + + public J parse(String json) { + return load(JsUtils.parseJSON(json)); + } + + public J parse(String json, boolean fix) { + return fix ? parse(Properties.wrapPropertiesString(json)) : parse(json); + } + + @SuppressWarnings("unchecked") + public J load(Object prp) { + assert prp == null || prp instanceof JavaScriptObject || prp instanceof String; + if (prp != null && prp instanceof String) { + return parse((String)prp); + } + p = prp == null ? Properties.create() : (Properties)prp; + while (JsUtils.isArray(p)) { + p = p.get(0); + } + return (J)this; + } + + protected void setArrayBase(String n, T[] r) { + JsObjectArray a = JsObjectArray.create(); + a.add(r); + p.set(n, a); + } + + @SuppressWarnings("unchecked") + protected T[] getArrayBase(String n, T[] r, Class clazz) { + JsObjectArray a = p.getArray(n).cast(); + int l = r.length; + for (int i = 0 ; i < l ; i++) { + Object w = a.get(i); + Class c = w.getClass(); + do { + if (c.equals(clazz)) { + r[i] = (T)w; + break; + } + c = c.getSuperclass(); + } while (c != null); + } + return r; + } + + protected Properties getPropertiesBase(String n) { + Properties r = p.getJavaScriptObject(n); + return r != null ? r : Properties.create(); + } + + public String toString() { + return p.tostring(); + } + + public Properties getProperties() { + return p; + } +} diff --git a/gwtquery-core/src/main/java/com/google/gwt/query/client/builders/JsonName.java b/gwtquery-core/src/main/java/com/google/gwt/query/client/builders/JsonName.java new file mode 100644 index 00000000..c3855793 --- /dev/null +++ b/gwtquery-core/src/main/java/com/google/gwt/query/client/builders/JsonName.java @@ -0,0 +1,29 @@ +/* + * Copyright 2011, The gwtquery team. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.google.gwt.query.client.builders; + +import static java.lang.annotation.ElementType.METHOD; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + */ +@Target({METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface JsonName { + String value(); +} diff --git a/gwtquery-core/src/main/java/com/google/gwt/query/client/js/JsCache.java b/gwtquery-core/src/main/java/com/google/gwt/query/client/js/JsCache.java index afc62dd2..151116d9 100644 --- a/gwtquery-core/src/main/java/com/google/gwt/query/client/js/JsCache.java +++ b/gwtquery-core/src/main/java/com/google/gwt/query/client/js/JsCache.java @@ -1,3 +1,18 @@ +/* + * Copyright 2011, The gwtquery team. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ package com.google.gwt.query.client.js; import com.google.gwt.core.client.JavaScriptObject; @@ -45,7 +60,8 @@ public class JsCache extends JavaScriptObject { } public final native boolean getBoolean(T id) /*-{ - return !!this[id]; + var r = this[id], t = typeof r; + return 'boolean' == r ? r : 'true' == String(r); }-*/; public final float getFloat(T id) { @@ -53,8 +69,8 @@ public class JsCache extends JavaScriptObject { } public final native double getDouble(T id) /*-{ - var r = this[id]; - return r && (typeof r == 'number') ? r : 0; + var r = this[id] ? Number(this[id]) : 0; + return r ? r : 0; }-*/; public final int getInt(T id) { diff --git a/gwtquery-core/src/main/java/com/google/gwt/query/client/js/JsUtils.java b/gwtquery-core/src/main/java/com/google/gwt/query/client/js/JsUtils.java index f7af867c..4145dd1e 100644 --- a/gwtquery-core/src/main/java/com/google/gwt/query/client/js/JsUtils.java +++ b/gwtquery-core/src/main/java/com/google/gwt/query/client/js/JsUtils.java @@ -280,6 +280,11 @@ public class JsUtils { * to get the content. */ public static Properties parseJSON(String json) { - return utilsImpl.parseJSON(json); + try { + return utilsImpl.parseJSON(json); + } catch (Exception e) { + System.err.println("Error while parsing json: " + e.getMessage() + ".\n" + json); + return Properties.create(); + } } } diff --git a/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/ajax/Ajax.java b/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/ajax/Ajax.java new file mode 100644 index 00000000..18d99a37 --- /dev/null +++ b/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/ajax/Ajax.java @@ -0,0 +1,209 @@ +package com.google.gwt.query.client.plugins.ajax; + +import com.google.gwt.core.client.GWT; +import com.google.gwt.dom.client.Element; +import com.google.gwt.http.client.Request; +import com.google.gwt.http.client.RequestBuilder; +import com.google.gwt.http.client.RequestBuilder.Method; +import com.google.gwt.http.client.RequestCallback; +import com.google.gwt.http.client.RequestException; +import com.google.gwt.http.client.Response; +import com.google.gwt.query.client.Function; +import com.google.gwt.query.client.Properties; +import com.google.gwt.query.client.builders.JsonBuilder; +import com.google.gwt.query.client.js.JsUtils; + +/** + * Ajax class for GQuery. + * + * The jQuery library has a full suite of AJAX capabilities, but GWT + * is plenty of classes to get data from server side: RPC, XHR, RF, etc. + * + * This class is not a substitute for the GWT utilities, but a complement + * to get server data in a jquery way, specially when querying non java + * backends. + * + * We do not pretend to clone all the jquery Ajax API inside gquery, just take + * its syntax and to implement the most popular usage of it. + * This implementation is almost thought to be used as an alternative to + * the GWT-XHR, GWT-XML and GWT-JSON modules. + * + * This class is not a plugin because in jquery it does not extends the jquery + * object, but we prefer this name-space in order to centralize the jquery core + * features in a common folder. + * + */ +public class Ajax { + + /** + * Ajax Settings object + */ + public interface Settings extends JsonBuilder { + String getType(); + Settings setType(String t); + String getUrl(); + Settings setUrl(String u); + Properties getData(); + Settings setData(Properties p); + String getDataString(); + Settings setDataString(String d); + String getDataType(); + Settings setDataType(String t); + int getTimeout(); + Settings setTimeout(int t); + String getUsername(); + Settings setUsername(String u); + String getPassword(); + Settings setPassword(String p); + String getContentType(); + Settings setContentType(String t); + Properties getHeaders(); + Settings setHeaders(Properties p); + Element getContext(); + Settings setContext(Element e); + Function getSuccess(); + Settings setSuccess(Function f); + Function getError(); + Settings setError(Function f); + } + + public void ajax(String url, Function onSuccess, Function onError, Properties p) { + Settings settings = GWT.create(Settings.class); + settings.load(p); + ajax(url, onSuccess, onError, settings); + } + + public void ajax(String url, Function onSuccess, Function onError) { + ajax(url, onSuccess, onError, (Settings)null); + } + + public void ajax(String url, Function onSuccess, Function onError, Settings settings) { + if (settings == null) { + settings = GWT.create(Settings.class); + } + settings.setUrl(url).setSuccess(onSuccess).setError(onError); + ajax(settings); + } + + /** + * Perform an ajax request to the server. + * + * + * Example: + *
+    import static com.google.gwt.query.client.GQ.*
+    ...
+    Properties properties = $$("dataType: xml, type: post; data: {q: 'gwt'}, headers: {X-Powered-By: GQuery}");
+    ajax("test.php", new Function() {
+      public void f() {
+        Element xmlElem = getData()[0];
+        System.out.println($("message", xmlElem));
+      }
+    }, new Function(){
+      public void f() {
+        System.err.println("Ajax Error: " + getData()[1]);
+      }
+    }, properties);
+   * 
+ * + * @param url The url to connect + * @param onSuccess a function to execute in the case of success + * @param onError the function to execute on error + * @param settings a Properties object with the configuration of the Ajax request. + */ + public void ajax(Settings settings) { + Method httpMethod = RequestBuilder.POST; + String method = settings.getType(); + if ("get".equalsIgnoreCase(method)) { + httpMethod = RequestBuilder.GET; + } + + String url = settings.getUrl(); + + String data = settings.getDataString(); + if (data == null) { + data = settings.getData().toQueryString(); + } + + if (data != null && httpMethod == RequestBuilder.GET) { + url += (url.contains("?") ? "&" : "?") + data; + } + RequestBuilder r = new RequestBuilder(httpMethod, url); + if (data != null && httpMethod != RequestBuilder.GET) { + r.setRequestData(data); + } + + r.setTimeoutMillis(settings.getTimeout()); + + String user = settings.getUsername(); + if (user != null) { + r.setUser(user); + } + + String password = settings.getPassword(); + if (password != null) { + r.setPassword(password); + } + + String ctype = settings.getContentType(); + r.setHeader("Content-type", ctype != null ? ctype + : "application/x-www-form-urlencoded"); + + final String dataType = settings.getDataType() != null + ? settings.getDataType() : "text"; + + Properties p = settings.getHeaders(); + for (String s : p.keys()) { + r.setHeader(s, p.getStr(s)); + } + + final Function onSuccess = settings.getSuccess(); + if (onSuccess != null) { + onSuccess.setElement(settings.getContext()); + } + final Function onError = settings.getError(); + if (onError != null) { + onError.setElement(settings.getContext()); + } + + r.setCallback(new RequestCallback() { + public void onResponseReceived(Request request, Response response) { + if (response.getStatusCode() > 202) { + if (onError != null) { + onError.f(response.getText(), "error", request, response); + } + } else if (onSuccess != null) { + Object retData = null; + try { + if ("xml".equalsIgnoreCase(dataType)) { + retData = JsUtils.parseXML(response.getText()); + } else if ("json".equalsIgnoreCase(dataType)) { + retData = JsUtils.parseJSON(response.getText()); + } else { + retData = response.getText(); + } + } catch (Exception e) { + System.err.println("Error parsing '" + dataType + + "' received data: " + e.getMessage()); + System.err.println("Server response was: \n" + response.getText()); + } + onSuccess.f(retData, "success", request, response); + } + } + + public void onError(Request request, Throwable exception) { + if (onError != null) { + onError.f(null, exception.getMessage(), request, null, exception); + } + } + }); + + try { + r.send(); + } catch (RequestException e) { + if (onError != null) { + onError.f(null, -1, null, null, e); + } + } + } +} diff --git a/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/ajax/AjaxImpl.java b/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/ajax/AjaxImpl.java deleted file mode 100644 index f10d712e..00000000 --- a/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/ajax/AjaxImpl.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.google.gwt.query.client.plugins.ajax; - -import static com.google.gwt.query.client.GQuery.$$; - -import com.google.gwt.dom.client.Element; -import com.google.gwt.http.client.Request; -import com.google.gwt.http.client.RequestBuilder; -import com.google.gwt.http.client.RequestCallback; -import com.google.gwt.http.client.RequestException; -import com.google.gwt.http.client.Response; -import com.google.gwt.http.client.RequestBuilder.Method; -import com.google.gwt.query.client.Function; -import com.google.gwt.query.client.GQ; -import com.google.gwt.query.client.Properties; -import com.google.gwt.query.client.js.JsUtils; - -/** - * Ajax class for GQuery. - * - * It is not actually a plugin but we prefer this name-space in order - * to centralize jquery core features in a common folder. - * - */ -public class AjaxImpl { - - /** - * The jQuery library has a full suite of AJAX capabilities, but GWT - * is plenty of classes to get data from server side: RPC, XHR, RF, etc. - * - * This class is not a substitute for the GWT utilities, but a complement - * to get server data in a jquery way, specially when querying non java - * backends. - * - * We do not pretend to clone all the jquery Ajax API inside gquery, just take - * its syntax and to implement the most popular usage of it. - * This implementation is almost thought to be used as an alternative to - * the GWT-XHR, GWT-XML and GWT-JSON modules. - * - * Example: - *
-    import static com.google.gwt.query.client.GQ.*
-    ...
-    Properties properties = $$("dataType: xml, type: post; data: {q: 'gwt'}, headers: {X-Powered-By: GQuery}");
-    ajax("test.php", new Function() {
-      public void f() {
-        Element xmlElem = getData()[0];
-        System.out.println($("message", xmlElem));
-      }
-    }, new Function(){
-      public void f() {
-        System.err.println("Ajax Error: " + getData()[1]);
-      }
-    }, properties);
-   * 
- * - * @param url The url to connect - * @param onSuccess a function to execute in the case of success - * @param onError the function to execute on error - * @param settings a Properties object with the configuration of the Ajax request. - */ - public void ajax(String url, Function onSuccess, Function onError, - Properties settings) { - Method httpMethod = RequestBuilder.POST; - String method = settings.getStr("type"); - if ("get".equalsIgnoreCase(method)) { - httpMethod = RequestBuilder.GET; - } - - if (settings.getStr("url") != null) { - url = settings.getStr("url"); - } - - String data = null; - Properties props = settings.getJavaScriptObject("data"); - if (props != null) { - data = props.toQueryString(); - } else { - data = settings.getStr("data"); - } - - if (data != null && httpMethod == RequestBuilder.GET) { - url += (url.contains("?") ? "&" : "?") + data; - } - RequestBuilder r = new RequestBuilder(httpMethod, url); - if (data != null && httpMethod != RequestBuilder.GET) { - r.setRequestData(data); - } - - int timeout = settings.getInt("timeout"); - r.setTimeoutMillis(timeout); - - String user = settings.getStr("username"); - if (user != null) { - r.setUser(user); - } - - String password = settings.getStr("password"); - if (password != null) { - r.setPassword(password); - } - - String ctype = settings.getStr("contentType"); - r.setHeader("Content-type", ctype != null ? ctype - : "application/x-www-form-urlencoded"); - - final String dataType = settings.defined("dataType") - ? settings.getStr("dataType") : "text"; - - Properties p = settings.getJavaScriptObject("headers"); - if (p != null) { - for (String s : p.keys()) { - r.setHeader(s, p.getStr(s)); - } - } - - Element ctx = settings.getJavaScriptObject("context"); - if (ctx != null) { - if (onSuccess != null) { - onSuccess.setElement(ctx); - } - if (onError != null) { - onError.setElement(ctx); - } - } - - Object o = settings.getObject("success"); - final Function success = (o != null && (o instanceof Function)) - ? (Function) o : onSuccess; - - o = settings.getObject("error"); - final Function error = (o != null && (o instanceof Function)) - ? (Function) o : onError; - - r.setCallback(new RequestCallback() { - public void onResponseReceived(Request request, Response response) { - if (response.getStatusCode() > 202) { - if (error != null) { - error.f(response.getText(), "error", request, response); - } - } else if (success != null) { - Object retData = null; - try { - if ("xml".equalsIgnoreCase(dataType)) { - retData = JsUtils.parseXML(response.getText()); - } else if ("json".equalsIgnoreCase(dataType)) { - retData = JsUtils.parseJSON(response.getText()); - } else { - retData = response.getText(); - } - } catch (Exception e) { - System.err.println("Error parsing '" + dataType - + "' received data: " + e.getMessage()); - System.err.println("Server response was: \n" + response.getText()); - } - success.f(retData, "success", request, response); - } - } - - public void onError(Request request, Throwable exception) { - if (error != null) { - error.f(null, exception.getMessage(), request, null, exception); - } - } - }); - - try { - r.send(); - } catch (RequestException e) { - if (onError != null) { - onError.f(null, -1, null, null, e); - } - } - } -} diff --git a/gwtquery-core/src/test/java/com/google/gwt/query/client/GQueryAjaxTest.java b/gwtquery-core/src/test/java/com/google/gwt/query/client/GQueryAjaxTest.java new file mode 100644 index 00000000..7a84c6a8 --- /dev/null +++ b/gwtquery-core/src/test/java/com/google/gwt/query/client/GQueryAjaxTest.java @@ -0,0 +1,83 @@ +/* + * Copyright 2011, The gwtquery team. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.google.gwt.query.client; + + +import com.google.gwt.core.client.GWT; +import com.google.gwt.dom.client.Element; +import com.google.gwt.junit.client.GWTTestCase; +import com.google.gwt.query.client.builders.JsonBuilder; +import com.google.gwt.query.client.builders.JsonName; +import com.google.gwt.user.client.ui.HTML; +import com.google.gwt.user.client.ui.RootPanel; + +/** + * Test class for testing ajax stuff. + */ +public class GQueryAjaxTest extends GWTTestCase { + + static Element e = null; + + static HTML testPanel = null; + + public String getModuleName() { + return "com.google.gwt.query.Query"; + } + + public void gwtSetUp() { + if (e == null) { + testPanel = new HTML(); + RootPanel.get().add(testPanel); + e = testPanel.getElement(); + e.setId("core-tst"); + } else { + e.setInnerHTML(""); + } + } + + interface MyClass extends JsonBuilder { + int getA(); + MyClass getB(); + @JsonName("u") + String getUrl(); + long getD(); + Boolean getZ(); + String[] getT(); + MyClass setT(String[] strings); + MyClass setZ(Boolean b); + } + + public void testJsonBuilder() { + String json = "[{a:1, b:{a:2,b:{a:3}},u:url, d:'2','t':['hola','adios'], 'z': true}]"; + MyClass c = GWT.create(MyClass.class); + assertEquals(0, c.getA()); + c.parse(json, true); + assertEquals(1, c.getA()); + System.out.println(c); + assertNotNull(c.getB()); + assertEquals(2, c.getB().getA()); + assertEquals(3, c.getB().getB().getA()); + assertTrue(c.getZ()); + assertEquals("hola", c.getT()[0]); + assertEquals("adios", c.getT()[1]); + assertEquals("url", c.getUrl()); + c.setT(new String[]{"foo", "bar"}) + .setZ(false); + assertFalse(c.getZ()); + assertEquals("foo", c.getT()[0]); + assertEquals("bar", c.getT()[1]); + } +} -- 2.39.5