Example usage for com.google.gwt.user.server.rpc RPC decodeRequest

List of usage examples for com.google.gwt.user.server.rpc RPC decodeRequest

Introduction

In this page you can find the example usage for com.google.gwt.user.server.rpc RPC decodeRequest.

Prototype

public static RPCRequest decodeRequest(String encodedRequest, Class<?> type,
        SerializationPolicyProvider serializationPolicyProvider) 

Source Link

Document

Returns an RPCRequest that is built by decoding the contents of an encoded RPC request and optionally validating that type can handle the request.

Usage

From source file:cc.alcina.framework.servlet.servlet.CommonRemoteServiceServlet.java

License:Apache License

@Override
public String processCall(String payload) throws SerializationException {
    RPCRequest rpcRequest = null;//  www.j a v a 2  s  .com
    String threadName = Thread.currentThread().getName();
    try {
        LooseContext.push();
        initUserStateWithCookie(getThreadLocalRequest(), getThreadLocalResponse());
        LooseContext.set(CONTEXT_THREAD_LOCAL_HTTP_REQUEST, getThreadLocalRequest());
        LooseContext.set(CommonPersistenceBase.CONTEXT_CLIENT_IP_ADDRESS,
                ServletLayerUtils.robustGetRemoteAddr(getThreadLocalRequest()));
        LooseContext.set(CommonPersistenceBase.CONTEXT_CLIENT_INSTANCE_ID,
                SessionHelper.getAuthenticatedSessionClientInstanceId(getThreadLocalRequest()));
        rpcRequest = RPC.decodeRequest(payload, this.getClass(), this);
        if (rpcRequest.getSerializationPolicy() instanceof LegacySerializationPolicy) {
            throw new IncompatibleRemoteServiceException();
        }
        getThreadLocalRequest().setAttribute(THRD_LOCAL_RPC_RQ, rpcRequest);
        getThreadLocalRequest().setAttribute(THRD_LOCAL_RPC_PAYLOAD, payload);
        String name = rpcRequest.getMethod().getName();
        RPCRequest f_rpcRequest = rpcRequest;
        Thread.currentThread().setName(Ax.format("gwt-rpc:%s", name));
        onAfterAlcinaAuthentication(name);
        LooseContext.set(CONTEXT_RPC_USER_ID, PermissionsManager.get().getUserId());
        InternalMetrics.get().startTracker(rpcRequest, () -> describeRpcRequest(f_rpcRequest, ""),
                InternalMetricTypeAlcina.client, Thread.currentThread().getName(), () -> true);
        Method method;
        try {
            method = this.getClass().getMethod(name, rpcRequest.getMethod().getParameterTypes());
            if (method.isAnnotationPresent(WebMethod.class)) {
                WebMethod webMethod = method.getAnnotation(WebMethod.class);
                AnnotatedPermissible ap = new AnnotatedPermissible(webMethod.customPermission());
                if (!PermissionsManager.get().isPermissible(ap)) {
                    WebException wex = new WebException("Action not permitted: " + name);
                    logRpcException(wex, LogMessageType.PERMISSIONS_EXCEPTION.toString());
                    return RPC.encodeResponseForFailure(null, wex);
                }
                if (!webMethod.readonlyPermitted()) {
                    AppPersistenceBase.checkNotReadOnly();
                }
            }
        } catch (SecurityException ex) {
            RPC.encodeResponseForFailure(null, ex);
        } catch (NoSuchMethodException ex) {
            RPC.encodeResponseForFailure(null, ex);
        }
        return invokeAndEncodeResponse(rpcRequest);
    } catch (IncompatibleRemoteServiceException ex) {
        getServletContext().log("An IncompatibleRemoteServiceException was thrown while processing this call.",
                ex);
        return RPC.encodeResponseForFailure(null, ex);
    } catch (UnexpectedException ex) {
        logRpcException(ex);
        throw ex;
    } catch (OutOfMemoryError e) {
        handleOom(payload, e);
        throw e;
    } catch (RuntimeException rex) {
        logRpcException(rex);
        throw rex;
    } finally {
        Thread.currentThread().setName(threadName);
        InternalMetrics.get().endTracker(rpcRequest);
        if (TransformManager.hasInstance()) {
            if (CommonUtils
                    .bv((Boolean) getThreadLocalRequest().getAttribute(PUSH_TRANSFORMS_AT_END_OF_REUQEST))) {
                Sx.commit();
            }
            ThreadlocalTransformManager.cast().resetTltm(null);
            LooseContext.pop();
        } else {
            try {
                LooseContext.pop();
            } catch (Exception e) {// squelch, probably webapp undeployed
            }
        }
    }
}

