Search in sources :

Example 26 with AsyncCallback

use of com.google.gwt.user.client.rpc.AsyncCallback in project activityinfo by bedatadriven.

the class RemoteDispatcherTest method exceptionsThrownByCallbacksDoNotDistubOthers.

/**
 * The RemoteDispatcher will group and bundle commands together-- we need to
 * make sure that different components remain isolated from failures within
 * other components.
 */
@Test
public void exceptionsThrownByCallbacksDoNotDistubOthers() {
    expectRemoteCall(new GetSchema());
    andCallbackWihSuccess(new SchemaDTO());
    replay(service);
    // Here we set up one component that will call request a command
    // but something will go wrong when the command return (successfully)
    // the error is unrelated to the remote command -- it just happens to be
    // there.
    dispatcher.execute(new GetSchema(), null, new AsyncCallback<SchemaDTO>() {

        @Override
        public void onFailure(Throwable caught) {
        }

        @Override
        public void onSuccess(SchemaDTO result) {
            throw new RuntimeException();
        }
    });
    // the second command independently requests the same command,
    // we need to make sure we receive a result
    AsyncCallback secondCallback = makeCallbackThatExpectsNonNullSuccess();
    dispatcher.execute(new GetSchema(), null, secondCallback);
    processPendingCommands();
    verify(secondCallback);
}
Also used : AsyncCallback(com.google.gwt.user.client.rpc.AsyncCallback) GetSchema(org.activityinfo.legacy.shared.command.GetSchema) SchemaDTO(org.activityinfo.legacy.shared.model.SchemaDTO) Test(org.junit.Test)

Example 27 with AsyncCallback

use of com.google.gwt.user.client.rpc.AsyncCallback in project activityinfo by bedatadriven.

the class RemoteDispatcherTest method successiveCommandsServedByProxyAreCorrectlyHandleded.

@Test
public void successiveCommandsServedByProxyAreCorrectlyHandleded() {
    GetSchema command = new GetSchema();
    expect(proxy.maybeExecute(eq(command))).andReturn(new CacheResult(new SchemaDTO())).anyTimes();
    replay(proxy);
    // no calls should be made to the remote service
    replay(service);
    final AsyncCallback callback2 = makeCallbackThatExpectsNonNullSuccess();
    proxyManager.registerProxy(GetSchema.class, proxy);
    dispatcher.execute(new GetSchema(), new AsyncCallback<SchemaDTO>() {

        @Override
        public void onFailure(Throwable arg0) {
            throw new AssertionError();
        }

        @Override
        public void onSuccess(SchemaDTO arg0) {
            dispatcher.execute(new GetSchema(), callback2);
        }
    });
    processPendingCommands();
    processPendingCommands();
    verify(proxy, service, callback2);
}
Also used : AsyncCallback(com.google.gwt.user.client.rpc.AsyncCallback) CacheResult(org.activityinfo.ui.client.dispatch.remote.cache.CacheResult) GetSchema(org.activityinfo.legacy.shared.command.GetSchema) SchemaDTO(org.activityinfo.legacy.shared.model.SchemaDTO) Test(org.junit.Test)

Example 28 with AsyncCallback

use of com.google.gwt.user.client.rpc.AsyncCallback in project data-access by pentaho.

the class MetadataImportDialogController method createSubmitCompleteHandler.

