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.servioticy.queueclient.SimpleQueueClient.java

LinkedList<Object> readQueue() throws ClassNotFoundException, IOException {
    LinkedList<Object> queue;
    try {//from  w ww  .  j a  v a  2s .  c  om
        FileInputStream fileIn;
        fileIn = new FileInputStream(filePath);
        ObjectInputStream in = new ObjectInputStream(fileIn);
        queue = (LinkedList<Object>) in.readObject();
        in.close();
        fileIn.close();
    } catch (FileNotFoundException e) {
        queue = new LinkedList<Object>();
    }
    return queue;
}

From source file:com.scoredev.scores.HighScore.java

public void setHighScore(final int score) throws IOException {
    //check permission first
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new HighScorePermission(gameName));
    }// w  ww . j  a v a 2  s .  co m

    // need a doPrivileged block to manipulate the file
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IOException {
                Hashtable scores = null;
                // try to open the existing file. Should have a locking
                // protocol (could use File.createNewFile).
                try {
                    FileInputStream fis = new FileInputStream(highScoreFile);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    scores = (Hashtable) ois.readObject();
                } catch (Exception e) {
                    // ignore, try and create new file
                }

                // if scores is null, create a new hashtable
                if (scores == null)
                    scores = new Hashtable(13);

                // update the score and save out the new high score
                scores.put(gameName, new Integer(score));
                FileOutputStream fos = new FileOutputStream(highScoreFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(scores);
                oos.close();
                return null;
            }
        });
    } catch (PrivilegedActionException pae) {
        throw (IOException) pae.getException();
    }
}

From source file:com.talis.storage.s3.ExternalizableS3ObjectTest.java

@Test
public void roundTripS3ObjectSerialization() throws Exception {
    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(tmp);

    byte[] bytes = ("When replying to any emails you have prior to migration "
            + "(ie any in your inbox before you have been migrated) "
            + "you will need to change the way you reply to them").getBytes();

    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
    buffer.put(bytes);/*from  w  ww  .ja v  a 2s.c  o  m*/

    S3ObjectFactory factory = new S3ObjectFactory("bucket");
    S3Object original = factory.newObject("foo", 0, MediaType.TEXT_PLAIN_TYPE, buffer);

    out.writeObject(original);
    out.flush();
    out.close();

    byte[] serialized = tmp.toByteArray();

    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(serialized));
    S3Object clone = (S3Object) in.readObject();

    assertObjectsEqual(original, clone);
}

From source file:com.jaspersoft.jasperserver.api.metadata.data.cache.JavaDataSnapshotSerializer.java

public DataSnapshot readSnapshot(InputStream in) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("deserializing data snapshot");
    }// w  w  w.  j av a 2 s  . c  o  m

    ObjectInputStream objectInput = new ObjectInputStream(in);
    DataSnapshot snapshot;
    try {
        snapshot = (DataSnapshot) objectInput.readObject();
    } catch (ClassNotFoundException e) {
        throw new JSExceptionWrapper("Failed to deserialize data snapshot", e);
    }

    if (log.isDebugEnabled()) {
        log.debug("deserialized data snapshot of type " + snapshot.getClass().getName());
    }

    return snapshot;
}

From source file:com.github.stephanarts.cas.ticket.registry.provider.UpdateMethod.java

/**
 * Execute the JSONRPCFunction./* w w w . j  a  v  a2 s  .c  om*/
 *
 * @param params    JSONRPC Method Parameters.
 *
 * @return          JSONRPC result object
 *
 * @throws JSONRPCException implementors can throw JSONRPCExceptions containing the error.
 */
