Example usage for java.io ObjectInputStream close

List of usage examples for java.io ObjectInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the input stream.

Usage

From source file:com.thoughtworks.acceptance.WriteReplaceTest.java

public void testReplacesAndResolves() throws IOException, ClassNotFoundException {
    Thing thing = new Thing(3, 6);

    // ensure that Java serialization does not cause endless loop for a Thing
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(thing);/*  w ww  .ja  va2s .  com*/
    oos.close();

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream ios = new ObjectInputStream(bais);
    assertEquals(thing, ios.readObject());
    ios.close();

    // ensure that XStream does not cause endless loop for a Thing
    xstream.alias("thing", Thing.class);

    String expectedXml = "" + "<thing>\n" + "  <a>3000</a>\n" + "  <b>6000</b>\n" + "</thing>";

    assertBothWays(thing, expectedXml);
}

From source file:aptgraph.server.JsonRpcServer.java

/**
 * Start the server, blocking. This method will only return if the server
 * crashed.../*from w  ww  . ja  v  a2s .c  o m*/
 * @throws java.io.IOException if the graph file cannot be read
 * @throws java.lang.ClassNotFoundException if the Graph class is not found
 * @throws java.lang.Exception if the server cannot start...
 */
public final void start() throws IOException, ClassNotFoundException, Exception {

    LOGGER.info("Reading graphs from disk...");
    ObjectInputStream input = new ObjectInputStream(new BufferedInputStream(input_file));
    HashMap<String, LinkedList<Graph<Request>>> user_graphs = (HashMap<String, LinkedList<Graph<Request>>>) input
            .readObject();
    input.close();

    Map.Entry<String, LinkedList<Graph<Request>>> entry_set = user_graphs.entrySet().iterator().next();
    String first_key = entry_set.getKey();
    LOGGER.log(Level.INFO, "Graph has {0} features", user_graphs.get(first_key).size());
    LOGGER.log(Level.INFO, "k-NN Graph : k = {0}", user_graphs.get(first_key).getFirst().getK());
    LOGGER.log(Level.INFO, "Starting JSON-RPC server at http://{0}:{1}",
            new Object[] { config.getServerHost(), config.getServerPort() });

    RequestHandler request_handler = new RequestHandler(user_graphs);

    ObjectMapper object_mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Graph.class, new GraphSerializer());
    module.addSerializer(Domain.class, new DomainSerializer());
    module.addSerializer(Neighbor.class, new NeighborSerializer());
    object_mapper.registerModule(module);

    com.googlecode.jsonrpc4j.JsonRpcServer jsonrpc_server = new com.googlecode.jsonrpc4j.JsonRpcServer(
            object_mapper, request_handler);

    QueuedThreadPool thread_pool = new QueuedThreadPool(config.getMaxThreads(), config.getMinThreads(),
            config.getIdleTimeout(), new ArrayBlockingQueue<Runnable>(config.getMaxPendingRequests()));

    http_server = new org.eclipse.jetty.server.Server(thread_pool);
    //http_server = new org.eclipse.jetty.server.Server();

    ServerConnector http_connector = new ServerConnector(http_server);
    http_connector.setHost(config.getServerHost());
    http_connector.setPort(config.getServerPort());

    http_server.setConnectors(new Connector[] { http_connector });
    http_server.setHandler(new JettyHandler(jsonrpc_server));

    http_server.start();
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.si.dictionary.GoogleDictionaryInventory.java

