Example usage for java.io ObjectOutputStream writeObject

List of usage examples for java.io ObjectOutputStream writeObject

Introduction

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

Prototype

public final void writeObject(Object obj) throws IOException 

Source Link

Document

Write the specified object to the ObjectOutputStream.

Usage

From source file:com.stgmastek.core.logic.ExecutionOrder.java

/**
 * Saves the state of the batch for revision runs usage 
 * If the current batch is 1000 and revision is 1 then the file would 
 * be saved as '1000_1.savepoint' /* w w w  . j av a 2s.  c  o  m*/
 * 
 * @param batchContext
 *         The job batchContext of the batch 
 * @throws BatchException
 *          Any exception occurred during the serialization process 
 */
public static synchronized void saveBatchState(BatchContext batchContext) throws BatchException {
    BatchInfo toSaveBatchInfo = batchContext.getBatchInfo();
    toSaveBatchInfo.setProgressLevelAtLastSavePoint(
            (ProgressLevel) ProgressLevel.getProgressLevel(toSaveBatchInfo.getBatchNo()).clone()); //clone is necessary as ProgresLevel is static
    if (logger.isDebugEnabled()) {
        logger.debug("Saving Current Batch progress level as ==>"
                + ProgressLevel.getProgressLevel(toSaveBatchInfo.getBatchNo()).toString());
    }
    String savepointFilePath = Configurations.getConfigurations().getConfigurations("CORE", "SAVEPOINT",
            "DIRECTORY");
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(new FileOutputStream(FilenameUtils.concat(savepointFilePath,
                toSaveBatchInfo.getBatchNo() + "_" + toSaveBatchInfo.getBatchRevNo() + ".savepoint")));
        oos.writeObject(toSaveBatchInfo);
        oos.flush();
        batchContext.setBatchStateSaved(true);
    } catch (FileNotFoundException e) {
        batchContext.setBatchStateSaved(false);
        logger.error(e);
        throw new BatchException(e.getMessage(), e);
    } catch (IOException e) {
        batchContext.setBatchStateSaved(false);
        logger.error(e);
        throw new BatchException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(oos);
    }
}

From source file:com.newatlanta.appengine.datastore.CachingDatastoreService.java

private static byte[] serialize(Object object) throws IOException {
    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
    ObjectOutputStream objectOut = new ObjectOutputStream(new BufferedOutputStream(bytesOut));
    objectOut.writeObject(object);
    objectOut.close();//from  w w w .  j a v a  2s.  c om
    if (isDevelopment()) { // workaround for issue #2097
        return encodeBase64(bytesOut.toByteArray());
    }
    return bytesOut.toByteArray();
}

From source file:com.newatlanta.appengine.taskqueue.Deferred.java

/**
 * Serialize an object into a byte array.
 *
 * @param obj An object to be serialized.
 * @return A byte array containing the serialized object
 * @throws QueueFailureException If an I/O error occurs during the
 * serialization process.//from   www.  j ava  2 s  .co m
 */
private static byte[] serialize(Object obj) {
    try {
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        ObjectOutputStream objectOut = new ObjectOutputStream(new BufferedOutputStream(bytesOut));
        objectOut.writeObject(obj);
        objectOut.close();
        //             if ( isDevelopment() ) { // workaround for issue #2097
        return encodeBase64(bytesOut.toByteArray());
        //             }
        //             return bytesOut.toByteArray();
    } catch (IOException e) {
        throw new QueueFailureException(e);
    }
}

From source file:com.googlecode.jtiger.modules.ecside.util.ExtremeUtils.java

public static int sessionSize(HttpSession session) {
    int total = 0;

    try {/*  w  ww.  j a va  2s  .c o  m*/
        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
        java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(baos);
        Enumeration enumeration = session.getAttributeNames();

        while (enumeration.hasMoreElements()) {
            String name = (String) enumeration.nextElement();
            Object obj = session.getAttribute(name);
            oos.writeObject(obj);

            int size = baos.size();
            total += size;
            logger.debug("The session name: " + name + " and the size is: " + size);
        }

        logger.debug("Total session size is: " + total);
    } catch (Exception e) {
        logger.error("Could not get the session size - " + ExceptionUtils.formatStackTrace(e));
    }

    return total;
}

From source file:com.gwtquickstarter.server.Deferred.java

/**
 * Serialize an object into a byte array.
 *
 * @param obj An object to be serialized.
 * @return A byte array containing the serialized object
 * @throws QueueFailureException If an I/O error occurs during the
 * serialization process./* w w w. j a va2  s  .c o  m*/
 */
private static byte[] serialize(Object obj) {
    try {
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        ObjectOutputStream objectOut = new ObjectOutputStream(new BufferedOutputStream(bytesOut));
        objectOut.writeObject(obj);
        objectOut.close();
        if (isDevelopment()) { // workaround for issue #2097
            return encodeBase64(bytesOut.toByteArray());
        }
        return bytesOut.toByteArray();
    } catch (IOException e) {
        throw new QueueFailureException(e);
    }
}

