Example usage for java.io ObjectOutputStream flush

List of usage examples for java.io ObjectOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

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

/**
 * //from w  ww.ja va  2 s  . c om
 * 
 * @param originObj
 * @return
 */
public final static Object objectClone(Object originObj) {
    ByteArrayOutputStream bao = null;
    ByteArrayInputStream bai = null;
    ObjectOutputStream oos;
    ObjectInputStream ois;
    try {
        bao = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(bao);
        oos.writeObject(originObj);
        oos.flush();
        oos.close();
        bai = new ByteArrayInputStream(bao.toByteArray());
        ois = new ObjectInputStream(bai);
        Object obj = ois.readObject();
        ois.close();
        oos = null;
        ois = null;
        return obj;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (bao != null) {
                bao.close();
                bao = null;
            }
            if (bai != null) {
                bai.close();
                bai = null;
            }
        } catch (IOException e) {
        }
    }
}

From source file:com.gamesalutes.utils.ByteUtils.java

/**
 * Returns a <code>byte[]</code> containing the byte representation
 * of the serializable object <code>obj</code>.
 * //w w  w  .j a va2s . c o  m
 * @param obj the <code>Object</code> to convert to a byte array
 * @return <code>byte[]</code> containing the byte representation
 * of <code>obj</code>.
 * 
 * @throws IOException if <code>obj</code> is not serializable or error occurs while writing the bytes
 */
public static byte[] getObjectBytes(Object obj) throws IOException {
    ByteArrayOutputStream bout = null;
    ObjectOutputStream out = null;
    byte[] data = null;
    try {
        bout = new ByteArrayOutputStream(READ_BUFFER_SIZE);
        out = new ObjectOutputStream(bout);
        out.writeObject(obj);
        out.flush();

        data = bout.toByteArray();
    } finally {
        MiscUtils.closeStream(out);
    } //end finally

    return data;
}

From source file:org.ajax4jsf.application.AjaxStateManager.java

private static final Object handleSaveState(FacesContext context, Object state) {
    if (ContextInitParameters.isSerializeServerState(context)) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        ObjectOutputStream oas = null;
        try {/*from www .j a v a2 s . c  o  m*/
            oas = new ObjectOutputStream(baos);
            oas.writeObject(state);
            oas.flush();
        } catch (Exception e) {
            throw new FacesException(e);
        } finally {
            if (oas != null) {
                try {
                    oas.close();
                } catch (IOException ignored) {
                }
            }
        }
        return baos.toByteArray();
    } else {
        return state;
    }
}

From source file:oscar.util.SqlUtils.java

/**
 * this utility-method assigns a particular value to a place holder of a PreparedStatement. it tries to find the correct setXxx() value, accoring to the field-type information
 * represented by "fieldType". quality: this method is bloody alpha (as you migth see :=)
 *//*  w w  w .jav a 2s.co m*/
