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

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

Introduction

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

Prototype

public static String encodeResponseForSuccess(Method serviceMethod, Object object)
        throws SerializationException 

Source Link

Document

Returns a string that encodes the object.

Usage

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;/* ww w.j  a  v  a 2s . c  om*/

    // 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.google.gwt.examples.rpc.server.AdvancedExample.java

License:Apache License

/**
 * An example of how you could integrate GWTs RPC functionality without using
 * the {@link com.google.gwt.user.server.rpc.RemoteServiceServlet}. Note that
 * it also shows how mapping between and RPC interface and some other POJO
 * could be performed./*ww  w.j av a  2s  .  c  o m*/
 */
@Override
public void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    String payload = readPayloadAsUtf8(httpRequest);

    try {
        try {
            RPCRequest rpcRequest = RPC.decodeRequest(payload);

            Object targetInstance = getInstanceToHandleRequest(httpRequest, rpcRequest);

            Method targetMethod = maybeMapRequestedMethod(targetInstance, rpcRequest.getMethod());

            Object[] targetParameters = maybeMapParameters(rpcRequest.getParameters());

            try {
                Object result = targetMethod.invoke(targetInstance, targetParameters);

                result = maybeMapResult(rpcRequest.getMethod(), result);

                /*
                 * Encode the object that will be given to the client code's
                 * AsyncCallback::onSuccess(Object) method.
                 */
                String encodedResult = RPC.encodeResponseForSuccess(rpcRequest.getMethod(), result);

                sendResponseForSuccess(httpResponse, encodedResult);
            } catch (IllegalArgumentException e) {
                SecurityException securityException = new SecurityException(
                        "Blocked attempt to invoke method " + targetMethod);
                securityException.initCause(e);
                throw securityException;
            } catch (IllegalAccessException e) {
                SecurityException securityException = new SecurityException(
                        "Blocked attempt to access inaccessible method " + targetMethod
                                + (targetInstance != null ? " on target " + targetInstance : ""));
                securityException.initCause(e);
                throw securityException;
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();

                Throwable mappedThrowable = maybeMapThrowable(cause, rpcRequest.getMethod());

                /*
                 * Encode the exception that will be passed back to the client's
                 * client code's AsyncCallback::onFailure(Throwable) method.
                 */
                String failurePayload = RPC.encodeResponseForFailure(rpcRequest.getMethod(), mappedThrowable);

                sendResponseForFailure(httpResponse, failurePayload);
            }
        } catch (IncompatibleRemoteServiceException e) {
            sendResponseForFailure(httpResponse, RPC.encodeResponseForFailure(null, e));
        }
    } catch (Throwable e) {
        /*
         * Return a generic error which will be passed to the client code's
         * AsyncCallback::onFailure(Throwable) method.
         */
        sendResponseForGenericFailure(httpResponse);
    }
}

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 ww .ja  v  a 2  s .c  om

    // 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:com.wallissoftware.alice.server.dispatch.AbstractActionHandler.java

License:Apache License

public ResultWithRpcString<R> executeToRPCString(final A action, final ExecutionContext context)
        throws ActionException {
    final R result = execute(action, context);
    try {//from  ww w . jav a2s . c o  m
        final String rpcString = RPC.encodeResponseForSuccess(
                getClass().getMethod("execute", Action.class, ExecutionContext.class), result).substring(4);
        return new ResultWithRpcString<R>(result, rpcString);
    } catch (NoSuchMethodException | SecurityException | SerializationException e) {
        return new ResultWithRpcString<R>(result, "error=" + e.getMessage());
    }
}

From source file:jolie.net.HttpProtocol.java

License:Open Source License

private EncodedContent send_encodeContent(CommMessage message, Method method, String charset, String format)
        throws IOException {
    EncodedContent ret = new EncodedContent();
    if (inInputPort == false && method == Method.GET) {
        // We are building a GET request
        return ret;
    }/*from w w w.  ja v a2s.c  om*/

    if ("xml".equals(format)) {
        Document doc = docBuilder.newDocument();
        Element root = doc.createElement(message.operationName() + ((inInputPort) ? "Response" : ""));
        doc.appendChild(root);
        if (message.isFault()) {
            Element faultElement = doc.createElement(message.fault().faultName());
            root.appendChild(faultElement);
            valueToDocument(message.fault().value(), faultElement, doc);
        } else {
            valueToDocument(message.value(), root, doc);
        }
        Source src = new DOMSource(doc);
        ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
        Result dest = new StreamResult(tmpStream);
        try {
            transformer.transform(src, dest);
        } catch (TransformerException e) {
            throw new IOException(e);
        }
        ret.content = new ByteArray(tmpStream.toByteArray());

        ret.contentType = "text/xml";
    } else if ("binary".equals(format)) {
        if (message.value().isByteArray()) {
            ret.content = (ByteArray) message.value().valueObject();
            ret.contentType = "application/octet-stream";
        }
    } else if ("html".equals(format)) {
        ret.content = new ByteArray(message.value().strValue().getBytes(charset));
        ret.contentType = "text/html";
    } else if ("multipart/form-data".equals(format)) {
        ret.contentType = "multipart/form-data; boundary=" + BOUNDARY;
        StringBuilder builder = new StringBuilder();
        for (Entry<String, ValueVector> entry : message.value().children().entrySet()) {
            if (!entry.getKey().startsWith("@")) {
                builder.append("--" + BOUNDARY + CRLF);
                builder.append("Content-Disposition: form-data; name=\"" + entry.getKey() + '\"' + CRLF + CRLF);
                builder.append(entry.getValue().first().strValue() + CRLF);
            }
        }
        builder.append("--" + BOUNDARY + "--");
        ret.content = new ByteArray(builder.toString().getBytes(charset));
    } else if ("x-www-form-urlencoded".equals(format)) {
        ret.contentType = "application/x-www-form-urlencoded";
        Iterator<Entry<String, ValueVector>> it = message.value().children().entrySet().iterator();
        Entry<String, ValueVector> entry;
        StringBuilder builder = new StringBuilder();
        while (it.hasNext()) {
            entry = it.next();
            builder.append(
                    entry.getKey() + "=" + URLEncoder.encode(entry.getValue().first().strValue(), "UTF-8"));
            if (it.hasNext()) {
                builder.append('&');
            }
        }
        ret.content = new ByteArray(builder.toString().getBytes(charset));
    } else if ("text/x-gwt-rpc".equals(format)) {
        ret.contentType = "text/x-gwt-rpc";
        try {
            if (message.isFault()) {
                ret.content = new ByteArray(RPC.encodeResponseForFailure(JolieService.class.getMethods()[0],
                        JolieGWTConverter.jolieToGwtFault(message.fault())).getBytes(charset));
            } else {
                joliex.gwt.client.Value v = new joliex.gwt.client.Value();
                JolieGWTConverter.jolieToGwtValue(message.value(), v);
                ret.content = new ByteArray(
                        RPC.encodeResponseForSuccess(JolieService.class.getMethods()[0], v).getBytes(charset));
            }
        } catch (SerializationException e) {
            throw new IOException(e);
        }
    }
    return ret;
}

