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

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

Introduction

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

Prototype

Callback

Source Link

Usage

From source file:$.ZoomToLocationController.java

License:Open Source License

public void onMouseUp(MouseUpEvent event) {
        //      StyleElement se = (StyleElement) Document.get().getElementById("inlineStyle");
        //      se.setInnerText(".msRibbon { background: green; }");

        final Geolocation geo = Geolocation.getIfSupported();
        if (geo != null) {
            geo.getCurrentPosition(new Callback<Position, PositionError>() {

                @Override/*from  w w  w  .  j a v  a  2  s. c  o m*/
                public void onSuccess(final Position result) {
                    Coordinates coord = result.getCoordinates();
                    TransformGeometryRequest req = new TransformGeometryRequest();
                    GeometryFactory gf = new GeometryFactory(4326, 1);
                    Point point = gf.createPoint(new Coordinate(coord.getLongitude(), coord.getLatitude()));

                    req.setGeometry(GeometryConverter.toDto(point));
                    req.setSourceCrs("EPSG:4326");
                    req.setTargetCrs(mapWidget.getMapModel().getCrs());

                    GwtCommand command = new GwtCommand(TransformGeometryRequest.COMMAND);
                    command.setCommandRequest(req);

                    GwtCommandDispatcher.getInstance().execute(command, new CommandCallback<CommandResponse>() {

                        @Override
                        public void execute(CommandResponse response) {
                            if (response.getErrors().isEmpty()) {
                                org.geomajas.geometry.Geometry geom = ((TransformGeometryResponse) response)
                                        .getGeometry();
                                double accuracy = result.getCoordinates().getAccuracy();

                                Bbox box = new Bbox(geom.getCoordinates()[0].getX() - (accuracy / 2),
                                        geom.getCoordinates()[0].getY() - (accuracy / 2), accuracy, accuracy);
                                mapWidget.getMapModel().getMapView().applyBounds(box, ZoomOption.LEVEL_FIT);
                            }
                        }
                    });

                }

                @Override
                public void onFailure(PositionError reason) {
                    // TODO Auto-generated method stub

                }
            });
        }
        event.stopPropagation();
    }

From source file:cc.kune.embed.client.actions.EmbedSignOutAction.java

License:GNU Affero Public License

@Override
public void actionPerformed(final ActionEvent event) {
    SessionInstance.get().signOut();//www.  j a va 2s .c om
    final String signOutUrl = EmbedHelper.getServerWithPath() + "cors/SiteCORSService/logout";
    EmbedHelper.processRequest(signOutUrl, new Callback<Response, Void>() {

        @Override
        public void onFailure(final Void reason) {
        }

        @Override
        public void onSuccess(final Response response) {

        }
    });
}

From source file:cc.kune.embed.client.panels.EmbedPresenter.java

License:GNU Affero Public License

private void getContentFromHistoryHash(final String stateTokenS) {
    Log.info("Opening statetoken: " + stateTokenS);
    final boolean isGroupToken = TokenMatcher.isGroupToken(stateTokenS);
    final boolean isWaveToken = TokenMatcher.isWaveToken(stateTokenS);
    final String suffix = isGroupToken ? "" : isWaveToken ? "ByWaveRef" : "";

    if (isGroupToken || isWaveToken) {
        // Ok is a token like group.tool.number
        final String getContentUrl = EmbedHelper.getServerWithPath() + "cors/ContentCORSService/getContent"
                + suffix + "?" + new UrlParam(JSONConstants.TOKEN_PARAM, URL.encodeQueryString(stateTokenS));

        // FIXME Exception if is not public?

        EmbedHelper.processRequest(getContentUrl, new Callback<Response, Void>() {

            @Override//from   w ww . ja  va  2s .c  om
            public void onFailure(final Void reason) {
                notFound();
            }

            @Override
            public void onSuccess(final Response response) {
                // final StateToken currentToken = new StateToken(currentHash);
                NotifyUser.hideProgress();
                final StateAbstractDTOJs state = JsonUtils.safeEval(response.getText());
                final StateTokenJs stateTokenJs = (StateTokenJs) state.getStateToken();

                // getContent returns the default content if doesn't finds the content
                if ((isGroupToken && stateTokenS.equals(stateTokenJs.getEncoded()))
                        || (isWaveToken && stateTokenS.equals(state.getWaveRef()))) {
                    onGetContentSuccessful(session, EmbedHelper.parse(state));
                } else {
                    // getContent returns def content if content not found
                    notFound();
                }
            }
        });

    } else {
        // Do something
        notFound();
    }
}

From source file:cc.kune.embed.client.panels.EmbedPresenter.java

License:GNU Affero Public License

