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 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. /*
  2. * Copyright 2014, The gwtquery team.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.google.gwt.query.client.plugins.ajax;
  17. import com.google.gwt.core.client.GWT;
  18. import com.google.gwt.core.client.JavaScriptObject;
  19. import com.google.gwt.core.client.ScriptInjector;
  20. import com.google.gwt.dom.client.Element;
  21. import com.google.gwt.http.client.Request;
  22. import com.google.gwt.http.client.Response;
  23. import com.google.gwt.query.client.Function;
  24. import com.google.gwt.query.client.GQ;
  25. import com.google.gwt.query.client.GQuery;
  26. import com.google.gwt.query.client.IsProperties;
  27. import com.google.gwt.query.client.Promise;
  28. import com.google.gwt.query.client.builders.JsonBuilder;
  29. import com.google.gwt.query.client.js.JsUtils;
  30. import com.google.gwt.query.client.plugins.Plugin;
  31. import com.google.gwt.query.client.plugins.deferred.PromiseFunction;
  32. import com.google.gwt.user.client.Timer;
  33. import com.google.gwt.user.client.ui.FormPanel;
  34. /**
  35. * Ajax class for GQuery.
  36. *
  37. * The jQuery library has a full suite of AJAX capabilities, but GWT is plenty of classes to get
  38. * data from server side: RPC, XHR, RF, etc.
  39. *
  40. * This class is not a substitute for the GWT utilities, but a complement to get server data in a
  41. * jquery way, specially when querying non java backends.
  42. *
  43. * We do not pretend to clone all the jquery Ajax API inside gquery, just take its syntax and to
  44. * implement the most popular usage of it. This implementation is almost thought to be used as an
  45. * alternative to the GWT-XHR, GWT-XML and GWT-JSON modules.
  46. *
  47. */
  48. public class Ajax extends GQuery {
  49. public static final String JSON_CONTENT_TYPE = "application/json";
  50. public static final String JSON_CONTENT_TYPE_UTF8 = JSON_CONTENT_TYPE + "; charset=utf-8";
  51. /**
  52. * Ajax Transport object.
  53. */
  54. public interface AjaxTransport {
  55. Promise getJsonP(Settings settings);
  56. Promise getLoadScript(Settings settings);
  57. Promise getXhr(Settings settings);
  58. }
  59. /**
  60. * Ajax Settings object.
  61. */
  62. public interface Settings extends JsonBuilder {
  63. String getContentType();
  64. Element getContext();
  65. IsProperties getData();
  66. String getDataString();
  67. String getDataType();
  68. Function getError();
  69. IsProperties getHeaders();
  70. String getPassword();
  71. Function getSuccess();
  72. int getTimeout();
  73. String getType();
  74. String getUrl();
  75. String getUsername();
  76. boolean getWithCredentials();
  77. Settings setContentType(String t);
  78. Settings setContext(Element e);
  79. Settings setData(Object p);
  80. Settings setDataString(String d);
  81. Settings setDataType(String t);
  82. Settings setError(Function f);
  83. Settings setHeaders(IsProperties p);
  84. Settings setPassword(String p);
  85. Settings setSuccess(Function f);
  86. Settings setTimeout(int t);
  87. Settings setType(String t);
  88. Settings setUrl(String u);
  89. Settings setUsername(String u);
  90. Settings setWithCredentials(boolean b);
  91. }
  92. public static final Class<Ajax> Ajax = registerPlugin(Ajax.class, new Plugin<Ajax>() {
  93. public Ajax init(GQuery gq) {
  94. return new Ajax(gq);
  95. }
  96. });
  97. public static Promise ajax(IsProperties p) {
  98. Settings s = createSettings();
  99. s.load(p);
  100. return ajax(s);
  101. }
  102. /**
  103. * Perform an ajax request to the server.
  104. *
  105. * Example:
  106. *
  107. * <pre>
  108. import static com.google.gwt.query.client.GQ.*
  109. ...
  110. Properties properties = $$("dataType: xml, type: post; data: {q: 'gwt'}, headers: {X-Powered-By: GQuery}");
  111. ajax("test.php", new Function() {
  112. public void f() {
  113. Element xmlElem = getData()[0];
  114. System.out.println($("message", xmlElem));
  115. }
  116. }, new Function(){
  117. public void f() {
  118. System.err.println("Ajax Error: " + getData()[1]);
  119. }
  120. }, properties);
  121. * </pre>
  122. *
  123. */
  124. public static Promise ajax(Settings settings) {
  125. resolveSettings(settings);
  126. final Function onSuccess = settings.getSuccess();
  127. if (onSuccess != null) {
  128. onSuccess.setElement(settings.getContext());
  129. }
  130. final Function onError = settings.getError();
  131. if (onError != null) {
  132. onError.setElement(settings.getContext());
  133. }
  134. final String dataType = settings.getDataType();
  135. Promise ret = null;
  136. if ("jsonp".equalsIgnoreCase(dataType)) {
  137. ret = GQ.getAjaxTransport().getJsonP(settings);
  138. } else if ("loadscript".equalsIgnoreCase(dataType)) {
  139. ret = GQ.getAjaxTransport().getLoadScript(settings);
  140. } else {
  141. ret = GQ.getAjaxTransport().getXhr(settings)
  142. .then(new Function() {
  143. public Object f(Object... args) {
  144. Response response = arguments(0);
  145. Request request = arguments(1);
  146. Object retData = response.getText();
  147. if (retData != null && !"".equals(retData)) {
  148. try {
  149. if ("xml".equalsIgnoreCase(dataType)) {
  150. retData = JsUtils.parseXML(response.getText());
  151. } else if ("json".equalsIgnoreCase(dataType)) {
  152. retData = GQ.create(response.getText());
  153. } else {
  154. retData = response.getText();
  155. if ("script".equalsIgnoreCase(dataType)) {
  156. ScriptInjector.fromString((String) retData).setWindow(window).inject();
  157. }
  158. }
  159. } catch (Exception e) {
  160. if (GWT.isClient() && GWT.getUncaughtExceptionHandler() != null) {
  161. GWT.getUncaughtExceptionHandler().onUncaughtException(e);
  162. } else {
  163. e.printStackTrace();
  164. }
  165. }
  166. }
  167. return new Object[] {retData, "success", request, response};
  168. }
  169. }, new Function() {
  170. public Object f(Object... args) {
  171. Throwable exception = arguments(0);
  172. Request request = getArgument(1, Request.class);
  173. String msg = String.valueOf(exception);
  174. return new Object[] {null, msg, request, null, exception};
  175. }
  176. });
  177. }
  178. if (onSuccess != null) {
  179. ret.done(onSuccess);
  180. }
  181. if (onError != null) {
  182. ret.fail(onError);
  183. }
  184. return ret;
  185. }
  186. private static void resolveSettings(Settings settings) {
  187. String url = settings.getUrl();
  188. assert settings != null && settings.getUrl() != null : "no url found in settings";
  189. String type = "POST";
  190. if (settings.getType() != null) {
  191. type = settings.getType().toUpperCase();
  192. }
  193. if ("jsonp".equalsIgnoreCase(settings.getDataType())) {
  194. type = "GET";
  195. }
  196. settings.setType(type);
  197. IsProperties data = settings.getData();
  198. if (data != null) {
  199. String dataString = null, contentType = null;
  200. if (data.getDataImpl() instanceof JavaScriptObject
  201. && JsUtils.isFormData(data.<JavaScriptObject> getDataImpl())) {
  202. dataString = null;
  203. contentType = FormPanel.ENCODING_URLENCODED;
  204. } else if (settings.getType().matches("(POST|PUT)")
  205. && "json".equalsIgnoreCase(settings.getDataType())) {
  206. dataString = data.toJson();
  207. contentType = JSON_CONTENT_TYPE_UTF8;
  208. } else {
  209. dataString = data.toQueryString();
  210. contentType = FormPanel.ENCODING_URLENCODED;
  211. }
  212. settings.setDataString(dataString);
  213. settings.setContentType(contentType);
  214. }
  215. if ("GET".equals(settings.getType()) && settings.getDataString() != null) {
  216. url += (url.contains("?") ? "&" : "?") + settings.getDataString();
  217. settings.setUrl(url);
  218. }
  219. }
  220. public static Promise ajax(String url, Function onSuccess, Function onError) {
  221. return ajax(url, onSuccess, onError, (Settings) null);
  222. }
  223. public static Promise ajax(String url, Function onSuccess, Function onError, Settings s) {
  224. if (s == null) {
  225. s = createSettings();
  226. }
  227. s.setUrl(url).setSuccess(onSuccess).setError(onError);
  228. return ajax(s);
  229. }
  230. public static Promise ajax(String url, IsProperties p) {
  231. Settings s = createSettings();
  232. s.load(p);
  233. s.setUrl(url);
  234. return ajax(s);
  235. }
  236. public static Promise ajax(String url, Settings settings) {
  237. return ajax(settings.setUrl(url));
  238. }
  239. public static Settings createSettings() {
  240. return createSettings("");
  241. }
  242. public static Settings createSettings(String prop) {
  243. Settings s = GQ.create(Settings.class);
  244. if (prop != null && !prop.isEmpty())
  245. s.parse(prop);
  246. return s;
  247. }
  248. public static Settings createSettings(IsProperties p) {
  249. Settings s = GQ.create(Settings.class);
  250. s.load(p.getDataImpl());
  251. return s;
  252. }
  253. public static Promise get(String url) {
  254. return get(url, null);
  255. }
  256. public static Promise get(String url, IsProperties data) {
  257. return get(url, (IsProperties) data, null);
  258. }
  259. /**
  260. * @deprecated Use promises instead
  261. */
  262. public static Promise get(String url, IsProperties data, Function onSuccess) {
  263. Settings s = createSettings();
  264. s.setUrl(url);
  265. s.setDataType("txt");
  266. s.setType("get");
  267. s.setData(data);
  268. s.setSuccess(onSuccess);
  269. return ajax(s);
  270. }
  271. public static Promise getJSON(String url, IsProperties data) {
  272. return getJSON(url, data, null);
  273. }
  274. public static Promise getJSON(String url, IsProperties data, Function onSuccess) {
  275. Settings s = createSettings();
  276. s.setUrl(url);
  277. s.setDataType("json");
  278. s.setType("post");
  279. s.setData(data);
  280. s.setSuccess(onSuccess);
  281. return ajax(s);
  282. }
  283. public static Promise getJSONP(String url) {
  284. return getJSONP(url, null);
  285. }
  286. public static Promise getJSONP(String url, IsProperties data) {
  287. return getJSONP(url, (IsProperties) data, null);
  288. }
  289. public static Promise getJSONP(String url, IsProperties data, Function onSuccess) {
  290. Settings s = createSettings();
  291. s.setUrl(url);
  292. s.setDataType("jsonp");
  293. s.setType("get");
  294. s.setData(data);
  295. s.setSuccess(onSuccess);
  296. return ajax(s);
  297. }
  298. public static Promise getJSONP(String url, Function success, Function error, int timeout) {
  299. return ajax(createSettings()
  300. .setUrl(url)
  301. .setDataType("jsonp")
  302. .setType("get")
  303. .setTimeout(timeout)
  304. .setSuccess(success)
  305. .setError(error));
  306. }
  307. /**
  308. * Get a JavaScript file from the server using a GET HTTP request, then execute it.
  309. */
  310. public static Promise getScript(String url) {
  311. return getScript(url, null);
  312. }
  313. public static Promise getScript(final String url, Function success) {
  314. return ajax(createSettings()
  315. .setUrl(url)
  316. .setType("get")
  317. .setDataType("script")
  318. .setSuccess(success));
  319. }
  320. /**
  321. * Load a JavaScript file from any url using the script tag mechanism.
  322. */
  323. public static Promise loadScript(String url) {
  324. return loadScript(url, null);
  325. }
  326. public static Promise loadScript(final String url, Function success) {
  327. if (!GWT.isClient() || $("script[src^='" + url + "']").isEmpty()) {
  328. return ajax(createSettings()
  329. .setUrl(url)
  330. .setType("get")
  331. .setDataType("loadscript")
  332. .setSuccess(success));
  333. } else {
  334. return Deferred().resolve().promise();
  335. }
  336. }
  337. public static Promise post(String url, IsProperties data) {
  338. return post(url, (IsProperties) data, null);
  339. }
  340. public static Promise post(String url, IsProperties data, final Function onSuccess) {
  341. Settings s = createSettings();
  342. s.setUrl(url);
  343. s.setDataType("txt");
  344. s.setType("post");
  345. s.setData(data);
  346. s.setSuccess(onSuccess);
  347. return ajax(s);
  348. }
  349. protected Ajax(GQuery gq) {
  350. super(gq);
  351. }
  352. public Ajax load(String url, IsProperties data) {
  353. return load(url, data);
  354. }
  355. public Ajax load(String url, IsProperties data, final Function onSuccess) {
  356. Settings s = createSettings();
  357. final String filter = url.contains(" ") ? url.replaceFirst("^[^\\s]+\\s+", "") : "";
  358. s.setUrl(url.replaceAll("\\s+.+$", ""));
  359. s.setDataType("html");
  360. s.setType("get");
  361. s.setData(data);
  362. s.setSuccess(new Function() {
  363. public void f() {
  364. try {
  365. // We clean up the returned string to smoothly append it to our document
  366. // Note: using '\s\S' instead of '.' because gwt String emulation does
  367. // not support java embedded flag expressions (?s) and javascript does
  368. // not have multidot flag.
  369. String s = arguments(0).toString().replaceAll("<![^>]+>\\s*", "")
  370. .replaceAll("</?html[\\s\\S]*?>\\s*", "")
  371. .replaceAll("<head[\\s\\S]*?</head>\\s*", "")
  372. .replaceAll("<script[\\s\\S]*?</script>\\s*", "")
  373. .replaceAll("</?body[\\s\\S]*?>\\s*", "");
  374. // We wrap the results in a div
  375. s = "<div>" + s + "</div>";
  376. Ajax.this.empty().append(filter.isEmpty() ? $(s) : $(s).find(filter));
  377. if (onSuccess != null) {
  378. onSuccess.setElement(Ajax.this.get(0));
  379. onSuccess.f();
  380. }
  381. } catch (Exception e) {
  382. if (GWT.getUncaughtExceptionHandler() != null) {
  383. GWT.getUncaughtExceptionHandler().onUncaughtException(e);
  384. }
  385. }
  386. }
  387. });
  388. ajax(s);
  389. return this;
  390. }
  391. /**
  392. * Load an external resource using the link tag element.
  393. * It is appended to the head of the document.
  394. *
  395. * @param rel Specifies the relationship between the current document and the linked document.
  396. * @param url Specifies the location of the linked document
  397. * @return a Promise which will be resolved when the external resource has been loaded.
  398. */
  399. public static Promise loadLink(final String rel, final String url) {
  400. GQuery link = $("link[rel='" + rel + "'][href^='" + url + "']");
  401. if (link.isEmpty()) {
  402. return new PromiseFunction() {
  403. public void f(final Deferred dfd) {
  404. GQuery link = $("<link rel='" + rel + "' href='" + url + "'/>");
  405. link.on("load", new Function() {
  406. public void f() {
  407. // load event is fired before the imported stuff has actually
  408. // being ready, we delay it to be sure it is ready.
  409. new Timer() {
  410. public void run() {
  411. dfd.resolve();
  412. }
  413. }.schedule(100);
  414. }
  415. });
  416. $(document.getHead()).append(link);
  417. }
  418. };
  419. } else {
  420. return Deferred().resolve().promise();
  421. }
  422. }
  423. /**
  424. * Load an external html resource using the link tag element, it sets
  425. * the relationship between the current document as 'import'.
  426. * It is very useful to import web-components.
  427. */
  428. public static Promise importHtml(String url) {
  429. return loadLink("import", url);
  430. }
  431. }