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.sentaroh.android.TextFileBrowser.MainActivity.java

private void saveViewContents(Bundle outState) {
    outState.putInt("SpinnerPos", mViewedFileListSpinner.getSelectedItemPosition());
    outState.putInt("FAH_Size", mGlblParms.viewedFileList.size());
    try {/* w  w  w .  j a va2  s . c  om*/
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024 * 32);
        ObjectOutputStream oos = new ObjectOutputStream(bos);

        for (int i = 0; i < mGlblParms.viewedFileList.size(); i++) {
            ViewedFileListItem vfli = mGlblParms.viewedFileList.get(i);
            vfli.writeExternal(oos);
        }
        oos.flush();
        byte[] buf = bos.toByteArray();
        outState.putByteArray("FAH_List", buf);
        oos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.trianacode.taskgraph.service.RunnableTask.java

/**
 * Makes a copy of the specified data. If the data is of TrianaType the copyMe method is used, otherwise the data is
 * serialized then deserialized.//from   w  w w  .j ava  2s  .com
 * <p/>
 * Note: this relies on all data types being serialisable Note2: this method uses ByteArrayInputStream and
 * OutputStream which are not optimised, they are synchronized (not needed here) and the buffer size and growth
 * factor could be tweeked
 */
private Object copyData(Object data) throws IOException, ClassNotFoundException {
    /*
    // TODO
    if (data instanceof TrianaType)
    return ((TrianaType) data).copyMe();
    else {*/
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream objout = new ObjectOutputStream(bos);
    objout.writeObject(data);
    objout.flush();
    objout.close();
    bos.close();

    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    ObjectInputStream objin = new TrianaObjectInputStream(bis);
    Object ret = null;
    try {
        ret = objin.readObject();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    objin.close();
    return ret;
    //}
}

From source file:org.ecoinformatics.seek.ecogrid.EcoGridServicesController.java

public void writeServices() throws Exception {
    File saveFile = new File(_saveFileName);
    if (saveFile.exists()) {
        if (isDebugging)
            log.debug("delete " + saveFile);
        saveFile.delete();/*from ww w. j av a2s. c  o m*/
    }
    try {
        OutputStream os = new FileOutputStream(saveFile);
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(currentServicesList);
        oos.flush();
        if (isDebugging) {
            log.debug("wrote " + saveFile);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.torque.util.BasePeer.java

/**
 * Converts a hashtable to a byte array for storage/serialization.
 *
 * @param hash The Hashtable to convert.
 * @return A byte[] with the converted Hashtable.
 * @exception TorqueException//from  w  w  w. j  a va  2  s  .  c  o  m
 */
public static byte[] hashtableToByteArray(Hashtable hash) throws TorqueException {
    Hashtable saveData = new Hashtable(hash.size());
    String key = null;
    Object value = null;
    byte[] byteArray = null;

    Iterator keys = hash.keySet().iterator();
    while (keys.hasNext()) {
        key = (String) keys.next();
        value = hash.get(key);
        if (value instanceof Serializable) {
            saveData.put(key, value);
        }
    }

    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();
        byteArray = baos.toByteArray();
    } catch (Exception e) {
        throw new TorqueException(e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ignored) {
            }
        }

        if (bos != null) {
            try {
                bos.close();
            } catch (IOException ignored) {
            }
        }

        if (baos != null) {
            try {
                baos.close();
            } catch (IOException ignored) {
            }
        }
    }
    return byteArray;
}

From source file:org.hyperic.hq.agent.server.AgentDListProvider.java

public void addObjectToFolder(String folderName, Object obj, long createTime, int maxElementsInFolder) {
    File folder = new File(this.writeDir + System.getProperty("file.separator") + folderName);
    if (!folder.exists()) {
        folder.mkdir();//w w w.j a v  a 2 s. c  om
    }
    File[] files = folder.listFiles();
    int numberOfElementsInFolder = files.length;
    if (numberOfElementsInFolder >= maxElementsInFolder) {
        // sort the files by create time
        Arrays.sort(files, new Comparator<File>() {
            public int compare(File f1, File f2) {
                return (Long.valueOf(f1.lastModified()).compareTo(f2.lastModified()));
            }
        });
        int i = 0;
        while (numberOfElementsInFolder >= maxElementsInFolder) {
            files[i].delete();
            numberOfElementsInFolder--;
            i++;
        }
    }

    ObjectOutputStream outputStream = null;
    try {
        outputStream = new ObjectOutputStream(new FileOutputStream(
                folder.getAbsolutePath() + System.getProperty("file.separator") + createTime));
        outputStream.writeObject(obj);
    } catch (Exception ex) {
    } finally {
        try {
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        } catch (IOException ex) {
        }
    }
}

From source file:fr.pasteque.pos.ticket.TicketInfo.java

/** Serialize as shared ticket */
public byte[] serialize() throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream(2048);
    ObjectOutputStream out = new ObjectOutputStream(bos);
    out.writeObject(m_sId);//ww w. ja  v  a  2s. c  o m
    out.writeInt(tickettype);
    out.writeInt(m_iTicketId);
    out.writeObject(m_Customer);
    out.writeObject(m_dDate);
    out.writeObject(attributes);
    out.writeObject(m_aLines);
    out.writeObject(this.customersCount);
    out.writeObject(this.tariffAreaId);
    out.writeObject(this.discountProfileId);
    out.writeDouble(this.discountRate);
    out.flush();
    byte[] data = bos.toByteArray();
    out.close();
    return data;
}

From source file:junk.gui.HazardDataSetCalcCondorApp.java

/**
 * this connects to the servlet on web server to check if dataset name already exists
 * or computation have already been for these parameter settings.
 * @return//from w ww  .  jav  a 2 s.c  o  m
 */
private Object checkForHazardMapComputation() {

    try {
        if (D)
            System.out.println("starting to make connection with servlet");
        URL hazardMapServlet = new URL(DATASET_CHECK_SERVLET_URL);

        URLConnection servletConnection = hazardMapServlet.openConnection();
        if (D)
            System.out.println("connection established");

        // inform the connection that we will send output and accept input
        servletConnection.setDoInput(true);
        servletConnection.setDoOutput(true);

        // Don't use a cached version of URL connection.
        servletConnection.setUseCaches(false);
        servletConnection.setDefaultUseCaches(false);
        // Specify the content type that we will send binary data
        servletConnection.setRequestProperty("Content-Type", "application/octet-stream");

        ObjectOutputStream toServlet = new ObjectOutputStream(servletConnection.getOutputStream());

        //sending the parameters info. to the servlet
        toServlet.writeObject(getParametersInfo());

        //sending the dataset id to the servlet
        toServlet.writeObject(datasetIdText.getText());

        toServlet.flush();
        toServlet.close();

        // Receive the datasetnumber from the servlet after it has received all the data
        ObjectInputStream fromServlet = new ObjectInputStream(servletConnection.getInputStream());
        Object obj = fromServlet.readObject();
        //if(D) System.out.println("Receiving the Input from the Servlet:"+success);
        fromServlet.close();
        return obj;

    } catch (Exception e) {
        ExceptionWindow bugWindow = new ExceptionWindow(this, e, getParametersInfo());
        bugWindow.setVisible(true);
        bugWindow.pack();

    }
    return null;
}

From source file:org.apache.axis2.engine.ObjectSaveTest.java

public void testObjectSerializable() throws Exception {
    File theFile = null;//  ww w  .jav  a 2s. c o m
    String theFilename = null;
    boolean saved = false;
    boolean restored = false;
    boolean done = false;

    log.debug("ObjectSaveTest:testObjectSerializable():  BEGIN ---------------");

    // ---------------------------------------------------------
    // setup an object to use
    // ---------------------------------------------------------
    MetaDataEntry obj = new MetaDataEntry("object_1", "object_1");

    // ---------------------------------------------------------
    // setup a temporary file to use
    // ---------------------------------------------------------
    try {
        theFile = File.createTempFile("objectTest", null);
        theFilename = theFile.getName();
        log.debug("ObjectSaveTest:testObjectSerializable(): temp file = [" + theFilename + "]");
    } catch (Exception ex) {
        log.debug("ObjectSaveTest:testObjectSerializable(): error creating temp file = [" + ex.getMessage()
                + "]");
        theFile = null;
    }

    if (theFile != null) {
        // ---------------------------------------------------------
        // save to the temporary file
        // ---------------------------------------------------------
        try {
            // 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
            log.debug("ObjectSaveTest:testObjectSerializable(): saving .....");
            saved = false;
            ObjectStateUtils.writeObject(outObjStream, obj, "testObject:Serializable");

            // close out the streams
            outObjStream.flush();
            outObjStream.close();
            outStream.flush();
            outStream.close();

            saved = true;
            log.debug("ObjectSaveTest:testObjectSerializable(): ....save operation completed.....");

            long filesize = theFile.length();
            log.debug("ObjectSaveTest:testObjectSerializable(): file size after save [" + filesize
                    + "]   temp file = [" + theFilename + "]");
        } catch (Exception ex2) {
            log.debug("ObjectSaveTest:testObjectSerializable(): error during save [" + ex2.getClass().getName()
                    + " : " + ex2.getMessage() + "]");
            ex2.printStackTrace();
        }

        assertTrue(saved);

        // ---------------------------------------------------------
        // restore from the temporary file
        // ---------------------------------------------------------
        try {
            // 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);

            // try to restore the options
            log.debug("ObjectSaveTest:testObjectSerializable(): restoring .....");
            restored = false;
            MetaDataEntry restored_obj = (MetaDataEntry) ObjectStateUtils.readObject(inObjStream,
                    "testObject:serializable");
            inObjStream.close();
            inStream.close();

            restored = true;
            log.debug("ObjectSaveTest:testObjectSerializable(): ....restored operation completed.....");

        } catch (Exception ex2) {
            log.debug("ObjectSaveTest:testObjectSerializable(): error during restore ["
                    + ex2.getClass().getName() + " : " + ex2.getMessage() + "]");
            ex2.printStackTrace();
        }

        assertTrue(restored);

        // if the save/restore of the object succeeded,
        // then don't keep the temporary file around
        boolean removeTmpFile = saved && restored;
        if (removeTmpFile) {
            try {
                theFile.delete();
            } catch (Exception e) {
                // just absorb it
            }
        }

        // indicate that the temp file was created ok
        done = true;
    }

    // this is false when there are problems with the temporary file
    assertTrue(done);

    log.debug("ObjectSaveTest:testObjectSerializable():  END ---------------");
}

From source file:net.sf.nmedit.jtheme.store.DefaultStorageContext.java

private void __writeCache(File cacheFile) throws Exception {
    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(cacheFile)));
    try {/*from   w ww  .java2 s.co  m*/
        // css
        out.writeObject(cssStyleSheet);

        // defs
        out.writeInt(imageResourceMap.size());
        for (Object key : imageResourceMap.keySet()) {
            out.writeObject(key);
            Object ir = imageResourceMap.get(key);
            out.writeObject(ir);
        }
        // modules
        out.writeInt(moduleStoreMap.size());
        for (ModuleElement e : moduleStoreMap.values()) {
            out.writeObject(e);
        }
    } finally {
        out.flush();
        out.close();
    }
}