private SubmitCompleteHandler createSubmitCompleteHandler() {
    return new SubmitCompleteHandler() {

        @Override
        public void onSubmitComplete(SubmitCompleteEvent event) {
            // delete all surrounded tags
            final String jsonResponseText = new HTML(event.getResults()).getText();
            final JSONObject jsonResponse;
            JSONValue jsonVal = JSONParser.parseStrict(jsonResponseText);
            if (jsonVal != null) {
                jsonResponse = jsonVal.isObject();
            } else {
                jsonResponse = null;
            }
            if (jsonResponse == null) {
                onImportError("wrong data from xmi file checker");
                return;
            }
            String tempFileName = jsonResponse.get("xmiFileName").isString().stringValue();
            RequestBuilder checkFileRequest = new RequestBuilder(RequestBuilder.GET, METADATA_CHECK_URL + "?tempFileName=" + URL.encode(tempFileName));
            checkFileRequest.setCallback(new RequestCallback() {

                @Override
                public void onResponseReceived(Request request, Response response) {
                    if (response.getStatusCode() == HttpStatus.SC_OK) {
                        if (Boolean.TRUE.toString().equalsIgnoreCase(response.getText())) {
                            promptImportMetadata(resBundle.getString("importDialog.IMPORT_METADATA"), resBundle.getString("importDialog.CONFIRMATION_LOAD_DSW"), resBundle.getString("importDialog.DIALOG_DSW_RADIO", "Data Source Wizard (Includes Analysis model)"), resBundle.getString("importDialog.DIALOG_METADATA_RADIO", "Metadata model"), new AsyncCallback<Boolean>() {

                                @Override
                                public void onSuccess(Boolean result) {
                                    new XmiImporterRequest((Boolean) result ? METADATA_IMPORT_DSW_URL : METADATA_IMPORT_XMI_URL, jsonResponse).doImport(false);
                                }

                                @Override
                                public void onFailure(Throwable caught) {
                                    onImportError(caught.getMessage());
                                }
                            });
                        } else if (Boolean.FALSE.toString().equals(response.getText())) {
                            new XmiImporterRequest(METADATA_IMPORT_XMI_URL, jsonResponse).doImport(false);
                        } else {
                            onImportError("wrong data from xmi file checker");
                        }
                    } else {
                        onImportError("[server data error] , wrong code: " + response.getStatusCode());
                    }
                }

                @Override
                public void onError(Request request, Throwable exception) {
                    onImportError("[request error] " + exception.getMessage());
                }
            });
            try {
                checkFileRequest.send();
            } catch (RequestException e) {
                onImportError(e.getMessage());
            }
        }
    };
}
Also used : RequestBuilder(com.google.gwt.http.client.RequestBuilder) AsyncCallback(com.google.gwt.user.client.rpc.AsyncCallback) Request(com.google.gwt.http.client.Request) HTML(com.google.gwt.user.client.ui.HTML) SubmitCompleteEvent(com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent) SubmitCompleteHandler(com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler) RequestException(com.google.gwt.http.client.RequestException) JSONValue(com.google.gwt.json.client.JSONValue) Response(com.google.gwt.http.client.Response) JSONObject(com.google.gwt.json.client.JSONObject) RequestCallback(com.google.gwt.http.client.RequestCallback)

Example 29 with AsyncCallback

use of com.google.gwt.user.client.rpc.AsyncCallback in project gwt-test-utils by gwt-test-utils.

the class GwtRpcInvocationHandler method invoke.

