Example usage for com.google.gwt.user.client DeferredCommand addCommand

List of usage examples for com.google.gwt.user.client DeferredCommand addCommand

Introduction

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

Prototype

public static void addCommand(IncrementalCommand cmd) 

Source Link

Document

Enqueues an IncrementalCommand to be fired after all current events have been handled.

Usage

From source file:anzsoft.xmpp4gwt.client.Bosh2Connector.java

License:Open Source License

public Bosh2Connector(final User user) {
    this.setUser(user);
    standardHandler = new RequestCallback() {

        public void onError(Request request, Throwable exception) {
            final String lastSendedBody = activeRequests.remove(request);
            if (exception instanceof RequestTimeoutException) {
                GWT.log("Request too old. Trying again.", null);
                DeferredCommand.addCommand(new Command() {
                    public void execute() {
                        if (lastSendedBody != null && state == State.connected && sid != null
                                && sid.length() > 0)
                            send(lastSendedBody, standardHandler);
                        else
                            continuousConnection(null);
                    }/*from   w  ww  .  j  a v  a2s  .c o  m*/
                });
            } else if (exception.getMessage().startsWith("Unable to read XmlHttpRequest.status;")) {
                GWT.log("Lost request. Ignored. Resend.", null);
                if (lastSendedBody != null) {
                    DeferredCommand.addCommand(new Command() {
                        public void execute() {
                            if (state == State.connected && sid != null && sid.length() > 0) {
                                send(lastSendedBody, standardHandler);
                            }
                        }
                    });
                }
            } else {
                state = State.disconnected;
                GWT.log("Connection error", exception);
                exception.printStackTrace();
                fireEventError(BoshErrorCondition.remote_connection_failed, null,
                        "Response error: " + exception.getMessage());
            }
        }

        public void onResponseReceived(Request request, Response response) {
            if (state == State.disconnected)
                return;

            final String httpResponse = response.getText();
            final int httpStatusCode = response.getStatusCode();
            final String lastSendedBody = activeRequests.remove(request);

            System.out.println(" IN (" + httpStatusCode + "): " + httpResponse);
            fireOnBodyReceive(response, httpResponse);

            final Packet body = parse2(response.getText().replaceAll(";", ";"));

            final String type = body == null ? null : body.getAtribute("type");
            final String receivedSid = body == null ? null : body.getAtribute("sid");
            String $tmp = body == null ? null : body.getAtribute("rid");
            //final Long rid = $tmp == null ? null : Long.valueOf($tmp);
            final String ack = body == null ? null : body.getAtribute("ack");
            $tmp = body == null ? null : body.getAtribute("condition");
            if ($tmp != null)
                $tmp = $tmp.replace("-", "_");
            final BoshErrorCondition boshCondition = $tmp == null ? null : BoshErrorCondition.valueOf($tmp);

            final String wait = body == null ? null : body.getAtribute("wait");
            final String inactivity = body == null ? null : body.getAtribute("inactivity");
            if (wait != null && inactivity != null) {
                try {
                    int w = Integer.parseInt(wait);
                    int i = Integer.parseInt(inactivity);
                    int t = (w + i / 2) * 1000;
                    builder.setTimeoutMillis(t);
                    GWT.log("New timeout: " + t + "ms", null);
                } catch (Exception e) {
                    GWT.log("Error in wait and inactivity attributes", e);
                }
            }

            if (httpStatusCode != 200 || body == null
                    || type != null && ("terminate".equals(type) || "error".equals(type))) {
                GWT.log("ERROR (" + httpStatusCode + "): " + httpResponse, null);
                ErrorCondition condition = body == null ? ErrorCondition.bad_request
                        : ErrorCondition.undefined_condition;
                String msg = null;
                Packet error = body == null ? null : body.getFirstChild("error");
                if (error != null) {
                    for (Packet c : error.getChildren()) {
                        String xmlns = c.getAtribute("xmlns");
                        if ("text".equals(c.getName())) {
                            msg = c.getCData();
                            break;
                        } else if (xmlns != null && "urn:ietf:params:xml:ns:xmpp-stanzas".equals(xmlns)) {
                            condition = getCondition(c.getName(), httpStatusCode);
                        }
                    }
                }

                if (condition == ErrorCondition.item_not_found) {
                    state = State.disconnected;
                    fireEventError(boshCondition, condition, msg);
                } else if (errorCounter < MAX_ERRORS) {
                    errorCounter++;
                    send(lastSendedBody, standardHandler);
                } else if (type != null && "terminate".equals(type)) {
                    GWT.log("Disconnected by server", null);
                    state = State.disconnected;
                    fireDisconnectByServer(boshCondition, condition, msg);
                } else {
                    state = State.disconnected;
                    if (msg == null) {
                        msg = "[" + httpStatusCode + "] " + condition.name().replace('_', '-');
                    }
                    fireEventError(boshCondition, condition, msg);
                }
            } else {
                errorCounter = 0;
                if (receivedSid != null && sid != null && !receivedSid.equals(sid)) {
                    state = State.disconnected;
                    fireEventError(BoshErrorCondition.policy_violation, ErrorCondition.unexpected_request,
                            "Unexpected session initialisation.");
                } else if (receivedSid != null && sid == null) {
                    sid = receivedSid;
                    Cookies.setCookie(user.getResource() + "sid", sid, null, null, "/", false);
                    state = State.connected;
                }

                final List<? extends Packet> children = body.getChildren();
                if (children.size() > 0) {
                    fireEventReceiveStanzas(children);
                }
                continuousConnection(ack);
            }
            System.out.println("............sid value is:" + sid);
        }
    };

    //added by zhongfanglin@antapp.com
    scriptHandler = new ScriptSyntaxRequestCallback() {
        public void onError(String callbackID) {
            state = State.disconnected;
            GWT.log("Connection error", null);
            fireEventError(BoshErrorCondition.remote_connection_failed, null,
                    "Response error: request timeout or 404!");
        }

        public void onResponseReceived(String callbackID, String responseText) {

            if (state == State.disconnected)
                return;

            final String httpResponse = responseText;
            final String lastSendedBody = activeScriptRequests.remove(callbackID);

            System.out.println(" IN:" + httpResponse);
            fireOnBodyReceive(null, httpResponse);

            final Packet body = parse2(responseText.replaceAll("&semi;", ";"));

            final String type = body == null ? null : body.getAtribute("type");
            final String receivedSid = body == null ? null : body.getAtribute("sid");
            String $tmp = body == null ? null : body.getAtribute("rid");
            //final Long rid = $tmp == null ? null : Long.valueOf($tmp);
            final String ack = body == null ? null : body.getAtribute("ack");
            $tmp = body == null ? null : body.getAtribute("condition");
            if ($tmp != null)
                $tmp = $tmp.replace("-", "_");
            final BoshErrorCondition boshCondition = $tmp == null ? null : BoshErrorCondition.valueOf($tmp);

            final String wait = body == null ? null : body.getAtribute("wait");
            final String inactivity = body == null ? null : body.getAtribute("inactivity");
            if (wait != null && inactivity != null) {
                try {
                    int w = Integer.parseInt(wait);
                    int i = Integer.parseInt(inactivity);
                    int t = (w + i / 2) * 1000;
                    scriptBuilder.setTimeoutMillis(t);
                    GWT.log("New timeout: " + t + "ms", null);
                } catch (Exception e) {
                    GWT.log("Error in wait and inactivity attributes", e);
                }
            }

            if (body == null || type != null && ("terminate".equals(type) || "error".equals(type))) {
                GWT.log("ERROR : " + httpResponse, null);
                ErrorCondition condition = body == null ? ErrorCondition.bad_request
                        : ErrorCondition.undefined_condition;
                String msg = null;
                Packet error = body == null ? null : body.getFirstChild("error");
                if (error != null) {
                    for (Packet c : error.getChildren()) {
                        String xmlns = c.getAtribute("xmlns");
                        if ("text".equals(c.getName())) {
                            msg = c.getCData();
                            break;
                        } else if (xmlns != null && "urn:ietf:params:xml:ns:xmpp-stanzas".equals(xmlns)) {
                            condition = getCondition(c.getName(), -1);
                        }
                    }
                }

                if (condition == ErrorCondition.item_not_found) {
                    state = State.disconnected;
                    fireEventError(boshCondition, condition, msg);
                } else if (errorCounter < MAX_ERRORS) {
                    errorCounter++;
                    send(lastSendedBody, scriptHandler);
                } else if (type != null && "terminate".equals(type)) {
                    GWT.log("Disconnected by server", null);
                    state = State.disconnected;
                    fireDisconnectByServer(boshCondition, condition, msg);
                } else {
                    state = State.disconnected;
                    if (msg == null) {
                        msg = condition.name().replace('_', '-');
                    }
                    fireEventError(boshCondition, condition, msg);
                }
            } else {
                errorCounter = 0;
                if (receivedSid != null && sid != null && !receivedSid.equals(sid)) {
                    state = State.disconnected;
                    fireEventError(BoshErrorCondition.policy_violation, ErrorCondition.unexpected_request,
                            "Unexpected session initialisation.");
                } else if (receivedSid != null && sid == null) {
                    sid = receivedSid;
                    Cookies.setCookie(user.getResource() + "sid", sid, null, null, "/", false);
                    state = State.connected;
                }

                List<? extends Packet> children = body.getChildren();
                if (children.size() > 0) {
                    fireEventReceiveStanzas(children);
                }
                continuousConnection(ack);
            }
        }

    };
    //end added 
}

