Example usage for com.google.gwt.user.server.rpc.impl ServerSerializationStreamWriter ServerSerializationStreamWriter

List of usage examples for com.google.gwt.user.server.rpc.impl ServerSerializationStreamWriter ServerSerializationStreamWriter

Introduction

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

Prototype

public ServerSerializationStreamWriter(SerializationPolicy serializationPolicy) 

Source Link

Usage

From source file:com.brightedu.server.util.MyRPC.java

License:Apache License

/**
 * Returns a string that encodes the results of an RPC call. Private
 * overload that takes a flag signaling the preamble of the response
 * payload.//from  w  w w.  j  a  v a2 s  .c o m
 * 
 * @param object
 *            the object that we wish to send back to the client
 * @param wasThrown
 *            if true, the object being returned was an exception thrown by
 *            the service method; if false, it was the result of the service
 *            method's invocation
 * @return a string that encodes the response from a service method
 * @throws SerializationException
 *             if the object cannot be serialized
 */
public static String encodeResponse(Class<?> responseClass, Object object, boolean wasThrown, int flags,
        SerializationPolicy serializationPolicy) throws SerializationException {

    ServerSerializationStreamWriter stream = new ServerSerializationStreamWriter(serializationPolicy);
    stream.setFlags(flags);

    stream.prepareToWrite();
    if (responseClass != void.class) {
        stream.serializeValue(object, responseClass);
    }

    String bufferStr = (wasThrown ? "//EX" : "//OK") + stream.toString();
    return bufferStr;
}

From source file:com.guit.server.guice.GuiceGwtServlet.java

License:Apache License

protected String encodeResponse(Class<?> responseClass, Object object, boolean wasThrown, int flags,
        SerializationPolicy serializationPolicy) throws SerializationException {

    ServerSerializationStreamWriter stream = new ServerSerializationStreamWriter(serializationPolicy);
    stream.setFlags(flags);/*from   ww  w .j  av  a  2s .com*/

    stream.prepareToWrite();
    stream.serializeValue(object, responseClass);

    return (wasThrown ? "//EX" : "//OK") + stream.toString();
}

From source file:com.seanchenxi.gwt.storage.server.ServerStorageSerializer.java

License:Apache License

public <T> String serialize(Class<? super T> clazz, T instance, SerializationPolicy serializationPolicy)
        throws SerializationException {
    if (instance == null) {
        return null;
    } else if (String.class.equals(clazz)) {
        return (String) instance;
    }/*from   w  ww .ja  v  a  2s .  co  m*/

    if (serializationPolicy == null) {
        throw new IllegalArgumentException(
                "SerializationPolicy is null, please call StorageUtils.PolicyLoader.load(...) before");
    }

    ServerSerializationStreamWriter stream = new ServerSerializationStreamWriter(serializationPolicy);
    stream.setFlags(AbstractSerializationStream.DEFAULT_FLAGS);
    stream.prepareToWrite();
    if (clazz != void.class) {
        stream.serializeValue(instance, clazz);
    }
    return stream.toString();
}

From source file:de.csenk.gwt.ws.server.filter.serialization.ServerGWTSerializer.java

License:Open Source License

@Override
public String serialize(Object obj) throws SerializationException {
    SerializationPolicy policy = (serializationPolicy == null) ? RPC.getDefaultSerializationPolicy()
            : serializationPolicy;/*w ww  . ja  v  a2s.  c o m*/

    ServerSerializationStreamWriter streamWriter = new ServerSerializationStreamWriter(policy);
    streamWriter.prepareToWrite();

    streamWriter.writeString(obj.getClass().getName());
    streamWriter.serializeValue(obj, obj.getClass());

    return streamWriter.toString();
}

From source file:de.novanic.eventservice.service.connection.strategy.connector.streaming.StreamingServerConnector.java

License:Open Source License

/**
 * Transforms an event to a String to make it streamable.
 * @param anEvent event to serialize//from  w  ww .  j  a  v  a 2s .c om
 * @return serialized event (the event as a String)
 * @throws EventServiceException
 */