public GoogleDictionaryInventory(String inputPath, String serializiblePath, String neededMentionsPath)
        throws FileNotFoundException, IOException {
    // Open the serialized version or create it from scratch
    try {/*  w  ww .  ja v  a2 s .co  m*/
        logger.debug("Trying to load dictionary " + this.getClass().getSimpleName() + " from serializable.");
        ObjectInputStream dictionaryReader = new ObjectInputStream(
                new BZip2CompressorInputStream(new FileInputStream(serializiblePath)));
        dictionary = (GoogleDictionary) dictionaryReader.readObject();
        dictionaryReader.close();
        logger.debug("Loaded dictionary " + this.getClass().getSimpleName() + " from serializable.");
    } catch (Exception e) {
        logger.debug("Trying to load dictionary " + this.getClass().getSimpleName() + " from input.");
        dictionary = new GoogleDictionary(inputPath, neededMentionsPath);
        System.out.println("Loaded dictionary " + this.getClass().getSimpleName() + " from input.");

        ObjectOutputStream dictionaryWriter = new ObjectOutputStream(
                new BZip2CompressorOutputStream(new FileOutputStream(serializiblePath)));
        dictionaryWriter.writeObject(dictionary);
        dictionaryWriter.close();
        logger.debug("Stored dictionary " + this.getClass().getSimpleName() + " in serializable.");

    }
}

From source file:net.sf.ehcache.StatisticsTest.java

/**
 * We want to be able to use Statistics as a value object.
 * We need to do some magic with the refernence held to Cache
 *///from  w ww  .  j  a  v  a2s . c o m
public void testSerialization() throws IOException, ClassNotFoundException {

    Cache cache = new Cache("test", 1, true, false, 5, 2);
    manager.addCache(cache);

    cache.put(new Element("key1", "value1"));
    cache.put(new Element("key2", "value1"));
    cache.get("key1");
    cache.get("key1");

    Statistics statistics = cache.getStatistics();
    assertEquals(2, statistics.getCacheHits());
    assertEquals(1, statistics.getOnDiskHits());
    assertEquals(1, statistics.getInMemoryHits());
    assertEquals(0, statistics.getCacheMisses());
    assertEquals(Statistics.STATISTICS_ACCURACY_BEST_EFFORT, statistics.getStatisticsAccuracy());
    statistics.clearStatistics();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bout);
    oos.writeObject(statistics);
    byte[] serializedValue = bout.toByteArray();
    oos.close();
    Statistics afterDeserializationStatistics = null;
    ByteArrayInputStream bin = new ByteArrayInputStream(serializedValue);
    ObjectInputStream ois = new ObjectInputStream(bin);
    afterDeserializationStatistics = (Statistics) ois.readObject();
    ois.close();

    //Check after Serialization
    assertEquals(2, afterDeserializationStatistics.getCacheHits());
    assertEquals(1, afterDeserializationStatistics.getOnDiskHits());
    assertEquals(1, afterDeserializationStatistics.getInMemoryHits());
    assertEquals(0, afterDeserializationStatistics.getCacheMisses());
    assertEquals(Statistics.STATISTICS_ACCURACY_BEST_EFFORT, statistics.getStatisticsAccuracy());
    statistics.clearStatistics();

}

From source file:com.twelvemonkeys.util.ObjectAbstractTestCase.java

public void testSerializeDeserializeThenCompare() throws Exception {
    Object obj = makeObject();/*  w  ww  . j  a  v  a 2 s  .c  om*/
    if (obj instanceof Serializable && isTestSerialization()) {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(buffer);
        out.writeObject(obj);
        out.close();

        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
        Object dest = in.readObject();
        in.close();
        if (isEqualsCheckable()) {
            assertEquals("obj != deserialize(serialize(obj))", obj, dest);
        }
    }
}

From source file:com.npower.unicom.sync.AbstractExportDaemonPlugIn.java

/**
 * //from ww  w .ja  v  a2  s  . c o m
 * @param date
 */
private Date loadLastSyncTimeStamp() {
    File requestDir = this.getRequestDir();
    File file = new File(requestDir, AbstractExportDaemonPlugIn.FILENAME_LAST_SYNC_TIME_STAMP);
    try {
        if (file.exists()) {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            Date time = (Date) in.readObject();
            in.close();
            return time;
        }
    } catch (ClassNotFoundException e) {
        log.error("failure to update last sync time stamp: " + e.getMessage(), e);
    } catch (IOException e) {
        log.error("failure to update last sync time stamp: " + e.getMessage(), e);
    }
    return null;
}