From source file:anzsoft.xmpp4gwt.client.Session.java

License:Open Source License

public void logout() {
    Presence presence = presencePlugin.offlinePresence();
    con.disconnect(presence);//from w  ww  .  j  a va  2 s. c  om
    DeferredCommand.addCommand(new Command() {

        public void execute() {
            reset();
        }
    });
    fireOnLoginOut();
}

From source file:asquare.gwt.sb.client.util.CommandQueueDeferred.java

License:Apache License

protected void deferRun() {
    //      Debug.println("CommandQueue.deferRun()");
    if (m_runScheduled)
        return;/* ww w. jav a2 s.  c  o  m*/

    m_runScheduled = true;

    DeferredCommand.addCommand(new Command() {
        public void execute() {
            m_runScheduled = false;
            run();
        }
    });
}

From source file:asquare.gwt.tk.client.ui.behavior.impl.TabFocusControllerStandard.java

License:Apache License

public void onBlurImpl(Object source) {
    //      Debug.println(" TabFocusControllerStandard.onBlurImpl(" + GWT.getTypeName(source) + ")");
    if (m_blurEvalCommand != null) {
        m_blurEvalCommand.cancel();/*w  w  w  .  ja va2 s.  c  om*/
    }
    m_blurEvalCommand = new BlurEvalCommand(source);
    DeferredCommand.addCommand(m_blurEvalCommand);
}

