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:org.apache.torque.util.VillageUtils.java

/**
 * Converts a hashtable to a byte array for storage/serialization.
 *
 * @param  hash  The Hashtable to convert.
 *
 * @return  A byte[] with the converted Hashtable.
 *
 * @throws  Exception  If an error occurs.
 *///from ww w.  ja v a2 s  .c  o m
public static byte[] hashtableToByteArray(final Hashtable hash) throws Exception {
    Hashtable saveData = new Hashtable(hash.size());
    byte[] byteArray = null;

    Iterator keys = hash.entrySet().iterator();
    while (keys.hasNext()) {
        Map.Entry entry = (Map.Entry) keys.next();
        if (entry.getValue() instanceof Serializable) {
            saveData.put(entry.getKey(), entry.getValue());
        }
    }

    ByteArrayOutputStream baos = null;
    BufferedOutputStream bos = null;
    ObjectOutputStream out = null;
    try {
        // These objects are closed in the finally.
        baos = new ByteArrayOutputStream();
        bos = new BufferedOutputStream(baos);
        out = new ObjectOutputStream(bos);

        out.writeObject(saveData);

        out.flush();
        bos.flush();
        baos.flush();
        byteArray = baos.toByteArray();
    } finally {
        close(out);
        close(bos);
        close(baos);
    }
    return byteArray;
}

From source file:org.apache.geode.internal.util.IOUtils.java

/**
 * Convenience method to serialize a Serializable Object into a byte array.
 * <p/>/*from   w w  w .  j a v a2  s .c  o m*/
 * 
 * @param obj the Serializable Object to serialize into an array of bytes.
 * @return a byte array of the serialized Object.
 * @throws IOException if an I/O error occurs during the serialization process.
 * @see #deserializeObject(byte[])
 * @see java.io.ByteArrayOutputStream
 * @see java.io.ObjectOutputStream
 * @see java.io.Serializable
 */
public static byte[] serializeObject(final Object obj) throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    ObjectOutputStream objOut = null;

    try {
        objOut = new ObjectOutputStream(out);
        objOut.writeObject(obj);
        objOut.flush();

        return out.toByteArray();
    } finally {
        close(objOut);
    }
}

From source file:org.apache.axis2.jaxws.message.util.MessageUtils.java

/**
 * This is for debug purposes only//from  w  w w . j a  va  2  s .c o m
 * @param mc
 */
private static void persistMessageContext(MessageContext mc) {
    try {
        ConfigurationContext cc = mc.getConfigurationContext();
        OperationContext op = mc.getOperationContext();
        if (cc == null && op != null) {
            cc = op.getConfigurationContext();
        }

        File theFile = null;
        theFile = File.createTempFile("DebugPersist", null);

        // Setup an output stream to a physical file
        FileOutputStream outStream = new FileOutputStream(theFile);

        // Attach a stream capable of writing objects to the 
        // stream connected to the file
        ObjectOutputStream outObjStream = new ObjectOutputStream(outStream);

        // Try to save the message context
        outObjStream.writeObject(mc);
        outObjStream.flush();
        outObjStream.close();
        outStream.flush();
        outStream.close();

        // Now read in the persisted message
        // Setup an input stream to the file
        FileInputStream inStream = new FileInputStream(theFile);

        // attach a stream capable of reading objects from the 
        // stream connected to the file
        ObjectInputStream inObjStream = new ObjectInputStream(inStream);

        org.apache.axis2.context.MessageContext restoredMC = (org.apache.axis2.context.MessageContext) inObjStream
                .readObject();
        inObjStream.close();
        inStream.close();
        if (cc == null && op == null) {
            return;
        }

        if (cc != null) {
            restoredMC.activate(cc);
        } else {
            restoredMC.activateWithOperationContext(op);
        }
        if (restoredMC.getServiceContext() == null) {
            throw ExceptionFactory.makeWebServiceException("No Service Group!");
        }
        if (cc != null) {
            mc.activate(cc);
        } else {
            mc.activateWithOperationContext(op);
        }
        if (mc.getOperationContext() == null) {
            throw new RuntimeException("No Operation Context");
        }
        if (mc.getOperationContext().getServiceContext() == null) {
            throw new RuntimeException("No Service Context");
        }
        return;
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    } catch (ClassNotFoundException e) {
    }
    return;
}

From source file:org.ow2.proactive.utils.ObjectByteConverter.java

/**
 * Convert the given Serializable Object into a byte array.
 * <p>/* w  ww.  jav a  2  s .  c o  m*/
 * The returned byteArray can be compressed by setting compress boolean argument value to <code>true</code>.
 * 
 * @param obj the Serializable object to be compressed
 * @param compress true if the returned byteArray must be also compressed, false if no compression is required.
 * @return a compressed (or not) byteArray representing the Serialization of the given object.
 * @throws IOException if an I/O exception occurs when writing the output byte array
 */
public static final byte[] objectToByteArray(Object obj, boolean compress) throws IOException {
    ByteArrayOutputStream baos = null;
    ObjectOutputStream oos = null;
    if (obj == null) {
        return null;
    }
    try {
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(obj);
        oos.flush();
        if (!compress) {
            // Return the UNCOMPRESSED data
            return baos.toByteArray();
        } else {
            // Compressor with highest level of compression
            Deflater compressor = new Deflater();
            compressor.setLevel(Deflater.BEST_COMPRESSION);
            // Give the compressor the data to compress
            compressor.setInput(baos.toByteArray());
            compressor.finish();

            ByteArrayOutputStream bos = null;
            try {
                // Create an expandable byte array to hold the compressed data.
                bos = new ByteArrayOutputStream();
                // Compress the data
                byte[] buf = new byte[512];
                while (!compressor.finished()) {
                    int count = compressor.deflate(buf);
                    bos.write(buf, 0, count);
                }
                // Return the COMPRESSED data
                return bos.toByteArray();
            } finally {
                if (bos != null) {
                    bos.close();
                }
            }
        }
    } finally {
        if (oos != null) {
            oos.close();
        }
        if (baos != null) {
            baos.close();
        }
    }
}

