PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/ajax/Ajax.java

http://gwtquery.googlecode.com/
Java | 420 lines | 297 code | 42 blank | 81 comment | 71 complexity | 3e63133932adea639acfcdb62fbf9293 MD5 | raw file
  1. package com.google.gwt.query.client.plugins.ajax;
  2. import com.google.gwt.core.client.GWT;
  3. import com.google.gwt.dom.client.Element;
  4. import com.google.gwt.http.client.Request;
  5. import com.google.gwt.http.client.RequestBuilder;
  6. import com.google.gwt.http.client.RequestBuilder.Method;
  7. import com.google.gwt.http.client.RequestCallback;
  8. import com.google.gwt.http.client.RequestException;
  9. import com.google.gwt.http.client.Response;
  10. import com.google.gwt.query.client.Function;
  11. import com.google.gwt.query.client.GQuery;
  12. import com.google.gwt.query.client.Properties;
  13. import com.google.gwt.query.client.builders.JsonBuilder;
  14. import com.google.gwt.query.client.js.JsUtils;
  15. import com.google.gwt.query.client.plugins.Plugin;
  16. import com.google.gwt.user.client.ui.FormPanel;
  17. /**
  18. * Ajax class for GQuery.
  19. *
  20. * The jQuery library has a full suite of AJAX capabilities, but GWT is plenty of classes to get
  21. * data from server side: RPC, XHR, RF, etc.
  22. *
  23. * This class is not a substitute for the GWT utilities, but a complement to get server data in a
  24. * jquery way, specially when querying non java backends.
  25. *
  26. * We do not pretend to clone all the jquery Ajax API inside gquery, just take its syntax and to
  27. * implement the most popular usage of it. This implementation is almost thought to be used as an
  28. * alternative to the GWT-XHR, GWT-XML and GWT-JSON modules.
  29. *
  30. */
  31. public class Ajax extends GQuery {
  32. /**
  33. * Ajax Settings object
  34. */
  35. public interface Settings extends JsonBuilder {
  36. String getContentType();
  37. Element getContext();
  38. Properties getData();
  39. String getDataString();
  40. String getDataType();
  41. Function getError();
  42. Properties getHeaders();
  43. String getPassword();
  44. Function getSuccess();
  45. int getTimeout();
  46. String getType();
  47. String getUrl();
  48. String getUsername();
  49. Settings setContentType(String t);
  50. Settings setContext(Element e);
  51. Settings setData(Properties p);
  52. Settings setDataString(String d);
  53. Settings setDataType(String t);
  54. Settings setError(Function f);
  55. Settings setHeaders(Properties p);
  56. Settings setPassword(String p);
  57. Settings setSuccess(Function f);
  58. Settings setTimeout(int t);
  59. Settings setType(String t);
  60. Settings setUrl(String u);
  61. Settings setUsername(String u);
  62. }
  63. public static final Class<Ajax> Ajax = registerPlugin(Ajax.class, new Plugin<Ajax>() {
  64. public Ajax init(GQuery gq) {
  65. return new Ajax(gq);
  66. }
  67. });
  68. public static void ajax(Properties p) {
  69. Settings s = createSettings();
  70. s.load(p);
  71. ajax(s);
  72. }
  73. /**
  74. * Perform an ajax request to the server.
  75. *
  76. *
  77. * Example:
  78. *
  79. * <pre>
  80. import static com.google.gwt.query.client.GQ.*
  81. ...
  82. Properties properties = $$("dataType: xml, type: post; data: {q: 'gwt'}, headers: {X-Powered-By: GQuery}");
  83. ajax("test.php", new Function() {
  84. public void f() {
  85. Element xmlElem = getData()[0];
  86. System.out.println($("message", xmlElem));
  87. }
  88. }, new Function(){
  89. public void f() {
  90. System.err.println("Ajax Error: " + getData()[1]);
  91. }
  92. }, properties);
  93. * </pre>
  94. *
  95. * @param url The url to connect
  96. * @param onSuccess a function to execute in the case of success
  97. * @param onError the function to execute on error
  98. * @param settings a Properties object with the configuration of the Ajax request.
  99. */
  100. public static void ajax(Settings settings) {
  101. final Function onSuccess = settings.getSuccess();
  102. if (onSuccess != null) {
  103. onSuccess.setElement(settings.getContext());
  104. }
  105. final Function onError = settings.getError();
  106. if (onError != null) {
  107. onError.setElement(settings.getContext());
  108. }
  109. Method httpMethod = resolveHttpMethod(settings);
  110. String data = resolveData(settings, httpMethod);
  111. String url = resolveUrl(settings, httpMethod, data);
  112. final String dataType = settings.getDataType();
  113. if ("jsonp".equalsIgnoreCase(dataType)) {
  114. int timeout = settings.getTimeout();
  115. getJSONP(url, onSuccess, onError, timeout);
  116. return;
  117. }
  118. final RequestBuilder requestBuilder = createRequestBuilder(settings, httpMethod, url, data);
  119. requestBuilder.setCallback(new RequestCallback() {
  120. public void onError(Request request, Throwable exception) {
  121. if (onError != null) {
  122. onError.f(null, exception.getMessage(), request, null, exception);
  123. }
  124. }
  125. public void onResponseReceived(Request request, Response response) {
  126. if (response.getStatusCode() >= 400) {
  127. if (onError != null) {
  128. onError.fe(response.getText(), "error", request, response);
  129. }
  130. } else if (onSuccess != null) {
  131. Object retData = null;
  132. try {
  133. if ("xml".equalsIgnoreCase(dataType)) {
  134. retData = JsUtils.parseXML(response.getText());
  135. } else if ("json".equalsIgnoreCase(dataType)) {
  136. retData = JsUtils.parseJSON(response.getText());
  137. } else {
  138. retData = response.getText();
  139. }
  140. } catch (Exception e) {
  141. if (GWT.getUncaughtExceptionHandler() != null) {
  142. GWT.getUncaughtExceptionHandler().onUncaughtException(e);
  143. }
  144. }
  145. onSuccess.fe(retData, "success", request, response);
  146. }
  147. }
  148. });
  149. try {
  150. requestBuilder.send();
  151. } catch (RequestException e) {
  152. if (onError != null) {
  153. onError.f(null, -1, null, null, e);
  154. }
  155. }
  156. }
  157. private static RequestBuilder createRequestBuilder(Settings settings, Method httpMethod, String url, String data) {
  158. RequestBuilder requestBuilder = new RequestBuilder(httpMethod, url);
  159. if (data != null && httpMethod != RequestBuilder.GET) {
  160. String ctype = settings.getContentType();
  161. if (ctype == null) {
  162. String type = settings.getDataType();
  163. if (type != null && type.toLowerCase().startsWith("json")) {
  164. ctype = "application/json; charset=utf-8";
  165. } else {
  166. ctype = FormPanel.ENCODING_URLENCODED;
  167. }
  168. }
  169. requestBuilder.setHeader("Content-Type", ctype);
  170. requestBuilder.setRequestData(data);
  171. }
  172. requestBuilder.setTimeoutMillis(settings.getTimeout());
  173. String user = settings.getUsername();
  174. if (user != null) {
  175. requestBuilder.setUser(user);
  176. }
  177. String password = settings.getPassword();
  178. if (password != null) {
  179. requestBuilder.setPassword(password);
  180. }
  181. Properties headers = settings.getHeaders();
  182. if (headers != null) {
  183. for (String headerKey : headers.keys()) {
  184. requestBuilder.setHeader(headerKey, headers.getStr(headerKey));
  185. }
  186. }
  187. return requestBuilder;
  188. }
  189. private static String resolveUrl(Settings settings, Method httpMethod, String data) {
  190. String url = settings.getUrl();
  191. assert url != null : "no url found in settings";
  192. if (httpMethod == RequestBuilder.GET && data != null) {
  193. url += (url.contains("?") ? "&" : "?") + data;
  194. }
  195. return url;
  196. }
  197. private static String resolveData(Settings settings, Method httpMethod) {
  198. String data = settings.getDataString();
  199. if (data == null && settings.getData() != null) {
  200. String type = settings.getDataType();
  201. if (type != null
  202. && (httpMethod == RequestBuilder.POST || httpMethod == RequestBuilder.PUT)
  203. && type.equalsIgnoreCase("json")) {
  204. data = settings.getData().toJsonString();
  205. } else {
  206. data = settings.getData().toQueryString();
  207. }
  208. }
  209. return data;
  210. }
  211. private static Method resolveHttpMethod(Settings settings) {
  212. String method = settings.getType();
  213. if ("get".equalsIgnoreCase(method)) {
  214. return RequestBuilder.GET;
  215. }else if("post".equalsIgnoreCase(method)){
  216. return RequestBuilder.POST;
  217. }else if("put".equalsIgnoreCase(method)){
  218. return RequestBuilder.PUT;
  219. }else if("delete".equalsIgnoreCase(method)){
  220. return RequestBuilder.DELETE;
  221. }else if("head".equalsIgnoreCase(method)){
  222. return RequestBuilder.HEAD;
  223. }
  224. GWT.log("unknow method type -> use POST as default method");
  225. return RequestBuilder.POST;
  226. }
  227. public static void ajax(String url, Function onSuccess, Function onError) {
  228. ajax(url, onSuccess, onError, (Settings) null);
  229. }
  230. public static void ajax(String url, Function onSuccess, Function onError, Settings s) {
  231. if (s == null) {
  232. s = createSettings();
  233. }
  234. s.setUrl(url).setSuccess(onSuccess).setError(onError);
  235. ajax(s);
  236. }
  237. public static void ajax(String url, Properties p) {
  238. Settings s = createSettings();
  239. s.load(p);
  240. s.setUrl(url);
  241. ajax(s);
  242. }
  243. public static void ajax(String url, Settings settings) {
  244. ajax(settings.setUrl(url));
  245. }
  246. public static Settings createSettings() {
  247. return createSettings($$(""));
  248. }
  249. public static Settings createSettings(String prop) {
  250. return createSettings($$(prop));
  251. }
  252. public static Settings createSettings(Properties p) {
  253. Settings s = GWT.create(Settings.class);
  254. s.load(p);
  255. return s;
  256. }
  257. public static void get(String url, Properties data, final Function onSuccess) {
  258. Settings s = createSettings();
  259. s.setUrl(url);
  260. s.setDataType("txt");
  261. s.setType("get");
  262. s.setData(data);
  263. s.setSuccess(onSuccess);
  264. ajax(s);
  265. }
  266. public static void getJSON(String url, Properties data, final Function onSuccess) {
  267. Settings s = createSettings();
  268. s.setUrl(url);
  269. s.setDataType("json");
  270. s.setType("post");
  271. s.setData(data);
  272. s.setSuccess(onSuccess);
  273. ajax(s);
  274. }
  275. public static void getJSONP(String url, Properties data, Function onSuccess) {
  276. Settings s = createSettings();
  277. s.setUrl(url);
  278. s.setDataType("jsonp");
  279. s.setType("get");
  280. s.setData(data);
  281. s.setSuccess(onSuccess);
  282. ajax(s);
  283. }
  284. public static void getJSONP(String url, Function success, Function error, int timeout) {
  285. if (!url.contains("=?") && !url.contains("callback=")) {
  286. url += (url.contains("?") ? "&" : "?") + "callback=?";
  287. }
  288. url += "&_=" + System.currentTimeMillis();
  289. Element e = $("head").get(0);
  290. if (e == null) {
  291. e = document.getDocumentElement();
  292. }
  293. getJsonpImpl(e, url, null, success, error == null ? success : error, timeout);
  294. }
  295. public static void post(String url, Properties data, final Function onSuccess) {
  296. Settings s = createSettings();
  297. s.setUrl(url);
  298. s.setDataType("txt");
  299. s.setType("post");
  300. s.setData(data);
  301. s.setSuccess(onSuccess);
  302. ajax(s);
  303. }
  304. protected Ajax(GQuery gq) {
  305. super(gq);
  306. }
  307. public Ajax load(String url, Properties data, final Function onSuccess) {
  308. Settings s = createSettings();
  309. final String filter = url.contains(" ") ? url.replaceFirst("^[^\\s]+\\s+", "") : "";
  310. s.setUrl(url.replaceAll("\\s+.+$", ""));
  311. s.setDataType("html");
  312. s.setType("get");
  313. s.setData(data);
  314. s.setSuccess(new Function() {
  315. public void f() {
  316. try {
  317. // We clean up the returned string to smoothly append it to our document
  318. // Note: using '\s\S' instead of '.' because gwt String emulation does
  319. // not support java embedded flag expressions (?s) and javascript does
  320. // not have multidot flag.
  321. String s = getData()[0].toString().replaceAll("<![^>]+>\\s*", "")
  322. .replaceAll("</?html[\\s\\S]*?>\\s*", "")
  323. .replaceAll("<head[\\s\\S]*?</head>\\s*", "")
  324. .replaceAll("<script[\\s\\S]*?</script>\\s*", "")
  325. .replaceAll("</?body[\\s\\S]*?>\\s*", "");
  326. // We wrap the results in a div
  327. s = "<div>" + s + "</div>";
  328. Ajax.this.empty().append(filter.isEmpty() ? $(s) : $(s).find(filter));
  329. if (onSuccess != null) {
  330. onSuccess.setElement(Ajax.this.get(0));
  331. onSuccess.f();
  332. }
  333. } catch (Exception e) {
  334. if (GWT.getUncaughtExceptionHandler() != null) {
  335. GWT.getUncaughtExceptionHandler().onUncaughtException(e);
  336. }
  337. }
  338. }
  339. });
  340. ajax(s);
  341. return this;
  342. }
  343. private static int callBackCounter = 0;
  344. public static native void getJsonpImpl(Element elem, String url, String charset, Function success, Function error, int timeout) /*-{
  345. var fName = "__GQ_cb_" + @com.google.gwt.query.client.plugins.ajax.Ajax::callBackCounter ++;
  346. var done = false;
  347. $wnd[fName] = function(data) {
  348. if (!done) {
  349. done = true;
  350. $wnd[fName] = null;
  351. success.@com.google.gwt.query.client.Function::fe(Ljava/lang/Object;)(data);
  352. }
  353. }
  354. function err() {
  355. if (!done) {
  356. done = true;
  357. $wnd[fName] = null;
  358. var func = error ? error : success;
  359. func.@com.google.gwt.query.client.Function::fe(Ljava/lang/Object;)();
  360. }
  361. }
  362. if (timeout) {
  363. setTimeout(err, timeout);
  364. }
  365. url = url.replace(/=\?/g,'=' + fName);
  366. var script = document.createElement("script" );
  367. script.async = "async";
  368. if (charset) script.charset = charset;
  369. script.src = url;
  370. script.onload = script.onreadystatechange = function(evt) {
  371. script.onload = script.onreadystatechange = null;
  372. elem.removeChild(script);
  373. err();
  374. };
  375. elem.insertBefore(script, elem.firstChild);
  376. }-*/;
  377. }