Example usage for com.google.gwt.user.client Timer Timer

List of usage examples for com.google.gwt.user.client Timer Timer

Introduction

In this page you can find the example usage for com.google.gwt.user.client Timer Timer.

Prototype

Timer

Source Link

Usage

From source file:com.google.appinventor.client.explorer.commands.WaitForBuildWebResultCommand.java

License:Open Source License

@Override
public void execute(final ProjectNode node) {
    final Ode ode = Ode.getInstance();
    messagesOutput.clear();/* w  w w . j ava2  s  . c om*/
    messagesOutput.addMessages(MESSAGES.buildRequestedMessage(node.getName(), buildRequestTime));

    OdeAsyncCallback<RpcResult> callback = new OdeAsyncCallback<RpcResult>(
            // failure message
            MESSAGES.buildError()) {
        @Override
        public void onSuccess(RpcResult result) {
            messagesOutput.addMessages("Waiting for " + getElapsedMillis() / 1000 + " seconds.");
            messagesOutput.addMessages(result.getOutput());
            messagesOutput.addMessages(result.getError());
            Tracking.trackEvent(Tracking.PROJECT_EVENT, Tracking.PROJECT_SUBACTION_BUILD_YA, node.getName(),
                    getElapsedMillis());
            if (result.succeeded()) {
                ode.getTopToolbar().updateKeystoreFileMenuButtons();
                executeNextCommand(node);
            } else if (result.getResult() == 1) {
                // General build error
                String errorMsg = result.getError();
                // This is not an internal App Inventor bug. The error should be
                // reported in a yellow info box.
                ErrorReporter
                        .reportInfo(MESSAGES.buildFailedError() + (errorMsg.isEmpty() ? "" : " " + errorMsg));
                executionFailedOrCanceled();
            } else if (result.getResult() == 2) {
                // Yail generation error
                String formName = extractFormName(result);
                ErrorReporter.reportError(MESSAGES.errorGeneratingYail(formName));
                String blocksFileName = formName + YoungAndroidSourceAnalyzer.CODEBLOCKS_SOURCE_EXTENSION;
                YoungAndroidBlocksNode blocksNode = findBlocksNode((YoungAndroidProjectNode) node,
                        blocksFileName);
                if (blocksNode != null) {
                    showProblemBlocks(blocksNode);
                }
                executionFailedOrCanceled();
            } else {
                // Build isn't done yet
                Timer timer = new Timer() {
                    @Override
                    public void run() {
                        execute(node);
                    }
                };
                // TODO(user): Maybe do an exponential backoff here.
                timer.schedule(WAIT_INTERVAL_MILLIS);
            }
        }

        @Override
        public void onFailure(Throwable caught) {
            super.onFailure(caught);
            executionFailedOrCanceled();
        }
    };

    ode.getProjectService().getBuildWebResult(node.getProjectId(), target, callback);
}

From source file:com.google.appinventor.client.explorer.commands.WaitForEclipseProjectBuildResultCommand.java

License:Open Source License

@Override
public void execute(final ProjectNode node) {
    final Ode ode = Ode.getInstance();
    messagesOutput.clear();/*ww w  .  java 2  s .  c o  m*/
    messagesOutput.addMessages(MESSAGES.buildRequestedMessage(node.getName(), buildRequestTime));

    OdeAsyncCallback<RpcResult> callback = new OdeAsyncCallback<RpcResult>(
            // failure message
            MESSAGES.buildError()) {
        @Override
        public void onSuccess(RpcResult result) {
            messagesOutput.addMessages("Waiting for " + getElapsedMillis() / 1000 + " seconds.");
            messagesOutput.addMessages(result.getOutput());
            messagesOutput.addMessages(result.getError());
            Tracking.trackEvent(Tracking.PROJECT_EVENT, Tracking.PROJECT_SUBACTION_BUILD_YA, node.getName(),
                    getElapsedMillis());
            if (result.succeeded()) {
                executeNextCommand(node);
            } else if (result.getResult() == 3) {
                // General build error
                String errorMsg = result.getError();
                // This is not an internal App Inventor bug. The error should be
                // reported in a yellow info box.
                ErrorReporter
                        .reportInfo(MESSAGES.buildFailedError() + (errorMsg.isEmpty() ? "" : " " + errorMsg));
                executionFailedOrCanceled();
            } else {
                // Build isn't done yet
                Timer timer = new Timer() {
                    @Override
                    public void run() {
                        execute(node);
                    }
                };
                // TODO(user): Maybe do an exponential backoff here.
                timer.schedule(WAIT_INTERVAL_MILLIS);
            }
        }

        @Override
        public void onFailure(Throwable caught) {
            super.onFailure(caught);
            executionFailedOrCanceled();
        }
    };

    ode.getProjectService().getEclipseProjectBuildResult(node.getProjectId(), target, buildOption, callback);
}