From source file:oscar.util.Doc2PDF.java

public static void SavePDF2File(String fileName, String docBin) {

    try {/*from   w ww.  j  a v a 2s.  co m*/

        FileOutputStream ostream = new FileOutputStream(fileName);

        ObjectOutputStream p = new ObjectOutputStream(ostream);

        p.writeBytes(docBin);

        p.flush();
        ostream.close();

    } catch (IOException ioe) {
        MiscUtils.getLogger().debug("IO error: " + ioe);
    }
}

From source file:org.mule.providers.jcr.JcrUtils.java

public static Value newPropertyValue(Session session, Object value) throws RepositoryException, IOException {

    if (value == null) {
        throw new IllegalArgumentException("Impossible to store a null value in JCR!");

    } else if (value instanceof Boolean) {
        return session.getValueFactory().createValue(((Boolean) value).booleanValue());

    } else if (value instanceof Calendar) {
        return session.getValueFactory().createValue((Calendar) value);

    } else if (value instanceof Double) {
        return session.getValueFactory().createValue(((Double) value).doubleValue());

    } else if (value instanceof InputStream) {
        return session.getValueFactory().createValue((InputStream) value);

    } else if (value instanceof byte[]) {
        return session.getValueFactory().createValue(new ByteArrayInputStream((byte[]) value));

    } else if (value instanceof Long) {
        return session.getValueFactory().createValue(((Long) value).longValue());

    } else if (value instanceof Node) {
        return session.getValueFactory().createValue((Node) value);

    } else if (value instanceof String) {
        return session.getValueFactory().createValue((String) value);

    } else if (value instanceof Serializable) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(value);// w  ww.  ja  v  a 2 s .c  om
        oos.flush();
        oos.close();

        return session.getValueFactory().createValue(new ByteArrayInputStream(baos.toByteArray()));
    } else {
        throw new IllegalArgumentException("Impossible to store object of type: " + value.getClass());
    }

}

From source file:org.openhie.openempi.util.ConvertUtil.java

public static void serializeObject(String configDirectory, String fileName, Object o) {
    String fullFilename = configDirectory + "/" + fileName;
    log.debug("Attempting to serialize object into file: " + fullFilename);
    try {// w w w . jav a 2  s. c  o  m
        ObjectOutputStream ois = new ObjectOutputStream(
                new BufferedOutputStream(new FileOutputStream(fullFilename)));
        ois.writeObject(o);
        ois.flush();
        ois.close();
    } catch (Exception e) {
        log.error("Failed while serializing object (into the file" + fullFilename + " ): " + e.getMessage(), e);
        throw new RuntimeException(
                "Failed while serializing object (into the file" + fullFilename + " ): " + e.getMessage());
    }
}

From source file:io.bitsquare.common.util.Utilities.java

public static Object copy(Serializable orig) throws IOException, ClassNotFoundException {
    try {//w w w .j  a va 2s  .  c  om
        // Write the object out to a byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        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 LookAheadObjectInputStream(new ByteArrayInputStream(bos.toByteArray()),
                true);
        Object obj = in.readObject();
        return obj;
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:de.alpharogroup.io.SerializedObjectExtensions.java

/**
 * Copys the given Object and returns the copy from the object or null if the object can't be
 * serialized./*from w w  w . j  a va 2  s  . co m*/
 *
 * @param <T>
 *            the generic type of the given object
 * @param orig
 *            The object to copy.
 * @return Returns a copy from the original object.
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ClassNotFoundException
 *             is thrown when a class is not found in the classloader or no definition for the
 *             class with the specified name could be found.
 */
@SuppressWarnings("unchecked")
public static <T extends Serializable> T copySerializedObject(final T orig)
        throws IOException, ClassNotFoundException {
    T object = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    ObjectOutputStream objectOutputStream = null;
    try {
        byteArrayOutputStream = new ByteArrayOutputStream();
        objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(orig);
        objectOutputStream.flush();
        objectOutputStream.close();
        final ByteArrayInputStream bis = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        final ObjectInputStream ois = new ObjectInputStream(bis);
        object = (T) ois.readObject();
    } finally {
        StreamExtensions.closeOutputStream(byteArrayOutputStream);
        StreamExtensions.closeOutputStream(objectOutputStream);
    }
    return object;
}

From source file:de.alpharogroup.io.SerializedObjectUtils.java

/**
 * Copys the given Object and returns the copy from the object or null if the object can't be
 * serialized.//w  w w.j  av a  2 s .c om
 *
 * @param <T>
 *            the generic type of the given object
 * @param orig
 *            The object to copy.
 * @return Returns a copy from the original object.
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ClassNotFoundException
 *             is thrown when a class is not found in the classloader or no definition for the
 *             class with the specified name could be found.
 */
@SuppressWarnings("unchecked")
public static <T extends Serializable> T copySerializedObject(final T orig)
        throws IOException, ClassNotFoundException {
    T object = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    ObjectOutputStream objectOutputStream = null;
    try {
        byteArrayOutputStream = new ByteArrayOutputStream();
        objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(orig);
        objectOutputStream.flush();
        objectOutputStream.close();
        final ByteArrayInputStream bis = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        final ObjectInputStream ois = new ObjectInputStream(bis);
        object = (T) ois.readObject();
    } finally {
        StreamUtils.closeOutputStream(byteArrayOutputStream);
        StreamUtils.closeOutputStream(objectOutputStream);
    }
    return object;
}