2 * Copyright 2013, The gwtquery team.
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software distributed under the License
10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 * or implied. See the License for the specific language governing permissions and limitations under
14 package com.google.gwt.query.client.plugins.deferred;
16 import com.google.gwt.jsonp.client.JsonpRequestBuilder;
17 import com.google.gwt.query.client.js.JsObjectArray;
18 import com.google.gwt.query.client.js.JsRegexp;
19 import com.google.gwt.query.client.plugins.deferred.Deferred.DeferredPromiseImpl;
20 import com.google.gwt.user.client.rpc.AsyncCallback;
23 * Utility class used to create promises for JsonpRequestBuilder.
25 * Promise p = new PromiseJsonpReqBuilder(url, 4000);
27 * p.done(new Function() {
29 * Properties p = arguments(0);
31 * }).fail(new Function() {
33 * Throwable error = arguments(0);
38 public class PromiseReqBuilderJSONP extends DeferredPromiseImpl {
40 private static final JsRegexp callbackRegex = new JsRegexp("^(.+[\\?&])([^=]+)=\\?(.*)$");
42 public PromiseReqBuilderJSONP(String url) {
46 public PromiseReqBuilderJSONP(String url, int timeout) {
47 this(url, null, timeout);
50 public PromiseReqBuilderJSONP(String url, String callbackParam, int timeout) {
51 JsonpRequestBuilder builder = new JsonpRequestBuilder();
53 builder.setTimeout(timeout);
55 // jQuery allows a parameter callback=? to figure out the callback parameter
56 if (callbackParam == null) {
57 JsObjectArray<String> tmp = callbackRegex.exec(url);
58 if (tmp.length() == 4) {
59 callbackParam = tmp.get(2);
60 url = tmp.get(1) + tmp.get(3);
63 if (callbackParam != null) {
64 builder.setCallbackParam(callbackParam);
66 send(builder, url, new AsyncCallback<Object>() {
67 public void onFailure(Throwable caught) {
71 public void onSuccess(Object result) {
77 // Using jsni because method send in JsonpRequestBuilder is private
78 private final native void send(JsonpRequestBuilder bld, String url, AsyncCallback<?> cb) /*-{
79 bld.@com.google.gwt.jsonp.client.JsonpRequestBuilder::send(Ljava/lang/String;Lcom/google/gwt/user/client/rpc/AsyncCallback;Z)(url,cb,false);