private String serialize(DomainEvent anEvent) throws EventServiceException {
    try {
        ServerSerializationStreamWriter theServerSerializationStreamWriter = new ServerSerializationStreamWriter(
                mySerializationPolicy);
        theServerSerializationStreamWriter.setFlags(0);
        theServerSerializationStreamWriter.prepareToWrite();

        theServerSerializationStreamWriter.serializeValue(anEvent, DomainEvent.class);

        return theServerSerializationStreamWriter.toString();
    } catch (SerializationException e) {
        throw new EventServiceException("Error on serializing the event \"" + anEvent + "\" for domain \""
                + anEvent.getDomain() + "\"!", e);
    }
}

From source file:net.zschech.gwt.comet.server.impl.CometServletResponseImpl.java

License:Apache License

protected String serialize(Serializable message) throws NotSerializableException, UnsupportedEncodingException {
    try {/*from w ww.  j  av  a 2s. c om*/
        if (clientOracle == null) {
            ServerSerializationStreamWriter streamWriter = new ServerSerializationStreamWriter(
                    serializationPolicy);
            streamWriter.prepareToWrite();
            streamWriter.writeObject(message);
            return streamWriter.toString();
        } else {
            ByteArrayOutputStream result = new ByteArrayOutputStream();
            RPC.streamResponseForSuccess(clientOracle, result, message);
            return new String(result.toByteArray(), "UTF-8");
        }
    } catch (SerializationException e) {
        throw new NotSerializableException("Unable to serialize object, message: " + e.getMessage());
    }
}

From source file:nl.fontys.fhict.jea.gwt.jee7.server.bus.impl.gwt.RpcSerializationPolicyProvider.java

@Produces
@Dependent
public ServerSerializationStreamWriter createWriter() {
    return new ServerSerializationStreamWriter(getSerializationPolicy());
}

From source file:org.gwtspringhibernate.reference.rlogman.spring.GwtServiceExporter.java

License:Apache License

/**
 * This is public so that it can be unit tested easily without HTTP.
 *//*  www. ja  v a  2  s.c o  m*/
