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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. package com.google.gwt.query.client.plugins.ajax;
  2. import com.google.gwt.core.client.GWT;
  3. import com.google.gwt.core.client.JavaScriptObject;
  4. import com.google.gwt.core.client.ScriptInjector;
  5. import com.google.gwt.dom.client.Element;
  6. import com.google.gwt.http.client.Request;
  7. import com.google.gwt.http.client.Response;
  8. import com.google.gwt.query.client.Binder;
  9. import com.google.gwt.query.client.Function;
  10. import com.google.gwt.query.client.GQ;
  11. import com.google.gwt.query.client.GQuery;
  12. import com.google.gwt.query.client.Promise;
  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. public static final String JSON_CONTENT_TYPE = "application/json";
  33. public static final String JSON_CONTENT_TYPE_UTF8 = JSON_CONTENT_TYPE + "; charset=utf-8";
  34. public static interface AjaxTransport {
  35. Promise getJsonP(Settings settings);
  36. Promise getLoadScript(Settings settings);
  37. Promise getXhr(Settings settings);
  38. }
  39. static AjaxTransport transport = GQ.getAjaxTransport();
  40. /**
  41. * Ajax Settings object
  42. */
  43. public interface Settings extends JsonBuilder {
  44. String getContentType();
  45. Element getContext();
  46. Binder getData();
  47. String getDataString();
  48. String getDataType();
  49. Function getError();
  50. Binder getHeaders();
  51. String getPassword();
  52. Function getSuccess();
  53. int getTimeout();
  54. String getType();
  55. String getUrl();
  56. String getUsername();
  57. Settings setContentType(String t);
  58. Settings setContext(Element e);
  59. Settings setData(Object p);
  60. Settings setDataString(String d);
  61. Settings setDataType(String t);
  62. Settings setError(Function f);
  63. Settings setHeaders(Binder p);
  64. Settings setPassword(String p);
  65. Settings setSuccess(Function f);
  66. Settings setTimeout(int t);
  67. Settings setType(String t);
  68. Settings setUrl(String u);
  69. Settings setUsername(String u);
  70. }
  71. public static final Class<Ajax> Ajax = registerPlugin(Ajax.class, new Plugin<Ajax>() {
  72. public Ajax init(GQuery gq) {
  73. return new Ajax(gq);
  74. }
  75. });
  76. public static Promise ajax(Binder p) {
  77. Settings s = createSettings();
  78. s.load(p);
  79. return ajax(s);
  80. }
  81. /**
  82. * Perform an ajax request to the server.
  83. *
  84. *
  85. * Example:
  86. *
  87. * <pre>
  88. import static com.google.gwt.query.client.GQ.*
  89. ...
  90. Properties properties = $$("dataType: xml, type: post; data: {q: 'gwt'}, headers: {X-Powered-By: GQuery}");
  91. ajax("test.php", new Function() {
  92. public void f() {
  93. Element xmlElem = getData()[0];
  94. System.out.println($("message", xmlElem));
  95. }
  96. }, new Function(){
  97. public void f() {
  98. System.err.println("Ajax Error: " + getData()[1]);
  99. }
  100. }, properties);
  101. * </pre>
  102. *
  103. * @param url The url to connect
  104. * @param onSuccess a function to execute in the case of success
  105. * @param onError the function to execute on error
  106. * @param settings a Properties object with the configuration of the Ajax request.
  107. */
  108. public static Promise ajax(Settings settings) {
  109. resolveSettings(settings);
  110. final Function onSuccess = settings.getSuccess();
  111. if (onSuccess != null) {
  112. onSuccess.setElement(settings.getContext());
  113. }
  114. final Function onError = settings.getError();
  115. if (onError != null) {
  116. onError.setElement(settings.getContext());
  117. }
  118. final String dataType = settings.getDataType();
  119. Promise ret = null;
  120. if ("jsonp".equalsIgnoreCase(dataType)) {
  121. ret = transport.getJsonP(settings);
  122. } else if ("loadscript".equalsIgnoreCase(dataType)){
  123. ret = transport.getLoadScript(settings);
  124. } else {
  125. ret = transport.getXhr(settings)
  126. .then(new Function() {
  127. public Object f(Object...args) {
  128. Response response = arguments(0);
  129. Request request = arguments(1);
  130. Object retData = response.getText();
  131. try {
  132. if ("xml".equalsIgnoreCase(dataType)) {
  133. retData = JsUtils.parseXML(response.getText());
  134. } else if ("json".equalsIgnoreCase(dataType)) {
  135. retData = GQ.create(response.getText());
  136. } else {
  137. retData = response.getText();
  138. if ("script".equalsIgnoreCase(dataType)) {
  139. ScriptInjector.fromString((String)retData).setWindow(window).inject();
  140. }
  141. }
  142. } catch (Exception e) {
  143. if (GWT.isClient() && GWT.getUncaughtExceptionHandler() != null) {
  144. GWT.getUncaughtExceptionHandler().onUncaughtException(e);
  145. } else {
  146. e.printStackTrace();
  147. }
  148. }
  149. return new Object[]{retData, "success", request, response};
  150. }
  151. }, new Function() {
  152. public Object f(Object...args) {
  153. Throwable exception = arguments(0);
  154. Request request = arguments(1);
  155. String msg = String.valueOf(exception);
  156. return new Object[]{null, msg, request, null, exception};
  157. }
  158. });
  159. }
  160. if (onSuccess != null) {
  161. ret.done(onSuccess);
  162. }
  163. if (onError != null) {
  164. ret.fail(onError);
  165. }
  166. return ret;
  167. }
  168. private static void resolveSettings(Settings settings) {
  169. String url = settings.getUrl();
  170. assert settings != null && settings.getUrl() != null: "no url found in settings";
  171. String type = "POST";
  172. if (settings.getType() != null) {
  173. type = settings.getType().toUpperCase();
  174. }
  175. if ("jsonp".equalsIgnoreCase(settings.getDataType())) {
  176. type = "GET";
  177. }
  178. settings.setType(type);
  179. Binder data = settings.getData();
  180. if (data != null) {
  181. String dataString = null, contentType = null;
  182. if (data.getBound() instanceof JavaScriptObject && JsUtils.isFormData(data.<JavaScriptObject>getBound())) {
  183. dataString = null;
  184. contentType = FormPanel.ENCODING_URLENCODED;
  185. } else if (settings.getType().matches("(POST|PUT)") && "json".equalsIgnoreCase(settings.getDataType())) {
  186. dataString = data.toJson();
  187. contentType = JSON_CONTENT_TYPE_UTF8;
  188. } else {
  189. dataString = data.toQueryString();
  190. contentType = FormPanel.ENCODING_URLENCODED;
  191. }
  192. settings.setDataString(dataString);
  193. settings.setContentType(contentType);
  194. }
  195. if ("GET".equals(settings.getType()) && settings.getDataString() != null) {
  196. url += (url.contains("?") ? "&" : "?") + settings.getDataString();
  197. settings.setUrl(url);
  198. }
  199. }
  200. public static Promise ajax(String url, Function onSuccess, Function onError) {
  201. return ajax(url, onSuccess, onError, (Settings) null);
  202. }
  203. public static Promise ajax(String url, Function onSuccess, Function onError, Settings s) {
  204. if (s == null) {
  205. s = createSettings();
  206. }
  207. s.setUrl(url).setSuccess(onSuccess).setError(onError);
  208. return ajax(s);
  209. }
  210. public static Promise ajax(String url, Binder p) {
  211. Settings s = createSettings();
  212. s.load(p);
  213. s.setUrl(url);
  214. return ajax(s);
  215. }
  216. public static Promise ajax(String url, Settings settings) {
  217. return ajax(settings.setUrl(url));
  218. }
  219. public static Settings createSettings() {
  220. return createSettings("");
  221. }
  222. public static Settings createSettings(String prop) {
  223. Settings s = GQ.create(Settings.class);
  224. if (prop != null && !prop.isEmpty())
  225. s.parse(prop);
  226. return s;
  227. }
  228. public static Settings createSettings(Binder p) {
  229. Settings s = GQ.create(Settings.class);
  230. s.load(p.getBound());
  231. return s;
  232. }
  233. public static Promise get(String url) {
  234. return get(url, null);
  235. }
  236. public static Promise get(String url, Binder data) {
  237. return get(url, (Binder)data, null);
  238. }
  239. public static Promise get(String url, Binder data, Function onSuccess) {
  240. Settings s = createSettings();
  241. s.setUrl(url);
  242. s.setDataType("txt");
  243. s.setType("get");
  244. s.setData(data);
  245. s.setSuccess(onSuccess);
  246. return ajax(s);
  247. }
  248. public static Promise getJSON(String url, Binder data) {
  249. return getJSON(url, data, null);
  250. }
  251. public static Promise getJSON(String url, Binder data, Function onSuccess) {
  252. Settings s = createSettings();
  253. s.setUrl(url);
  254. s.setDataType("json");
  255. s.setType("post");
  256. s.setData(data);
  257. s.setSuccess(onSuccess);
  258. return ajax(s);
  259. }
  260. public static Promise getJSONP(String url) {
  261. return getJSONP(url, null);
  262. }
  263. public static Promise getJSONP(String url, Binder data) {
  264. return getJSONP(url, (Binder)data, null);
  265. }
  266. public static Promise getJSONP(String url, Binder 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. return ajax(s);
  274. }
  275. public static Promise getJSONP(String url, Function success, Function error, int timeout) {
  276. return ajax(createSettings()
  277. .setUrl(url)
  278. .setDataType("jsonp")
  279. .setType("get")
  280. .setTimeout(timeout)
  281. .setSuccess(success)
  282. .setError(error)
  283. );
  284. }
  285. /**
  286. * Get a JavaScript file from the server using a GET HTTP request, then execute it.
  287. */
  288. public static Promise getScript(String url) {
  289. return getScript(url, null);
  290. }
  291. public static Promise getScript(final String url, Function success) {
  292. return ajax(createSettings()
  293. .setUrl(url)
  294. .setType("get")
  295. .setDataType("script")
  296. .setSuccess(success)
  297. );
  298. }
  299. /**
  300. * Load a JavaScript file from any url using the script tag mechanism
  301. */
  302. public static Promise loadScript(String url) {
  303. return loadScript(url, null);
  304. }
  305. public static Promise loadScript(final String url, Function success) {
  306. return ajax(createSettings()
  307. .setUrl(url)
  308. .setType("get")
  309. .setDataType("loadscript")
  310. .setSuccess(success)
  311. );
  312. }
  313. public static Promise post(String url, Binder data) {
  314. return post(url, (Binder)data, null);
  315. }
  316. public static Promise post(String url, Binder data, final Function onSuccess) {
  317. Settings s = createSettings();
  318. s.setUrl(url);
  319. s.setDataType("txt");
  320. s.setType("post");
  321. s.setData(data);
  322. s.setSuccess(onSuccess);
  323. return ajax(s);
  324. }
  325. protected Ajax(GQuery gq) {
  326. super(gq);
  327. }
  328. public Ajax load(String url, Binder data) {
  329. return load(url, data);
  330. }
  331. public Ajax load(String url, Binder data, final Function onSuccess) {
  332. Settings s = createSettings();
  333. final String filter = url.contains(" ") ? url.replaceFirst("^[^\\s]+\\s+", "") : "";
  334. s.setUrl(url.replaceAll("\\s+.+$", ""));
  335. s.setDataType("html");
  336. s.setType("get");
  337. s.setData(data);
  338. s.setSuccess(new Function() {
  339. public void f() {
  340. try {
  341. // We clean up the returned string to smoothly append it to our document
  342. // Note: using '\s\S' instead of '.' because gwt String emulation does
  343. // not support java embedded flag expressions (?s) and javascript does
  344. // not have multidot flag.
  345. String s = arguments(0).toString().replaceAll("<![^>]+>\\s*", "")
  346. .replaceAll("</?html[\\s\\S]*?>\\s*", "")
  347. .replaceAll("<head[\\s\\S]*?</head>\\s*", "")
  348. .replaceAll("<script[\\s\\S]*?</script>\\s*", "")
  349. .replaceAll("</?body[\\s\\S]*?>\\s*", "");
  350. // We wrap the results in a div
  351. s = "<div>" + s + "</div>";
  352. Ajax.this.empty().append(filter.isEmpty() ? $(s) : $(s).find(filter));
  353. if (onSuccess != null) {
  354. onSuccess.setElement(Ajax.this.get(0));
  355. onSuccess.f();
  356. }
  357. } catch (Exception e) {
  358. if (GWT.getUncaughtExceptionHandler() != null) {
  359. GWT.getUncaughtExceptionHandler().onUncaughtException(e);
  360. }
  361. }
  362. }
  363. });
  364. ajax(s);
  365. return this;
  366. }
  367. }