Example usage for com.google.gwt.query.client.plugins.ajax Ajax createSettings

List of usage examples for com.google.gwt.query.client.plugins.ajax Ajax createSettings

Introduction

In this page you can find the example usage for com.google.gwt.query.client.plugins.ajax Ajax createSettings.

Prototype

public static Settings createSettings() 

Source Link

Usage

From source file:org.lirazs.gbackbone.client.core.net.NetworkSyncStrategy.java

License:Apache License

/**
 * // Override this function to change the manner in which Backbone persists
 // models to the server. You will be passed the type of request, and the
 // model in question. By default, makes a RESTful Ajax request
 // to the model's `url()`. Some possible customizations could be:
 ///*from www  .  jav a  2s. c  om*/
 // * Use `setTimeout` to batch rapid-fire updates into a single request.
 // * Send up the models as XML instead of JSON.
 // * Persist models via WebSockets instead of Ajax.
 //
 // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
 // as `POST`, with a `_method` parameter containing the true HTTP method,
 // as well as all requests with the body as `application/x-www-form-urlencoded`
 // instead of `application/json` with the model in a param named `model`.
 // Useful when interfacing with server-side languages like **PHP** that make
 // it difficult to read the body of `PUT` requests.
        
 export function sync(method, model, options) {
 var type = methodMap[method];
        
 // Default options, unless specified.
 _.defaults(options || (options = {}), {
     emulateHTTP: Backbone.emulateHTTP,
     emulateJSON: Backbone.emulateJSON
 });
        
 // Default JSON-request options.
 var params = <any> { type: type, dataType: 'json' };
        
 // Ensure that we have a URL.
 if (!options.url) {
    params.url = _.result(model, 'url') || Helpers.urlError();
 }
        
 // Ensure that we have the appropriate request data.
 if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
     params.contentType = 'application/json';
     params.data = JSON.stringify(options.attrs || model.toJSON(options));
 }
        
 // For older servers, emulate JSON by encoding the request into an HTML-form.
 if (options.emulateJSON) {
     params.contentType = 'application/x-www-form-urlencoded';
     params.data = params.data ? { model: params.data } : {};
 }
        
 // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
 // And an `X-HTTP-Method-Override` header.
 if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
     params.type = 'POST';
        
     if (options.emulateJSON) params.data._method = type;
        
     var beforeSend = options.beforeSend;
        
     options.beforeSend = function (xhr) {
         xhr.setRequestHeader('X-HTTP-Method-Override', type);
         if (beforeSend) return beforeSend.apply(this, arguments);
     };
 }
        
 // Don't process data on a non-GET request.
 if (params.type !== 'GET' && !options.emulateJSON) {
    params.processData = false;
 }
        
 // If we're sending a `PATCH` request, and we're in an old Internet Explorer
 // that still has ActiveX enabled by default, override jQuery to use that
 // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
 if (params.type === 'PATCH' && noXhrPatch) {
 params.xhr = function () {
 return new ActiveXObject("Microsoft.XMLHTTP");
     };
 }
        
 // Make the request, allowing the user to override any Ajax options.
 var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
 model.trigger('request', model, xhr, options);
        
 return xhr;
 };
 */