public JSONObject execute(final JSONObject params) throws JSONRPCException {
    JSONObject result = new JSONObject();

    Ticket ticket;

    String ticketId = null;
    String serializedTicket = null;

    logger.debug("Update Ticket {}", ticketId);

    if (params.length() != 2) {
        throw new JSONRPCException(-32602, "Invalid Params");
    }
    if (!(params.has("ticket-id") && params.has("ticket"))) {
        throw new JSONRPCException(-32602, "Invalid Params");
    }

    try {
        ticketId = params.getString("ticket-id");
        serializedTicket = params.getString("ticket");

        ByteArrayInputStream bi = new ByteArrayInputStream(
                DatatypeConverter.parseBase64Binary(serializedTicket));
        ObjectInputStream si = new ObjectInputStream(bi);

        ticket = (Ticket) si.readObject();

        if (ticket.isExpired()) {
            logger.info("Ticket Expired {}", ticketId);
        }

        if (!this.map.containsKey(ticket.hashCode())) {
            logger.warn("Missing Key {}", ticketId);
        }

        this.map.put(ticketId.hashCode(), ticket);
    } catch (final Exception e) {
        throw new JSONRPCException(-32501, "Could not decode Ticket");
    }

    logger.debug("Ticket-ID '{}'", ticketId);

    return result;
}

From source file:com.joliciel.talismane.machineLearning.perceptron.PerceptronClassificationModel.java

@Override
public void loadModelFromStream(InputStream inputStream) {
    try {// www . j a va 2  s.com
        ObjectInputStream in = new ObjectInputStream(inputStream);
        params = (PerceptronModelParameters) in.readObject();
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }

}

From source file:com.cyberway.issue.crawler.datamodel.CrawlURITest.java

/**
 * Test serialization/deserialization works.
 * //from   ww w .j a va  2  s. co m
 * @throws IOException
 * @throws ClassNotFoundException
 */
final public void testSerialization() throws IOException, ClassNotFoundException {
    File serialize = new File(getTmpDir(), this.getClass().getName() + ".serialize");
    try {
        FileOutputStream fos = new FileOutputStream(serialize);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(this.seed);
        oos.reset();
        oos.writeObject(this.seed);
        oos.reset();
        oos.writeObject(this.seed);
        oos.close();
        // Read in the object.
        FileInputStream fis = new FileInputStream(serialize);
        ObjectInputStream ois = new ObjectInputStream(fis);
        CrawlURI deserializedCuri = (CrawlURI) ois.readObject();
        deserializedCuri = (CrawlURI) ois.readObject();
        deserializedCuri = (CrawlURI) ois.readObject();
        assertTrue("Deserialized not equal to original",
                this.seed.toString().equals(deserializedCuri.toString()));
        String host = this.seed.getUURI().getHost();
        assertTrue("Deserialized host not null", host != null && host.length() >= 0);
    } finally {
        serialize.delete();
    }
}

From source file:com.adobe.acs.commons.httpcache.keys.AbstractCacheKey.java

protected void parentReadObject(ObjectInputStream o) throws IOException, ClassNotFoundException {

    authenticationRequirement = (String) o.readObject();
    uri = (String) o.readObject();
    resourcePath = (String) o.readObject();
    hierarchyResourcePath = (String) o.readObject();
}

From source file:com.gargoylesoftware.htmlunit.WebDriverOldTestsTest.java

/**
 * @param expectedFile the expected file
 * @throws Exception if the test fails//from  w w w .  j av  a 2 s.  c  o m
 */
@SuppressWarnings("unchecked")
public WebDriverOldTestsTest(final File expectedFile) throws Exception {
    final FileInputStream fis = new FileInputStream(expectedFile);
    final ObjectInputStream oos = new ObjectInputStream(fis);
    final List<String> list = (List<String>) oos.readObject();
    for (final String s : list) {
        expectedLog_.add(s.trim());
    }
    oos.close();

    final String testFileName = expectedFile.getName().replaceFirst("\\.html\\..*", ".html");
    testFile_ = new File(expectedFile.getParentFile(), testFileName).toURI().toURL();
}

From source file:dkpro.similarity.algorithms.wikipedia.measures.WikiLinkCache.java

/**
 * Loads the cache from file/* w  ww .j  ava  2  s . com*/
 *
 * @param file
 * @throws IOException
 * @throws FileNotFoundException
 * @throws ClassNotFoundException
 * @throws Exception
 */
public Object deserializeObject(File file) throws FileNotFoundException, IOException, ClassNotFoundException {
    logger.info("Loading cache from file: " + file.getAbsolutePath());

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
    Object o = ois.readObject();
    ois.close();

    logger.info("Done.");

    return o;
}