From source file:com.uberspot.storageutils.StorageUtils.java

/** Save the given object to a file in external storage
 * @param obj the object to save//w  w  w . j a  va 2  s  .  c  o m
 * @param directory the directory in the SD card to save it into
 * @param fileName the name of the file
 * @param overwrite if set to true the file will be overwritten if it already exists
 * @return true if the file was written successfully, false otherwise
 */
public static boolean saveObjectToExternalStorage(Object obj, String directory, String fileName,
        boolean overwrite) {
    if (!directory.startsWith(File.separator))
        directory = File.separator + directory;

    File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + directory);
    if (!dir.exists())
        dir.mkdirs();

    File file = new File(dir, fileName);
    if (file.exists() && !overwrite)
        return false;
    ObjectOutputStream output = null;
    try {
        output = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
        output.writeObject(obj);
        output.flush();
        return true;
    } catch (Exception e) {
        e.printStackTrace(System.out);
    } finally {
        if (output != null)
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace(System.out);
            }
    }
    return false;
}

From source file:com.threerings.media.tile.bundle.tools.TileSetBundler.java

/**
 * Create a tileset bundle jar file./*from   ww  w. j av a2s . c o m*/
 *
 * @param target the tileset bundle file that will be created.
 * @param bundle contains the tilesets we'd like to save out to the bundle.
 * @param improv the image provider.
 * @param imageBase the base directory for getting images for non-ObjectTileSet tilesets.
 * @param keepOriginalPngs bundle up the original PNGs as PNGs instead of converting to the
 * FastImageIO raw format
 */
public static boolean createBundleJar(File target, TileSetBundle bundle, ImageProvider improv, String imageBase,
        boolean keepOriginalPngs, boolean uncompressed) throws IOException {
    // now we have to create the actual bundle file
    FileOutputStream fout = new FileOutputStream(target);
    Manifest manifest = new Manifest();
    JarOutputStream jar = new JarOutputStream(fout, manifest);
    jar.setLevel(uncompressed ? Deflater.NO_COMPRESSION : Deflater.BEST_COMPRESSION);

    try {
        // write all of the image files to the bundle, converting the
        // tilesets to trimmed tilesets in the process
        Iterator<Integer> iditer = bundle.enumerateTileSetIds();

        // Store off the updated TileSets in a separate Map so we can wait to change the
        // bundle till we're done iterating.
        HashIntMap<TileSet> toUpdate = new HashIntMap<TileSet>();
        while (iditer.hasNext()) {
            int tileSetId = iditer.next().intValue();
            TileSet set = bundle.getTileSet(tileSetId);
            String imagePath = set.getImagePath();

            // sanity checks
            if (imagePath == null) {
                log.warning("Tileset contains no image path " + "[set=" + set + "]. It ain't gonna work.");
                continue;
            }

            // if this is an object tileset, trim it
            if (!keepOriginalPngs && (set instanceof ObjectTileSet)) {
                // set the tileset up with an image provider; we
                // need to do this so that we can trim it!
                set.setImageProvider(improv);

                // we're going to trim it, so adjust the path
                imagePath = adjustImagePath(imagePath);
                jar.putNextEntry(new JarEntry(imagePath));

                try {
                    // create a trimmed object tileset, which will
                    // write the trimmed tileset image to the jar
                    // output stream
                    TrimmedObjectTileSet tset = TrimmedObjectTileSet.trimObjectTileSet((ObjectTileSet) set,
                            jar);
                    tset.setImagePath(imagePath);
                    // replace the original set with the trimmed
                    // tileset in the tileset bundle
                    toUpdate.put(tileSetId, tset);

                } catch (Exception e) {
                    e.printStackTrace(System.err);

                    String msg = "Error adding tileset to bundle " + imagePath + ", " + set.getName() + ": "
                            + e;
                    throw (IOException) new IOException(msg).initCause(e);
                }

            } else {
                // read the image file and convert it to our custom
                // format in the bundle
                File ifile = new File(imageBase, imagePath);
                try {
                    BufferedImage image = ImageIO.read(ifile);
                    if (!keepOriginalPngs && FastImageIO.canWrite(image)) {
                        imagePath = adjustImagePath(imagePath);
                        jar.putNextEntry(new JarEntry(imagePath));
                        set.setImagePath(imagePath);
                        FastImageIO.write(image, jar);
                    } else {
                        jar.putNextEntry(new JarEntry(imagePath));
                        FileInputStream imgin = new FileInputStream(ifile);
                        StreamUtil.copy(imgin, jar);
                    }
                } catch (Exception e) {
                    String msg = "Failure bundling image " + ifile + ": " + e;
                    throw (IOException) new IOException(msg).initCause(e);
                }
            }
        }
        bundle.putAll(toUpdate);

        // now write a serialized representation of the tileset bundle
        // object to the bundle jar file
        JarEntry entry = new JarEntry(BundleUtil.METADATA_PATH);
        jar.putNextEntry(entry);
        ObjectOutputStream oout = new ObjectOutputStream(jar);
        oout.writeObject(bundle);
        oout.flush();

        // finally close up the jar file and call ourself done
        jar.close();

        return true;

    } catch (Exception e) {
        // remove the incomplete jar file and rethrow the exception
        jar.close();
        if (!target.delete()) {
            log.warning("Failed to close botched bundle '" + target + "'.");
        }
        String errmsg = "Failed to create bundle " + target + ": " + e;
        throw (IOException) new IOException(errmsg).initCause(e);
    }
}