public Promise sync(String method, Synchronized model, Options options) {
    String type = methodMap.get(method);

    /**
     * // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
     // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
     // set a `X-Http-Method-Override` header.
     export var emulateHTTP = false;
            
     // Turn on `emulateJSON` to support legacy servers that can't deal with direct
     // `application/json` requests ... will encode the body as
     // `application/x-www-form-urlencoded` instead and will send the model in a
     // form param named `model`.
     export var emulateJSON = false;
     */
    // Default options, unless specified.
    if (options == null)
        options = new Options();
    options.defaults(new Options("emulateHTTP", false, "emulateJSON", false));

    // Default JSON-request options.
    Ajax.Settings settings = Ajax.createSettings();
    settings.setType(type);
    settings.setDataType("json");

    // Ensure that we have a URL.
    if (!options.containsKey("url")) {
        String url = model.getUrl();
        if (url == null || url.isEmpty())
            throw new Error("A 'url' property or function must be specified");

        settings.setUrl(url);
    }

    // Ensure that we have the appropriate request data.
    if (!options.containsKey("data") && model != null
            && (method.equals("create") || method.equals("update") || method.equals("patch"))) {
        settings.setContentType("application/json");

        String data;
        if (options.containsKey("attrs")) {
            JsonSerializable attrs = options.get("attrs");
            data = attrs.toJsonString();
        } else {
            JsonSerializable attrs = model.toJSON();
            data = attrs.toJsonString();
        }
        settings.setData(data);
    }

    // For older servers, emulate JSON by encoding the request into an HTML-form.
    if (options.getBoolean("emulateJSON")) {
        settings.setContentType("application/x-www-form-urlencoded");
        IsProperties data = settings.getData();
        if (data != null) {
            data = Properties.create().$$("model", data.toJson());
        } else {
            data = Properties.create();
        }
        settings.setData(data);
    }

    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
    // And an `X-HTTP-Method-Override` header.
    if (options.getBoolean("emulateHTTP")
            && (type.equals("PUT") || type.equals("DELETE") || type.equals("PATCH"))) {
        settings.setType("POST");

        if (options.getBoolean("emulateJSON"))
            settings.getData().set("_method", type);

        Function beforeSend = options.get("beforeSend");

        //NOTE: Before send implementation is not supported by GQuery (another way for backbone users?)
        /*options.beforeSend = function (xhr) {
        xhr.setRequestHeader('X-HTTP-Method-Override', type);
        if (beforeSend) return beforeSend.apply(this, arguments);
        };*/
    }

    // Don't process data on a non-GET request.
    if (!settings.getType().equals("GET") && !options.getBoolean("emulateJSON")) {
        //NOTE: Disable of process data is not available in the GQuery Ajax API
        //params.processData = false;
    }

    /**
     * // If we're sending a `PATCH` request, and we're in an old Internet Explorer
     // that still has ActiveX enabled by default, override jQuery to use that
     // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
     if (params.type === 'PATCH' && noXhrPatch) {
     params.xhr = function () {
        return new ActiveXObject("Microsoft.XMLHTTP");
     };
     }
     */
    // If we're sending a `PATCH` request, and we're in an old Internet Explorer
    // that still has ActiveX enabled by default, override jQuery to use that
    // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
    if (settings.getType().equals("PATCH") && noXhrPatch()) {
        //NOTE: no set Xhr in the GQuery Ajax Library
        //settings.setXhr();
    }

    // Make the request, allowing the user to override any Ajax options.
    /**
     * Ajax.Settings setContentType(String var1);
     Ajax.Settings setContext(Element var1);
     Ajax.Settings setData(Object var1);
     Ajax.Settings setDataString(String var1);
     Ajax.Settings setDataType(String var1);
     Ajax.Settings setError(Function var1);
     Ajax.Settings setHeaders(IsProperties var1);
     Ajax.Settings setPassword(String var1);
     Ajax.Settings setSuccess(Function var1);
     Ajax.Settings setTimeout(int var1);
     Ajax.Settings setType(String var1);
     Ajax.Settings setUrl(String var1);
     Ajax.Settings setUsername(String var1);
     Ajax.Settings setWithCredentials(boolean var1);
     */
    if (options.containsKey("contentType"))
        settings.setContentType(options.<String>get("contentType"));
    if (options.containsKey("context"))
        settings.setContext(options.<Element>get("context"));
    if (options.containsKey("data")) {
        Object data = options.get("data");
        // make sure options object is not just passed along to the GQuery Ajax
        if (data instanceof Options)
            data = ((Options) data).toJsonString();

        settings.setData(data);
    }
    if (options.containsKey("dataString"))
        settings.setDataString(options.<String>get("dataString"));
    if (options.containsKey("dataType"))
        settings.setDataString(options.<String>get("dataType"));
    if (options.containsKey("error"))
        settings.setError(options.<Function>get("error"));
    //TODO: Support for headers
    /*if(options.containsKey("headers"))
    settings.setHeaders(options.getJsObject("headers").toProperties());*/
    if (options.containsKey("password"))
        settings.setDataString(options.<String>get("password"));
    if (options.containsKey("success"))
        settings.setSuccess(options.<Function>get("success"));
    if (options.containsKey("timeout"))
        settings.setTimeout(options.getInt("timeout"));
    if (options.containsKey("type"))
        settings.setType(options.<String>get("type"));
    if (options.containsKey("url"))
        settings.setUrl(options.<String>get("url"));
    if (options.containsKey("username"))
        settings.setUsername(options.<String>get("username"));
    if (options.containsKey("withCredentials"))
        settings.setWithCredentials(options.getBoolean("withCredentials"));

    saveLastAjaxSettings(settings);

    Promise xhr = GQuery.ajax(settings);
    options.put("xhr", xhr);

    if (model != null)
        model.trigger("request", model, xhr, options);

    return xhr;
}

From source file:org.lirazs.gbackbone.client.core.net.NetworkSyncStrategy.java

License:Apache License