From source file:com.apress.progwt.server.gwt.GWTController.java

License:Apache License

@Override
public String processCall(String payload) throws SerializationException {
    try {//  w  ww  .  j av a  2s.  co m

        RPCRequest rpcRequest = RPC.decodeRequest(payload, this.getClass(), this);
        ServerSerializationStreamWriter_1_5_3 writer = getWriter(rpcRequest);

        return RPC1524.invokeAndEncodeResponse(this, rpcRequest.getMethod(), rpcRequest.getParameters(),
                writer);

    } catch (IncompatibleRemoteServiceException ex) {
        log.error("An IncompatibleRemoteServiceException was thrown while processing this call.", ex);
        return RPC.encodeResponseForFailure(null, ex);
    } catch (Exception e) {
        log.error("An Exception was thrown while processing this call.", e);
        return RPC.encodeResponseForFailure(null, e);
    }
}

From source file:com.brightedu.server.BrightServlet.java

License:Apache License

/**
 * Process a call originating from the given request. Uses the
 * {@link RPC#invokeAndEncodeResponse(Object, java.lang.reflect.Method, Object[])}
 * method to do the actual work./*from  ww  w.j  a  va2  s . c  o m*/
 * <p>
 * Subclasses may optionally override this method to handle the payload in
 * any way they desire (by routing the request to a framework component, for
 * instance). The {@link HttpServletRequest} and {@link HttpServletResponse}
 * can be accessed via the {@link #getThreadLocalRequest()} and
 * {@link #getThreadLocalResponse()} methods.
 * </p>
 * This is public so that it can be unit tested easily without HTTP.
 * 
 * @param payload
 *            the UTF-8 request payload
 * @return a string which encodes either the method's return, a checked
 *         exception thrown by the method, or an
 *         {@link IncompatibleRemoteServiceException}
 * @throws SerializationException
 *             if we cannot serialize the response
 * @throws UnexpectedException
 *             if the invocation throws a checked exception that is not
 *             declared in the service method's signature
 * @throws RuntimeException
 *             if the service method throws an unchecked exception (the
 *             exception will be the one thrown by the service)
 */
public String processCall(String payload) throws SerializationException {
    // First, check for possible XSRF situation
    checkPermutationStrongName();

    try {
        RPCRequest rpcRequest = RPC.decodeRequest(payload, delegate.getClass(), this);
        onAfterRequestDeserialized(rpcRequest);
        return RPC.invokeAndEncodeResponse(delegate, rpcRequest.getMethod(), rpcRequest.getParameters(),
                rpcRequest.getSerializationPolicy(), rpcRequest.getFlags());
    } catch (IncompatibleRemoteServiceException ex) {
        log("An IncompatibleRemoteServiceException was thrown while processing this call.", ex);
        return RPC.encodeResponseForFailure(null, ex);
    } catch (RpcTokenException tokenException) {
        log("An RpcTokenException was thrown while processing this call.", tokenException);
        return RPC.encodeResponseForFailure(null, tokenException);
    }
}

From source file:com.colinalworth.gwt.websockets.server.GwtWebService.java

License:Apache License

@Override
public void onMessage(WebSocketConnection connection, String msg) throws Throwable {
    RPCRequest req = RPC.decodeRequest(msg, null, makeProvider());
    //Method m = req.getMethod();//garbage

    Object message = req.getParameters()[0];

    if (message instanceof ServerCallbackInvocation) {
        ServerCallbackInvocation callbackInvoke = (ServerCallbackInvocation) message;

        if (callbacks.containsKey(callbackInvoke.getCallbackId())) {
            @SuppressWarnings("unchecked")
            Callback<Object, Object> callback = (Callback<Object, Object>) callbacks
                    .remove(callbackInvoke.getCallbackId());

            if (callbackInvoke.isSuccess()) {
                callback.onSuccess(callbackInvoke.getResponse());
            } else {
                callback.onFailure(callbackInvoke.getResponse());
            }/*from  w ww  . java2s . c om*/
        }
        return;
    }

    ServerInvocation invoke = (ServerInvocation) message;

    //TODO verify the method to be invoked
    Method method;
    synchronized (cachedMethods) {
        method = cachedMethods.get(invoke.getMethod());
        if (method == null) {
            for (Method m : server.getClass().getMethods()) {
                if (m.getName().equals(invoke.getMethod())) {
                    //TODO check better than this, verify the method may be invoked from the client
                    method = m;
                    break;
                }
            }
            if (method == null) {
                //TODO throw something
            } else {
                cachedMethods.put(invoke.getMethod(), method);
            }
        }
    }

    server.setClient((C) connection.data(getClass().getName() + ".client"));
    try {
        if (invoke.getCallbackId() != 0) {
            Object[] args = addCallbackToArgs(invoke.getParameters(), invoke.getCallbackId(), connection);
            method.invoke(server, args);
        } else {
            method.invoke(server, invoke.getParameters());
        }
    } catch (InvocationTargetException ex) {
        Throwable unwrapped = ex.getCause();
        server.onError(unwrapped);
    } finally {
        server.setClient(null);
    }
}

From source file:com.cubusmail.gwtui.server.services.MailboxService.java

License:Open Source License

@Override
public String processCall(String payload) throws SerializationException {

    if (this.applicationContext == null) {
        this.applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    }//w  w w.  j  a  v  a2 s  . c o m

    if (SessionManager.isLoggedIn()) {
        try {
            return super.processCall(payload);
        } catch (SerializationException e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    } else {
        RPCRequest rpcRequest = RPC.decodeRequest(payload, this.getClass(), this);
        return RPC.encodeResponseForFailure(rpcRequest.getMethod(), new GWTInvalidSessionException());
    }
}

From source file:com.cubusmail.gwtui.server.services.UserAccountService.java

License:Open Source License

@Override
public String processCall(String payload) throws SerializationException {

    if (SessionManager.isLoggedIn()) {
        try {//  ww w .  jav a 2  s . c  o  m
            return super.processCall(payload);
        } catch (SerializationException e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    } else {
        RPCRequest rpcRequest = RPC.decodeRequest(payload, this.getClass(), this);
        return RPC.encodeResponseForFailure(rpcRequest.getMethod(), new GWTInvalidSessionException());
    }
}

From source file:com.dotspots.rpcplus.flexiblerpc.FlexibleRemoteServiceServlet.java

License:Apache License

/**
 * Process a call originating from the given request. Uses the
 * {@link RPC#invokeAndEncodeResponse(Object, java.lang.reflect.Method, Object[])} method to do the actual work.
 * <p>/* www  .j  a va 2s. co m*/
 * Subclasses may optionally override this method to handle the payload in any way they desire (by routing the
 * request to a framework component, for instance). The {@link HttpServletRequest} and {@link HttpServletResponse}
 * can be accessed via the {@link #getThreadLocalRequest()} and {@link #getThreadLocalResponse()} methods.
 * </p>
 * This is public so that it can be unit tested easily without HTTP.
 * 
 * @param payload
 *            the UTF-8 request payload
 * @return a string which encodes either the method's return, a checked exception thrown by the method, or an
 *         {@link IncompatibleRemoteServiceException}
 * @throws SerializationException
 *             if we cannot serialize the response
 * @throws UnexpectedException
 *             if the invocation throws a checked exception that is not declared in the service method's signature
 * @throws RuntimeException
 *             if the service method throws an unchecked exception (the exception will be the one thrown by the
 *             service)
 */
public String processCall(String payload) throws SerializationException {
    try {
        RPCRequest rpcRequest = RPC.decodeRequest(payload, this.getClass(), this);
        onAfterRequestDeserialized(rpcRequest);
        return RPC.invokeAndEncodeResponse(this, rpcRequest.getMethod(), rpcRequest.getParameters(),
                rpcRequest.getSerializationPolicy());
    } catch (IncompatibleRemoteServiceException ex) {
        log("An IncompatibleRemoteServiceException was thrown while processing this call.", ex);
        return RPC.encodeResponseForFailure(null, ex);
    }
}

From source file:com.edgenius.wiki.gwt.server.handler.GWTSpringController.java

License:Open Source License

public String processCall(String payload) throws SerializationException {
    try {//w  w  w .  j a v  a  2  s .  co  m
        // Copy & pasted & edited from the GWT 1.4.3 RPC documentation
        RPCRequest rpcRequest = RPC.decodeRequest(payload, this.getClass(), this);

        Method targetMethod = rpcRequest.getMethod();
        Object[] targetParameters = rpcRequest.getParameters();
        SerializationPolicy policy = rpcRequest.getSerializationPolicy();
        try {
            Object result = targetMethod.invoke(this, targetParameters);
            String encodedResult;
            String redir = getRedir();
            if (redir != null) {
                Throwable ae;
                if (redir.endsWith(WikiConstants.URL_CAPTCHA_VERIFIED_ERROR)) {
                    ae = new CaptchaVerifiedException(redir);
                } else if (redir.endsWith(WikiConstants.URL_ACCESS_DENIED)) {
                    ae = new ClientAccessDeniedException(redir);
                } else {
                    //OK, maybe accessDenied or authentication or other error, then let Gwt redirect it anyway.
                    ae = new ClientAuthenticationException(redir);
                }
                log.info("Send redir value " + redir);
                encodedResult = RPC.encodeResponseForFailure(null, ae, policy);
            } else {
                if (result instanceof GeneralModel) {
                    //set current user info,so that client can check if its session is expired for each request
                    User user = WikiUtil.getUser();
                    ((GeneralModel) result).loginUserFullname = user.getFullname();
                    ((GeneralModel) result).loginUsername = user.getUsername();
                    ((GeneralModel) result).loginUserUid = user.getUid();
                }
                //return correct result
                encodedResult = RPC.encodeResponseForSuccess(rpcRequest.getMethod(), result, policy);
            }
            return encodedResult;
        } catch (IllegalArgumentException e) {
            log.error("Handle ajax call for service " + this + " with exception.", e);
            SecurityException securityException = new SecurityException(
                    "Blocked attempt to invoke method " + targetMethod);
            securityException.initCause(e);
            throw securityException;
        } catch (IllegalAccessException e) {
            log.error("Handle ajax call for service " + this + " with exception.", e);
            SecurityException securityException = new SecurityException(
                    "Blocked attempt to access inaccessible method " + targetMethod
                            + (this != null ? " on service " + this : ""));
            securityException.initCause(e);
            throw securityException;
        } catch (InvocationTargetException e) {
            log.error("Handle ajax call for service " + this + " with exception.", e);
            Throwable cause = e.getCause();
            log.warn("Get RPC InvocationTargetException exception, the root cause is " + cause);
            //following handle are not exactly response if redir value is null: accessDenied is only for login user, here does not check this. 
            //so MethodExceptionHandler.handleException() give more exactly response.
            //MethodSecurityInterceptor.invoke() may throw Authentication and AccessDenied Exception, if targetMethod does not
            //capture these exception, then they will go to here!! The example is PageControllerImpl.viewPage(), it handle the accessDenied
            //exception, if it does not, then here will handle it...
            if (cause instanceof AuthenticationException) {
                String redir = getRedir();
                if (redir == null)
                    //system default value
                    redir = WikiConstants.URL_LOGIN;
                log.info("Send Authentication redirect URL " + redir);
                ClientAuthenticationException ae = new ClientAuthenticationException(redir);
                return RPC.encodeResponseForFailure(null, ae, policy);
            } else if (cause instanceof AccessDeniedException) {
                String redir = getRedir();
                if (redir == null)
                    //system default value
                    redir = WikiConstants.URL_ACCESS_DENIED;
                log.info("Send AccessDenied redirect URL " + redir);
                ClientAccessDeniedException ae = new ClientAccessDeniedException(redir);
                return RPC.encodeResponseForFailure(null, ae, policy);
            }

            log.info("Return unexpected exception to client side " + cause);
            String failurePayload = RPC.encodeResponseForFailure(rpcRequest.getMethod(), cause, policy);
            return failurePayload;
        }
    } catch (IncompatibleRemoteServiceException e) {
        log.warn(e.getMessage());
        return RPC.encodeResponseForFailure(null, e);
    } catch (Exception e) {
        log.error("Ajax call failed", e);
        throw new RuntimeException(e);
    }
}

From source file:com.foo.server.rpc230.GWTController.java

License:Apache License

@Override
public String processCall(String payload) throws SerializationException {
    try {//from w  w w.j a  v a2 s  . c  o m
        RPCRequest rpcRequest = RPC.decodeRequest(payload, this.getClass(), this);
        ServerSerializationStreamWriterSenasa writer = getWriter(rpcRequest);

        return CustomRPC.invokeAndEncodeResponse(this, rpcRequest.getMethod(), rpcRequest.getParameters(),
                writer);

    } catch (IncompatibleRemoteServiceException ex) {
        logger.error("An IncompatibleRemoteServiceException was thrown while processing this call.", ex);
        return RPC.encodeResponseForFailure(null, ex);
    } catch (Exception e) {
        logger.error("An Exception was thrown while processing this call.", e);

        return RPC.encodeResponseForFailure(null, e);
    }
}

From source file:com.googlcode.strut2gwtplugin.interceptor.GWTServlet.java

License:Apache License

public String processCall(String payload) throws SerializationException {

    // default return value - Should this be something else?
    // no known constants to use in this case
    String result = null;//from  w  w w  .  j  a  v  a2s .  c  o m

    // get the RPC Request from the request data
    //RPCRequest rpcRequest= RPC.decodeRequest(payload);
    RPCRequest rpcRequest = RPC.decodeRequest(payload, null, this);

    onAfterRequestDeserialized(rpcRequest);

    // get the parameter types for the method look-up
    Class<?>[] paramTypes = rpcRequest.getMethod().getParameterTypes();
    paramTypes = rpcRequest.getMethod().getParameterTypes();

    // we need to get the action method from Struts
    Method method = findInterfaceMethod(actionInvocation.getAction().getClass(),
            rpcRequest.getMethod().getName(), paramTypes, true);

    // if the method is null, this may be a hack attempt
    // or we have some other big problem
    if (method == null) {
        // present the params
        StringBuffer params = new StringBuffer();
        for (int i = 0; i < paramTypes.length; i++) {
            params.append(paramTypes[i]);
            if (i < paramTypes.length - 1) {
                params.append(", ");
            }
        }

        // throw a security exception, could be attempted hack
        throw new GWTServletException("Failed to locate method " + rpcRequest.getMethod().getName() + "("
                + params + ") on interface " + actionInvocation.getAction().getClass().getName()
                + " requested through interface " + rpcRequest.getClass().getName());
    }

    Object callResult = null;
    try {
        callResult = method.invoke(actionInvocation.getAction(), rpcRequest.getParameters());
        // package  up response for GWT
        result = RPC.encodeResponseForSuccess(method, callResult);

    } catch (Exception e) {
        // check for checked exceptions
        if (e.getCause() != null) {
            Throwable cause = e.getCause();
            boolean found = false;
            for (Class<?> checkedException : rpcRequest.getMethod().getExceptionTypes()) {
                if (cause.getClass().equals(checkedException)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new GWTServletException("Unchecked exception: " + e.getCause().getClass().getName());
            }
            result = RPC.encodeResponseForFailure(null, e.getCause(), rpcRequest.getSerializationPolicy());
        } else {
            throw new GWTServletException("Unable to serialize the exception.");
        }
    }

    // return our response
    return result;
}