Example usage for com.google.gwt.core.client Callback onSuccess

List of usage examples for com.google.gwt.core.client Callback onSuccess

Introduction

In this page you can find the example usage for com.google.gwt.core.client Callback onSuccess.

Prototype

void onSuccess(T result);

Source Link

Document

Called when an asynchronous call completes successfully.

Usage

From source file:cc.kune.embed.client.EmbedHelper.java

License:GNU Affero Public License

/**
 * Process json request./*from  w w w  . java  2 s  .  c  o m*/
 *
 * @param url
 *          the url
 * @param callback
 *          the callback
 */
public static void processJSONRequest(final String url, final Callback<JavaScriptObject, Void> callback) {
    final JsonpRequestBuilder builder = new JsonpRequestBuilder();
    builder.setTimeout(60000);
    @SuppressWarnings("unused")
    final JsonpRequest<JavaScriptObject> request = builder.requestObject(url,
            new AsyncCallback<JavaScriptObject>() {
                @Override
                public void onFailure(final Throwable exception) {
                    Log.error("JSON exception: ", exception);
                    callback.onFailure(null);
                }

                @Override
                public void onSuccess(final JavaScriptObject result) {
                    callback.onSuccess(result);
                }
            });
}

From source file:cc.kune.embed.client.EmbedHelper.java

License:GNU Affero Public License

/**
 * Process request./*from   w  w  w  .  j a  va2 s  .  co m*/
 *
 * @param url
 *          the url
 * @param callback
 *          the callback
 */
public static void processRequest(final String url, final Callback<Response, Void> callback) {
    try {
        final RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
        // Needed for CORS
        builder.setIncludeCredentials(true);
        @SuppressWarnings("unused")
        final Request request = builder.sendRequest(null, new RequestCallback() {
            @Override
            public void onError(final Request request, final Throwable exception) {
                Log.error("CORS exception: ", exception);
                callback.onFailure(null);
            }

            @Override
            public void onResponseReceived(final Request request, final Response response) {
                if (200 == response.getStatusCode()) {
                    callback.onSuccess(response);
                } else {
                    Log.error("Couldn't retrieve CORS (" + response.getStatusText() + ")");
                    callback.onFailure(null);
                }
            }
        });
    } catch (final RequestException exception) {
        Log.error("CORS exception: ", exception);
        callback.onFailure(null);
    }
}

From source file:ch.gbrain.gwtstorage.manager.StorageManager.java

License:Apache License

/**
 * Write the item to the local fileentry asynchronous
 * /*www .  j av  a 2 s .co  m*/
 * @param fileEntry
 * @param item
 * @param callback Is called once the asynch action completed or failed
 * @return false if the asynchronous action invocation failed.
 */
private boolean writeStorageItemToLocalFile(FileEntry fileEntry, final StorageItem item,
        final Callback<StorageItem, StorageError> callback) {
    if (item == null)
        return false;
    try {
        logger.log(Level.INFO, "writeStorageItem to local file invoked" + item.getLogId());
        fileEntry.createWriter(new FileCallback<FileWriter, FileError>() {
            @Override
            public void onSuccess(FileWriter writer) {
                writer.setOnWriteEndCallback(new WriterCallback<FileWriter>() {
                    @Override
                    public void onCallback(FileWriter result) {
                        // file written
                        logger.log(Level.INFO, "writeToLocalFile successfully written" + item.getLogId());
                        if (callback != null) {
                            callback.onSuccess(item);
                        }
                    }
                });
                writer.setOnErrorCallback(new WriterCallback<FileWriter>() {
                    @Override
                    public void onCallback(FileWriter result) {
                        // Error while writing file
                        logger.log(Level.SEVERE,
                                "Failure file write StorageItem" + item.getLogId() + " : " + result.toString());
                        if (callback != null) {
                            callback.onFailure(new StorageError(result.getError()));
                        }
                    }
                });
                JSONValue json = item.toJson();
                writer.write(json.toString());
            }

            @Override
            public void onFailure(FileError error) {
                // can not create writer
                logger.log(Level.SEVERE, "Failure file writer creation StorageItem" + item.getLogId() + " : "
                        + error.toString());
                if (callback != null) {
                    callback.onFailure(new StorageError(error));
                }
            }
        });
        return true;
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception file write StorageItem" + item.toString(), ex);
        if (callback != null) {
            callback.onFailure(new StorageError(FileError.ABORT_ERR));
        }
    }
    return false;
}