From source file:net.sf.jasperreports.engine.util.JRLoader.java

/**
 *
 *///from   w  w  w . j a  v  a2 s .com
public static Object loadObject(JasperReportsContext jasperReportsContext, File file) throws JRException {
    if (!file.exists() || !file.isFile()) {
        throw new JRException(new FileNotFoundException(String.valueOf(file)));
    }

    Object obj = null;

    FileInputStream fis = null;
    ObjectInputStream ois = null;

    try {
        fis = new FileInputStream(file);
        BufferedInputStream bufferedIn = new BufferedInputStream(fis);
        ois = new ContextClassLoaderObjectInputStream(jasperReportsContext, bufferedIn);
        obj = ois.readObject();
    } catch (IOException e) {
        throw new JRException(EXCEPTION_MESSAGE_KEY_OBJECT_FROM_FILE_LOADING_ERROR, new Object[] { file }, e);
    } catch (ClassNotFoundException e) {
        throw new JRException(EXCEPTION_MESSAGE_KEY_CLASS_NOT_FOUND_FROM_FILE, new Object[] { file }, e);
    } finally {
        if (ois != null) {
            try {
                ois.close();
            } catch (IOException e) {
            }
        }

        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
            }
        }
    }

    return obj;
}

From source file:com.servioticy.queueclient.KestrelThriftClient.java

protected Object deserialize(byte[] in) {
    Object rv = null;//w  w w  .  j  a  v  a2 s .c om
    ByteArrayInputStream bis = null;
    ObjectInputStream is = null;
    try {
        if (in != null) {
            bis = new ByteArrayInputStream(in);
            is = new ObjectInputStream(bis);
            rv = is.readObject();
            is.close();
            bis.close();
        }
    } catch (IOException e) {
        logger.warn("Caught IOException decoding %d bytes of data", in == null ? 0 : in.length, e);
    } catch (ClassNotFoundException e) {
        logger.warn("Caught CNFE decoding %d bytes of data", in == null ? 0 : in.length, e);
    }
    return rv;
}

From source file:de.elatePortal.autotool.SubTasklet_AutotoolImpl.java

private Object deserialize(byte[] arr) {
    try {//from w  w w .  j  a  v  a 2  s .  co  m
        ByteArrayInputStream bos = new ByteArrayInputStream(arr);
        ObjectInputStream oos = new ObjectInputStream(bos);
        Object o = oos.readObject();
        oos.close();
        bos.close();
        return o;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.centurylink.mdw.common.translator.impl.JavaObjectTranslator.java

public Object realToObject(String str) throws TranslationException {
    ObjectInputStream ois = null;
    try {//  w  w w. j a  v a2s.  co  m
        byte[] decoded = decodeBase64(str);
        ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
        ois = new ObjectInputStream(bais);
        try {
            return ois.readObject();
        } catch (ClassNotFoundException ex) {
            ois.close();
            bais = new ByteArrayInputStream(decoded);
            ois = new ObjectInputStream(bais) {
                @Override
                protected Class<?> resolveClass(ObjectStreamClass desc)
                        throws IOException, ClassNotFoundException {
                    try {
                        return CompiledJavaCache.getResourceClass(desc.getName(), getClass().getClassLoader(),
                                getPackage());
                    } catch (ClassNotFoundException ex) {
                        if (getPackage() != null && getPackage().getCloudClassLoader() != null)
                            return getPackage().getCloudClassLoader().loadClass(desc.getName());
                        else
                            throw ex;
                    } catch (MdwJavaException ex) {
                        throw new ClassNotFoundException(desc.getName(), ex);
                    }
                }
            };
            return ois.readObject();
        }
    } catch (Throwable t) { // including NoClassDefFoundError
        throw new TranslationException(t.getMessage(), t);
    } finally {
        if (ois != null) {
            try {
                ois.close();
            } catch (IOException ex) {
            }
        }
    }
}