public String processCall(String payload) throws SerializationException {

    // Let subclasses see the serialized request.
    //
    onBeforeRequestDeserialized(payload);

    // Create a stream to deserialize the request.
    //
    ServerSerializationStreamReader streamReader = new ServerSerializationStreamReader(serializableTypeOracle);
    streamReader.prepareToRead(payload);

    // Read the service interface
    //
    String serviceIntfName = streamReader.readString();

    // TODO(mmendez): need to check the signature
    // Verify that this very servlet implements the specified interface
    // name.
    //
    if (!isImplementedRemoteServiceInterface(serviceIntfName)) {
        // Bad payload, possible hack attempt.
        //
        throw new SecurityException("Blocked attempt to access interface '" + serviceIntfName
                + "', which is either not implemented by this servlet or which doesn't extend RemoteService; this is either misconfiguration or a hack attempt");
    }

    // Actually get the service interface, so that we can query its methods.
    //
    Class serviceIntf;
    try {
        serviceIntf = getClassFromName(serviceIntfName);
    } catch (ClassNotFoundException e) {
        throw new SerializationException("Unknown service interface class '" + serviceIntfName + "'", e);
    }

    // Read the method name.
    //
    String methodName = streamReader.readString();

    // Read the number and names of the parameter classes from the stream.
    // We have to do this so that we can find the correct overload of the
    // method.
    //
    int paramCount = streamReader.readInt();
    Class[] paramTypes = new Class[paramCount];
    for (int i = 0; i < paramTypes.length; i++) {
        String paramClassName = streamReader.readString();
        try {
            paramTypes[i] = getClassFromName(paramClassName);
        } catch (ClassNotFoundException e) {
            throw new SerializationException("Unknown parameter " + i + " type '" + paramClassName + "'", e);
        }
    }

    // For security, make sure the method is found in the service interface
    // and not just one that happens to be defined on this class.
    //
    Method serviceIntfMethod = findInterfaceMethod(serviceIntf, methodName, paramTypes, true);

    // If it wasn't found, don't continue.
    //
    if (serviceIntfMethod == null) {
        // Bad payload, possible hack attempt.
        //
        throw new SecurityException("Method '" + methodName + "' (or a particular overload) on interface '"
                + serviceIntfName + "' was not found, this is either misconfiguration or a hack attempt");
    }

    // Deserialize the parameters.
    //
    Object[] args = new Object[paramCount];
    for (int i = 0; i < args.length; i++) {
        args[i] = streamReader.deserializeValue(paramTypes[i]);
    }

    // Make the call via reflection.
    //
    String responsePayload = GENERIC_FAILURE_MSG;
    ServerSerializationStreamWriter streamWriter = new ServerSerializationStreamWriter(serializableTypeOracle);
    Throwable caught = null;
    try {
        Class returnType = serviceIntfMethod.getReturnType();
        /**
         * The method is not invoked from <code>this</code> but from <code>this.proxy</code>;
         * <code>this</code> is the exporter, <code>this.proxy</code> is the actual service
         * implementation
         * @author rlogman@gmail.com
         */
        Object returnVal = serviceIntfMethod.invoke(this.proxy, args);
        responsePayload = createResponse(streamWriter, returnType, returnVal, false);
    } catch (IllegalArgumentException e) {
        caught = e;
    } catch (IllegalAccessException e) {
        caught = e;
    } catch (InvocationTargetException e) {
        // Try to serialize the caught exception if the client is expecting
        // it,
        // otherwise log the exception server-side.
        caught = e;
        Throwable cause = e.getCause();
        if (cause != null) {
            // Update the caught exception to the underlying cause
            caught = cause;
            // Serialize the exception back to the client if it's a declared
            // exception
            if (isExpectedException(serviceIntfMethod, cause)) {
                Class thrownClass = cause.getClass();
                responsePayload = createResponse(streamWriter, thrownClass, cause, true);
                // Don't log the exception on the server
                caught = null;
            }
        }
    }

    if (caught != null) {
        responsePayload = GENERIC_FAILURE_MSG;
        // servletContext may be null (for example, when unit testing)
        /**
         * Our logger will not be servlet context's log (we don't have
         * direct access to it at this point)
         * @author rlogman@gmail.com
         */
        if (logger != null) {
            // Log the exception server side
            logger.error("Exception while dispatching incoming RPC call", caught);
        }
    }

    // Let subclasses see the serialized response.
    //
    onAfterResponseSerialized(responsePayload);

    return responsePayload;
}

From source file:org.jboss.seam.remoting.gwt.GWTRemoteServiceServlet.java

License:Open Source License

/**
 * This is public so that it can be unit tested easily without HTTP.
 *///from  ww  w .ja v a  2 s  .co  m