From source file:ch.gbrain.gwtstorage.manager.StorageManager.java

License:Apache License

/**
 * Read the StorageItem from the given FileEntry and refresh the given
 * CommonView//from   w w w.  ja v  a2  s . co  m
 * 
 * @param fileEntry
 * @param item
 * @param callback Is called once the asynch action completed or failed
 * @return false if the asynchronous action invocation failed.
 */
private boolean readStorageItemFromLocalFile(FileEntry fileEntry, final StorageItem item,
        final Callback<StorageItem, StorageError> callback) {
    if (item == null)
        return false;
    try {
        // logger.log(Level.INFO,"readStorageItem from local file invoked" +
        // item.getLogId());
        FileReader reader = phonegap.getFile().createReader();
        reader.setOnloadCallback(new ReaderCallback<FileReader>() {
            @Override
            public void onCallback(FileReader result) {
                String json = result.getResult();
                // do something with the content
                item.fromJson(json);
                logger.log(Level.INFO,
                        "readStorageItem from local file load completed for item" + item.getLogId());
                if (callback != null) {
                    callback.onSuccess(item);
                }
            }
        });
        reader.setOnErrorCallback(new ReaderCallback<FileReader>() {
            @Override
            public void onCallback(FileReader result) {
                // error while reading file...
                logger.log(Level.SEVERE,
                        "Error StorageItem file writer reading" + item.getLogId() + " : " + result.toString());
                if (callback != null) {
                    callback.onFailure(new StorageError(result.getError()));
                }
            }
        });
        return true;
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception file read StorageItem" + item.getLogId(), ex);
        if (callback != null) {
            callback.onFailure(new StorageError(FileError.ABORT_ERR));
        }
    }
    return false;
}

From source file:ch.gbrain.gwtstorage.manager.StorageManager.java

License:Apache License

/**
 * Retrieve the item from the storage. First try local storage, if the version
 * and the validTime are valid, it is returned. Else it tries to retrieve it
 * from the remote backend. If found, it is cached locally for fast access.
 * /*  w  ww . ja v a  2s  . c  o m*/
 * @param item The item to be read by ID from 1. the cache, 2. localAppPath 3.
 *          remoteAppPath in this priority order
 * @param useCache If true, the system will first try to retrieve the value
 *          from the local cache before it reads the same from the
 *          applications path
 * @param validTime The maximum age in seconds of the cache to be accepted as
 *          a valid item value, if elapsed it will try to read from the
 *          applications path / If <= 0 don't care
 * @param expectedVersion The versionNumber which must be available in the
 *          cache to be a valid cache item. If <=0 don't care.
 */