From source file:org.apache.axis2.engine.ObjectSaveTest.java

public void testHashMap() throws Exception {
    File theFile = null;//  ww w .  ja v a  2  s .c om
    String theFilename = null;
    boolean saved = false;
    boolean restored = false;
    boolean done = false;
    boolean comparesOK = false;

    log.debug("ObjectSaveTest:testHashMap():  BEGIN ---------------");

    // ---------------------------------------------------------
    // setup the object to use
    // ---------------------------------------------------------
    HashMap obj = new HashMap();
    obj.put(new String("key1"), new Integer(1));
    obj.put(new String("key2"), new Integer(2));
    obj.put(new String("key3"), new String("value1"));
    obj.put(new String("key4"), System.out);
    obj.put(new String("key5"), new Integer(3));
    obj.put(new String("key6"), new Integer(4));
    obj.put(new String("key7"), System.err);
    obj.put(new String("key8"), new Integer(5));
    obj.put(new String("key9"), new Integer(6));
    obj.put(new NotSerializableObject("TestForHashMapKey"), new Integer(7));
    obj.put(new String("key10"), new Integer(8));

    int initial_size = obj.size();

    // ---------------------------------------------------------
    // setup a temporary file to use
    // ---------------------------------------------------------
    try {
        theFile = File.createTempFile("hashmapTest", null);
        theFilename = theFile.getName();
        log.debug("ObjectSaveTest:testHashMap(): temp file = [" + theFilename + "]");
    } catch (Exception ex) {
        log.debug("ObjectSaveTest:testHashMap(): error creating temp file = [" + ex.getMessage() + "]");
        theFile = null;
    }

    if (theFile != null) {
        // ---------------------------------------------------------
        // save to the temporary file
        // ---------------------------------------------------------
        try {
            // 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
            log.debug("ObjectSaveTest:testHashMap(): saving .....");
            saved = false;
            ObjectStateUtils.writeHashMap(outObjStream, obj, "testObject:HashMap");

            // close out the streams
            outObjStream.flush();
            outObjStream.close();
            outStream.flush();
            outStream.close();

            saved = true;
            log.debug("ObjectSaveTest:testHashMap(): ....save operation completed.....");

            long filesize = theFile.length();
            log.debug("ObjectSaveTest:testHashMap(): file size after save [" + filesize + "]   temp file = ["
                    + theFilename + "]");
        } catch (Exception ex2) {
            log.debug("ObjectSaveTest:testHashMap(): error during save [" + ex2.getClass().getName() + " : "
                    + ex2.getMessage() + "]");
            ex2.printStackTrace();
        }

        assertTrue(saved);

        // ---------------------------------------------------------
        // restore from the temporary file
        // ---------------------------------------------------------
        HashMap restored_obj = null;

        try {
            // 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);

            // try to restore the options
            log.debug("ObjectSaveTest:testHashMap(): restoring .....");
            restored = false;
            restored_obj = ObjectStateUtils.readHashMap(inObjStream, "testObject:HashMap");
            inObjStream.close();
            inStream.close();

            restored = true;
            log.debug("ObjectSaveTest:testHashMap(): ....restored operation completed.....");

        } catch (Exception ex2) {
            log.debug("ObjectSaveTest:testHashMap(): error during restore [" + ex2.getClass().getName() + " : "
                    + ex2.getMessage() + "]");
            ex2.printStackTrace();
        }

        // if the save/restore of the object succeeded,
        // then don't keep the temporary file around
        boolean removeTmpFile = saved && restored;
        if (removeTmpFile) {
            try {
                theFile.delete();
            } catch (Exception e) {
                // just absorb it
            }
        }

        assertTrue(restored);

        if (restored_obj != null) {
            int restored_size = restored_obj.size();
            if (restored_size == (initial_size - 3)) {
                // there are entries in the map that are not serializable
                comparesOK = true;
            }
        }

        // TODO: check for exact entries

        assertTrue(comparesOK);

        // indicate that the temp file was created ok
        done = true;
    }

    // this is false when there are problems with the temporary file
    assertTrue(done);

    log.debug("ObjectSaveTest:testHashMap():  END ---------------");
}