From source file:com.google.appinventor.client.jsonp.JsonpConnection.java

License:Open Source License

/**
 * Sends a JSONP request by embedding a SCRIPT tag into the document and
 * then polls for the result by resending the request with the parameter
 * {@link JsonpConstants#POLLING}. We continue polling until we receive a
 * response that is not {@link JsonpConstants#NOT_FINISHED_YET}.
 *
 * @param request the request to be made
 * @param p the parameters for the request
 * @param function a function that transforms the response into the type
 *        that the callback needs//from  w  w  w .jav a 2  s .  com
 * @param callback the callback that should be called with the transformed
 *        response
 */
public <T> void sendJsonpRequestAndPoll(final String request, Map<String, Object> p,
        final Function<String, ? extends T> function, final AsyncCallback<T> callback) {
    // Make a new parameters Map so we can add the POLLING parameter below.
    final Map<String, Object> parameters = new HashMap<String, Object>();
    if (p != null) {
        parameters.putAll(p);
    }
    final String initialRequestId = getNextRequestId();

    AsyncCallback<String> pollingCallback = new AsyncCallback<String>() {
        @Override
        public void onSuccess(String response) {
            if (JsonpConstants.NOT_FINISHED_YET.equals(response)) {
                // No response is available yet, create a timer to try again in a second.
                parameters.put(JsonpConstants.POLLING, initialRequestId);

                final AsyncCallback<String> pollingCallback = this;
                Timer timer = new Timer() {
                    @Override
                    public void run() {
                        sendJsonpRequest(request, parameters, stringResponseDecoder, pollingCallback);
                    }
                };
                timer.schedule(1000); // schedule the timer
            } else {
                // The response is available, convert it to the correct type T.
                T result;
                try {
                    result = function.apply(response);
                } catch (RuntimeException e) {
                    callback.onFailure(e);
                    return;
                }
                callback.onSuccess(result);
            }
        }

        @Override
        public void onFailure(Throwable caught) {
            callback.onFailure(caught);
        }
    };

    sendJsonpRequest(initialRequestId, request, parameters, stringResponseDecoder, pollingCallback);
}

From source file:com.google.appinventor.client.jsonp.JsonpConnection.java

License:Open Source License

private void createConnectivityTimers() {
    // We create these GWT timers lazily.
    // We must not create them during a java test because they will cause test failures.

    if (contactTimer == null) {
        // Create (but don't schedule) a timer to send a contact request.
        contactTimer = new Timer() {
            @Override//from   www  .j  a va 2  s.c  om
            public void run() {
                sendContactRequest();
            }
        };
    }
    if (unresponsiveConnectionTimer == null) {
        unresponsiveConnectionTimer = new Timer() {
            @Override
            public void run() {
                handleUnresponsiveConnection();
            }
        };
    }
}

From source file:com.google.appinventor.client.Ode.java

License:Open Source License

