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.asquareb.kaaval.MachineKey.java

/**
 * Method to decrypt a string. Accepts the string to be decrypted and the
 * name of the file which stores the key values
 *//*from  w ww  .java  2s  .co  m*/
public static String decrypt(String property, String app) throws IOException, KaavalException {
    SecretKey key = null;
    ObjectInputStream is = null;
    MachineKey mKey = null;
    int eti = 0;
    Cipher pbeCipher = null;
    InetAddress ip = InetAddress.getLocalHost();
    NetworkInterface macAddress = NetworkInterface.getByInetAddress(ip);
    byte[] macId = macAddress.getHardwareAddress();
    try {
        is = new ObjectInputStream(new BufferedInputStream(new FileInputStream(app)));
        mKey = (MachineKey) is.readObject();
        key = mKey.yek;
        salt = mKey.tlas;
        eti = mKey.eti;
        String ipa = ip.getHostAddress();
        if (!ipa.equals(mKey.api) || !new String(macId).equals(mKey.macad))
            throw new KaavalException(5, "Key file is not for this machine");
        is.close();
        pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(salt, eti));
        return new String(pbeCipher.doFinal(base64Decode(property)));
    } catch (IOException e) {
        throw new KaavalException(3, "Error in reading key file during decryption", e);
    } catch (KaavalException e) {
        throw e;
    } catch (Exception e) {
        throw new KaavalException(4, "Error during decryption", e);
    } finally {
        if (is != null)
            is.close();
    }
}

From source file:Main.java

/**
 * Reads a <code>Shape</code> object that has been serialised by the
 * {@link #writeShape(Shape, ObjectOutputStream)} method.
 *
 * @param stream  the input stream (<code>null</code> not permitted).
 *
 * @return The shape object (possibly <code>null</code>).
 *
 * @throws IOException  if there is an I/O problem.
 * @throws ClassNotFoundException  if there is a problem loading a class.
 *//*from  w w w  .  ja  v  a2  s.  c o m*/
public static Shape readShape(final ObjectInputStream stream) throws IOException, ClassNotFoundException {

    if (stream == null) {
        throw new IllegalArgumentException("Null 'stream' argument.");
    }
    Shape result = null;
    final boolean isNull = stream.readBoolean();
    if (!isNull) {
        final Class c = (Class) stream.readObject();
        if (c.equals(Line2D.class)) {
            final double x1 = stream.readDouble();
            final double y1 = stream.readDouble();
            final double x2 = stream.readDouble();
            final double y2 = stream.readDouble();
            result = new Line2D.Double(x1, y1, x2, y2);
        } else if (c.equals(Rectangle2D.class)) {
            final double x = stream.readDouble();
            final double y = stream.readDouble();
            final double w = stream.readDouble();
            final double h = stream.readDouble();
            result = new Rectangle2D.Double(x, y, w, h);
        } else if (c.equals(Ellipse2D.class)) {
            final double x = stream.readDouble();
            final double y = stream.readDouble();
            final double w = stream.readDouble();
            final double h = stream.readDouble();
            result = new Ellipse2D.Double(x, y, w, h);
        } else if (c.equals(Arc2D.class)) {
            final double x = stream.readDouble();
            final double y = stream.readDouble();
            final double w = stream.readDouble();
            final double h = stream.readDouble();
            final double as = stream.readDouble(); // Angle Start
            final double ae = stream.readDouble(); // Angle Extent
            final int at = stream.readInt(); // Arc type
            result = new Arc2D.Double(x, y, w, h, as, ae, at);
        } else if (c.equals(GeneralPath.class)) {
            final GeneralPath gp = new GeneralPath();
            final float[] args = new float[6];
            boolean hasNext = stream.readBoolean();
            while (!hasNext) {
                final int type = stream.readInt();
                for (int i = 0; i < 6; i++) {
                    args[i] = stream.readFloat();
                }
                switch (type) {
                case PathIterator.SEG_MOVETO:
                    gp.moveTo(args[0], args[1]);
                    break;
                case PathIterator.SEG_LINETO:
                    gp.lineTo(args[0], args[1]);
                    break;
                case PathIterator.SEG_CUBICTO:
                    gp.curveTo(args[0], args[1], args[2], args[3], args[4], args[5]);
                    break;
                case PathIterator.SEG_QUADTO:
                    gp.quadTo(args[0], args[1], args[2], args[3]);
                    break;
                case PathIterator.SEG_CLOSE:
                    gp.closePath();
                    break;
                default:
                    throw new RuntimeException("JFreeChart - No path exists");
                }
                gp.setWindingRule(stream.readInt());
                hasNext = stream.readBoolean();
            }
            result = gp;
        } else {
            result = (Shape) stream.readObject();
        }
    }
    return result;

}

From source file:com.griddynamics.jagger.util.SerializationUtils.java

public static <T extends Serializable> T fromString(String s) {
    if (s.isEmpty()) {
        log.info("fromString({}, '{}')", fromStringCount.getAndIncrement(), s);
    }/*from ww  w.  j  av a2  s  .  co  m*/
    ObjectInputStream ois = null;
    try {
        byte[] data = Base64Coder.decode(s);
        try {
            //TODO fixes for support old reports
            ois = new JBossObjectInputStream(new ByteArrayInputStream(data));
        } catch (IOException e) {
            // /data stored not with JBoss
            ois = new ObjectInputStream(new ByteArrayInputStream(data));
        }
        T obj = (T) ois.readObject();
        return obj;
    } catch (IOException e) {
        log.error("Deserialization exception ", e);
        log.error("fromString('{}')", s);
        throw new TechnicalException(e);
    } catch (ClassNotFoundException e) {
        log.error("Deserialization exception ", e);
        throw new TechnicalException(e);
    } finally {
        try {
            Closeables.close(ois, true);
        } catch (IOException e) {
            log.warn("IOException should not have been thrown.", e);
        }
    }
}

