Search in sources :

Example 1 with GwtTestException

use of com.googlecode.gwt.test.exceptions.GwtTestException 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 2 with GwtTestException

use of com.googlecode.gwt.test.exceptions.GwtTestException in project gwt-test-utils by gwt-test-utils.

the class UiBinderParser method createUiComponent.

/**
 * Parse the .ui.xml file to fill the corresponding objects.
 *
 * @param rootComponentClass the root component's class that UiBinder has to instanciated.
 * @param uiBinderClass      the UiBinder subinterface which is used
 * @param owner              The owner of the UiBinder template, with {@link UiField} fields.
 */
<T> T createUiComponent(Class<UiBinder<?, ?>> uiBinderClass, Object owner) {
    @SuppressWarnings("unchecked") Class<T> rootComponentClass = (Class<T>) getRootElementClass(uiBinderClass);
    InputStream uiXmlStream = getUiXmlFile(owner.getClass(), uiBinderClass);
    if (uiXmlStream == null) {
        throw new GwtTestUiBinderException("Cannot find the .ui.xml file corresponding to '" + owner.getClass().getName() + "'");
    }
    UiXmlContentHandler<T> contentHandler = new UiXmlContentHandler<T>(rootComponentClass, owner);
    XMLReader saxReader = XmlUtils.newXMLReader();
    try {
        saxReader.setContentHandler(contentHandler);
        saxReader.parse(new InputSource(uiXmlStream));
    } catch (Exception e) {
        if (GwtTestException.class.isInstance(e)) {
            throw (GwtTestException) e;
        } else {
            throw new GwtTestUiBinderException("Error while parsing '" + owner.getClass().getSimpleName() + ".ui.xml'", e);
        }
    } finally {
        try {
            uiXmlStream.close();
        } catch (IOException e) {
        // do nothing
        }
    }
    return contentHandler.getRootComponent();
}
Also used : InputSource(org.xml.sax.InputSource) InputStream(java.io.InputStream) IOException(java.io.IOException) GwtTestException(com.googlecode.gwt.test.exceptions.GwtTestException) IOException(java.io.IOException) GwtTestUiBinderException(com.googlecode.gwt.test.exceptions.GwtTestUiBinderException) GwtTestUiBinderException(com.googlecode.gwt.test.exceptions.GwtTestUiBinderException) GwtTestException(com.googlecode.gwt.test.exceptions.GwtTestException) XMLReader(org.xml.sax.XMLReader)

Example 3 with GwtTestException

use of com.googlecode.gwt.test.exceptions.GwtTestException in project gwt-test-utils by gwt-test-utils.

the class GwtMockitoAnnotations method processInjectMocks.

private static void processInjectMocks(GwtTestWithMockito testInstance) {
    GwtMockitoUtils.getMockFields(testInstance.getClass(), InjectMocks.class).forEach(injectMocksField -> {
        try {
            GwtReflectionUtils.makeAccessible(injectMocksField);
            Object injectMocks = injectMocksField.get(testInstance);
            testInstance.getAllMocksByType().forEach((key, value) -> GwtReflectionUtils.getFields(injectMocks.getClass()).stream().filter(field -> field.getType().isAssignableFrom(key)).forEach(field -> {
                try {
                    GwtReflectionUtils.makeAccessible(field);
                    Object mock = field.get(injectMocks);
                    if (mock == null) {
                        field.set(injectMocks, value);
                    }
                } catch (IllegalAccessException e) {
                    // should never append
                    throw new GwtTestException("", e);
                }
            }));
        } catch (IllegalAccessException e) {
            // should never append
            throw new GwtTestException("", e);
        }
    });
}
Also used : InjectMocks(org.mockito.InjectMocks) MockitoAnnotations(org.mockito.MockitoAnnotations) GwtTestException(com.googlecode.gwt.test.exceptions.GwtTestException) Annotation(java.lang.annotation.Annotation) Set(java.util.Set) GwtReflectionUtils(com.googlecode.gwt.test.utils.GwtReflectionUtils) Field(java.lang.reflect.Field) GwtTestWithMockito(com.googlecode.gwt.test.GwtTestWithMockito) GwtTestException(com.googlecode.gwt.test.exceptions.GwtTestException) InjectMocks(org.mockito.InjectMocks)

Example 4 with GwtTestException

use of com.googlecode.gwt.test.exceptions.GwtTestException in project gwt-test-utils by gwt-test-utils.

the class JSONParserPatcher method evaluate.

