Example usage for java.io ObjectOutputStream close

List of usage examples for java.io ObjectOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the stream.

Usage

From source file:com.nebhale.jsonpath.JsonPathTest.java

@Test
public void serializable() throws IOException, ClassNotFoundException {
    assertTrue(Serializable.class.isAssignableFrom(JsonPath.class));

    JsonPath jsonPath = JsonPath.compile("$.store.book[0].title");
    assertEquals("Sayings of the Century", jsonPath.read(STRING_VALID, String.class));

    byte[] serialized;
    ObjectOutputStream out = null;
    try {/*from ww w  . j  a  v a  2 s  . c om*/
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        out = new ObjectOutputStream(bytes);

        out.writeObject(jsonPath);
        out.flush();

        serialized = bytes.toByteArray();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }

    JsonPath newJsonPath;
    ObjectInputStream in = null;
    try {
        in = new ObjectInputStream(new ByteArrayInputStream(serialized));

        newJsonPath = (JsonPath) in.readObject();
    } finally {
        if (in != null) {
            in.close();
        }
    }

    assertEquals("Sayings of the Century", newJsonPath.read(STRING_VALID, String.class));
}

From source file:cai.flow.packets.V5_Packet.java

/**
 * UDPflowsVector/*from w  w  w. j av  a  2  s  .  c  om*/
 *
 * @param RouterIP
 * @param buf
 * @param len
 * @throws DoneException
 */