From source file:Main.java

/**
 * Serialises a <code>Shape</code> object.
 *
 * @param shape  the shape object (<code>null</code> permitted).
 * @param stream  the output stream (<code>null</code> not permitted).
 *
 * @throws IOException if there is an I/O error.
 *///from ww w  .  ja v  a2 s .co m
public static void writeShape(final Shape shape, final ObjectOutputStream stream) throws IOException {

    if (stream == null) {
        throw new IllegalArgumentException("Null 'stream' argument.");
    }
    if (shape != null) {
        stream.writeBoolean(false);
        if (shape instanceof Line2D) {
            final Line2D line = (Line2D) shape;
            stream.writeObject(Line2D.class);
            stream.writeDouble(line.getX1());
            stream.writeDouble(line.getY1());
            stream.writeDouble(line.getX2());
            stream.writeDouble(line.getY2());
        } else if (shape instanceof Rectangle2D) {
            final Rectangle2D rectangle = (Rectangle2D) shape;
            stream.writeObject(Rectangle2D.class);
            stream.writeDouble(rectangle.getX());
            stream.writeDouble(rectangle.getY());
            stream.writeDouble(rectangle.getWidth());
            stream.writeDouble(rectangle.getHeight());
        } else if (shape instanceof Ellipse2D) {
            final Ellipse2D ellipse = (Ellipse2D) shape;
            stream.writeObject(Ellipse2D.class);
            stream.writeDouble(ellipse.getX());
            stream.writeDouble(ellipse.getY());
            stream.writeDouble(ellipse.getWidth());
            stream.writeDouble(ellipse.getHeight());
        } else if (shape instanceof Arc2D) {
            final Arc2D arc = (Arc2D) shape;
            stream.writeObject(Arc2D.class);
            stream.writeDouble(arc.getX());
            stream.writeDouble(arc.getY());
            stream.writeDouble(arc.getWidth());
            stream.writeDouble(arc.getHeight());
            stream.writeDouble(arc.getAngleStart());
            stream.writeDouble(arc.getAngleExtent());
            stream.writeInt(arc.getArcType());
        } else if (shape instanceof GeneralPath) {
            stream.writeObject(GeneralPath.class);
            final PathIterator pi = shape.getPathIterator(null);
            final float[] args = new float[6];
            stream.writeBoolean(pi.isDone());
            while (!pi.isDone()) {
                final int type = pi.currentSegment(args);
                stream.writeInt(type);
                // TODO: could write this to only stream the values
                // required for the segment type
                for (int i = 0; i < 6; i++) {
                    stream.writeFloat(args[i]);
                }
                stream.writeInt(pi.getWindingRule());
                pi.next();
                stream.writeBoolean(pi.isDone());
            }
        } else {
            stream.writeObject(shape.getClass());
            stream.writeObject(shape);
        }
    } else {
        stream.writeBoolean(true);
    }
}

From source file:com.nary.Debug.java

public static void saveClass(OutputStream _out, Object _class, boolean _compress) throws IOException {
    if (_compress) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream OOS = new ObjectOutputStream(bos);
        OOS.writeObject(_class);

        byte[] dataArray = bos.toByteArray();
        byte[] test = new byte[dataArray.length]; // this is where the byte array gets compressed to
        Deflater def = new Deflater(Deflater.BEST_COMPRESSION);
        def.setInput(dataArray);// w  ww.ja  va  2 s  . co  m
        def.finish();
        def.deflate(test);
        _out.write(test, 0, def.getTotalOut());
    } else {
        ObjectOutputStream OS = new ObjectOutputStream(_out);
        OS.writeObject(_class);
    }
}

From source file:com.nineash.hutsync.client.NetworkUtilities.java

/** Write the object to a Base64 string. */
private static String toString(Serializable o) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(o);
    oos.close();/*from w  ww  . j  ava  2 s  .co  m*/
    return new String(Base64Coder.encode(baos.toByteArray()));
}