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:de.tudarmstadt.ukp.dkpro.tc.weka.util.WekaUtils.java

/**
 * Reads a file serialized with {@link WekaUtils#writeMlResultToFile(MultilabelResult, File)}.
 *
 * @param file the file to read from/*w ww  .  j  a  v a 2 s.com*/
 * @return an object holding the results
 * @throws IOException i/o error
 * @throws ClassNotFoundException file not found
 */
public static MultilabelResult readMlResultFromFile(File file) throws IOException, ClassNotFoundException {
    ObjectInputStream stream = new ObjectInputStream(new FileInputStream(file));
    MultilabelResult result = (MultilabelResult) stream.readObject();
    stream.close();
    return result;
}

From source file:net.carinae.dev.async.util.SerializerJavaImpl.java

/**
 * {@inheritDoc}/*from  w w  w . j  a  v a2s  .  c o  m*/
 */
@Override
public Object deserializeObject(byte[] serializedObj) {

    try {
        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(serializedObj));
        Object obj = in.readObject();
        return obj;
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalArgumentException("Could not deserialize", e);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        throw new IllegalArgumentException("Could not deserialize", e);
    }

}

From source file:com.topekalabs.bigmachine.lib.app.ContinuationSerializationTest.java

@Test
public void simpleSerializationTest() throws Exception {
    MutableInt context = new MutableInt();
    Continuation c = Continuation.startWith(new SimpleContinuationRunnable(), context);
    logger.debug("Is serializable: {}", c.isSerializable());

    Assert.assertEquals("The value of the context was not set properly", SimpleContinuationRunnable.FIRST_VALUE,
            context.getValue());//from  w  w  w  .ja  v  a2  s  . co m

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(c);
    oos.close();

    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
    c = (Continuation) ois.readObject();
    ois.close();

    Continuation.continueWith(c, context);

    Assert.assertEquals("The value of the context was not set properly",
            SimpleContinuationRunnable.SECOND_VALUE, context.getValue());
}

From source file:PersisTest.java

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == clearBtn) {
        // Repaint with an empty display list.
        displayList = new ArrayList();
        repaint();//from   www  .  ja  v  a 2s.c  o  m
    } else if (e.getSource() == saveBtn) {
        // Write display list array list to an object output stream.
        try {
            FileOutputStream fos = new FileOutputStream(pathname);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(displayList);
            oos.flush();
            oos.close();
            fos.close();
        } catch (IOException ex) {
            System.err.println("Trouble writing display list array list");
        }
    } else if (e.getSource() == restoreBtn) {
        // Read a new display list array list from an object input stream.
        try {
            FileInputStream fis = new FileInputStream(pathname);
            ObjectInputStream ois = new ObjectInputStream(fis);
            displayList = (ArrayList) (ois.readObject());
            ois.close();
            fis.close();
            repaint();
        } catch (ClassNotFoundException ex) {
            System.err.println("Trouble reading display list array list");
        } catch (IOException ex) {
            System.err.println("Trouble reading display list array list");
        }
    } else if (e.getSource() == quitBtn) {
        System.exit(0);
    }
}

From source file:ch.epfl.data.squall.utilities.SquallSerializationDelegate.java

@Override
public Object deserialize(byte[] bytes) {
    try {/*w  w w .j  a v a  2s  . co  m*/
        return super.deserialize(bytes);
    } catch (RuntimeException e) {
        try {
            if (classdir == null)
                throw e;

            URLClassLoader classloader = new URLClassLoader(new URL[] { classdir },
                    Thread.currentThread().getContextClassLoader());

            // Read the object
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ClassLoaderObjectInputStream(classloader, bis);
            Object ret = ois.readObject();
            ois.close();
            return ret;
        } catch (ClassNotFoundException error) {
            throw new RuntimeException(error);
        } catch (IOException error) {
            throw new RuntimeException(error);
        }
    }
}

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

/**
 * get the high score. return -1 if it hasn't been set.
 *
 *///from  w w w  . j  a  v a 2 s . com