private void onAppStarted() {
    // We set the prefix for avatars url with the server url
    final String serverUrl = EmbedConfiguration.get().getServerUrl();
    clientDownUtils.setPrefix(serverUrl);
    final String serverNoSlash = serverUrl.replaceAll("/$", "");
    KuneWaveProfileManager.urlPrefix = serverNoSlash;
    AtmosphereConnectionImpl.urlPrefix = serverNoSlash;

    final String userHash = session.getUserHash();
    Log.info("Started embed presenter with user hash: " + userHash);

    final String initUrl = EmbedHelper.getServerWithPath() + "cors/SiteCORSService/getInitData";

    EmbedHelper.processRequest(initUrl, new Callback<Response, Void>() {
        @Override/*from   ww  w  . j  a v  a2s.c  o m*/
        public void onFailure(final Void reason) {
            // Do nothing
            Log.info("Failed to get init data");
        }

        @Override
        public void onSuccess(final Response response) {
            final InitDataDTOJs initData = JsonUtils.safeEval(response.getText());
            session.setInitData(EmbedHelper.parse(initData));
            final UserInfoDTOJs userInfo = (UserInfoDTOJs) initData.getUserInfo();
            if (userInfo != null) {
                session.setUserHash(userInfo.getUserHash());
                session.setCurrentUserInfo(EmbedHelper.parse(userInfo), null);
            } else {
                if (session.getUserHash() != null) {
                    // Probably the session expired
                    session.signOut();
                }
            }
            final String currentHash = getCurrentHistoryHash();
            final boolean isValid = isCurrentHistoryHashValid(currentHash);
            if (stateTokenToOpen != null) {
                // The open event already received, so open the content
                Log.info("Opening token from JSNI open call");
                getContentFromHistoryHash(stateTokenToOpen);
            } else if (isValid) {
                // We start the embed from the url #hash
                Log.info("Opening token from history token");
                stateTokenToOpen = currentHash;
                getContentFromHistoryHash(currentHash);
            } else {
                // We embed the document via JSNI, so, we wait for the open event
            }
            // We configure sign-out
            session.onUserSignOut(false, new UserSignOutHandler() {
                @Override
                public void onUserSignOut(final UserSignOutEvent event) {
                    Log.info("On user sign out");
                    if (stateTokenToOpen != null) {
                        getContentFromHistoryHash(stateTokenToOpen);
                    }
                }
            });
        }
    });
}

From source file:cc.kune.gspace.client.viewers.ContentViewerPanel.java

License:GNU Affero Public License

@Override
public void injectSplash() {
    ScriptInjector.fromUrl("others/splash/js/wave-rpc.js").setWindow(ScriptInjector.TOP_WINDOW).inject();
    ScriptInjector.fromUrl("others/splash/js/gadget.js").setWindow(ScriptInjector.TOP_WINDOW).inject();
    ScriptInjector.fromUrl("others/splash/js/rpc.js").setWindow(ScriptInjector.TOP_WINDOW)
            .setCallback(new Callback<Void, Exception>() {
                @Override/*  ww w  .jav  a2  s .c o m*/
                public void onFailure(Exception reason) {
                    Log.error("Failed to load rpc.js");
                }

                @Override
                public void onSuccess(Void result) {
                    ScriptInjector.fromUrl("others/splash/js/common_client.js")
                            .setWindow(ScriptInjector.TOP_WINDOW).inject();
                    ScriptInjector.fromUrl("others/splash/js/permalink_client.js")
                            .setWindow(ScriptInjector.TOP_WINDOW).inject();
                }
            }).inject();
}

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  a  2 s .  co 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

/**
 * 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 ww  .j  a  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.StorageResourceCollector.java

License:Apache License

/**
 * Download the given resource url and store it in the local cache Directory.
 * // w ww  .  j a v a2s.c o  m
 * @param resource
 * @param destinationDir The URL of the destination Directoy
 */
public void downloadCacheResource(final StorageResource resource) {
    try {
        if (resource == null)
            return;
        logger.log(Level.INFO,
                "downloadCacheResource " + resource.getResourceUrl() + " Version:" + resource.getVersion());
        storageManager.getCacheDirectoryEntry(new Callback<DirectoryEntry, StorageError>() {
            public void onSuccess(DirectoryEntry cacheDir) {
                try {
                    FileTransfer fileTransfer = phonegap.getFile().createFileTransfer();
                    String localFileName = storageManager.convertFilePathToFileName(resource.getResourceUrl());
                    String sourceUrl = storageManager.getRemoteAppBaseUrl() + resource.getResourceUrl();
                    String destUrl = cacheDir.toURL() + localFileName;
                    // String destUrl =
                    // "cdvfile://localhost/persistent/testapp/test.mp4";
                    logger.log(Level.INFO, "downloadResource invoked for : " + sourceUrl + " to : " + destUrl);
                    fileTransfer.download(sourceUrl, destUrl, getResourceDownloadHandler(resource));
                } catch (Exception lex) {
                    logger.log(Level.SEVERE, "Exception in downloadCacheResource success handler", lex);
                }
            }

            public void onFailure(StorageError error) {
                logger.log(Level.WARNING,
                        "Failed to download CacheResource for : " + resource.getResourceUrl());
                if (resource.getDownloadNotification() != null) {
                    resource.getDownloadNotification()
                            .onFailure(new TransferError(error.getErrorCode(), error.getErrorReason()));
                }
            }
        });
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception resourceDownload for : " + resource.getResourceUrl(), ex);
    }
}

From source file:cimav.client.view.MainUI.java