From source file:com.intuit.tank.project.Script.java

@SuppressWarnings("unchecked")
public static List<ScriptStep> deserializeBlob(SerializedScriptStep serializedScriptStep) {
    List<ScriptStep> result = null;
    ObjectInputStream s = null;
    try {//from  w  w w .ja  v a  2 s.c  om
        if (serializedScriptStep != null && serializedScriptStep.getSerialzedBlob() != null) {
            s = new ObjectInputStream(serializedScriptStep.getSerialzedBlob().getBinaryStream());
            result = (List<ScriptStep>) s.readObject();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(s);
    }
    return result;
}

From source file:com.yahoo.labs.yamall.local.Yamall.java

private static double evalHoldoutError() throws FileNotFoundException, IOException, ClassNotFoundException {
    double cumLoss = 0;
    double weightedSampleSum = 0;
    ObjectInputStream oin = new ObjectInputStream(new FileInputStream("cache_holdout.bin"));

    Instance testSample;//  w  ww.j a va2 s .c o m
    while ((testSample = (Instance) oin.readObject()) != null) {
        weightedSampleSum += testSample.getWeight();
        double score = learner.predict(testSample);
        score = Math.min(Math.max(score, minPrediction), maxPrediction);
        if (!binary)
            cumLoss += learner.getLoss().lossValue(score, testSample.getLabel()) * testSample.getWeight();
        else if (Math.signum(score) != testSample.getLabel())
            cumLoss += testSample.getWeight();
    }
    oin.close();

    return cumLoss / weightedSampleSum;
}

From source file:edu.usc.pgroup.floe.utils.Utils.java

/**
 * Deserializer for Zookeeper data. See comments for serialize function.
 *
 * @param serialized serialized byte array (default java serialized)
 *                   obtained from the serialize function.
 * @return the constructed java object. Needs to be typecasted to
 * appropriate object before using. No checks are actionCompleted here.
 *///from www  . j a v a 2s  .c o m
public static Object deserialize(final byte[] serialized) {
    try {
        ByteArrayInputStream bis = new ByteArrayInputStream(serialized);
        ObjectInputStream ois = new ObjectInputStream(bis);
        Object ret = ois.readObject();
        ois.close();
        return ret;
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.nineash.hutsync.client.NetworkUtilities.java

/** Read the object from Base64 string. */
private static Object fromString(String s) throws IOException, ClassNotFoundException {
    byte[] data = Base64Coder.decode(s);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
    Object o = ois.readObject();
    ois.close();//from www . j a  v  a 2  s.com
    return o;
}

From source file:com.newatlanta.appengine.datastore.CachingDatastoreService.java

private static Object deserialize(HttpServletRequest req) throws Exception {
    if (req.getContentLength() == 0) {
        return null;
    }/*from   ww w  .j a  v  a2s .  com*/
    byte[] bytesIn = new byte[req.getContentLength()];
    req.getInputStream().readLine(bytesIn, 0, bytesIn.length);
    if (isDevelopment()) { // workaround for issue #2097
        bytesIn = decodeBase64(bytesIn);
    }
    ObjectInputStream objectIn = new ObjectInputStream(
            new BufferedInputStream(new ByteArrayInputStream(bytesIn)));
    try {
        return objectIn.readObject();
    } finally {
        objectIn.close();
    }
}

From source file:com.beetle.framework.util.ObjectUtil.java

/**
 * ?/* w  w w. ja v  a  2  s.  c o m*/
 * 
 * @param bytes
 * @return
 */
public final static Object bytesToObj(byte[] bytes) {
    ByteArrayInputStream bai = null;
    ObjectInputStream ois;
    try {
        bai = new ByteArrayInputStream(bytes);
        ois = new ObjectInputStream(bai);
        Object obj = ois.readObject();
        ois.close();
        ois = null;
        return obj;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (bai != null) {
                bai.close();
                bai = null;
            }
        } catch (IOException e) {
        }
    }
}

From source file:com.icantrap.collections.dawg.Dawg.java

/**
 * Factory method.  Creates a new Dawg entry by reading in data from the given InputStream.  Once the data is read,
 * the stream remains open.// www .j  a  va2 s . com
 *
 * @param is the stream with the data to create the Dawg instance.
 * @return a new Dawg instance with the data loaded
 * @throws DataFormatException if the InputStream doesn't contain the proper data format for loading a Dawg instance
 * @throws IOException if reading from the stream casues an IOException.
 */
public static Dawg load(InputStream is) throws IOException {
    BufferedInputStream bis = new BufferedInputStream(is, 8 * 1024);
    ObjectInputStream ois = new ObjectInputStream(bis);

    int[] ints;

    try {
        ints = (int[]) ois.readObject();
    } catch (ClassNotFoundException cnfe) {
        throw new DataFormatException("Bad file.  Not valid for loading com.icantrap.collections.dawg.Dawg",
                cnfe);
    }

    return new Dawg(ints);
}