From source file:org.appverse.web.framework.backend.frontfacade.gxt.controllers.FileUploadController.java

License:Appverse Public License

private void processCall(final HttpServletResponse response, byte[] bytes, final Map<String, String> parameters)
        throws Exception {
    Object presentationService = applicationContext.getBean(serviceName.get());
    if (!(presentationService instanceof IFileUploadPresentationService)) {
        throw new IllegalArgumentException("Requested Spring Bean is not a File Upload Presentation Service: ("
                + presentationService + ")");
    }/*from  w  w w  .  ja  va  2 s .co m*/
    String encodedResult = null;

    // XSS File upload protection. Clean parameters
    ESAPIHelper.cleanParams(parameters);

    // Check file size
    if (parameters.get(MAX_FILE_SIZE_PARAM_NAME) != null) {
        long maxFileSize = Long.parseLong(parameters.get(MAX_FILE_SIZE_PARAM_NAME));
        if (bytes.length > maxFileSize) {
            encodedResult = RPC
                    .encodeResponseForFailure(
                            ((IFileUploadPresentationService) presentationService).getClass()
                                    .getDeclaredMethod("uploadFile", bytes.getClass(), Map.class),
                            new GWTMaxFileSizeExceedException());
        }
    }

    // XSS File upload protection
    Tika tika = new Tika();
    String mime = tika.detect(bytes);
    if (mime.equals(org.apache.tika.mime.MediaType.APPLICATION_XML.toString())
            || mime.equals(org.apache.tika.mime.MediaType.TEXT_HTML.toString())
            || mime.equals(org.apache.tika.mime.MediaType.TEXT_PLAIN.toString())) {
        CharsetDetector charsetDetector = new CharsetDetector();
        charsetDetector.setText(bytes);
        // Get the bytes as a String autodetecting charset
        String fileString = charsetDetector.getString(bytes, null);

        // Skip possible XSS in string
        fileString = ESAPIHelper.stripXSS(fileString);

        // Write the skipped bytes respecting the autodetected charset
        bytes = fileString.getBytes(charsetDetector.detect().getName());
    }

    try {
        String result = ((IFileUploadPresentationService) presentationService).uploadFile(bytes, parameters);
        encodedResult = RPC.encodeResponseForSuccess(((IFileUploadPresentationService) presentationService)
                .getClass().getDeclaredMethod("uploadFile", bytes.getClass(), Map.class), result);
    } catch (PresentationException e) {
        GWTPresentationException pex = new GWTPresentationException(e);
        encodedResult = RPC.encodeResponseForFailure(((IFileUploadPresentationService) presentationService)
                .getClass().getDeclaredMethod("uploadFile", bytes.getClass(), Map.class), pex);
    }
    response.getOutputStream().write(encodedResult.getBytes());
    response.getOutputStream().flush();
}

From source file:org.appverse.web.framework.backend.frontfacade.gxt.controllers.GwtRpcController.java

License:Appverse Public License

@Override
public String processCall(final String payload) throws SerializationException {
    try {//from   www.  java 2 s.  c  o  m
        Object presentationService = applicationContext.getBean(serviceName.get());
        if (!(presentationService instanceof RemoteService)) {
            throw new IllegalArgumentException(
                    "Requested Spring Bean is not a GWT RemoteService Presentation Service: " + payload + " ("
                            + presentationService + ")");
        }

        RPCRequest rpcRequest = RPC.decodeRequest(payload, presentationService.getClass(), this);
        if (presentationService instanceof AuthenticationServiceFacade && rpcRequest.getMethod()
                .equals(AuthenticationServiceFacade.class.getMethod("getXSRFSessionToken"))) {
            return RPC.encodeResponseForSuccess(rpcRequest.getMethod(),
                    SecurityHelper.createXSRFToken(getThreadLocalRequest()));
        }
        return RPC.invokeAndEncodeResponse(presentationService, rpcRequest.getMethod(),
                rpcRequest.getParameters(), rpcRequest.getSerializationPolicy(), rpcRequest.getFlags());
    } catch (Exception e) {
        GWTPresentationException pex = new GWTPresentationException(e.getMessage());
        return RPC.encodeResponseForFailure(null, pex);
    }
}