Example usage for java.io ObjectInputStream readObject

List of usage examples for java.io ObjectInputStream readObject

Introduction

In this page you can find the example usage for java.io ObjectInputStream readObject.

Prototype

public final Object readObject() throws IOException, ClassNotFoundException 

Source Link

Document

Read an object from the ObjectInputStream.

Usage

From source file:com.clustercontrol.plugin.impl.AsyncTask.java

/**
 * ??BinarySerializable???//from   w w w .  j a v  a 2 s  .co  m
 * @param bytes ??Binary
 * @return Serializable
 * @throws IOException
 * @throws ClassNotFoundException
 */
public static Serializable decodeBinary(byte[] bytes) throws IOException, ClassNotFoundException {
    ByteArrayInputStream iaos = null;
    ObjectInputStream ois = null;
    Object obj = null;

    try {
        iaos = new ByteArrayInputStream(bytes);
        ois = new ObjectInputStream(iaos);

        obj = ois.readObject();
    } finally {
        if (iaos != null) {
            iaos.close();
        }
        if (ois != null) {
            ois.close();
        }
    }

    return (Serializable) obj;
}

From source file:hudson.console.ConsoleNote.java

/**
 * Reads a note back from {@linkplain #encodeTo(OutputStream) its encoded form}.
 *
 * @param in//www.j av a  2s  . c o m
 *      Must point to the beginning of a preamble.
 *
 * @return null if the encoded form is malformed.
 */
public static ConsoleNote readFrom(DataInputStream in) throws IOException, ClassNotFoundException {
    try {
        byte[] preamble = new byte[PREAMBLE.length];
        in.readFully(preamble);
        if (!Arrays.equals(preamble, PREAMBLE))
            return null; // not a valid preamble

        DataInputStream decoded = new DataInputStream(new UnbufferedBase64InputStream(in));
        int sz = decoded.readInt();
        byte[] buf = new byte[sz];
        decoded.readFully(buf);

        byte[] postamble = new byte[POSTAMBLE.length];
        in.readFully(postamble);
        if (!Arrays.equals(postamble, POSTAMBLE))
            return null; // not a valid postamble

        ObjectInputStream ois = new ObjectInputStreamEx(new GZIPInputStream(new ByteArrayInputStream(buf)),
                Jenkins.getInstance().pluginManager.uberClassLoader);
        try {
            return (ConsoleNote) ois.readObject();
        } finally {
            ois.close();
        }
    } catch (Error e) {
        // for example, bogus 'sz' can result in OutOfMemoryError.
        // package that up as IOException so that the caller won't fatally die.
        throw new IOException(e);
    }
}

From source file:com.floragunn.searchguard.util.SecurityUtil.java

public static Serializable decryptAnDeserializeObject(final String string, final SecretKey key) {

    if (string == null) {
        throw new IllegalArgumentException("string must not be null");
    }//  w  w  w.j  a v  a 2  s. com

    try {
        final byte[] userr = BaseEncoding.base64().decode(string);
        final ByteArrayInputStream bis = new ByteArrayInputStream(userr);
        final ObjectInputStream in = new ObjectInputStream(bis);
        final SealedObject ud = (SealedObject) in.readObject();
        return (Serializable) ud.getObject(key);
    } catch (final Exception e) {
        log.error(e.toString(), e);
        throw new ElasticsearchException(e.toString());
    }
}

From source file:lirmm.inria.fr.math.TestUtils.java

/**
 * Serializes an object to a bytes array and then recovers the object from the bytes array.
 * Returns the deserialized object.//from ww  w.j  a v a2s.  c o m
 *
 * @param o  object to serialize and recover
 * @return  the recovered, deserialized object
 */
public static Object serializeAndRecover(Object o) {
    try {
        // serialize the Object
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream so = new ObjectOutputStream(bos);
        so.writeObject(o);

        // deserialize the Object
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream si = new ObjectInputStream(bis);
        return si.readObject();
    } catch (IOException ioe) {
        return null;
    } catch (ClassNotFoundException cnfe) {
        return null;
    }
}

From source file:com.conversantmedia.mapreduce.tool.DistributedResourceManager.java