private void saveLastAjaxSettings(Ajax.Settings settings) {
    syncArgs = Ajax.createSettings();

    Object data = settings.get("data");

    syncArgs.setContentType(settings.getContentType());
    syncArgs.setContext(settings.getContext());
    if (data != null) {
        syncArgs.setData(data);/*  w  w  w . ja  va 2s . c  o m*/
    }
    syncArgs.setDataType(settings.getDataType());
    syncArgs.setDataString(settings.getDataString());
    syncArgs.setError(settings.getError());
    syncArgs.setHeaders(settings.getHeaders());
    syncArgs.setSuccess(settings.getSuccess());
    syncArgs.setTimeout(settings.getTimeout());
    syncArgs.setType(settings.getType());
    syncArgs.setUrl(settings.getUrl());
    syncArgs.setUsername(settings.getUsername());
    syncArgs.setWithCredentials(settings.getWithCredentials());
}

From source file:org.lirazs.gbackbone.client.core.view.TemplateFactory.java

License:Apache License

public static Promise loadTemplate(final String filePath, final Options templateSettings) {
    Promise promise;/* w  ww  .  j  av  a2 s  .  com*/
    String urlRoot = TEMPLATE_SETTINGS.get("urlRoot");

    if (templateSettings != null) {
        if (templateSettings.containsKey("urlRoot"))
            urlRoot = templateSettings.get("urlRoot", String.class);
    }
    final String finalFilePath = urlRoot + filePath;

    if (CACHED_TEMPLATES.containsKey(finalFilePath)) {
        promise = new PromiseFunction() {
            @Override
            public void f(Deferred dfd) {
                dfd.notify(1);
                dfd.resolve(CACHED_TEMPLATES.get(finalFilePath));
            }
        };
    } else {
        promise = new PromiseFunction() {
            @Override
            public void f(final Deferred dfd) {

                final Ajax.Settings settings = Ajax.createSettings();
                settings.setUrl(finalFilePath);
                settings.setType("get");
                settings.setDataType("text");
                settings.setSuccess(new Function() {
                    @Override
                    public void f() {
                        String templateString = getArgument(0);
                        Template template = template(templateString, templateSettings);

                        CACHED_TEMPLATES.put(finalFilePath, template);

                        dfd.notify(1);
                        dfd.resolve(template);
                    }
                });
                GQuery.ajax(settings);
            }
        };
    }

    return promise;
}

From source file:org.mindinformatics.gwt.domeo.plugins.persistence.annotopia.src.AnnotopiaPersistenceManager.java

License:Apache License

@Override
public void retrieveExistingAnnotationSetList(IRetrieveExistingAnnotationSetListHandler handler) {
    _application.getLogger().debug(this, "Retrieving list of existing annotation sets...");
    _application.getProgressPanelContainer()
            .setProgressMessage("Retrieving list of existing annotation sets from Annotopia...");

    try {/*from w w w.  j av  a2s  . c  om*/
        Ajax.ajax(Ajax.createSettings().setUrl(URL + "s/annotationset").setHeaders(getAnnotopiaOAuthToken())
                .setDataType("json") // txt, json, jsonp, xml
                .setType("get") // post, get
                .setData(GQuery.$$("apiKey: " + ApplicationUtils.getAnnotopiaApiKey() + ",outCmd:frame,tgtUrl:"
                        + ((IDomeo) _application).getPersistenceManager().getCurrentResource().getUrl())) // parameters for the query-string
                .setTimeout(10000).setSuccess(new Function() { // callback to be run if the request success
                    public void f() {
                        IDomeo _domeo = ((IDomeo) _application);
                        JsAnnotopiaSetsResultWrapper wrapper = (JsAnnotopiaSetsResultWrapper) parseJson(
                                getDataProperties().toJsonString());
                        AnnotopiaConverter unmarshaller = new AnnotopiaConverter(_domeo);
                        List<MAnnotopiaAnnotationSet> sets = unmarshaller.unmarshallAnnotationSetsList(wrapper);
                        _application.getLogger()
                                .debug(this,
                                        "Completed Execution of retrieveExistingAnnotationSetList() in "
                                                + (System.currentTimeMillis()
                                                        - ((IDomeo) _application).getDocumentPipelineTimer())
                                                + "ms");

                        if (sets.size() == 0) {
                            // TODO message no annotation found
                            _application.getLogger().info(this, "No annotation sets found");
                            _application.getProgressPanelContainer()
                                    .setCompletionMessage("No annotation exist for this document");
                        } else {
                            _application.getProgressPanelContainer().hide();
                            try {
                                ExistingAnnotationViewerPanel lwp = new ExistingAnnotationViewerPanel(
                                        (IDomeo) _application, sets);
                                new EnhancedGlassPanel((IDomeo) _application, lwp, lwp.getTitle(), false, false,
                                        false);
                            } catch (Exception e) {
                                _application.getLogger().exception(this,
                                        "Exeption in visualizing existing annotation");
                            }
                        }
                    }
                }).setError(new Function() { // callback to be run if the request fails
                    public void f() {
                        _application.getLogger().exception(this,
                                "Couldn't complete existing annotation sets list retrieval process");
                        _application.getProgressPanelContainer().setErrorMessage(
                                "Couldn't complete existing annotation sets list retrieval process");
                    }
                }));
    } catch (Exception e) {
        _application.getLogger().exception(this, "Couldn't complete existing annotation sets list retireval");
    }
}