public static void fillPreparedStatement(PreparedStatement ps, int col, Object val, int fieldType)
        throws SQLException {
    try {
        logger.info("fillPreparedStatement( ps, " + col + ", " + val + ", " + fieldType + ")...");
        Object value = null;
        // Check for hard-coded NULL
        if (!("$null$".equals(val))) {
            value = val;
        }
        if (value != null) {
            switch (fieldType) {
            case FieldTypes.INTEGER:
                ps.setInt(col, Integer.parseInt((String) value));
                break;
            case FieldTypes.NUMERIC:
                ps.setBigDecimal(col, createAppropriateNumeric(value));
                break;
            case FieldTypes.CHAR:
                ps.setString(col, (String) value);
                break;
            case FieldTypes.DATE:
                ps.setDate(col, createAppropriateDate(value));
                break; // #checkme
            case FieldTypes.TIMESTAMP:
                ps.setTimestamp(col, java.sql.Timestamp.valueOf((String) value));
                break;
            case FieldTypes.DOUBLE:
                ps.setDouble(col, Double.valueOf((String) value).doubleValue());
                break;
            case FieldTypes.FLOAT:
                ps.setFloat(col, Float.valueOf((String) value).floatValue());
                break;
            case FieldTypes.LONG:
                ps.setLong(col, Long.parseLong(String.valueOf(value)));
                break;
            case FieldTypes.BLOB:
                FileHolder fileHolder = (FileHolder) value;
                try {
                    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
                    ObjectOutputStream out = new ObjectOutputStream(byteOut);
                    out.writeObject(fileHolder);
                    out.flush();
                    byte[] buf = byteOut.toByteArray();
                    byteOut.close();
                    out.close();
                    ByteArrayInputStream bytein = new ByteArrayInputStream(buf);
                    int byteLength = buf.length;
                    ps.setBinaryStream(col, bytein, byteLength);
                    // store fileHolder as a whole (this way we don't lose file meta-info!)
                } catch (IOException ioe) {
                    MiscUtils.getLogger().error("Error", ioe);
                    logger.info(ioe.toString());
                    throw new SQLException("error storing BLOB in database - " + ioe.toString(), null, 2);
                }
                break;
            case FieldTypes.DISKBLOB:
                ps.setString(col, (String) value);
                break;
            default:
                ps.setObject(col, value); // #checkme
            }
        } else {
            switch (fieldType) {
            case FieldTypes.INTEGER:
                ps.setNull(col, java.sql.Types.INTEGER);
                break;
            case FieldTypes.NUMERIC:
                ps.setNull(col, java.sql.Types.NUMERIC);
                break;
            case FieldTypes.CHAR:
                ps.setNull(col, java.sql.Types.CHAR);
                break;
            case FieldTypes.DATE:
                ps.setNull(col, java.sql.Types.DATE);
                break;
            case FieldTypes.TIMESTAMP:
                ps.setNull(col, java.sql.Types.TIMESTAMP);
                break;
            case FieldTypes.DOUBLE:
                ps.setNull(col, java.sql.Types.DOUBLE);
                break;
            case FieldTypes.FLOAT:
                ps.setNull(col, java.sql.Types.FLOAT);
                break;
            case FieldTypes.BLOB:
                ps.setNull(col, java.sql.Types.BLOB);
            case FieldTypes.DISKBLOB:
                ps.setNull(col, java.sql.Types.CHAR);
            default:
                ps.setNull(col, java.sql.Types.OTHER);
            }
        }
    } catch (Exception e) {
        throw new SQLException("Field type seems to be incorrect - " + e.toString(), null, 1);
    }
}

From source file:net.librec.util.FileUtil.java

public static void serialize(Object obj, String filePath) throws Exception {
    FileOutputStream fos = new FileOutputStream(filePath);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(obj);/*from   w w w .j a  va 2  s .  c  om*/
    oos.flush();
    oos.close();
    fos.close();
}

From source file:org.limewire.util.FileUtils.java

/**
 * Writes the passed Object to corresponding file
 * @param file The file to which to write 
 * @param map The Object to be stored/*w  w w  . j a  v  a2 s .c om*/
 */
public static void writeObject(File f, Object obj) throws IOException {

    try {
        f = getCanonicalFile(f);
    } catch (IOException tryAnyway) {
    }

    ObjectOutputStream out = null;
    try {
        //open the file
        out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
        //write to the file
        out.writeObject(obj);
        out.flush();
    } finally {
        close(out);
    }
}

From source file:gov.nih.nci.caarray.util.CaArrayUtils.java

/**
 * Serializes the given object (zipped) to a byte array.
 * //  ww w.  j a v  a2s  . c  o m
 * @param serializable object to serialize
 * @return the serialized object as a byte array.
 */
public static byte[] serialize(Serializable serializable) {
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    GZIPOutputStream gZipOutputStream = null;
    ObjectOutputStream objectOutputStream = null;
    try {
        gZipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
        objectOutputStream = new ObjectOutputStream(gZipOutputStream);
        objectOutputStream.writeObject(serializable);
        objectOutputStream.flush();
        gZipOutputStream.finish();
        gZipOutputStream.flush();
        byteArrayOutputStream.flush();
    } catch (final IOException e) {
        throw new IllegalStateException("Couldn't serialize object", e);
    } finally {
        IOUtils.closeQuietly(objectOutputStream);
        IOUtils.closeQuietly(gZipOutputStream);
        IOUtils.closeQuietly(byteArrayOutputStream);
    }
    return byteArrayOutputStream.toByteArray();
}

From source file:org.opennms.netmgt.config.EventTranslatorConfigFactory.java

/**
 * <p>cloneEvent</p>/*from  ww  w  .  j  a  v a2s.  c  o m*/
 *
 * @param orig a {@link org.opennms.netmgt.xml.event.Event} object.
 * @return a {@link org.opennms.netmgt.xml.event.Event} object.
 */