public String processCall(String payload) throws SerializationException {

    // Let subclasses see the serialized request.
    //
    onBeforeRequestDeserialized(payload);

    // Create a stream to deserialize the request.
    //
    ServerSerializationStreamReader streamReader = new ServerSerializationStreamReader(
            Thread.currentThread().getContextClassLoader(), null);

    streamReader.prepareToRead(payload);

    // Read the service interface
    //
    String serviceIntfName = streamReader.readString();

    //    // TODO(mmendez): need a way to check the type signature of the service intf
    //    // Verify that this very servlet implements the specified interface name.
    //    //
    //    if (!isImplementedRemoteServiceInterface(serviceIntfName)) {
    //      // Bad payload, possible hack attempt.
    //      //
    //      throw new SecurityException(
    //          "Blocked attempt to access interface '"
    //              + serviceIntfName
    //              + "', which is either not implemented by this servlet or which doesn't extend RemoteService; this is either misconfiguration or a hack attempt");
    //    }

    // Actually get the service interface, so that we can query its methods.
    //
    //    Class serviceIntf;
    //    try {
    //      serviceIntf = getClassFromName(serviceIntfName);
    //    } catch (ClassNotFoundException e) {
    //      throw new SerializationException("Unknown service interface class '"
    //          + serviceIntfName + "'", e);
    //    }

    // Read the method name.
    //
    String methodName = streamReader.readString();

    // Read the number and names of the parameter classes from the stream.
    // We have to do this so that we can find the correct overload of the
    // method.
    //
    int paramCount = streamReader.readInt();
    Class[] paramTypes = new Class[paramCount];
    for (int i = 0; i < paramTypes.length; i++) {
        String paramClassName = streamReader.readString();
        try {
            paramTypes[i] = getClassOrPrimitiveFromName(paramClassName);
        } catch (ClassNotFoundException e) {
            throw new SerializationException("Unknown parameter " + i + " type '" + paramClassName + "'", e);
        }
    }

    //    // For security, make sure the method is found in the service interface
    //    // and not just one that happens to be defined on this class.
    //    //
    //    Method serviceIntfMethod = findInterfaceMethod(serviceIntf, methodName,
    //        paramTypes, true);

    //    // If it wasn't found, don't continue.
    //    //
    //    if (serviceIntfMethod == null) {
    //      // Bad payload, possible hack attempt.
    //      //
    //      throw new SecurityException(
    //          "Method '"
    //              + methodName
    //              + "' (or a particular overload) on interface '"
    //              + serviceIntfName
    //              + "' was not found, this is either misconfiguration or a hack attempt");
    //    }

    // Deserialize the parameters.
    //
    Object[] args = new Object[paramCount];
    for (int i = 0; i < args.length; i++) {
        args[i] = streamReader.deserializeValue(paramTypes[i]);
    }

    GWTToSeamAdapter adapter = new GWTToSeamAdapter();

    // Make the call via reflection.
    //
    String responsePayload = GENERIC_FAILURE_MSG;
    ServerSerializationStreamWriter streamWriter = new ServerSerializationStreamWriter(
            LegacySerializationPolicy.getInstance());
    Throwable caught = null;
    try {

        //call the component
        ReturnedObject returnedObject = adapter.callWebRemoteMethod(serviceIntfName, methodName, paramTypes,
                args);
        Class returnType = returnedObject.returnType;
        Object returnVal = returnedObject.returnedObject;
        //      Class returnType = serviceIntfMethod.getReturnType();
        //      Object returnVal = serviceIntfMethod.invoke(this, args);
        responsePayload = createResponse(streamWriter, returnType, returnVal, false);
    } catch (IllegalArgumentException e) {
        caught = e;
    } catch (IllegalAccessException e) {
        caught = e;
    } catch (InvocationTargetException e) {
        // Try to serialize the caught exception if the client is expecting it,
        // otherwise log the exception server-side.
        caught = e;
        Throwable cause = e.getCause();
        if (cause != null) {
            // Update the caught exception to the underlying cause
            caught = cause;
            // Serialize the exception back to the client if it's a declared
            // exception
            if (cause instanceof SerializableException) {
                Class thrownClass = cause.getClass();
                responsePayload = createResponse(streamWriter, thrownClass, cause, true);
                // Don't log the exception on the server
                caught = null;
            }
        }
    }

    if (caught != null) {

        responsePayload = GENERIC_FAILURE_MSG;
        ServletContext servletContext = getServletContext();
        // servletContext may be null (for example, when unit testing)
        if (servletContext != null) {
            // Log the exception server side
            servletContext.log("Exception while dispatching incoming RPC call", caught);
        }
    }

    // Let subclasses see the serialized response.
    //
    onAfterResponseSerialized(responsePayload);

    return responsePayload;
}

From source file:org.restlet.ext.gwt.ObjectRepresentation.java

License:LGPL

@Override
public String getText() {
    if ((this.object != null) && (super.getText() == null)) {
        try {/*from  w  w  w .  j  a  v  a  2 s  . c o  m*/
            ServerSerializationStreamWriter objectWriter = new ServerSerializationStreamWriter(
                    getSerializationPolicy());
            objectWriter.serializeValue(this.object, this.targetClass);
            setText("//OK" + objectWriter.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    return super.getText();
}