public void loginIn() {

    final AuthRequest req = new AuthRequest(GOOGLE_AUTH_URL, GOOGLE_CLIENT_ID)
            .withScopes(USER_INFO_PROFILE_SCOPE);

    // Calling login() will display a popup to the user the first time it is
    // called. Once the user has granted access to the application,
    // subsequent calls to login() will not display the popup, and will
    // immediately result in the callback being given the token to use.

    /* Esta es la llamada al Login */

    AUTH.login(req, new Callback<String, Throwable>() {
        @Override//from ww  w  .  java 2 s . c om
        public void onSuccess(final String tokenAutorizacion) {
            // Si se logea, regresa un Token Autorizado
            if (!tokenAutorizacion.trim().isEmpty()) { //TODO simpre considera que no tiene token
                // Si no tiene AUN el token autorizado, busca la autorizacin
                gwtServiceAsync.loginProfile(tokenAutorizacion, Ajax.call(new AsyncCallback<Usuario>() {
                    @Override
                    public void onFailure(Throwable caught) {
                        // Fall la autorizacin
                        GWT.log("login.autorizacion -> onFailure");

                        // se Deslogea
                        //loginOut();
                    }

                    @Override
                    public void onSuccess(Usuario usuarioSrv) {
                        // Paso la autorizacin

                        // asigna el usuario logeado del lado del servidor al usuario del lado del cliente
                        usuario = usuarioSrv;

                        // Si tiene nombre es que se pudo logear.
                        usuario.setLoggedIn(
                                usuario.getNombre() != null && !usuario.getNombre().trim().isEmpty());

                        // Actulizar componentes de Login
                        //                            loginImage.setVisible(true);
                        //                            loginImage.setUrl(usuario.getPictureUrl());
                        //                            loginLabel.setText(usuario.getNombre());
                        //                            loginSignImage.setTitle("Salir");
                        //                            loginSignImage.setUrl(Constantes.ICON_SIGN_OUT);                            

                        // Muestra toda el Area Central
                        //                            centralFlowPanel.setVisible(true);

                        BaseREST.initHeader(usuario.getCuenta());
                    }
                }));

            }

        }

        @Override
        public void onFailure(Throwable caught) {
            // No se logeo
            GWT.log("login -> onFailure");

            // se Deslogea
            //                loginOut();
        }
    });

}

From source file:cimav.visorglass.client.widgets.MainLayout.java

License:Apache License

public void loginIn() {

    final AuthRequest req = new AuthRequest(GOOGLE_AUTH_URL, GOOGLE_CLIENT_ID)
            .withScopes(USER_INFO_PROFILE_SCOPE);

    // Calling login() will display a popup to the user the first time it is
    // called. Once the user has granted access to the application,
    // subsequent calls to login() will not display the popup, and will
    // immediately result in the callback being given the token to use.

    /* Esta es la llamada al Login */

    AUTH.login(req, new Callback<String, Throwable>() {
        @Override/*  w w w .  ja v a2  s.c om*/
        public void onSuccess(final String tokenAutorizacion) {
            // Si se logea, regresa un Token Autorizado
            if (!tokenAutorizacion.trim().isEmpty()) { //TODO simpre considera que no tiene token
                // Si no tiene AUN el token autorizado, busca la autorizacin
                gwtServiceAsync.loginProfile(tokenAutorizacion, Ajax.call(new AsyncCallback<Usuario>() {
                    @Override
                    public void onFailure(Throwable caught) {
                        // Fall la autorizacin
                        GWT.log("login.autorizacion -> onFailure");

                        // se Deslogea
                        loginOut();
                    }

                    @Override
                    public void onSuccess(Usuario usuarioSrv) {
                        // Paso la autorizacin

                        // asigna el usuario logeado del lado del servidor al usuario del lado del cliente
                        usuario = usuarioSrv;

                        // Si tiene nombre es que se pudo logear.
                        usuario.setLoggedIn(
                                usuario.getNombre() != null && !usuario.getNombre().trim().isEmpty());

                        // Actulizar componentes de Login
                        loginImage.setVisible(true);
                        loginImage.setUrl(usuario.getPictureUrl());
                        loginLabel.setText(usuario.getNombre());
                        loginSignImage.setTitle("Salir");
                        loginSignImage.setUrl(Constantes.ICON_SIGN_OUT);

                        // Muestra toda el Area Central
                        centralFlowPanel.setVisible(true);

                        // Carga la Estructura del Usuario
                        // TODO la re-carga no debera ir aqui. Falta revisar todo lo referente al re-login, re-authentication y re-carga.
                        // Al usuario logeado le cargo los Deptos-Permiso a lo que tiene derecho
                        // Al logearse
                        usuario.setDeptos(cargarDepartamentosUsuario());

                        // Ahora, basado en los Departamentos del Usuario, le cargo sus Tipos y Documentos en el Arbol
                        cargaArbol();

                        panelesLayout.setServidorArchivosVigentes(usuario.getServidorArchivosVigentes());
                    }
                }));

            }

        }

        @Override
        public void onFailure(Throwable caught) {
            // No se logeo
            GWT.log("login -> onFailure");

            // se Deslogea
            loginOut();
        }
    });

}