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

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

Introduction

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

Prototype

public static String encodeResponseForFailure(Method serviceMethod, Throwable cause,
        SerializationPolicy serializationPolicy) throws SerializationException 

Source Link

Document

Returns a string that encodes an exception.

Usage

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

License:Open Source License

public String processCall(String payload) throws SerializationException {
    try {//from  w w w  . j a  v a 2  s .  c om
        // 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.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;//w w  w  .j  a v  a2  s  .  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;
}

From source file:com.googlecode.struts2gwtplugin.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  ava  2s.  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) {
            log.error("Struts2GWT exception", e.getCause());
            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 Struts2GWTBridgeException("Unhandled exception!", cause);
            }
            result = RPC.encodeResponseForFailure(null, e.getCause(), rpcRequest.getSerializationPolicy());
        } else {
            throw new Struts2GWTBridgeException("Unable to serialize the exception.", e);
        }
    }

    // return our response
    return result;
}

From source file:de.itsvs.cwtrpc.security.AbstractRpcFailureHandler.java

License:Apache License

protected void writeExpectedException(HttpServletRequest request, HttpServletResponse response,
        Exception remoteException) throws IOException {
    final RPCRequest rpcRequest;
    final String responsePayload;

    rpcRequest = AbstractRpcAuthenticationProcessingFilter.getRpcRequest(request);
    try {//from   w ww .  ja  v  a2 s  . c om
        if (rpcRequest != null) {
            /* checked exceptions must be declared by service method */
            responsePayload = RPC.encodeResponseForFailure(rpcRequest.getMethod(), remoteException,
                    rpcRequest.getSerializationPolicy());
        } else {
            log.warn("Could not determine RPC request. Using default serialization.");
            responsePayload = RPC.encodeResponseForFailure(null, remoteException);
        }
    } catch (UnexpectedException e) {
        if (rpcRequest != null) {
            log.error("Exception " + remoteException.getClass().getName() + " is unexpected for method "
                    + rpcRequest.getMethod() + " of declaring class "
                    + rpcRequest.getMethod().getDeclaringClass().getName(), e);
        } else {
            log.error("Exception " + remoteException.getClass().getName() + " is unexpected for unknown method",
                    e);
        }
        writeUnexpectedException(request, response, remoteException);
        return;
    } catch (SerializationException e) {
        log.error("Error while serializing " + remoteException.getClass().getName(), e);
        writeUnexpectedException(request, response, remoteException);
        return;
    }

    if (CwtRpcUtils.getRpcSessionInvalidationPolicy(request).isInvalidateOnExpectedException()) {
        invalidateSession(request);
    }

    response.reset();
    addNoCacheResponseHeaders(request, response);
    RPCServletUtils.writeResponse(getServletContext(), response, responsePayload, false);
    response.flushBuffer();
}

From source file:edu.caltech.ipac.firefly.server.rpc.BaseRemoteService.java

@Override
protected void doUnexpectedFailure(Throwable e) {
    RPCRequest req = (RPCRequest) ServerContext.getRequestOwner().getAttribute("rpcRequest");
    if (req == null) {
        super.doUnexpectedFailure(e);
        return;//from  w  w w . j a v a  2 s. co m
    }
    try {
        RPC.encodeResponseForFailure(req.getMethod(), e, req.getSerializationPolicy());
    } catch (Exception ex) {
        ex.printStackTrace();
        super.doUnexpectedFailure(ex);
    }
}

From source file:net.sf.gilead.comet.PersistentCometService.java

License:Apache License

/**
 * if a PendingRequest class was created, you should call
 * 'invokeService(PendingRequest)'//from   w w w .  j av  a2s  .  com
 * 
 * @param p_rpcRequest
 * @param p_event
 * @throws IOException
 */