public void blocksTruncatedDialog(final long projectId, final String fileId, final String content,
        final OdeAsyncCallback callback) {
    final DialogBox dialogBox = new DialogBox(false, true); // DialogBox(autohide, modal)
    dialogBox.setStylePrimaryName("ode-DialogBox");
    dialogBox.setText(MESSAGES.blocksTruncatedDialogText());
    dialogBox.setHeight("150px");
    dialogBox.setWidth("600px");
    dialogBox.setGlassEnabled(true);//from www. java  2  s.co m
    dialogBox.setAnimationEnabled(true);
    dialogBox.center();
    String[] fileParts = fileId.split("/");
    String screenNameParts = fileParts[fileParts.length - 1];
    final String screenName = screenNameParts.split("\\.")[0]; // Get rid of the .bky part
    final String userEmail = user.getUserEmail();
    VerticalPanel DialogBoxContents = new VerticalPanel();
    HTML message = new HTML(MESSAGES.blocksTruncatedDialogMessage().replace("%1", screenName));
    message.setStyleName("DialogBox-message");
    FlowPanel holder = new FlowPanel();
    final Button continueSession = new Button(MESSAGES.blocksTruncatedDialogButtonSave());
    continueSession.addClickListener(new ClickListener() {
        public void onClick(Widget sender) {
            dialogBox.hide();
            // call save2 again, this time with force = true so the empty workspace will be written
            getProjectService().save2(getSessionId(), projectId, fileId, true, content, callback);
        }
    });
    holder.add(continueSession);
    final Button cancelSession = new Button(MESSAGES.blocksTruncatedDialogButtonNoSave());
    final OdeAsyncCallback<Void> logReturn = new OdeAsyncCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            reloadWindow(false);
        }
    };
    cancelSession.addClickListener(new ClickListener() {
        public void onClick(Widget sender) {
            // Note: We do *not* remove the dialog, this locks the UI up (our intent)
            // Wait for a few seconds for other I/O to complete
            cancelSession.setEnabled(false); // Disable button to prevent further clicking
            continueSession.setEnabled(false); // This one as well
            Timer t = new Timer() {
                int count = 5;

                @Override
                public void run() {
                    if (count > 0) {
                        HTML html = (HTML) ((VerticalPanel) dialogBox.getWidget()).getWidget(0);
                        html.setHTML(MESSAGES.blocksTruncatedDialogButtonHTML().replace("%1", "" + count));
                        count -= 1;
                    } else {
                        this.cancel();
                        getProjectService().log("Disappearing Blocks: ProjectId = " + projectId + " fileId = "
                                + fileId + " User = " + userEmail, logReturn);
                    }
                }
            };
            t.scheduleRepeating(1000); // Run every second
        }
    });
    holder.add(cancelSession);
    DialogBoxContents.add(message);
    DialogBoxContents.add(holder);
    dialogBox.setWidget(DialogBoxContents);
    dialogBox.show();
}

From source file:com.google.appinventor.client.youngandroid.CodeblocksManager.java

License:Open Source License

private void downloadJnlpAndMakeConnection() {
    // fire up codeblocks via JavaWebStart. The download command goes from
    // the client to the ODE Server, which responds with the JNLP file
    // that causes the browser to start codeblocks via JavaWebStart.
    // We append a hash of the userid to the file name because we need the
    // jnlp file to be user-specific, while still be cacheable.
    String userId = Ode.getInstance().getUser().getUserId();
    Downloader.getInstance().download(ServerLayout.WEBSTART_JNLP_SERVLET_BASE
            + ServerLayout.WEBSTART_JNLP_PURPOSE_CODEBLOCKS + "/" + userId.hashCode());

    final long[] timeToStopTryingToConnect = { System.currentTimeMillis() + MAX_TIME_TO_CONNECT_MILLIS };

    // Get the connection info for the codeblocks HTTP server.
    Timer timer = new Timer() {
        @Override//  w  ww.  j  a v  a 2 s . c om
        public void run() {
            Ode.getInstance().getLaunchService().retrieveJsonpConnectionInfo(
                    YaHttpServerConstants.CODEBLOCKS_INFO_FILE_PREFIX,
                    new AsyncCallback<JsonpConnectionInfo>() {
                        @Override
                        public void onSuccess(JsonpConnectionInfo connInfo) {
                            if (connInfo == null) {
                                // The connection info has not been sent to the ODE server yet.
                                boolean continueConnecting = true;
                                if (System.currentTimeMillis() > timeToStopTryingToConnect[0]) {
                                    continueConnecting = askIfUserWantsToContinueTryingToConnect();
                                    if (continueConnecting) {
                                        timeToStopTryingToConnect[0] = System.currentTimeMillis()
                                                + MAX_TIME_TO_CONNECT_MILLIS;
                                    }
                                }
                                // Try again, unless the user has canceled.
                                if (startCanceled || !continueConnecting) {
                                    startingCodeblocks = false;
                                    updateCodeblocksButton();
                                } else {
                                    schedule(CODEBLOCKS_CONNECTION_RETRY_DELAY_MILLIS); // schedule the timer
                                }
                            } else {
                                conn = new CodeblocksConnection(connInfo, new ClientJsonParser(),
                                        Urls.getEscapeQueryParameterFunction());
                                conn.addConnectivityListener(CodeblocksManager.this);

                                startingCodeblocks = false;
                                updateCodeblocksButton();

                                // The user may have switched projects/forms while codeblocks was starting.
                                // We want the current project/form now.
                                YaFormEditor formEditor = Ode.getInstance().getCurrentYoungAndroidFormEditor();
                                if (formEditor != null) {
                                    YoungAndroidFormNode formNode = formEditor.getFormNode();
                                    loadPropertiesAndBlocks(formNode, null);
                                }
                            }
                        }

                        @Override
                        public void onFailure(Throwable caught) {
                            ErrorReporter.reportError(MESSAGES.startingCodeblocksFailed());
                            startingCodeblocks = false;
                            updateCodeblocksButton();
                        }
                    });
        }
    };

    // Schedule the timer for 1 second to give some time for the download to occur.
    timer.schedule(CODEBLOCKS_CONNECTION_RETRY_DELAY_MILLIS);
}