From source file:org.mindinformatics.gwt.domeo.plugins.persistence.annotopia.src.AnnotopiaPersistenceManager.java

License:Apache License

@Override
public void retrieveExistingAnnotationSets(List<String> urls, IRetrieveExistingAnnotationSetHandler handler) {
    _application.getLogger().debug(this, "Retrieving requested annotation sets...");
    _application.getProgressPanelContainer()
            .setProgressMessage("Retrieving requested annotation sets from Annotopia...");

    for (String url : urls) {
        try {/*from  w ww.ja v  a  2 s . c  o m*/
            Ajax.ajax(Ajax.createSettings().setUrl(url).setHeaders(getAnnotopiaOAuthToken()).setDataType("json") // txt, json, jsonp, xml
                    .setType("get") // post, get
                    .setData(GQuery.$$("apiKey: " + ApplicationUtils.getAnnotopiaApiKey() + ",outCmd:frame")) // parameters for the query-string
                    .setTimeout(10000).setSuccess(new Function() { // callback to be run if the request success
                        public void f() {
                            IDomeo _domeo = ((IDomeo) _application);
                            JsAnnotopiaAnnotationSetGraph wrapper = (JsAnnotopiaAnnotationSetGraph) parseJson(
                                    getDataProperties().toJsonString());
                            AnnotopiaConverter unmarshaller = new AnnotopiaConverter(_domeo);

                            MAnnotationSet set = unmarshaller.unmarshallAnnotationSet(wrapper, true);
                            if (set == null) {
                                // TODO message no annotation found
                                _application.getLogger().info(this, "No annotation set found");
                                _application.getProgressPanelContainer()
                                        .setCompletionMessage("Annotation Set not found");
                            } else {
                                ((AnnotationPersistenceManager) _domeo.getPersistenceManager())
                                        .loadAnnotationSet(set);
                                _application.getProgressPanelContainer().hide();
                                _application.getLogger().debug(this,
                                        "Completed Execution of retrieveExistingAnnotationSets() in "
                                                + (System.currentTimeMillis()
                                                        - ((IDomeo) _application).getDocumentPipelineTimer())
                                                + "ms");
                                _domeo.refreshAllComponents();
                            }
                        }
                    }).setError(new Function() { // callback to be run if the request fails
                        public void f() {
                            _application.getLogger().exception(this,
                                    "Couldn't complete existing annotation sets list retrieval process");
                            _application.getProgressPanelContainer().setErrorMessage(
                                    "Couldn't complete existing annotation sets list retrieval process");
                        }
                    }));
        } catch (Exception e) {
            _application.getLogger().exception(this,
                    "Couldn't complete existing annotation sets list retrieval");
        }
    }
}

From source file:org.mindinformatics.gwt.domeo.plugins.persistence.annotopia.src.AnnotopiaPersistenceManager.java

License:Apache License