public static Event cloneEvent(Event orig) {
    Event copy = null;
    try {
        // Write the object out to a byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(orig);
        out.flush();
        out.close();

        // Make an input stream from the byte array and read
        // a copy of the object back in.
        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
        copy = (Event) in.readObject();
    } catch (IOException e) {
        LOG.error("Exception cloning event", e);
    } catch (ClassNotFoundException cnfe) {
        LOG.error("Exception cloning event", cnfe);
    }
    return copy;
}

From source file:com.heliosapm.tsdblite.json.JSON.java

private static byte[] jserialize(final Serializable ser) {
    if (ser == null)
        return new byte[0];
    ByteArrayOutputStream baos = null;
    ObjectOutputStream oos = null;
    try {//from   w  w  w  . ja v  a2s.  c  o  m
        baos = new ByteArrayOutputStream(1024);
        oos = new ObjectOutputStream(baos);
        oos.writeObject(ser);
        oos.flush();
        baos.flush();
        return baos.toByteArray();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        if (oos != null)
            try {
                oos.close();
            } catch (Exception x) {
                /* No Op */}
        if (baos != null)
            try {
                baos.close();
            } catch (Exception x) {
                /* No Op */}
    }
}

From source file:io.github.tavernaextras.biocatalogue.model.Util.java

/**
 * This method is "clones" an object supplied as an argument. It uses
 * serialisation to achieve this (as opposed to manually implementing deep
 * copying of all referenced objects in the graph of the provided object).
 * This technique is used to make sure that the new object will be exact
 * replica, but totally independent of the original one.
 * /* ww  w  .  j a  v  a2  s .  c  om*/
 * Note that this code works ~100 times slower than it would do if deep copying
 * was implemented. However, this will not be used in tight loops (and in loops
 * at all), so for one-off tasks it is fine.
 * 
 * @author Dave Miller<br/>
 * Original version of the code in this method is taken from
 * <a href="http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=2">
 *    http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=2
 * </a> [accessed on 25/Feb/2010].
 * <br/><br/>
 * 
 * @author Subhajit Dasgupta<br/>
 * Example of using an alternative class loader during object de-serialisation
 * was taken from
 * <a href="http://blogs.sun.com/adventures/entry/desrializing_objects_custom_class_loaders">
 *    http://blogs.sun.com/adventures/entry/desrializing_objects_custom_class_loaders
 * </a> [accessed on 29/Mar/2010].
 * 
 * @return Deep copy of the provided object. If deep copying doesn't succeed,
 *         <code>null</code> is returned.
 */
public static Object deepCopy(Object objectToCopy) {
    // a "safety net" - a class loader of BioCatalogue perspective may be used in
    // de-serialisation process to make sure that all classes are recognised
    // (system class loader may not be able to "see" all BioCatalogue plugin's files,
    //  but just those in Taverna's /lib folder)
    final ClassLoader[] customClassLoaders = new ClassLoader[] {
            BioCataloguePerspective.class.getClassLoader() };

    try {
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);

            // serialise and pass the object
            oos.writeObject(objectToCopy);
            oos.flush();

            // read and return the new object
            ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bin) {
                /**
                 * <code>resolveClass()</code> method is overridden to make use of
                 * custom ClassLoader in the de-serialisation process.
                 * <br/>
                 * This is needed to make sure that the ClassLoader of the BioCatalogue
                 * perspective is used as opposed to the system ClassLoader which will
                 * only be able to see classes from Taverna's /lib folder.
                 */
                protected Class<?> resolveClass(ObjectStreamClass desc)
                        throws IOException, ClassNotFoundException {
                    String className = desc.getName();
                    try {
                        // attempt to use default class loader
                        return Class.forName(className);
                    } catch (ClassNotFoundException exc) {
                        // default class loader was unable to locate a required class -
                        // attempt to use one of the provided class loaders
                        for (ClassLoader cl : customClassLoaders) {
                            try {
                                return cl.loadClass(className);
                            } catch (ClassNotFoundException e) {
                                /* do nothing here - there may be other class loaders to try */
                            }
                        }
                        // none of the class loaders was able to recognise the currently
                        // de-serialised class, so it's indeed an exception
                        throw new ClassNotFoundException(className
                                + " -- neither system, nor alternative class loaders were able to load this class");
                    }
                }
            };
            return ois.readObject();
        } catch (Exception e) {
            logger.error("Could not perform deep copy of " + objectToCopy.getClass() + " instance", e);
        } finally {
            oos.close();
            ois.close();
        }
    } catch (Exception e) {
        logger.error(
                "Could not close object streams during deep copy of " + objectToCopy.getClass() + " instance");
    }

    // Error occurred - couldn't produce the deep copy...
    return null;
}