Search in sources :

Example 11 with ObjectInput

use of java.io.ObjectInput in project jdk8u_jdk by JetBrains.

the class UnicastServerRef method oldDispatch.

/**
     * Handle server-side dispatch using the RMI 1.1 stub/skeleton
     * protocol, given a non-negative operation number that has
     * already been read from the call stream.
     *
     * @param obj the target remote object for the call
     * @param call the "remote call" from which operation and
     * method arguments can be obtained.
     * @param op the operation number
     * @exception IOException if unable to marshal return result or
     * release input or output streams
     */
public void oldDispatch(Remote obj, RemoteCall call, int op) throws IOException {
    // hash for matching stub with skeleton
    long hash;
    try {
        // read remote call header
        ObjectInput in;
        try {
            in = call.getInputStream();
            try {
                Class<?> clazz = Class.forName("sun.rmi.transport.DGCImpl_Skel");
                if (clazz.isAssignableFrom(skel.getClass())) {
                    ((MarshalInputStream) in).useCodebaseOnly();
                }
            } catch (ClassNotFoundException ignore) {
            }
            hash = in.readLong();
        } catch (Exception readEx) {
            throw new UnmarshalException("error unmarshalling call header", readEx);
        }
        // if calls are being logged, write out object id and operation
        logCall(obj, skel.getOperations()[op]);
        unmarshalCustomCallData(in);
        // dispatch to skeleton for remote object
        skel.dispatch(obj, call, op, hash);
    } catch (Throwable e) {
        logCallException(e);
        ObjectOutput out = call.getResultStream(false);
        if (e instanceof Error) {
            e = new ServerError("Error occurred in server thread", (Error) e);
        } else if (e instanceof RemoteException) {
            e = new ServerException("RemoteException occurred in server thread", (Exception) e);
        }
        if (suppressStackTraces) {
            clearStackTraces(e);
        }
        out.writeObject(e);
    } finally {
        // in case skeleton doesn't
        call.releaseInputStream();
        call.releaseOutputStream();
    }
}
Also used : ServerException(java.rmi.ServerException) ObjectOutput(java.io.ObjectOutput) ServerError(java.rmi.ServerError) ServerError(java.rmi.ServerError) UnmarshalException(java.rmi.UnmarshalException) ServerException(java.rmi.ServerException) ExportException(java.rmi.server.ExportException) SkeletonNotFoundException(java.rmi.server.SkeletonNotFoundException) ServerNotActiveException(java.rmi.server.ServerNotActiveException) MarshalException(java.rmi.MarshalException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(java.rmi.RemoteException) UnmarshalException(java.rmi.UnmarshalException) ObjectInput(java.io.ObjectInput) RemoteException(java.rmi.RemoteException)

Example 12 with ObjectInput

use of java.io.ObjectInput in project jdk8u_jdk by JetBrains.

the class UnicastServerRef method dispatch.

/**
     * Call to dispatch to the remote object (on the server side).
     * The up-call to the server and the marshalling of return result
     * (or exception) should be handled before returning from this
     * method.
     * @param obj the target remote object for the call
     * @param call the "remote call" from which operation and
     * method arguments can be obtained.
     * @exception IOException If unable to marshal return result or
     * release input or output streams
     */
public void dispatch(Remote obj, RemoteCall call) throws IOException {
    // positive operation number in 1.1 stubs;
    // negative version number in 1.2 stubs and beyond...
    int num;
    long op;
    try {
        // read remote call header
        ObjectInput in;
        try {
            in = call.getInputStream();
            num = in.readInt();
            if (num >= 0) {
                if (skel != null) {
                    oldDispatch(obj, call, num);
                    return;
                } else {
                    throw new UnmarshalException("skeleton class not found but required " + "for client version");
                }
            }
            op = in.readLong();
        } catch (Exception readEx) {
            throw new UnmarshalException("error unmarshalling call header", readEx);
        }
        /*
             * Since only system classes (with null class loaders) will be on
             * the execution stack during parameter unmarshalling for the 1.2
             * stub protocol, tell the MarshalInputStream not to bother trying
             * to resolve classes using its superclasses's default method of
             * consulting the first non-null class loader on the stack.
             */
        MarshalInputStream marshalStream = (MarshalInputStream) in;
        marshalStream.skipDefaultResolveClass();
        Method method = hashToMethod_Map.get(op);
        if (method == null) {
            throw new UnmarshalException("unrecognized method hash: " + "method not supported by remote object");
        }
        // if calls are being logged, write out object id and operation
        logCall(obj, method);
        // unmarshal parameters
        Object[] params = null;
        try {
            unmarshalCustomCallData(in);
            params = unmarshalParameters(obj, method, marshalStream);
        } catch (java.io.IOException e) {
            throw new UnmarshalException("error unmarshalling arguments", e);
        } catch (ClassNotFoundException e) {
            throw new UnmarshalException("error unmarshalling arguments", e);
        } finally {
            call.releaseInputStream();
        }
        // make upcall on remote object
        Object result;
        try {
            result = method.invoke(obj, params);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
        // marshal return value
        try {
            ObjectOutput out = call.getResultStream(true);
            Class<?> rtype = method.getReturnType();
            if (rtype != void.class) {
                marshalValue(rtype, result, out);
            }
        } catch (IOException ex) {
            throw new MarshalException("error marshalling return", ex);
        /*
                 * This throw is problematic because when it is caught below,
                 * we attempt to marshal it back to the client, but at this
                 * point, a "normal return" has already been indicated,
                 * so marshalling an exception will corrupt the stream.
                 * This was the case with skeletons as well; there is no
                 * immediately obvious solution without a protocol change.
                 */
        }
    } catch (Throwable e) {
        logCallException(e);
        ObjectOutput out = call.getResultStream(false);
        if (e instanceof Error) {
            e = new ServerError("Error occurred in server thread", (Error) e);
        } else if (e instanceof RemoteException) {
            e = new ServerException("RemoteException occurred in server thread", (Exception) e);
        }
        if (suppressStackTraces) {
            clearStackTraces(e);
        }
        out.writeObject(e);
    } finally {
        // in case skeleton doesn't
        call.releaseInputStream();
        call.releaseOutputStream();
    }
}
Also used : MarshalException(java.rmi.MarshalException) ServerException(java.rmi.ServerException) ObjectOutput(java.io.ObjectOutput) ServerError(java.rmi.ServerError) ServerError(java.rmi.ServerError) IOException(java.io.IOException) Method(java.lang.reflect.Method) IOException(java.io.IOException) UnmarshalException(java.rmi.UnmarshalException) ServerException(java.rmi.ServerException) ExportException(java.rmi.server.ExportException) SkeletonNotFoundException(java.rmi.server.SkeletonNotFoundException) ServerNotActiveException(java.rmi.server.ServerNotActiveException) MarshalException(java.rmi.MarshalException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(java.rmi.RemoteException) InvocationTargetException(java.lang.reflect.InvocationTargetException) UnmarshalException(java.rmi.UnmarshalException) ObjectInput(java.io.ObjectInput) RemoteException(java.rmi.RemoteException)

Example 13 with ObjectInput

use of java.io.ObjectInput in project tomee by apache.

the class Client method processRequest.

protected Response processRequest(final Request req, final Response res, final ServerMetaData server) throws RemoteException {
    if (server == null) {
        throw new IllegalArgumentException("Server instance cannot be null");
    }
    final long start = System.nanoTime();
    final ClusterMetaData cluster = getClusterMetaData(server);
    //Determine which protocol to use for request writes
    final ProtocolMetaData protocolRequest = (null != COMPATIBLE_META_DATA ? COMPATIBLE_META_DATA : PROTOCOL_META_DATA);
    /*----------------------------*/
    /* Get a connection to server */
    /*----------------------------*/
    final Connection conn;
    try {
        conn = ConnectionManager.getConnection(cluster, server, req);
    } catch (final IOException e) {
        throw new RemoteException("Unable to connect", e);
    }
    OutputStream out = null;
    InputStream in = null;
    try {
        /*----------------------------------*/
        try {
            out = conn.getOutputStream();
        } catch (final IOException e) {
            throw newIOException("Cannot open output stream to server: ", e);
        }
        /*----------------------------------*/
        try {
            protocolRequest.writeExternal(out);
            out.flush();
        } catch (final IOException e) {
            throw newIOException("Cannot write the protocol metadata to the server: ", e);
        }
        /*----------------------------------*/
        /* Get output streams */
        /*----------------------------------*/
        final ObjectOutput objectOut;
        try {
            objectOut = new ObjectOutputStream(out);
        } catch (final IOException e) {
            throw newIOException("Cannot open object output stream to server: ", e);
        }
        /*----------------------------------*/
        try {
            server.setMetaData(protocolRequest);
            server.writeExternal(objectOut);
        } catch (final IOException e) {
            throw newIOException("Cannot write the ServerMetaData to the server: ", e);
        }
        /*----------------------------------*/
        try {
            final ClusterRequest clusterRequest = new ClusterRequest(cluster);
            clusterRequest.setMetaData(protocolRequest);
            objectOut.write(clusterRequest.getRequestType().getCode());
            clusterRequest.writeExternal(objectOut);
        } catch (final Throwable e) {
            throw newIOException("Cannot write the ClusterMetaData to the server: ", e);
        }
        /*----------------------------------*/
        try {
            objectOut.write(req.getRequestType().getCode());
        } catch (final IOException e) {
            throw newIOException("Cannot write the request type to the server: ", e);
        }
        /*----------------------------------*/
        try {
            req.setMetaData(protocolRequest);
            req.writeExternal(objectOut);
            objectOut.flush();
            out.flush();
        } catch (final java.io.NotSerializableException e) {
            throw new IllegalArgumentException("Object is not serializable: " + e.getMessage());
        } catch (final IOException e) {
            throw newIOException("Cannot write the request to the server: " + e.getMessage(), e);
        }
        try {
            in = conn.getInputStream();
        } catch (final IOException e) {
            if (AuthenticationException.class.isInstance(e.getCause())) {
                throw e.getCause();
            }
            throw newIOException("Cannot open input stream to server: ", e);
        }
        //Determine the server response protocol for reading
        final ProtocolMetaData protocolResponse = new ProtocolMetaData();
        try {
            protocolResponse.readExternal(in);
        } catch (final EOFException e) {
            throw newIOException("Prematurely reached the end of the stream.  " + protocolResponse.getSpec() + " : " + e.getMessage(), e);
        } catch (final IOException e) {
            throw newIOException("Cannot determine server protocol version: Received " + protocolResponse.getSpec() + " : " + e.getMessage(), e);
        }
        final ObjectInput objectIn;
        try {
            objectIn = new EjbObjectInputStream(in);
        } catch (final IOException e) {
            throw newIOException("Cannot open object input stream to server (" + protocolResponse.getSpec() + ") : " + e.getMessage(), e);
        }
        /*----------------------------------*/
        try {
            final ClusterResponse clusterResponse = new ClusterResponse();
            clusterResponse.setMetaData(protocolResponse);
            clusterResponse.readExternal(objectIn);
            switch(clusterResponse.getResponseCode()) {
                case UPDATE:
                    {
                        setClusterMetaData(server, clusterResponse.getUpdatedMetaData());
                    }
                    break;
                case FAILURE:
                    {
                        throw clusterResponse.getFailure();
                    }
            }
        } catch (final ClassNotFoundException e) {
            throw new RemoteException("Cannot read the cluster response from the server.  The class for an object being returned is not located in this system:", e);
        } catch (final IOException e) {
            throw newIOException("Cannot read the cluster response from the server (" + protocolResponse.getSpec() + ") : " + e.getMessage(), e);
        } catch (final Throwable e) {
            throw new RemoteException("Error reading cluster response from server (" + protocolResponse.getSpec() + ") : " + e.getMessage(), e);
        }
        /*----------------------------------*/
        try {
            res.setMetaData(protocolResponse);
            res.readExternal(objectIn);
        } catch (final ClassNotFoundException e) {
            throw new RemoteException("Cannot read the response from the server.  The class for an object being returned is not located in this system:", e);
        } catch (final IOException e) {
            throw newIOException("Cannot read the response from the server (" + protocolResponse.getSpec() + ") : " + e.getMessage(), e);
        } catch (final Throwable e) {
            throw new RemoteException("Error reading response from server (" + protocolResponse.getSpec() + ") : " + e.getMessage(), e);
        }
        if (retryConditions.size() > 0) {
            if (res instanceof EJBResponse) {
                final EJBResponse ejbResponse = (EJBResponse) res;
                if (ejbResponse.getResult() instanceof ThrowableArtifact) {
                    final ThrowableArtifact artifact = (ThrowableArtifact) ejbResponse.getResult();
                    //noinspection ThrowableResultOfMethodCallIgnored
                    if (retryConditions.contains(artifact.getThrowable().getClass())) {
                        throw new RetryException(res);
                    //                            if (? < maxConditionRetry) {
                    //                                throw new RetryException(res);
                    //                            } else {
                    //                                if (FINER) {
                    //                                    logger.log(Level.FINER, "Giving up on " + artifact.getThrowable().getClass().getName().toString());
                    //                                }
                    //                            }
                    }
                }
            }
        }
        if (FINEST) {
            final long time = System.nanoTime() - start;
            final String message = String.format("Invocation %sns - %s - Request(%s) - Response(%s)", time, conn.getURI(), req, res);
            logger.log(Level.FINEST, message);
        }
    } catch (final RemoteException e) {
        throw e;
    } catch (final IOException e) {
        final URI uri = conn.getURI();
        final Set<URI> failed = getFailed();
        Client.fireEvent(new RequestFailed(uri, req, e));
        if (FINER) {
            logger.log(Level.FINER, "Add Failed " + uri.toString());
        }
        failed.add(uri);
        conn.discard();
        if (e instanceof RetryException || getRetry()) {
            try {
                Client.fireEvent(new RetryingRequest(req, server));
                processRequest(req, res, server);
            } catch (final RemoteFailoverException re) {
                throw re;
            } catch (final RemoteException re) {
                if (e instanceof RetryException) {
                    return ((RetryException) e).getResponse();
                }
                throw new RemoteFailoverException("Cannot complete request.  Retry attempted on " + failed.size() + " servers", e);
            }
        } else {
            throw new RemoteException("Cannot read the response from the server (" + protocolRequest.getSpec() + ") : " + e.getMessage(), e);
        }
    } catch (final Throwable error) {
        throw new RemoteException("Error while communicating with server: ", error);
    } finally {
        if (null != out) {
            try {
                out.close();
            } catch (final Throwable e) {
            //Ignore
            }
        }
        if (null != in) {
            try {
                in.close();
            } catch (final Throwable e) {
            //Ignore
            }
        }
        if (null != conn) {
            try {
                conn.close();
            } catch (final Throwable t) {
                logger.log(Level.WARNING, "Error closing connection with server: " + t.getMessage(), t);
            }
        }
    }
    return res;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) AuthenticationException(javax.naming.AuthenticationException) ObjectOutputStream(java.io.ObjectOutputStream) OutputStream(java.io.OutputStream) RequestFailed(org.apache.openejb.client.event.RequestFailed) ObjectOutputStream(java.io.ObjectOutputStream) URI(java.net.URI) RetryingRequest(org.apache.openejb.client.event.RetryingRequest) EOFException(java.io.EOFException) ObjectOutput(java.io.ObjectOutput) InputStream(java.io.InputStream) IOException(java.io.IOException) Exceptions.newIOException(org.apache.openejb.client.Exceptions.newIOException) ObjectInput(java.io.ObjectInput) RemoteException(java.rmi.RemoteException)

Example 14 with ObjectInput

use of java.io.ObjectInput in project ddf by codice.

the class FileSystemDataAccessObject method loadFromPersistence.

public Object loadFromPersistence(String storePath, String suffix, String key) {
    String pathString = storePath + key + suffix;
    File file = new File(pathString);
    if (!file.exists()) {
        return null;
    }
    try (InputStream inputStream = new FileInputStream(pathString)) {
        InputStream buffer = new BufferedInputStream(inputStream);
        try (ObjectInput input = new ObjectInputStream(buffer)) {
            return input.readObject();
        }
    } catch (IOException e) {
        LOGGER.debug("IOException", e);
    } catch (ClassNotFoundException e) {
        LOGGER.debug("ClassNotFoundException", e);
    }
    return null;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) ObjectInputStream(java.io.ObjectInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ObjectInput(java.io.ObjectInput) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream) ObjectInputStream(java.io.ObjectInputStream)

Example 15 with ObjectInput

use of java.io.ObjectInput in project stream-lib by addthis.

the class TestStreamSummary method testCounterSerialization.

@SuppressWarnings("unchecked")
@Test
public void testCounterSerialization() throws IOException, ClassNotFoundException {
    StreamSummary<String> vs = new StreamSummary<String>(3);
    String[] stream = { "X", "X", "Y", "Z", "A", "B", "C", "X", "X", "A", "C", "A", "A" };
    for (String i : stream) {
        vs.offer(i);
    }
    List<Counter<String>> topK = vs.topK(3);
    for (Counter<String> c : topK) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutput oo = new ObjectOutputStream(baos);
        oo.writeObject(c);
        oo.close();
        ObjectInput oi = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
        Counter<String> clone = (Counter<String>) oi.readObject();
        assertEquals(c.getCount(), clone.getCount());
        assertEquals(c.getError(), clone.getError());
        assertEquals(c.getItem(), clone.getItem());
    }
}
Also used : ObjectOutput(java.io.ObjectOutput) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectInput(java.io.ObjectInput) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.Test)

Aggregations

ObjectInput (java.io.ObjectInput)26 ObjectInputStream (java.io.ObjectInputStream)18 IOException (java.io.IOException)15 ByteArrayInputStream (java.io.ByteArrayInputStream)13 ObjectOutput (java.io.ObjectOutput)10 InputStream (java.io.InputStream)7 ObjectOutputStream (java.io.ObjectOutputStream)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 FileInputStream (java.io.FileInputStream)6 BufferedInputStream (java.io.BufferedInputStream)5 RemoteException (java.rmi.RemoteException)4 MotanFrameworkException (com.weibo.api.motan.exception.MotanFrameworkException)3 File (java.io.File)3 MarshalException (java.rmi.MarshalException)3 UnmarshalException (java.rmi.UnmarshalException)3 Test (org.junit.Test)3 DefaultRequest (com.weibo.api.motan.rpc.DefaultRequest)2 DefaultResponse (com.weibo.api.motan.rpc.DefaultResponse)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 ServerError (java.rmi.ServerError)2