@Override
protected void invokeService(RPCRequest p_rpcRequest, CometEvent p_event) throws IOException {
    if (p_rpcRequest == null || p_event == null) {
        return;
    }

    if (_log.isDebugEnabled()) {
        _log.debug("invokeService: " + p_rpcRequest.getMethod().getName());
    }
    // store perThreadRequest/Response to make this methods re-entrant
    //
    HttpServletRequest oldRequest = getPerThreadRequest().get();
    HttpServletResponse oldResponse = getPerThreadResponse().get();
    getPerThreadRequest().set(p_event.getHttpServletRequest());
    getPerThreadResponse().set(p_event.getHttpServletResponse());

    try {
        String responsePayload = null;
        try {
            try {
                Object returnValue = p_rpcRequest.getMethod().invoke(this, p_rpcRequest.getParameters());

                returnValue = GileadRPCHelper.parseReturnValue(returnValue, _beanManager);

                // Encode response
                //  
                responsePayload = RPC.encodeResponseForSuccess(p_rpcRequest.getMethod(), returnValue,
                        p_rpcRequest.getSerializationPolicy());

            } catch (IllegalAccessException e) {
                SecurityException securityException = new SecurityException(
                        "Blocked attempt to access inaccessible method " + p_rpcRequest.getMethod()
                                + " on target " + this);
                securityException.initCause(e);
                throw securityException;
            } catch (InvocationTargetException e) {
                // Clone exception if needed
                Exception exception = (Exception) GileadRPCHelper.parseReturnValue(e.getCause(), _beanManager);

                responsePayload = RPC.encodeResponseForFailure(p_rpcRequest.getMethod(), exception,
                        p_rpcRequest.getSerializationPolicy());
            }
        } catch (SerializationException e) {
            _log.error("Serialization exception : " + e.getMessage(), e);
            e.printStackTrace();
            responsePayload = "server error: " + e.getMessage();
        }
        writeResponse(p_event.getHttpServletResponse(), responsePayload);
        p_event.close();
    } finally {
        getPerThreadRequest().set(oldRequest);
        getPerThreadResponse().set(oldResponse);
    }
}

From source file:net.sf.gilead.gwt.PersistentRemoteService.java

License:Apache License

/**
 * Override of the RemoteServletService main method
 *///from  w w w  .j a va2 s  . c o m
@Override
public String processCall(String payload) throws SerializationException {
    // Normal processing
    //
    RPCRequest rpcRequest = null;
    try {
        // Decode request
        //
        rpcRequest = RPC.decodeRequest(payload, this.getClass(), this);

        if (rpcRequest == null) {
            throw new NullPointerException("No rpc request");
        }

        // Invoke method
        //
        GileadRPCHelper.parseInputParameters(rpcRequest, _beanManager, getThreadLocalRequest().getSession());
        Object returnValue = rpcRequest.getMethod().invoke(this, rpcRequest.getParameters());

        returnValue = GileadRPCHelper.parseReturnValue(returnValue, _beanManager);

        // Encode response
        //
        return RPC.encodeResponseForSuccess(rpcRequest.getMethod(), returnValue,
                rpcRequest.getSerializationPolicy());
    } catch (IllegalArgumentException e) {
        SecurityException securityException = new SecurityException(
                "Blocked attempt to invoke method " + rpcRequest.getMethod());
        securityException.initCause(e);
        throw securityException;
    } catch (IllegalAccessException e) {
        SecurityException securityException = new SecurityException(
                "Blocked attempt to access inaccessible method " + rpcRequest.getMethod() + " on target "
                        + this);
        securityException.initCause(e);
        throw securityException;
    } catch (InvocationTargetException e) {
        // Clone exception if needed
        Exception exception = (Exception) GileadRPCHelper.parseReturnValue(e.getCause(), _beanManager);

        return RPC.encodeResponseForFailure(rpcRequest.getMethod(), exception,
                rpcRequest.getSerializationPolicy());
    } catch (IncompatibleRemoteServiceException ex) {
        // Clone exception if needed
        Exception exception = (Exception) GileadRPCHelper.parseReturnValue(ex, _beanManager);
        return RPC.encodeResponseForFailure(null, exception, rpcRequest.getSerializationPolicy());
    }
}

From source file:org.pentaho.platform.web.servlet.AbstractGwtRpcProxyServlet.java

License:Open Source License

