You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Ajax.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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() > 202) {
  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
  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. }
  216. return RequestBuilder.POST;
  217. }
  218. public static void ajax(String url, Function onSuccess, Function onError) {
  219. ajax(url, onSuccess, onError, (Settings) null);
  220. }
  221. public static void ajax(String url, Function onSuccess, Function onError, Settings s) {
  222. if (s == null) {
  223. s = createSettings();
  224. }
  225. s.setUrl(url).setSuccess(onSuccess).setError(onError);
  226. ajax(s);
  227. }
  228. public static void ajax(String url, Properties p) {
  229. Settings s = createSettings();
  230. s.load(p);
  231. s.setUrl(url);
  232. ajax(s);
  233. }
  234. public static void ajax(String url, Settings settings) {
  235. ajax(settings.setUrl(url));
  236. }
  237. public static Settings createSettings() {
  238. return createSettings($$(""));
  239. }
  240. public static Settings createSettings(String prop) {
  241. return createSettings($$(prop));
  242. }
  243. public static Settings createSettings(Properties p) {
  244. Settings s = GWT.create(Settings.class);
  245. s.load(p);
  246. return s;
  247. }
  248. public static void get(String url, Properties data, final Function onSuccess) {
  249. Settings s = createSettings();
  250. s.setUrl(url);
  251. s.setDataType("txt");
  252. s.setType("get");
  253. s.setData(data);
  254. s.setSuccess(onSuccess);
  255. ajax(s);
  256. }
  257. public static void getJSON(String url, Properties data, final Function onSuccess) {
  258. Settings s = createSettings();
  259. s.setUrl(url);
  260. s.setDataType("json");
  261. s.setType("post");
  262. s.setData(data);
  263. s.setSuccess(onSuccess);
  264. ajax(s);
  265. }
  266. public static void getJSONP(String url, Properties data, Function onSuccess) {
  267. Settings s = createSettings();
  268. s.setUrl(url);
  269. s.setDataType("jsonp");
  270. s.setType("get");
  271. s.setData(data);
  272. s.setSuccess(onSuccess);
  273. ajax(s);
  274. }
  275. public static void getJSONP(String url, Function success, Function error, int timeout) {
  276. if (!url.contains("=?") && !url.contains("callback=")) {
  277. url += (url.contains("?") ? "&" : "?") + "callback=?";
  278. }
  279. url += "&_=" + System.currentTimeMillis();
  280. Element e = $("head").get(0);
  281. if (e == null) {
  282. e = document.getDocumentElement();
  283. }
  284. getJsonpImpl(e, url, null, success, error == null ? success : error, timeout);
  285. }
  286. public static void post(String url, Properties data, final Function onSuccess) {
  287. Settings s = createSettings();
  288. s.setUrl(url);
  289. s.setDataType("txt");
  290. s.setType("post");
  291. s.setData(data);
  292. s.setSuccess(onSuccess);
  293. ajax(s);
  294. }
  295. protected Ajax(GQuery gq) {
  296. super(gq);
  297. }
  298. public Ajax load(String url, Properties data, final Function onSuccess) {
  299. Settings s = createSettings();
  300. final String filter = url.contains(" ") ? url.replaceFirst("^[^\\s]+\\s+", "") : "";
  301. s.setUrl(url.replaceAll("\\s+.+$", ""));
  302. s.setDataType("html");
  303. s.setType("get");
  304. s.setData(data);
  305. s.setSuccess(new Function() {
  306. public void f() {
  307. // We clean up the returned string to smoothly append it to our document
  308. String s = getData()[0].toString().replaceAll("<![^>]+>\\s*", "")
  309. .replaceAll("(?si)</?html[^>]*>\\s*", "")
  310. .replaceFirst("(?si)<head[^>]*>.*</head>\\s*", "")
  311. .replaceFirst("(?si)<script[^>]*>.*</script>\\s*", "")
  312. .replaceAll("<?si></?body[^>]*>\\s*", "");
  313. // We wrap the results in a div
  314. s = "<div>" + s + "</div>";
  315. Ajax.this.empty().append(filter.isEmpty() ? $(s) : $(s).find(filter));
  316. if (onSuccess != null) {
  317. onSuccess.setElement(Ajax.this.get(0));
  318. onSuccess.f();
  319. }
  320. }
  321. });
  322. ajax(s);
  323. return this;
  324. }
  325. private static int callBackCounter = 0;
  326. public static native void getJsonpImpl(Element elem, String url, String charset, Function success, Function error, int timeout) /*-{
  327. var fName = "__GQ_cb_" + @com.google.gwt.query.client.plugins.ajax.Ajax::callBackCounter ++;
  328. var done = false;
  329. $wnd[fName] = function(data) {
  330. if (!done) {
  331. done = true;
  332. $wnd[fName] = null;
  333. success.@com.google.gwt.query.client.Function::fe(Ljava/lang/Object;)(data);
  334. }
  335. }
  336. function err() {
  337. if (!done) {
  338. done = true;
  339. $wnd[fName] = null;
  340. var func = error ? error : success;
  341. func.@com.google.gwt.query.client.Function::fe(Ljava/lang/Object;)();
  342. }
  343. }
  344. if (timeout) {
  345. setTimeout(err, timeout);
  346. }
  347. url = url.replace(/=\?/g,'=' + fName);
  348. var script = document.createElement("script" );
  349. script.async = "async";
  350. if (charset) script.charset = charset;
  351. script.src = url;
  352. script.onload = script.onreadystatechange = function(evt) {
  353. script.onload = script.onreadystatechange = null;
  354. elem.removeChild(script);
  355. err();
  356. };
  357. elem.insertBefore(script, elem.firstChild);
  358. }-*/;
  359. }