@SuppressWarnings("unchecked")
public Object invoke(Object proxy, Method method, Object[] args) {
    Object[] subArgs = new Object[args.length - 1];
    for (int i = 0; i < args.length - 1; i++) {
        subArgs[i] = args[i];
    }
    final AsyncCallback<Object> callback = (AsyncCallback<Object>) args[args.length - 1];
    final Method m = methodTable.get(method);
    Command asyncCallbackCommand;
    if (m == null) {
        logger.error("Method not found " + method);
        // error 500 async call
        asyncCallbackCommand = new Command() {

            public void execute() {
                callback.onFailure(new StatusCodeException(500, "No method found"));
            }
        };
    } else {
        try {
            logger.debug("Invoking " + m + " on " + target.getClass().getName());
            List<RemoteServiceExecutionHandler> handlers = GwtConfig.get().getModuleRunner().getRemoteServiceExecutionHandlers();
            // notify
            for (RemoteServiceExecutionHandler handler : handlers) {
                handler.beforeRpcRequestSerialization(m, subArgs);
            }
            // Serialize objects
            Object[] serializedArgs = new Object[subArgs.length];
            for (int i = 0; i < subArgs.length; i++) {
                try {
                    serializedArgs[i] = serializerHander.serializeUnserialize(subArgs[i]);
                } catch (Exception e) {
                    throw new GwtTestRpcException("Error while serializing argument " + i + " of type " + subArgs[i].getClass().getName() + " in method " + method.getDeclaringClass().getSimpleName() + "." + method.getName() + "(..)", e);
                }
            }
            // notify
            for (RemoteServiceExecutionHandler handler : handlers) {
                handler.beforeRpcRequestSerialization(m, serializedArgs);
            }
            AbstractRemoteServiceServletPatcher.currentCalledMethod = m;
            // notify
            for (RemoteServiceExecutionHandler handler : handlers) {
                handler.beforeRpcMethodExecution(m, serializedArgs);
            }
            Object resultObject = m.invoke(target, serializedArgs);
            // notify
            for (RemoteServiceExecutionHandler handler : handlers) {
                handler.afterRpcMethodExecution(m, resultObject);
            }
            Object returnObject;
            try {
                // notify
                for (RemoteServiceExecutionHandler handler : handlers) {
                    handler.beforeRpcResponseSerialization(m, resultObject);
                }
                returnObject = serializerHander.serializeUnserialize(resultObject);
                // notify
                for (RemoteServiceExecutionHandler handler : handlers) {
                    handler.afterRpcResponseSerialization(m, returnObject);
                }
            } catch (Exception e) {
                throw new GwtTestRpcException("Error while serializing object of type " + resultObject.getClass().getName() + " which was returned from RPC Service " + method.getDeclaringClass().getSimpleName() + "." + method.getName() + "(..)", e);
            }
            final Object o = returnObject;
            // success async call
            asyncCallbackCommand = new Command() {

                public void execute() {
                    logger.debug("Result of " + m.getName() + " : " + o);
                    callback.onSuccess(o);
                }
            };
        } catch (final InvocationTargetException e) {
            if (GwtTestException.class.isInstance(e.getCause())) {
                throw (GwtTestException) e.getCause();
            }
            asyncCallbackCommand = new Command() {

                public void execute() {
                    logger.info("Exception when invoking service throw to handler " + e.getMessage());
                    exceptionHandler.handle(e.getCause(), callback);
                }
            };
        } catch (final IllegalAccessException e) {
            asyncCallbackCommand = new Command() {

                public void execute() {
                    logger.error("GWT RPC exception : " + e.toString(), e);
                    callback.onFailure(new StatusCodeException(500, e.toString()));
                }
            };
        } catch (final IllegalArgumentException e) {
            asyncCallbackCommand = new Command() {

                public void execute() {
                    logger.error("GWT RPC exception : " + e.toString(), e);
                    callback.onFailure(new StatusCodeException(500, e.toString()));
                }
            };
        }
    }
    // delegate the execution to the Browser simulator
    BrowserSimulatorImpl.get().recordAsyncCall(asyncCallbackCommand);
    // async callback always return void
    return null;
}
Also used : AsyncCallback(com.google.gwt.user.client.rpc.AsyncCallback) RemoteServiceExecutionHandler(com.googlecode.gwt.test.RemoteServiceExecutionHandler) StatusCodeException(com.google.gwt.user.client.rpc.StatusCodeException) Method(java.lang.reflect.Method) GwtTestException(com.googlecode.gwt.test.exceptions.GwtTestException) GwtTestRpcException(com.googlecode.gwt.test.exceptions.GwtTestRpcException) InvocationTargetException(java.lang.reflect.InvocationTargetException) StatusCodeException(com.google.gwt.user.client.rpc.StatusCodeException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Command(com.google.gwt.user.client.Command) GwtTestRpcException(com.googlecode.gwt.test.exceptions.GwtTestRpcException) GwtTestException(com.googlecode.gwt.test.exceptions.GwtTestException)

Example 30 with AsyncCallback

use of com.google.gwt.user.client.rpc.AsyncCallback in project che by eclipse.

the class ContentAssistWidget method createProposalPopupItem.

/**
     * Creates a new proposal item.
     *
     * @param index
     *         of proposal
     */
private Element createProposalPopupItem(int index) {
    final CompletionProposal proposal = proposals.get(index);
    final Element element = Elements.createLiElement(popupResources.popupStyle().item());
    element.setId(Integer.toString(index));
    final Element icon = Elements.createDivElement(popupResources.popupStyle().icon());
    if (proposal.getIcon() != null && proposal.getIcon().getSVGImage() != null) {
        icon.appendChild((Node) proposal.getIcon().getSVGImage().getElement());
    } else if (proposal.getIcon() != null && proposal.getIcon().getImage() != null) {
        icon.appendChild((Node) proposal.getIcon().getImage().getElement());
    }
    element.appendChild(icon);
    final SpanElement label = Elements.createSpanElement(popupResources.popupStyle().label());
    label.setInnerHTML(proposal.getDisplayString());
    element.appendChild(label);
    element.setTabIndex(1);
    final EventListener validateListener = evt -> applyProposal(proposal);
    element.addEventListener(Event.DBLCLICK, validateListener, false);
    element.addEventListener(CUSTOM_EVT_TYPE_VALIDATE, validateListener, false);
    element.addEventListener(Event.CLICK, event -> select(element), false);
    element.addEventListener(Event.FOCUS, this, false);
    element.addEventListener(DOCUMENTATION, new EventListener() {

        @Override
        public void handleEvent(Event event) {
            proposal.getAdditionalProposalInfo(new AsyncCallback<Widget>() {

                @Override
                public void onSuccess(Widget info) {
                    if (info != null) {
                        docPopup.clear();
                        docPopup.add(info);
                        docPopup.getElement().getStyle().setOpacity(1);
                        if (!docPopup.isAttached()) {
                            final int x = popupElement.getOffsetLeft() + popupElement.getOffsetWidth() + 3;
                            final int y = popupElement.getOffsetTop();
                            RootPanel.get().add(docPopup);
                            updateMenuPosition(docPopup, x, y);
                        }
                    } else {
                        docPopup.getElement().getStyle().setOpacity(0);
                    }
                }

                @Override
                public void onFailure(Throwable e) {
                    Log.error(getClass(), e);
                    docPopup.getElement().getStyle().setOpacity(0);
                }
            });
        }
    }, false);
    return element;
}
Also used : SpanElement(elemental.html.SpanElement) OrionKeyModeOverlay(org.eclipse.che.ide.editor.orion.client.jso.OrionKeyModeOverlay) CustomEvent(elemental.events.CustomEvent) HTMLCollection(elemental.html.HTMLCollection) Elements(org.eclipse.che.ide.util.dom.Elements) LinearRange(org.eclipse.che.ide.api.editor.text.LinearRange) OrionTextViewOverlay(org.eclipse.che.ide.editor.orion.client.jso.OrionTextViewOverlay) Assisted(com.google.inject.assistedinject.Assisted) AsyncCallback(com.google.gwt.user.client.rpc.AsyncCallback) Style(com.google.gwt.dom.client.Style) Node(elemental.dom.Node) Element(elemental.dom.Element) AssistedInject(com.google.inject.assistedinject.AssistedInject) EventListener(elemental.events.EventListener) Window(elemental.html.Window) PopupResources(org.eclipse.che.ide.ui.popup.PopupResources) Event(elemental.events.Event) PX(elemental.css.CSSStyleDeclaration.Unit.PX) KeyboardEvent(elemental.events.KeyboardEvent) Completion(org.eclipse.che.ide.api.editor.codeassist.Completion) CompletionRequestEvent(org.eclipse.che.ide.api.editor.events.CompletionRequestEvent) CompletionProposal(org.eclipse.che.ide.api.editor.codeassist.CompletionProposal) RootPanel(com.google.gwt.user.client.ui.RootPanel) Log(org.eclipse.che.ide.util.loging.Log) HandlesUndoRedo(org.eclipse.che.ide.api.editor.texteditor.HandlesUndoRedo) Scheduler(com.google.gwt.core.client.Scheduler) Widget(com.google.gwt.user.client.ui.Widget) CompletionProposalExtension(org.eclipse.che.ide.api.editor.codeassist.CompletionProposalExtension) List(java.util.List) FlowPanel(com.google.gwt.user.client.ui.FlowPanel) UndoableEditor(org.eclipse.che.ide.api.editor.texteditor.UndoableEditor) OrionPixelPositionOverlay(org.eclipse.che.ide.editor.orion.client.jso.OrionPixelPositionOverlay) KeyCodes(com.google.gwt.event.dom.client.KeyCodes) SpanElement(elemental.html.SpanElement) OrionModelChangedEventOverlay(org.eclipse.che.ide.editor.orion.client.jso.OrionModelChangedEventOverlay) Timer(com.google.gwt.user.client.Timer) EventTarget(elemental.events.EventTarget) MouseEvent(elemental.events.MouseEvent) CompletionProposal(org.eclipse.che.ide.api.editor.codeassist.CompletionProposal) Element(elemental.dom.Element) SpanElement(elemental.html.SpanElement) Node(elemental.dom.Node) AsyncCallback(com.google.gwt.user.client.rpc.AsyncCallback) Widget(com.google.gwt.user.client.ui.Widget) CustomEvent(elemental.events.CustomEvent) Event(elemental.events.Event) KeyboardEvent(elemental.events.KeyboardEvent) CompletionRequestEvent(org.eclipse.che.ide.api.editor.events.CompletionRequestEvent) MouseEvent(elemental.events.MouseEvent) EventListener(elemental.events.EventListener)

Aggregations

AsyncCallback (com.google.gwt.user.client.rpc.AsyncCallback)64 GetSchema (org.activityinfo.legacy.shared.command.GetSchema)8 Test (org.junit.Test)7 SchemaDTO (org.activityinfo.legacy.shared.model.SchemaDTO)6 FormDialogCallback (org.activityinfo.ui.client.page.common.dialog.FormDialogCallback)6 CallbackGroup (com.google.gerrit.client.rpc.CallbackGroup)5 ProjectDTO (org.activityinfo.legacy.shared.model.ProjectDTO)4 FormDialogTether (org.activityinfo.ui.client.page.common.dialog.FormDialogTether)4 ChangeInfo (com.google.gerrit.client.info.ChangeInfo)3 Date (java.util.Date)3 GetActivityForm (org.activityinfo.legacy.shared.command.GetActivityForm)3 VoidResult (org.activityinfo.legacy.shared.command.result.VoidResult)3 MaskingAsyncMonitor (org.activityinfo.ui.client.dispatch.monitor.MaskingAsyncMonitor)3 FormDialogImpl (org.activityinfo.ui.client.page.common.dialog.FormDialogImpl)3 Operation (org.eclipse.che.api.promises.client.Operation)3 OperationException (org.eclipse.che.api.promises.client.OperationException)3 PromiseError (org.eclipse.che.api.promises.client.PromiseError)3 Path (org.eclipse.che.ide.resource.Path)3 EditInfo (com.google.gerrit.client.info.ChangeInfo.EditInfo)2 RevisionInfo (com.google.gerrit.client.info.ChangeInfo.RevisionInfo)2