public boolean readStorageItem(final StorageItem item, boolean useCache, int expectedVersion, int validTime,
        final Callback<StorageItem, StorageError> callback) {
    try {
        logger.log(Level.INFO, "readStorageItem" + item.getLogId());
        if (useCache && this.getCacheEnabled()) { // retrieve the item first from local storage cache
            if (this.readStorageItemFromLocalStorage(item, expectedVersion, validTime)) { // found it valid in the cache
                callback.onSuccess(item);
                return true;
            }
        }
        // didn't found a matching item in the cache yet or version mismatch or
        // cache time elapsed
        if (phonegap.isPhoneGapDevice()) {
            // we run in a locally installed app and want to retrieve now the value
            // from the given backend
            return this.readStorageItemFromRemoteApplication(item, callback);
        } else { // in the case of web app, load it from the applications relative base path
                 // this is automatically from the backend server where the app was
                 // loaded from
            return this.readStorageItemFromLocalApplication(item, callback);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception readStorageItem" + item.getLogId(), ex);
        if (callback != null) {
            callback.onFailure(new StorageError(FileError.ABORT_ERR));
        }
    }
    return false;
}

From source file:ch.gbrain.gwtstorage.manager.StorageManager.java

License:Apache License

/**
 * Creates and returns a Callback which treats the result for a url Item
 * retrieval//from w  w  w  . j  av a2s  .c  o  m
 * 
 * @param item The StorageItem (or a inheriting object) which must be read
 *          (filled in with the retrieved data)
 * @param callback The final resp. initial callback to be notified of the
 *          result
 * @param fallBack A URL to which a further request must be done if the call
 *          fails
 * @return The callback which deals with the asynch result of the remote item
 *         retrieval
 */
private Callback<StorageItem, StorageError> getReadStorageItemHandler(final StorageItem item,
        final Callback<StorageItem, StorageError> callback, final String fallbackUrl) {
    return new Callback<StorageItem, StorageError>() {
        public void onSuccess(StorageItem newItem) { // loading succeeded
                                                     // store it in the cache
            logger.log(Level.INFO, "Completed read item from url" + item.getLogId());
            writeStorageItemToLocalStorage(newItem);
            callback.onSuccess(newItem);
        }

        public void onFailure(StorageError error) {
            logger.log(Level.WARNING, "Failure url loading" + item.getLogId());
            // nothing found, check if we must retrieve it from a remote location
            if (fallbackUrl != null && !fallbackUrl.isEmpty()) {
                readStorageItemFromUrl(fallbackUrl, item, getReadStorageItemHandler(item, callback, null));
            } else {
                callback.onFailure(error);
            }
        }
    };
}

From source file:ch.gbrain.gwtstorage.manager.StorageManager.java

License:Apache License

/**
 * Read the JSON item asynch from the given url and the
 * standard name of the item eg. ch.gbrain.testapp.model.items-1.json
 * // w w w  . j av  a 2  s  .  c o m
 * @param url The url to read from eg. for local application relative path
 *          "storage/v1/" eg. for remote location
 *          "http://host.domain.ch/testapp/storage/v1/"
 * @param item
 * @param callback is called once the asynch action completed or failed
 * @return false if the asynchronous action invocation failed and no callback will be invoked
 */
public boolean readStorageItemFromUrl(String url, final StorageItem item,
        final Callback<StorageItem, StorageError> callback) {
    if (item == null)
        return false;
    try {
        Resource resource = new Resource(url + item.getJsonFileName() + "?noCache=" + new Date().getTime());
        Method method = resource.get();
        /**
         * if (username.isEmpty()) { method = resource.get(); }else { method =
         * resource.get().user(username).password(password); }
         */
        logger.log(Level.INFO, "Read from url:" + method.builder.getUrl());
        method.send(new JsonCallback() {
            public void onSuccess(Method method, JSONValue response) {
                logger.log(Level.INFO, "Read from url success");
                if (response != null) {
                    try {
                        logger.log(Level.INFO, "Successfully url read" + item.getLogId());
                        item.fromJson(response);
                        if (callback != null) {
                            callback.onSuccess(item);
                        }
                    } catch (Exception ex) {
                        logger.log(Level.SEVERE, "Failure url read" + item.getLogId(), ex);
                    }
                }
            }

            public void onFailure(Method method, Throwable exception) {
                logger.log(Level.WARNING, "Failure url read" + item.getLogId(), exception);
                if (callback != null) {
                    callback.onFailure(new StorageError(FileError.NOT_READABLE_ERR, exception.getMessage()));
                }
            }
        });
        logger.log(Level.INFO, "Read from url call complete");
        return true;
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Error url read" + item.getLogId(), ex);
        if (callback != null) {
            callback.onFailure(new StorageError(FileError.ABORT_ERR));
        }
    }
    return false;
}

From source file:ch.gbrain.gwtstorage.manager.StorageManager.java

License:Apache License

/**
 * Evaluates in case of the runtime (browser/phonegap) the full url where a
 * resource must be retrieved from. In case of Phonegap, it will check if we
 * have the resource already locally stored in the cache and return a url
 * pointing to this one instead.//w  w  w.  ja  va2  s .  c  o  m
 * 
 * @param relativeUrl of the resource as it is available in the application
 *          itself.
 * @param version Check if the version of the stored resource equals. Not
 *          checked if version=0
 * @return true if the retrieval was invoked successfully, means you could expect a callback, false otherwise.
 */
public boolean retrieveResourceUrl(final String relativeUrl, Integer version,
        final Callback<String, FileError> callback) {
    try {
        if (relativeUrl == null || relativeUrl.isEmpty()) {
            if (callback != null) {
                logger.log(Level.INFO,
                        "Web ResourceCacheReference retrieval impossible with invalid URL : " + relativeUrl);
                callback.onFailure(
                        new StorageError(FileError.SYNTAX_ERR, "Invalid Url given : " + relativeUrl));
            }
            return false;
        }
        if (!phonegap.isPhoneGapDevice()) {
            if (callback != null) {
                logger.log(Level.INFO, "Web ResourceCacheReference retrieval : " + relativeUrl);
                callback.onSuccess(relativeUrl);
            }
            return true;
        }
        // check if we have a cached resource (eg. with a corresponding cache item
        // in the storage)
        StorageResource resource = new StorageResource(relativeUrl, version, null);
        Boolean checkVersion = checkResourceVersion(resource);
        if (checkVersion == null) {
            logger.log(Level.INFO,
                    "No resource cache item found for : " + relativeUrl + " / version:" + version);
            if (callback != null) {
                callback.onFailure(new StorageError(FileError.NOT_FOUND_ERR, "No resource cache item found"));
            }
        } else if (checkVersion == true) {
            // it should be there already and version is ok
            logger.log(Level.INFO,
                    "Successful ResourceCacheReference retrieval : " + relativeUrl + " / version=" + version);
            getCacheDirectoryEntry(new Callback<DirectoryEntry, StorageError>() {
                public void onSuccess(DirectoryEntry dirEntry) {
                    if (callback != null) {
                        String localResourceUrl = dirEntry.toURL() + "/"
                                + convertFilePathToFileName(relativeUrl);
                        logger.log(Level.INFO, "Successful ResourceCacheUrl evaluation : " + localResourceUrl);
                        callback.onSuccess(localResourceUrl);
                    }
                }

                public void onFailure(StorageError error) {
                    logger.log(Level.WARNING, "Failure in ResourceCacheUrl evaluation : " + relativeUrl
                            + " error:" + error.getErrorCode());
                    if (callback != null) {
                        callback.onFailure(error);
                    }
                }
            });
            return true;
        } else {
            logger.log(Level.INFO,
                    "No matching resource cache item found for : " + relativeUrl + "version:" + version);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception resourceUrl evaluation for : " + relativeUrl, ex);
    }
    return false;
}

From source file:ch.gbrain.gwtstorage.manager.StorageManager.java

License:Apache License

public boolean getCacheDirectoryEntry(final Callback<DirectoryEntry, StorageError> callback) {
    try {//from  ww  w  . ja  v a  2 s  . co m
        if (cacheDirectoryEntry != null && callback != null) {
            callback.onSuccess(cacheDirectoryEntry);
            return true;
        }
        if (!phonegap.isPhoneGapDevice())
            return false;
        String cacheDir = getCacheDirectory();
        getLocalDirectoryEntry(cacheDir, new FileCallback<DirectoryEntry, StorageError>() {
            @Override
            public void onSuccess(DirectoryEntry entry) {
                logger.log(Level.INFO,
                        "CacheDirectory successfully retrieved with path:" + entry.getFullPath());
                cacheDirectoryEntry = entry;
                if (callback != null) {
                    callback.onSuccess(entry);
                }
            }

            @Override
            public void onFailure(StorageError error) {
                logger.log(Level.SEVERE,
                        "Failure Cache FileSystem Directory retrieval" + " : " + error.toString());
                // stop the whole stuff, it doesn't work at all, we don't continue
                // here. Caching will not work therefore
                if (callback != null) {
                    callback.onFailure(error);
                }
            }
        });
        return true;
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception Cache FileSystem Directory retrieval", ex);
    }
    return false;
}

From source file:client.managers.history.HistoryState.java

License:Open Source License

/**
 * Request an up-to-date {@code HistoryStateData}.
 *
 * @param callback {@code Callback} called when ready.
 *//*from w ww.j a v  a 2s  .  com*/
public void getData(final Callback<HistoryStateData, Void> callback) {
    if (data != null) {
        callback.onSuccess(data);
        return;
    }

    dataCallbacks.add(callback);

    if (loadingData) {
        return;
    }

    loadingData = true;

    /*
     * Make RPC request
     */
    WBIExplorationService.getStateData(this, new ClientRequest.Listener<HistoryStateData>() {
        @Override
        public void onSuccess(HistoryStateData data) {
            setData(data);

            // Call callbacks
            for (Callback<HistoryStateData, Void> callback : dataCallbacks) {

                callback.onSuccess(data);
            }

            dataCallbacks.clear();
        }

        @Override
        public void onFailure(ClientRequest.Error error) {
            invalidateData();

            // Call callbacks
            for (Callback<HistoryStateData, Void> callback : dataCallbacks) {

                callback.onFailure(null);
            }

            dataCallbacks.clear();
        }
    });
}