From source file:asquare.gwt.tk.client.ui.UrlLocation.java

License:Apache License

public void onFocus(FocusEvent event) {
    DeferredCommand.addCommand(new SelectAllCommand(this));
}

From source file:asquare.gwt.tkdemo.client.Demo.java

License:Apache License

public void onModuleLoad() {
    Debug.enableSilently();//  w  w w  . j  av a  2s  .  c o  m

    final AppPanelCollection panels = new DemoPanelCollection();

    String initialTabToken = History.getToken();
    int initialIndex = panels.getIndexForToken(initialTabToken);
    if (initialIndex == -1) {
        initialIndex = 0;
    }

    // use a table for border to work around bugs with 100% child width
    RowPanel outer = new RowPanel();
    DomUtil.setAttribute(outer, "id", "main");
    outer.setWidth("100%");

    ExposedCellPanel tabPanel = new ColumnPanel();
    tabPanel.setSize("100%", "100%");

    CTabBar tabbar = new CTabBar(new ListWidgetVTable(), new SideTabRenderer3());
    tabbar.removeController(tabbar.getController(CompositeCellViewHoverController.class));
    tabbar.setStyleName("DemoTabBar");
    History.addValueChangeHandler(new TabModelUpdateController(panels, tabbar.getListModel()));
    tabPanel.add(tabbar);
    tabPanel.setCellStyleName("DemoTabPanel-tabBar");

    tabPanel.add(new HTML("<h2 style='text-align: center; width: 100%; height: 100%;'>Loading...</h2>"));
    tabPanel.setCellStyleName("DemoTabPanel-tabBody");
    tabPanel.setCellWidth("100%");
    new TabBodyUpdateController(tabbar.getListModel(), tabPanel, panels);

    outer.add(tabPanel);
    RootPanel.get().add(outer);

    BrowserInfo browserInfo = (BrowserInfo) GWT.create(BrowserInfo.class);
    String compatMode = describeCompatMode();
    Label env = new Label(compatMode + " (" + browserInfo.getUserAgent() + ")");
    env.setStyleName("compatMode");
    outer.add(env);

    new DebugElementDumpInspector().install();

    /**
    * Incrementally add tabs to TabBar, allowing the UI to redraw to show
    * progress.
    */
    DeferredCommand.addCommand(new LoadUICommand(panels, tabbar, initialIndex));
}