private static Object getResourceValue(Field field, String valueString, String originalTypeClassname,
        Path[] distFiles) throws IOException, ClassNotFoundException {

    // First, determine our approach:
    Object value = null;/*from ww  w . j  a v a 2 s.co  m*/
    if (field.getType().isAssignableFrom(String.class)) {
        value = valueString;
    } else if (ClassUtils.isPrimitiveOrWrapper(field.getType())) {
        value = ConvertUtils.convert(valueString, field.getType());
    } else {
        Path path = distributedFilePath(valueString, distFiles);

        // This is something on the distributed cache (or illegal)
        if (field.getType() == Path.class) {
            value = path;
        } else if (field.getType() == File.class) {
            value = new File(path.toUri());
        }
        // Deserialize .ser file
        else if (field.getType().isAssignableFrom(Class.forName(originalTypeClassname))) {
            ObjectInputStream in = null;
            try {
                File beanSerFile = new File(path.toUri().getPath());
                FileInputStream fileIn = new FileInputStream(beanSerFile);
                in = new ObjectInputStream(fileIn);
                value = in.readObject();
            } finally {
                IOUtils.closeQuietly(in);
            }
        } else {
            throw new IllegalArgumentException("Cannot locate resource for field [" + field.getName() + "]");
        }
    }

    return value;
}

From source file:com.joliciel.jochre.lexicon.TextFileLexicon.java

public static TextFileLexicon deserialize(File memoryBaseFile) {
    LOG.debug("deserializeMemoryBase");
    boolean isZip = false;
    if (memoryBaseFile.getName().endsWith(".zip"))
        isZip = true;/*from   w  w w.j a  v a 2  s.  c  o m*/

    TextFileLexicon memoryBase = null;
    ZipInputStream zis = null;
    FileInputStream fis = null;
    ObjectInputStream in = null;

    try {
        fis = new FileInputStream(memoryBaseFile);
        if (isZip) {
            zis = new ZipInputStream(fis);
            memoryBase = TextFileLexicon.deserialize(zis);
        } else {
            in = new ObjectInputStream(fis);
            memoryBase = (TextFileLexicon) in.readObject();
            in.close();
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException(cnfe);
    }

    return memoryBase;
}

From source file:misc.TestUtils.java

@SuppressWarnings("unchecked")
public static <T extends Serializable> T cloneSerializable(T obj) {
    ObjectOutputStream out = null;
    ObjectInputStream in = null;

    try {//from   w  w  w  .  j a v a 2s.c om
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        out = new ObjectOutputStream(bout);

        out.writeObject(obj);
        out.close();

        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
        in = new ObjectInputStream(bin);
        Object copy = in.readObject();

        in.close();

        return (T) copy;
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }

            if (in != null) {
                in.close();
            }
        } catch (IOException ignore) {
        }
    }

    return null;
}

From source file:com.hazelcast.simulator.utils.FileUtils.java

@SuppressWarnings("unchecked")
public static <E> E readObject(File file) {
    FileInputStream stream = null;
    ObjectInputStream inputStream = null;
    try {//from  w  ww.  j  a va  2 s  . com
        stream = new FileInputStream(file);
        inputStream = new ObjectInputStream(stream);
        return (E) inputStream.readObject();
    } catch (IOException e) {
        throw new FileUtilsException(e);
    } catch (ClassNotFoundException e) {
        throw new FileUtilsException(e);
    } finally {
        closeQuietly(inputStream);
        closeQuietly(stream);
    }
}

From source file:Main.java

/**
 * Reads a <code>AttributedString</code> object that has been serialised by
 * the {@link SerialUtilities#writeAttributedString(AttributedString,
 * ObjectOutputStream)} method./*from ww w  . ja  va  2 s .co m*/
 *
 * @param stream  the input stream (<code>null</code> not permitted).
 *
 * @return The attributed string object (possibly <code>null</code>).
 *
 * @throws IOException  if there is an I/O problem.
 * @throws ClassNotFoundException  if there is a problem loading a class.
 */
public static AttributedString readAttributedString(ObjectInputStream stream)
        throws IOException, ClassNotFoundException {

    if (stream == null) {
        throw new IllegalArgumentException("Null 'stream' argument.");
    }
    AttributedString result = null;
    final boolean isNull = stream.readBoolean();
    if (!isNull) {
        // read string and attributes then create result
        String plainStr = (String) stream.readObject();
        result = new AttributedString(plainStr);
        char c = stream.readChar();
        int start = 0;
        while (c != CharacterIterator.DONE) {
            int limit = stream.readInt();
            Map atts = (Map) stream.readObject();
            result.addAttributes(atts, start, limit);
            start = limit;
            c = stream.readChar();
        }
    }
    return result;
}

From source file:io.bitsquare.common.util.Utilities.java

public static Object copy(Serializable orig) throws IOException, ClassNotFoundException {
    try {//w ww.  ja  va  2 s.  c o  m
        // Write the object out to a byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(orig);
        out.flush();
        out.close();

        // Make an input stream from the byte array and read
        // a copy of the object back in.
        ObjectInputStream in = new LookAheadObjectInputStream(new ByteArrayInputStream(bos.toByteArray()),
                true);
        Object obj = in.readObject();
        return obj;
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
        throw e;
    }
}