From source file:com.google.code.p.gwtchismes.client.GWTCPopupBox.java

License:Apache License

/**
 * Shows the alert dialog, and hides it after a period
 *  //ww w .j a v  a  2 s.  c  o  m
 * @param timeout
 *            timeout in seconds for autohide           
 */
public void show(int timeout) {
    if (timeout > 0) {
        Timer t = new Timer() {
            public void run() {
                hide();
            }
        };
        t.schedule(timeout * 1000);
    }
    center();
}

From source file:com.google.code.p.gwtchismes.client.GWTCPrint.java

License:Apache License

/**
 * Sends the page to the printer/*ww  w  . j  av  a 2s .com*/
 */
public void print() {
    setVisible(false);
    Window.print();
    Timer t = new Timer() {
        public void run() {
            setVisible(true);
        }
    };
    t.schedule(5 * 1000);
}

From source file:com.google.code.p.gwtchismes.client.GWTCWait.java

License:Apache License

/**
 *  Show the wait dialog for timeout seconds
 *  //w  w w  .  j a va2s.c o m
 * @param timeout seconds to wait before hide the dialog (timeout=0 wait for ever)
 */
public void show(int timeout) {
    if (timeout > 0) {
        Timer t = new Timer() {
            public void run() {
                hide();
            }
        };
        t.schedule(timeout * 1000);
    }
    setVisible(true);
    center();
}

From source file:com.google.collide.client.ui.dropdown.AutocompleteController.java

License:Open Source License

private void attachHandlers() {

    inputBox.addEventListener(Event.INPUT, new EventListener() {
        final Timer deferredShow = new Timer() {
            @Override//from www  .  ja va2s . c  om
            public void run() {
                JsonArray<M> items = callback.doCompleteQuery(inputBox.getValue());
                if (items.size() > 0) {
                    dropdown.setItems(items);
                    dropdown.show();
                } else {
                    dropdown.hide();
                }
            }
        };

        @Override
        public void handleEvent(Event evt) {
            KeyboardEvent event = (KeyboardEvent) evt;

            if (inputBox.getValue().length() < minimumCharactersBeforeCompletion) {
                dropdown.hide();
            } else {
                deferredShow.cancel();
                deferredShow.schedule(AUTOCOMPLETE_DELAY);
            }
        }
    }, false);

    inputBox.addEventListener(Event.BLUR, new EventListener() {
        @Override
        public void handleEvent(Event evt) {
            dropdown.hide();
        }
    }, false);

    inputBox.addEventListener(Event.KEYUP, new EventListener() {
        @Override
        public void handleEvent(Event evt) {
            KeyboardEvent event = (KeyboardEvent) evt;

            if (event.getKeyCode() == KeyCode.ESC) {
                dropdown.hide();
            }
        }
    }, false);

}