@PatchMethod
static JSONValue evaluate(String json, boolean strict) {
    JsonParser jp = null;
    try {
        JsonFactory f = new JsonFactory();
        if (!strict) {
            f.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            f.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            f.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            f.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
            f.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
            f.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
            f.configure(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS, true);
        }
        jp = f.createJsonParser(json);
        JsonToken token = jp.nextToken();
        if (JsonToken.START_ARRAY == token) {
            JSONArray jsonArray = extractJSONArray(json, null, jp);
            return jsonArray;
        } else {
            JSONObject jsonObject = extractJSONObject(json, jp);
            return jsonObject;
        }
    } catch (Exception e) {
        if (e instanceof GwtTestException) {
            throw (GwtTestException) e;
        }
        throw new GwtTestJSONException("Error while parsing JSON string '" + json + "'", e);
    } finally {
        if (jp != null) {
            try {
                // ensure resources get cleaned up timely and properly
                jp.close();
            } catch (IOException e) {
            // should never happen
            }
        }
    }
}
Also used : GwtTestException(com.googlecode.gwt.test.exceptions.GwtTestException) GwtTestJSONException(com.googlecode.gwt.test.exceptions.GwtTestJSONException) JsonFactory(org.codehaus.jackson.JsonFactory) JsonToken(org.codehaus.jackson.JsonToken) IOException(java.io.IOException) JsonParseException(org.codehaus.jackson.JsonParseException) GwtTestException(com.googlecode.gwt.test.exceptions.GwtTestException) IOException(java.io.IOException) GwtTestJSONException(com.googlecode.gwt.test.exceptions.GwtTestJSONException) JsonParser(org.codehaus.jackson.JsonParser) PatchMethod(com.googlecode.gwt.test.patchers.PatchMethod)

Example 5 with GwtTestException

use of com.googlecode.gwt.test.exceptions.GwtTestException in project gwt-test-utils by gwt-test-utils.

the class GwtTestWithEasyMock method beforeGwtTestWithEasyMock.

@Before
public void beforeGwtTestWithEasyMock() {
    mockedClasses.forEach(clazz -> getMockManager().registerMock(clazz, createMock(clazz)));
    try {
        for (Field f : mockFields) {
            Object mock = getMockManager().getMock(f.getType());
            GwtReflectionUtils.makeAccessible(f);
            f.set(this, mock);
        }
    } catch (Exception e) {
        if (GwtTestException.class.isInstance(e)) {
            throw (GwtTestException) e;
        } else {
            throw new ReflectionException("Error during gwt-test-utils @Mock creation", e);
        }
    }
}
Also used : Field(java.lang.reflect.Field) ReflectionException(com.googlecode.gwt.test.exceptions.ReflectionException) GwtTestException(com.googlecode.gwt.test.exceptions.GwtTestException) ReflectionException(com.googlecode.gwt.test.exceptions.ReflectionException) GwtTestException(com.googlecode.gwt.test.exceptions.GwtTestException) GwtTestPatchException(com.googlecode.gwt.test.exceptions.GwtTestPatchException) Before(org.junit.Before)

Aggregations

GwtTestException (com.googlecode.gwt.test.exceptions.GwtTestException)13 IOException (java.io.IOException)4 GwtTestConfigurationException (com.googlecode.gwt.test.exceptions.GwtTestConfigurationException)3 GwtTestPatchException (com.googlecode.gwt.test.exceptions.GwtTestPatchException)3 Field (java.lang.reflect.Field)3 GwtTestJSONException (com.googlecode.gwt.test.exceptions.GwtTestJSONException)2 GwtTestUiBinderException (com.googlecode.gwt.test.exceptions.GwtTestUiBinderException)2 ReflectionException (com.googlecode.gwt.test.exceptions.ReflectionException)2 PatchMethod (com.googlecode.gwt.test.patchers.PatchMethod)2 JsonParseException (org.codehaus.jackson.JsonParseException)2 JsonParser (org.codehaus.jackson.JsonParser)2 JavaScriptObject (com.google.gwt.core.client.JavaScriptObject)1 Command (com.google.gwt.user.client.Command)1 AsyncCallback (com.google.gwt.user.client.rpc.AsyncCallback)1 StatusCodeException (com.google.gwt.user.client.rpc.StatusCodeException)1 UIObject (com.google.gwt.user.client.ui.UIObject)1 UmbrellaException (com.google.web.bindery.event.shared.UmbrellaException)1 GwtTestWithMockito (com.googlecode.gwt.test.GwtTestWithMockito)1 RemoteServiceExecutionHandler (com.googlecode.gwt.test.RemoteServiceExecutionHandler)1 GwtTestDomException (com.googlecode.gwt.test.exceptions.GwtTestDomException)1