@Override
public String processCall(String payload) throws SerializationException {
    Map<Class<?>, Boolean> whitelist = new HashMap<Class<?>, Boolean>();
    whitelist.put(GwtRpcProxyException.class, Boolean.TRUE);
    Map<Class<?>, String> obfuscatedTypeIds = new HashMap<Class<?>, String>();
    StandardSerializationPolicy policy = new StandardSerializationPolicy(whitelist, whitelist,
            obfuscatedTypeIds);/*from   w w  w .  j  a  v a  2 s.c  o m*/

    String servletContextPath = getServletContextPath();

    Object target = null;
    try {
        target = resolveDispatchTarget(servletContextPath);
    } catch (GwtRpcProxyException ex) {
        logger.error(Messages.getInstance().getErrorString(
                "AbstractGwtRpcProxyServlet.ERROR_0001_FAILED_TO_RESOLVE_DISPATCH_TARGET", servletContextPath), //$NON-NLS-1$
                ex);
        return RPC.encodeResponseForFailure(null, ex, policy);
    }

    final ClassLoader origLoader = Thread.currentThread().getContextClassLoader();
    final ClassLoader altLoader = target.getClass().getClassLoader();

    try {
        // temporarily swap out the context classloader to an alternate classloader if
        // the targetBean has been loaded by one other than the context classloader.
        // This is necessary, so the RPC class can do a Class.forName and find the service
        // class specified in the request
        if (altLoader != origLoader) {
            Thread.currentThread().setContextClassLoader(altLoader);
        }

        RPCRequest rpcRequest = RPC.decodeRequest(payload, null, this);
        onAfterRequestDeserialized(rpcRequest);
        // don't require the server side to implement the service interface
        Method method = rpcRequest.getMethod();
        try {
            Method m = target.getClass().getMethod(method.getName(), method.getParameterTypes());
            if (m != null) {
                method = m;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RPC.invokeAndEncodeResponse(target, method, rpcRequest.getParameters(),
                rpcRequest.getSerializationPolicy());
    } catch (IncompatibleRemoteServiceException ex) {
        logger.error(Messages.getInstance().getErrorString(
                "AbstractGwtRpcProxyServlet.ERROR_0003_RPC_INVOCATION_FAILED", target.getClass().getName()), //$NON-NLS-1$
                ex);
        return RPC.encodeResponseForFailure(null, ex);
    } finally {
        // reset the context classloader if necessary
        if ((altLoader != origLoader) && origLoader != null) {
            Thread.currentThread().setContextClassLoader(origLoader);
        }
    }
}

From source file:org.unitime.timetable.spring.gwt.GwtDispatcherServlet.java

License:Apache License

@Override
public String processCall(String payload) throws SerializationException {
    try {/*from w w  w. j  a  v  a 2s.co m*/
        Object handler = getBean(getThreadLocalRequest());
        RPCRequest rpcRequest = RPC.decodeRequest(payload, handler.getClass(), this);
        onAfterRequestDeserialized(rpcRequest);
        try {
            if (ApplicationProperty.QueryLogJSON.isTrue())
                sLastQuery.set(new GwtCallInfo(rpcRequest.getMethod().getDeclaringClass().getSimpleName() + "#"
                        + rpcRequest.getMethod().getName(), iGson.toJson(rpcRequest.getParameters())));
            else
                sLastQuery.set(new GwtCallInfo(rpcRequest.getMethod().getDeclaringClass().getSimpleName() + "#"
                        + rpcRequest.getMethod().getName(), payload));
        } catch (Throwable t) {
        }
        try {
            return RPC.invokeAndEncodeResponse(handler, rpcRequest.getMethod(), rpcRequest.getParameters(),
                    rpcRequest.getSerializationPolicy());
        } catch (UnexpectedException ex) {
            if (ex.getCause() instanceof AccessDeniedException)
                return RPC.encodeResponseForFailure(rpcRequest.getMethod(),
                        new PageAccessException(ex.getCause().getMessage()),
                        rpcRequest.getSerializationPolicy());
            throw ex;
        }
    } catch (IncompatibleRemoteServiceException ex) {
        return RPC.encodeResponseForFailure(null, ex);
    }
}

From source file:stroom.servlet.RemoteServiceHandlerAdapter.java

License:Apache License

@Override
public String processCall(final String payload) throws SerializationException {
    // The code below is borrowed from RemoteServiceServlet.processCall,
    // with the following changes:
    // 1) Changed object for decoding and invocation to be the handler
    // (versus the original 'this')
    RPCRequest rpcRequest = null;//from   w ww .j  a v  a2 s  .c o  m
    String response = null;

    try {
        final Object handler = getCurrentHandler();

        rpcRequest = RPC.decodeRequest(payload, handler.getClass(), this);
        onAfterRequestDeserialized(rpcRequest);
        response = RPC.invokeAndEncodeResponse(handler, rpcRequest.getMethod(), rpcRequest.getParameters(),
                rpcRequest.getSerializationPolicy());
    } catch (final IncompatibleRemoteServiceException e) {
        LOGGER.error("An IncompatibleRemoteServiceException was thrown while processing this call.", e);
        if (rpcRequest != null) {
            response = RPC.encodeResponseForFailure(rpcRequest.getMethod(), e,
                    rpcRequest.getSerializationPolicy());
        } else {
            response = RPC.encodeResponseForFailure(null, e);
        }
    } catch (final Throwable e) {
        if (rpcRequest != null) {
            LOGGER.error(
                    "processCall() - rpcMethod=" + rpcRequest.getMethod() + ", rpcRequest=" + rpcRequest + " ",
                    e);
            response = RPC.encodeResponseForFailure(rpcRequest.getMethod(), e,
                    rpcRequest.getSerializationPolicy());
        } else {
            LOGGER.error("processCall() rpcRequest=null ", e);
            response = RPC.encodeResponseForFailure(null, e);
        }
    } finally {
        // Make sure this thread no longer references this request as it
        // might be reused for other processing. We also don't want to hold
        // on to this request for longer than necessary.
        httpServletRequestHolder.set(null);
    }

    return response;
}