public int getHighScore() throws IOException, ClassNotFoundException {
    //check permission first
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new HighScorePermission(gameName));
    }

    Integer score = null;

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

                // get the high score out
                return scores.get(gameName);
            }
        });
    } catch (PrivilegedActionException pae) {
        Exception e = pae.getException();
        if (e instanceof IOException)
            throw (IOException) e;
        else
            throw (ClassNotFoundException) e;
    }
    if (score == null)
        return -1;
    else
        return score.intValue();
}

From source file:com.pingcap.tikv.meta.TiTableInfoTest.java

@Test
public void testSerializable() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    TiTableInfo tableInfo = mapper.readValue(tableJson, TiTableInfo.class);
    ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(byteOutStream);
    oos.writeObject(tableInfo);/*from  w  ww.j ava 2s .  c o  m*/

    ByteArrayInputStream byteInStream = new ByteArrayInputStream(byteOutStream.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(byteInStream);
    TiTableInfo deserTable = (TiTableInfo) ois.readObject();
    assertEquals(deserTable.toProto(), tableInfo.toProto());
}

From source file:it.acubelab.smaph.SmaphAnnotator.java

/**
 * Set the file to which the Bing responses cache is bound.
 * /*  ww w  .j  a  va2  s . co m*/
 * @param cacheFilename
 *            the cache file name.
 * @throws FileNotFoundException
 *             if the file could not be open for reading.
 * @throws IOException
 *             if something went wrong while reading the file.
 * @throws ClassNotFoundException
 *             is the file contained an object of the wrong class.
 */
public static void setCache(String cacheFilename)
        throws FileNotFoundException, IOException, ClassNotFoundException {
    if (resultsCacheFilename != null && resultsCacheFilename.equals(cacheFilename))
        return;
    System.out.println("Loading bing cache...");
    resultsCacheFilename = cacheFilename;
    if (new File(resultsCacheFilename).exists()) {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(resultsCacheFilename));
        url2jsonCache = (HashMap<String, byte[]>) ois.readObject();
        ois.close();
    }
}

From source file:com.fuzhepan.arpc.client.ProxyHandler.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    log.debug("invoke was called!");

    if (method.getName().equals("toString")) {
        return "toString method was called";
    }/*w  ww.  ja  v  a 2 s  . c  o  m*/

    RpcContext rpcContext = new RpcContext(interfaceName, method.getName(), method.getParameterTypes(), args);

    //get service info and load balance
    List<HostPortPair> serviceList = RpcConfig.getServiceList(serviceName);
    if (serviceList == null || serviceList.size() == 0)
        throw new ClassNotFoundException("not find service : " + serviceName);
    int index = requestCount.get() % serviceList.size();
    if (requestCount.get() > 100)
        requestCount.set(0);
    else
        requestCount.getAndIncrement();
    HostPortPair hostPort = serviceList.get(index);

    Socket socket = new Socket(hostPort.host, hostPort.port);
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
    objectOutputStream.writeObject(rpcContext);
    objectOutputStream.flush();

    ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
    Object response = objectInputStream.readObject();

    objectInputStream.close();
    objectOutputStream.close();
    socket.close();

    Class methodReturnType = method.getReturnType();
    return methodReturnType.cast(response);
}

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

/**
 * Execute the JSONRPCFunction./* w w w.j  a  v a 2  s  . c  o m*/
 *
 * @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();

    String ticketId = null;
    String serializedTicket = null;

    Ticket ticket = null;

    logger.debug("Add Ticket");
    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();
    } catch (final Exception e) {
        throw new JSONRPCException(-32501, "Could not decode Ticket");
    }

    if (this.map.containsKey(ticketId.hashCode())) {
        logger.error("Duplicate Key {}", ticketId);
        throw new JSONRPCException(-32502, "Duplicate Ticket");
    } else {
        this.map.put(ticketId.hashCode(), ticket);
    }

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

    return result;
}