@SuppressWarnings("unchecked")
public V5_Packet(String RouterIP, byte[] buf, int len) throws DoneException {
    if (false) {//(Params.DEBUG) {
        // 
        File tmpFile = new File(Params.path + File.separator + "cache.tmp");
        if (tmpFile.exists()) {
            try {
                ObjectInputStream fIn = new ObjectInputStream(new FileInputStream(tmpFile));
                try {
                    buf = (byte[]) fIn.readObject();
                    len = ((Integer) fIn.readObject()).intValue();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                fIn.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                ObjectOutputStream fOut;
                fOut = new ObjectOutputStream(new FileOutputStream(tmpFile));
                fOut.writeObject(buf);
                fOut.writeObject(new Integer(len));
                fOut.flush();
                fOut.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        // 
    }
    if (len < V5_Header_Size)
        throw new DoneException("    * incomplete header *");

    this.RouterIP = RouterIP;
    count = Util.to_number(buf, 2, 2);

    if (count <= 0 || len != V5_Header_Size + count * V5_Flow_Size)
        throw new DoneException("    * corrupted packet " + len + "/" + count + "/"
                + (V5_Header_Size + count * V5_Flow_Size) + " *");

    SysUptime = Util.to_number(buf, 4, 4);
    unix_secs = Util.to_number(buf, 8, 4);
    unix_nsecs = Util.to_number(buf, 12, 4);
    flow_sequence = Util.to_number(buf, 16, 4);
    engine_type = buf[20];
    engine_id = buf[21];

    logger.debug("    uptime: " + Util.uptime(SysUptime / 1000) + ", date: " + unix_secs + "." + unix_nsecs);
    logger.debug("    sequence: " + flow_sequence + ", count: " + count + ", engine: " + engine_type + "/"
            + engine_id);

    flows = new Vector((int) count);

    for (int i = 0, p = V5_Header_Size; i < count; i++, p += V5_Flow_Size) {
        V5_Flow f;
        try {
            f = new V5_Flow(RouterIP, buf, p);
            if (Params.DEBUG) {
                if (!f.equals(
                        new V5_Flow(RouterIP, buf, p, TemplateManager.getTemplateManager().getV5Template()))) {
                    logger.error("ERROR: Data inconsistency with different algorithm");
                }
            }
            if (f.srcaddr != null && f.dstaddr != null) {
                flows.add(f);
            } else {
                if (Params.DEBUG) {
                    logger.error(f.srcaddr + "  " + f.dstaddr + "    ");
                }
            }
        } catch (DoneException e) {
            if (Params.DEBUG) {
                logger.debug("", e);
            }
            if (e.getMessage() != null && (!e.getMessage().equals(""))) {
                logger.debug("", e);
            }
        }
    }
}

From source file:com.bt.aloha.dao.StateInfoDaoTest.java

private SimpleTestInfo insertSimpleTestInfo(String id, String f1, String f2) {
    SimpleTestInfo sti = new SimpleTestInfo(id, f1, f2);
    byte[] stiBytes = null;
    try {/*from ww  w .  jav  a2  s. com*/
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(sti);
        oos.flush();
        oos.close();
        stiBytes = bos.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException("Unable to serialize SimpleTestInfo", e);
    }
    PreparedStatement s = null;
    try {
        s = connection.prepareStatement("insert into StateInfo"
                + "(object_id, object_type, object_version, last_use_time, is_dead, force_housekeep, object_value) values(?, 'Collection', ?, ?, ?, 0, ?)");
        s.setString(1, id);
        s.setString(2, "1");
        s.setLong(3, new java.util.Date().getTime());
        s.setInt(4, 0);
        s.setBytes(5, stiBytes);
        log.debug("Inserted row in Collection " + "for current SimpleTestInfo");
        s.execute();
        connection.commit();
    } catch (SQLException e) {
        try {
            if (connection != null)
                connection.rollback();
        } catch (SQLException e1) {
            throw new RuntimeException("Unable to rollback operation on SimpleTestInfo", e);
        }
        throw new RuntimeException("Unable to execute db operation on SimpleTestInfo. op rolledback", e);
    } finally {
        if (s != null)
            try {
                s.close();
            } catch (SQLException e) {
                log.warn("Unable to close prepared statement", e);
            }
    }
    return sti;
}

From source file:com.ibm.jaggr.core.impl.cache.CacheManagerImpl.java

/**
 * Serializes the specified cache object to the sepecified directory.  Note that we
 * actually serialize a clone of the specified cache because some of the objects
 * that are serialized require synchronization and we don't want to cause service
 * threads to block while we are doing file I/O.
 *//*from  w  w  w  .j  av a 2s .  co m*/
protected void serializeCache() {
    try {
        File file = new File(_directory, CACHE_META_FILENAME);
        // Synchronize on the cache object to keep the scheduled cache sync thread and
        // the thread processing servlet destroy from colliding.
        synchronized (cacheSerializerSyncObj) {
            ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(file));
            os.writeObject(_cache.get());
            os.close();
        }
    } catch (Exception e) {
        if (log.isLoggable(Level.SEVERE))
            log.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:com.adjust.sdk.PackageHandler.java

private void writePackageQueue() {
    if (dropOfflineActivities) {
        return; // don't write packages when offline tracking is disabled
    }/*from  w  w  w  . ja v  a2  s. c  o  m*/

    try {
        FileOutputStream outputStream = context.openFileOutput(PACKAGE_QUEUE_FILENAME, Context.MODE_PRIVATE);
        BufferedOutputStream bufferedStream = new BufferedOutputStream(outputStream);
        ObjectOutputStream objectStream = new ObjectOutputStream(bufferedStream);

        try {
            objectStream.writeObject(packageQueue);
            logger.debug("Package handler wrote %d packages", packageQueue.size());
        } catch (NotSerializableException e) {
            logger.error("Failed to serialize packages");
        } finally {
            objectStream.close();
        }
    } catch (Exception e) {
        logger.error("Failed to write packages (%s)", e.getLocalizedMessage());
        e.printStackTrace();
    }
}

From source file:de.tudarmstadt.ukp.dkpro.lexsemresource.graph.PersistentAdjacencyMatrix.java

private void indexEntities() throws LexicalSemanticResourceException {

    entityIndex = new HashMap<Entity, Integer>();
    indexToEntity = new HashMap<Integer, Entity>();

    logger.info("Indexing entities.");
    Iterator<Entity> entityIter = lexSemResource.getEntities().iterator();
    int index = -1;
    while (entityIter.hasNext()) {
        Entity entity = entityIter.next();

        // check whether the entity has already been indexed. if not, index it now.
        if (!entityIndex.keySet().contains(entity)) {
            index++;/*from ww w .  ja  v  a  2s .co  m*/
            entityIndex.put(entity, index);
            indexToEntity.put(index, entity);
        }

        // print progress:
        if (index % 10000 == 0) {
            logger.info("Index at " + index);
        }
    }
    logger.info("Indexing complete. Index runs from 0 to " + index);

    // now save the index maps:

    logger.info("Serializing the indices...");

    FileOutputStream fosEntIndex = null;
    ObjectOutputStream outEntIndex = null;

    FileOutputStream fosIndexEnt = null;
    ObjectOutputStream outIndexEnt = null;

    try {
        fosEntIndex = new FileOutputStream("EntityIndexSer" + "_" + resourceName);
        outEntIndex = new ObjectOutputStream(fosEntIndex);
        outEntIndex.writeObject(entityIndex);
        outEntIndex.close();

        fosIndexEnt = new FileOutputStream("IndexToEntitySer" + "_" + resourceName);
        outIndexEnt = new ObjectOutputStream(fosIndexEnt);
        outIndexEnt.writeObject(indexToEntity);
        outIndexEnt.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    logger.info("Indices serialized.");
}

From source file:com.joliciel.lefff.LefffMemoryLoader.java

public void serializeMemoryBase(LefffMemoryBase memoryBase, File memoryBaseFile) {
    LOG.debug("serializeMemoryBase");
    boolean isZip = false;
    if (memoryBaseFile.getName().endsWith(".zip"))
        isZip = true;/*from  ww  w.j ava 2 s.  c  o m*/

    FileOutputStream fos = null;
    ObjectOutputStream out = null;
    ZipOutputStream zos = null;
    try {
        fos = new FileOutputStream(memoryBaseFile);
        if (isZip) {
            zos = new ZipOutputStream(fos);
            zos.putNextEntry(new ZipEntry("lefff.obj"));
            out = new ObjectOutputStream(zos);
        } else {
            out = new ObjectOutputStream(fos);
        }

        try {
            out.writeObject(memoryBase);
        } finally {
            out.flush();
            out.close();
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

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 w w.j a va 2  s.  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.tecapro.inventory.common.util.CommonUtil.java

/**
 * encodeBase64 object/*from  w  w w .  j  a v a2  s.  co  m*/
 *
 * @param obj
 * @return
 * @throws Exception
 */
public byte[] serialize(Object obj) throws Exception {
    ByteArrayOutputStream byteStream = null;
    ObjectOutputStream ostream = null;
    byte[] result = null;

    try {
        byteStream = new ByteArrayOutputStream();
        ostream = new ObjectOutputStream(new BufferedOutputStream(byteStream));
        ostream.writeObject(obj);
        ostream.flush();
        result = Base64.encodeBase64(byteStream.toByteArray());
    } finally {
        if (byteStream != null) {
            byteStream.close();
        }
        if (ostream != null) {
            ostream.close();
        }
    }
    return result;
}

From source file:androidGLUESigner.pdf.PDFSignerEngine.java

/**
 * obtain the state of the SignerEngine (hash, ocsp, calendar from first run)
 * @return the obtained state as a byte[]
 *//*from   ww  w. j a  v a2s. c  o  m*/
public byte[] getState() {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos;
    try {
        oos = new ObjectOutputStream(bos);
        oos.writeObject(this.hash);
        oos.writeObject(this.ocsp);
        oos.writeObject(this.calendar);
        oos.writeObject(getCertificateChain());
        oos.close();
    } catch (Exception e) {
        Logger.toConsole(e);
    }
    return bos.toByteArray();
}