From source file:at.ait.dme.yuma.client.image.annotation.ImageAnnotationComposite.java

License:EUPL

/**
 * the image annotation composite constructor. needs an image composite
 * to show and hide fragments./*  w  w w  .j a  va 2 s. c  o m*/
 * 
 * @param imageComposite
 */
public ImageAnnotationComposite(ImageComposite imageComposite, ImageAnnotationForm imageAnnotationForm,
        Set<String> shapeTypes) {
    this.imageComposite = imageComposite;
    this.imageAnnotationForm = imageAnnotationForm;
    this.shapeTypes = shapeTypes;

    // Container panel for annotation tree & controls
    containerPanel.setStyleName("imageAnnotation-composite");
    containerPanel.add(createHeader(), new BorderLayoutData(BorderLayout.Region.NORTH));

    // 'Loading' panel
    loadingPanel.setHorizontalAlignment(DockPanel.ALIGN_CENTER);
    loadingPanel.setVerticalAlignment(DockPanel.ALIGN_MIDDLE);
    loadingPanel.add(loadingImage, DockPanel.CENTER);

    // Annotation tree
    createTree(shapeTypes);

    // Register annotation selection handler on image composite
    imageComposite.addImageAnnotationSelectionHandler(new ImageAnnotationSelectionHandler() {
        @Override
        public void onAnnotationSelection(ImageAnnotationSelectionEvent event) {
            final ImageAnnotationTreeNode node = annotationTree.getAnnotationNode(event.getAnnotation());
            if (node == null)
                return;

            annotationTree.selectAnnotationTreeNode(node, event.isSelected());
            if (event.isSelected()) {
                DeferredCommand.addCommand(new Command() {
                    public void execute() {
                        scrollPanel.ensureVisible(node.getAnnotationTreeItem());
                    }
                });
            }
        }
    });

    deckPanel.add(loadingPanel);
    deckPanel.add(scrollPanel);

    enableLoadingImage();

    containerPanel.add(deckPanel);
    initWidget(containerPanel);
}

From source file:at.ait.dme.yuma.client.image.annotation.ImageAnnotationComposite.java

License:EUPL

/**
 * shows the annotation form either underneath a tree node in case of an
 * update or reply to an existing annotation, or above the annotation tree
 * in case of an new annotation. if it is a fragment annotation it will also
 * show the active fragment panel.//from   w  w  w  . j  av  a2s.c om
 * 
 * @param annotationTreeNode
 * @param fragmentAnnotation true if annotation has a fragment, otherwise false
 * @param update true if the user updates an existing annotation, otherwise false
 */
public void showAnnotationForm(final ImageAnnotationTreeNode annotationTreeNode, boolean fragmentAnnotation,
        boolean update) {

    imageAnnotationForm = imageAnnotationForm.createNew(this, annotationTreeNode, fragmentAnnotation, update);

    scrollPosition = scrollPanel.getScrollPosition();

    if (annotationTreeNode != null) {
        annotationTreeNode.showAnnotationForm(imageAnnotationForm);
        DeferredCommand.addCommand(new Command() {
            public void execute() {
                scrollPanel.ensureVisible(imageAnnotationForm);
            }
        });

        if (fragmentAnnotation) {
            // if we update an existing annotation we first have to remove the
            // existing fragment and show an active fragment panel instead.
            if (update && annotationTreeNode.getImageFragment() != null) {
                imageComposite.showActiveFragmentPanel(annotationTreeNode.getAnnotation(), true);
                imageComposite.hideFragment(annotationTreeNode.getAnnotation());
            } else {
                imageComposite.showActiveFragmentPanel(null, true);
            }
        }
    } else {
        annotateButton.setEnabled(false);
        annotateFragmentButton.setEnabled(false);
        annotationFormPanel.add(imageAnnotationForm);
        if (fragmentAnnotation)
            imageComposite.showActiveFragmentPanel(null, true);
    }

    layout();
}