@Override
public void saveAnnotation() {
    _application.getLogger().debug(this, "Saving modified annotation sets...");
    _application.getProgressPanelContainer()
            .setProgressMessage("Saving modified annotation sets to Annotopia...");

    ArrayList<MAnnotationSet> setToSerialize = new ArrayList<MAnnotationSet>();
    for (MAnnotationSet set : ((IDomeo) _application).getAnnotationPersistenceManager()
            .getAllDiscussionSets()) {//from   w ww. j  ava 2 s .  c  o m
        if (set.getHasChanged() && set.getAnnotations().size() > 0)
            setToSerialize.add(set);
    }
    for (MAnnotationSet set : ((IDomeo) _application).getAnnotationPersistenceManager().getAllUserSets()) {
        if (set.getHasChanged() && set.getAnnotations().size() > 0)
            setToSerialize.add(set);
    }

    AnnotopiaSerializerManager manager = AnnotopiaSerializerManager.getInstance((IDomeo) _application);
    for (MAnnotationSet annotationSet : setToSerialize) {
        final String operation = (annotationSet.getVersionNumber() == null
                || annotationSet.getVersionNumber().isEmpty()) ? "post" : "put";
        JsUtils.JsUtilsImpl utils = new JsUtils.JsUtilsImpl();
        Properties v = utils.parseJSON("{\"apiKey\":\"" + ApplicationUtils.getAnnotopiaApiKey()
                + "\",\"outCmd\":\"frame\",\"set\":" + manager.serialize(annotationSet).toString() + "}");
        try {
            Ajax.ajax(Ajax.createSettings().setUrl(URL + "s/annotationset").setHeaders(getAnnotopiaOAuthToken())
                    .setDataType("json") // txt, json, jsonp, xml */
                    .setType(operation) // post, get
                    .setData(v) // parameters for the query-string setData(GQuery.$$("apiKey: testkey, set: " + value))
                    .setTimeout(10000).setSuccess(new Function() { // callback to be run if the request success
                        public void f() {
                            IDomeo _domeo = ((IDomeo) _application);
                            JsAnnotopiaSetResultWrapper wrapper = (JsAnnotopiaSetResultWrapper) parseJson(
                                    getDataProperties().toJsonString());
                            AnnotopiaConverter unmarshaller = new AnnotopiaConverter(_domeo);

                            MAnnotationSet set = unmarshaller
                                    .unmarshallAnnotationSet(wrapper.getResult().getSet().get(0), false);
                            if (set == null) {
                                // TODO message no annotation found
                                _application.getLogger().exception(this, "Annotation set not saved correctly");
                                _application.getProgressPanelContainer()
                                        .setErrorMessage("Annotation set not saved correctly");
                            } else {
                                MAnnotationSet currentSet = null;
                                if (operation.equals("post"))
                                    currentSet = _domeo.getPersistenceManager()
                                            .getAnnotationSetById(set.getPreviousVersion());
                                else
                                    currentSet = _domeo.getPersistenceManager()
                                            .getAnnotationSetById(set.getIndividualUri());

                                currentSet.setIndividualUri(set.getIndividualUri());
                                _application.getLogger().info(this,
                                        "Setting Set id to " + currentSet.getIndividualUri());
                                currentSet.setLastSavedOn(set.getLastSavedOn());
                                currentSet.setVersionNumber(set.getVersionNumber());
                                currentSet.setPreviousVersion(set.getPreviousVersion());
                                currentSet.setHasChanged(false);
                                _application.getLogger().info(this, "Set: " + currentSet.getIndividualUri());

                                for (MAnnotation annotation : set.getAnnotations()) {
                                    _application.getLogger().info(this,
                                            "Annotation " + annotation.getPreviousVersion());
                                    for (MAnnotation currentAnnotation : currentSet.getAnnotations()) {
                                        _application.getLogger().info(this,
                                                "Matching " + currentAnnotation.getIndividualUri());
                                        if (currentAnnotation.getIndividualUri()
                                                .equals(annotation.getPreviousVersion())) {

                                            _application.getLogger().info(this, "Matched");
                                            currentAnnotation.setIndividualUri(annotation.getIndividualUri());
                                            currentAnnotation.setLastSavedOn(annotation.getLastSavedOn());
                                            currentAnnotation.setVersionNumber(annotation.getVersionNumber());
                                            currentAnnotation
                                                    .setPreviousVersion(annotation.getPreviousVersion());
                                            currentAnnotation.setHasChanged(false);
                                            // TODO: Assumes one target
                                            currentAnnotation.getSelector()
                                                    .setUri(annotation.getSelector().getUri());
                                            break;
                                        }
                                    }
                                }
                                _application.getProgressPanelContainer().hide();
                                _application.getLogger().debug(this,
                                        "Completed saving of Annotation Set in "
                                                + (System.currentTimeMillis()
                                                        - ((IDomeo) _application).getDocumentPipelineTimer())
                                                + "ms");
                            }
                        }
                    }).setError(new Function() { // callback to be run if the request fails
                        public void f() {
                            Window.alert("There was an error " + getDataObject());

                            _application.getLogger().exception(this,
                                    "Couldn't complete existing annotation sets list saving");
                            _application.getProgressPanelContainer()
                                    .setErrorMessage("Couldn't complete existing annotation sets list saving");
                        }
                    }));
        } catch (Exception e) {
            _application.getLogger().exception(this, "Couldn't complete existing annotation sets list saving");
        }
    }
}