From source file:at.ait.dme.yuma.client.image.annotation.ImageAnnotationComposite.java

License:EUPL

/**
 *  hides the annotation form, again either from above the annotation tree or from
 *  underneath a tree node, also hides the active fragment panel. if in case of
 *  an update the operation was canceled we have to restore a possible fragment.
 *  /*from  w  w  w.  j a v a 2s . co m*/
 *  @param annotationTreeNode
 *    @param canceled true if the user canceled the operation, otherwise false
 *  @see #showAnnotationForm(ImageAnnotationTreeNode, boolean, boolean)
 */
public void hideAnnotationForm(final ImageAnnotationTreeNode annotationTreeNode, boolean canceled) {

    if (annotationTreeNode == null) {
        annotationFormPanel.clear();
        annotateButton.setEnabled(true);
        annotateFragmentButton.setEnabled(true);
    } else {
        annotationTreeNode.hideAnnotationForm();
        DeferredCommand.addCommand(new Command() {
            public void execute() {
                scrollPanel.setScrollPosition(scrollPosition);
                annotationTree.setSelectedItem(annotationTreeNode.getAnnotationTreeItem());
            }
        });
    }

    imageComposite.hideActiveFragmentPanel();
    if (canceled && annotationTreeNode != null && annotationTreeNode.getImageFragment() != null) {
        imageComposite.showFragment(annotationTreeNode.getAnnotation());
    }

    layout();
}

From source file:at.ait.dme.yuma.client.image.annotation.ImageAnnotationTree.java

License:EUPL

/**
 * add the given annotation and all replies to the annotation tree
 * //w w  w  .j a  va2  s.  co  m
 * @param annotation
 * @param parentAnnotation
 * @param parent
 */
private void addAnnotation(final ImageAnnotation annotation, ImageAnnotation parentAnnotation,
        TreeItem parent) {

    // create the tree node
    final ImageAnnotationTreeNode node = new ImageAnnotationTreeNode(annotationComposite, annotation,
            parentAnnotation);
    node.setAnnotationTreeItem((parent == null) ? this.addItem(node) : parent.addItem(node));
    node.addMouseOutHandler(new MouseOutHandler() {
        public void onMouseOut(MouseOutEvent event) {
            node.setStyleName("imageAnnotation");
            handlerManager.fireEvent(new ImageAnnotationSelectionEvent(annotation, false));
        }
    });
    node.addMouseOverHandler(new MouseOverHandler() {
        public void onMouseOver(MouseOverEvent event) {
            node.setStyleName("imageAnnotation-selected");
            handlerManager.fireEvent(new ImageAnnotationSelectionEvent(annotation, true));
        }
    });
    annotationNodes.put(annotation, node);

    // show the fragment
    if (annotation.hasFragment()) {
        DeferredCommand.addCommand(new Command() {
            public void execute() {
                imageComposite.showFragment(node.getAnnotation());
            }
        });
    }

    setSelectedItem(node.getAnnotationTreeItem());
    ensureSelectedItemVisible();

    // process replies
    if (annotation.hasReplies()) {
        // sort replies ascending by creation date
        List<ImageAnnotation> replies = annotation.getReplies();
        Collections.sort(replies, new Comparator<ImageAnnotation>() {
            public int compare(ImageAnnotation o1, ImageAnnotation o2) {
                return o1.getCreated().compareTo(o2.getCreated());
            }
        });
        // add replies to the tree
        for (ImageAnnotation reply : replies) {
            addAnnotation(reply, annotation, node.getAnnotationTreeItem());
        }
    }
}