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.interreg.docexplore.authoring.AuthoringMenu.java

void writeRecent() {
    try {//from   www.j a va2 s  .c  o  m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(recent);
        oos.flush();
        RandomAccessFile file = new RandomAccessFile(new File(DocExploreTool.getHomeDir(), "ATRecent"), "rw");
        file.setLength(0);
        file.write(baos.toByteArray());
        file.close();
        oos.close();

        //         ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File("ATRecent"), false));
        //         out.writeObject(recent);
        //         out.close();
    } catch (Exception e) {
        ErrorHandler.defaultHandler.submit(e, true);
    }
}

From source file:com.jiramot.foursquare.android.FSAPITest.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from  w  ww .  j  ava 2s  .c om*/

    venue = (Button) findViewById(R.id.button);
    OnClickListener venues = new OnClickListener() {
        @Override
        public void onClick(View v) {
            String aa = null;
            try {
                aa = searchVenue();
                JSONObject obj = new JSONObject(aa);
                //               Log.i("fsapitest", obj.toString(2));
                JSONObject response = obj.getJSONObject("response");
                JSONArray groups = response.getJSONArray("groups");
                JSONObject element = groups.getJSONObject(0);
                JSONArray items = element.getJSONArray("items");

                File sdcardpath = Environment.getExternalStorageDirectory();
                File f = new File(sdcardpath, "test" + count + ".txt");
                FileOutputStream outStream = new FileOutputStream(f);
                ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(outStream));

                for (int i = 0; i < items.length(); i++) {
                    JSONObject item = items.getJSONObject(i);
                    Log.i("corso", "item " + i + " -- " + item.getString("id"));
                    Log.i("corso", "item " + i + " -- " + item.getString("name"));
                }

                //               out.writeObject(items.toString(2));

                out.flush();
                out.close();
                outStream.close();

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    };

    OnClickListener friends = new OnClickListener() {

        @Override
        public void onClick(View v) {
            venue.setText("friends");

            try {
                String result = foursquare.request("users/self/friends");
                JSONObject obj = new JSONObject(result);
                JSONObject response = obj.getJSONObject("response");
                JSONObject friends = response.getJSONObject("friends");
                JSONArray items = friends.getJSONArray("items");

                for (int i = 0; i < items.length(); i++) {
                    JSONObject item = items.getJSONObject(i);

                    Log.i("debug", item.getString("id") + " - " + item.getString("firstName") + " "
                            + item.getString("lastName"));
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    };

    venue.setOnClickListener(friends);

    init(getIntent());

    //         JSONObject response = obj.getJSONObject("response");
    //         JSONArray venues = response.getJSONArray("groups");

    //         File sdcardpath = Environment.getExternalStorageDirectory();
    //         File f = new File(sdcardpath,"test"+count+".txt");
    //         FileOutputStream outStream = new FileOutputStream(f);
    //         ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(outStream));

    //         out.writeObject(obj.toString(2));

    //         for (int i=0; i<venues.length(); i++) {
    //            JSONObject venue = venues.getJSONObject(i);

    //            out.writeObject(venue.toString(2));

    //            Log.i("corso", venue.getString("id"));
    //            Log.i("corso", venue.getString("name"));
    //         }

    //         out.flush();
    //         out.close();
    //         outStream.close();
    //
    //         count++;
    //         Log.i("fsapitest", "calls: "+count);
    //
}

From source file:com.sumzerotrading.broker.ib.InteractiveBrokersBroker.java

protected void saveOrderMaps() throws Exception {
    tradeFileSemaphore.acquire();//from  w w  w.j a v a  2 s .  co m
    try {
        File file = new File(getDirName() + "orders.ser");
        ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file));
        output.writeObject(completedOrderMap);
        output.writeObject(orderMap);
        output.flush();
        output.close();
    } finally {
        tradeFileSemaphore.release();
    }
}

From source file:com.haulmont.cuba.core.sys.serialization.StandardSerialization.java

@Override
public void serialize(Object object, OutputStream os) {
    ObjectOutputStream out = null;
    boolean isObjectStream = os instanceof ObjectOutputStream;
    try {//from  w w w. j av a  2  s . c o m
        out = isObjectStream ? (ObjectOutputStream) os : new ObjectOutputStream(os);
        out.writeObject(object);
    } catch (IOException ex) {
        throw new IllegalStateException("Failed to serialize object", ex);
    } finally {
        //Prevent close stream. Stream closed only by:
        //com.haulmont.cuba.core.sys.remoting.HttpServiceExporter,
        //com.haulmont.cuba.core.sys.remoting.ClusteredHttpInvokerRequestExecutor()
        //Only flush buffer to output stream
        if (!isObjectStream && out != null) {
            try {
                out.flush();
            } catch (IOException ex) {
                throw new IllegalStateException("Failed to serialize object", ex);
            }
        }
    }
}

From source file:com.sec.ose.osi.thread.job.identify.data.IdentifyQueue.java

private void appendTransactionFile(IdentifyData pIdentifiedData) {

    log.debug("append transaction: " + pIdentifiedData.exportCSVForm());

    FileOutputStream fos = null;/*from w ww  .j  a va  2s . co m*/
    ObjectOutputStream oosWriter = null;
    try {
        File file = new File(transactionLogFilePath);
        if (file.exists() == true) {
            fos = new FileOutputStream(file, true);
            oosWriter = new ObjectOutputStream(fos);
        } else {
            fos = new FileOutputStream(file, true);

            oosWriter = new AppendAllowedObjectOutputStream(fos);
        }

        oosWriter.writeObject(pIdentifiedData);
        oosWriter.flush();
        oosWriter.close();

    } catch (IOException e) {
        log.warn(e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e) {
                log.debug(e);
            }
        }
    }
}

From source file:org.apache.lens.driver.hive.TestRemoteHiveDriver.java

/**
 * Persist context.//from   w  w  w.  j  a v  a 2  s.c o m
 *
 * @param ctx the ctx
 * @return the byte[]
 * @throws IOException Signals that an I/O exception has occurred.
 */
private byte[] persistContext(QueryContext ctx) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(baos);
    try {
        out.writeObject(ctx);
        boolean isDriverAvailable = (ctx.getSelectedDriver() != null);
        out.writeBoolean(isDriverAvailable);
        if (isDriverAvailable) {
            out.writeUTF(ctx.getSelectedDriver().getFullyQualifiedName());
        }
    } finally {
        out.flush();
        out.close();
        baos.close();
    }

    return baos.toByteArray();
}

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

public void testSaveAndRestore() throws Exception {
    File theFile = null;/*from w  w  w. j  av  a2  s. c  om*/
    String theFilename = null;
    boolean saved = false;
    boolean restored = false;
    boolean done = false;
    boolean comparesOk = false;

    log.debug("OperationContextSaveTest:testSaveAndRestore():  BEGIN ---------------");

    // ---------------------------------------------------------
    // setup a temporary file to use
    // ---------------------------------------------------------
    try {
        theFile = File.createTempFile("OpCtxSave", null);
        theFilename = theFile.getName();
        log.debug("OperationContextSaveTest:testSaveAndRestore(): temp file = [" + theFilename + "]");
    } catch (Exception ex) {
        log.debug("OperationContextSaveTest:testSaveAndRestore(): 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 the message context
            log.debug("OperationContextSaveTest:testSaveAndRestore(): saving .....");
            saved = false;
            outObjStream.writeObject(operationContext);

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

            saved = true;
            log.debug("OperationContextSaveTest:testSaveAndRestore(): ....save operation completed.....");

            long filesize = theFile.length();
            log.debug("OperationContextSaveTest:testSaveAndRestore(): file size after save [" + filesize
                    + "]   temp file = [" + theFilename + "]");

        } catch (Exception ex2) {
            log.debug("OperationContextSaveTest:testSaveAndRestore(): 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 context
            log.debug("OperationContextSaveTest:testSaveAndRestore(): restoring .....");
            restored = false;
            OperationContext opctx_restored = (OperationContext) inObjStream.readObject();
            inObjStream.close();
            inStream.close();

            opctx_restored.activate(configurationContext);

            restored = true;
            log.debug("OperationContextSaveTest:testSaveAndRestore(): ....restored operation completed.....");

            // compare to original
            comparesOk = opctx_restored.isEquivalent(operationContext);
            log.debug("OperationContextSaveTest:testSaveAndRestore():  OperationContext equivalency ["
                    + comparesOk + "]");
            assertTrue(comparesOk);

            ServiceContext restored_srvCtx = opctx_restored.getServiceContext();

            ServiceGroupContext restored_sgCtx = restored_srvCtx.getServiceGroupContext();
            comparesOk = restored_sgCtx.isEquivalent(serviceGroupContext);
            log.debug("OperationContextSaveTest:testSaveAndRestore():  ServiceGroupContext equivalency ["
                    + comparesOk + "]");
            assertTrue(comparesOk);

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

        assertTrue(restored);

        // if the save/restore of the operation context succeeded,
        // then don't keep the temporary file around
        boolean removeTmpFile = saved && restored && comparesOk;
        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("OperationContextSaveTest:testSaveAndRestore():  END ---------------");
}

From source file:de.forsthaus.example.TestCtrl.java

public void onClick$BtnSerializeTB(Event event) throws InterruptedException {

    Textbox fcOld;/*from w w w  .  j a  v  a  2  s. co m*/
    Textbox fcNew;

    fcOld = new Textbox("Test Textbox");

    // Serialize the original class object
    try {
        final FileOutputStream fo = new FileOutputStream("cde.tmp");
        final ObjectOutputStream so = new ObjectOutputStream(fo);
        so.writeObject(fcOld);
        so.flush();
        so.close();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

    // Deserialize in to new class object
    try {
        final FileInputStream fi = new FileInputStream("cde.tmp");
        final ObjectInputStream si = new ObjectInputStream(fi);
        fcNew = (Textbox) si.readObject();
        System.out.println(fcNew.getValue());
        si.close();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

}

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

/**
 * UDPflowsVector//  w  ww .  j  a  v a2  s  . c  o  m
 *
 * @param RouterIP
 * @param buf
 * @param len
 * @throws DoneException
 */
@SuppressWarnings("unchecked")
public V9_Packet(String RouterIP, byte[] buf, int len) throws DoneException {
    if (Params.DEBUG) {
        // 
        //            File tmpFile = new File("D:\\Dev\\netflow\\jnca\\savePacketT_211.98.0.147_256.cache.tmp");
        File tmpFile = new File("D:\\Dev\\netflow\\jnca\\savePacketT_211.98.0.147_256.cache.tmp");
        if (tmpFile.exists()) {
            try {
                ObjectInputStream fIn = new ObjectInputStream(new FileInputStream(tmpFile));
                System.out.println("Directly read from " + fIn);
                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 < V9_Header_Size) {
        throw new DoneException("    * incomplete header *");
    }

    this.routerIP = RouterIP;
    count = Util.to_number(buf, 2, 2); // (template data flowset

    SysUptime = Util.to_number(buf, 4, 4);
    Variation vrat = Variation.getInstance();
    vrat.setVary(Util.convertIPS2Long(RouterIP), SysUptime);
    unix_secs = Util.to_number(buf, 8, 4);
    packageSequence = Util.to_number(buf, 12, 4);
    sourceId = Util.to_number(buf, 16, 4);

    flows = new Vector((int) count * 30); // Let's first make some space
    optionFlows = new Vector();
    // t
    long flowsetLength = 0l;
    // flowset
    for (int flowsetCounter = 0, packetOffset = V9_Header_Size; flowsetCounter < count
            && packetOffset < len; flowsetCounter++, packetOffset += flowsetLength) {
        // flowset
        long flowsetId = Util.to_number(buf, packetOffset, 2);
        flowsetLength = Util.to_number(buf, packetOffset + 2, 2);
        if (flowsetLength == 0) {
            throw new DoneException("there is a flowset len=0packet invalid");
        }
        if (flowsetId == 0) {
            // template flowsettemplateiddata flowset
            // template flowset
            int thisTemplateOffset = packetOffset + 4;
            do {
                // template
                long templateId = Util.to_number(buf, thisTemplateOffset, 2);
                long fieldCount = Util.to_number(buf, thisTemplateOffset + 2, 2);
                if (TemplateManager.getTemplateManager().getTemplate(this.routerIP, (int) templateId) == null
                        || Params.v9TemplateOverwrite) {
                    try {
                        TemplateManager.getTemplateManager().acceptTemplate(this.routerIP, buf,
                                thisTemplateOffset);
                    } catch (Exception e) {
                        if (Params.DEBUG) {
                            e.printStackTrace();
                        }
                        if ((e.toString() != null) && (!e.toString().equals(""))) {
                            if (e.toString().startsWith("savePacket")) {
                                try {
                                    ObjectOutputStream fOut;
                                    fOut = new ObjectOutputStream(
                                            new FileOutputStream("./" + e.toString() + ".cache.tmp"));
                                    fOut.writeObject(buf);
                                    fOut.writeObject(new Integer(len));
                                    fOut.flush();
                                    fOut.close();
                                    System.err.println("Saved ");
                                } catch (FileNotFoundException e2) {
                                    e2.printStackTrace();
                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                }
                            } else {
                                System.err.println("An Error without save:" + e.toString());
                            }
                        }
                    }

                }
                thisTemplateOffset += fieldCount * 4 + 4; //
            } while (thisTemplateOffset - packetOffset < flowsetLength);
        } else if (flowsetId == 1) { // options flowset
            continue;
            //                int thisOptionTemplateOffset = packetOffset + 4;
            //                // bypass flowsetID and flowset length
            //                do {
            //                    // template
            //                    long optionTemplateId = Util.to_number(buf,
            //                            thisOptionTemplateOffset, 2);
            //                    long scopeLen = Util.to_number(buf,
            //                            thisOptionTemplateOffset + 2, 2);
            //                    long optionLen = Util.to_number(buf,
            //                            thisOptionTemplateOffset + 4, 2);
            //                    if (OptionTemplateManager.getOptionTemplateManager()
            //                        .getOptionTemplate(this.routerIP,
            //                                           (int) optionTemplateId) == null
            //                        || Params.v9TemplateOverwrite) {
            //                        OptionTemplateManager.getOptionTemplateManager()
            //                                .acceptOptionTemplate(this.routerIP, buf,
            //                                thisOptionTemplateOffset);
            //                    }
            //                    thisOptionTemplateOffset += scopeLen + optionLen + 6;
            //                } while (thisOptionTemplateOffset -
            //                         packetOffset < flowsetLength);
        } else if (flowsetId > 255) {
            // data flowset
            // templateId==flowsetId
            Template tOfData = TemplateManager.getTemplateManager().getTemplate(this.routerIP, (int) flowsetId); // flowsetId==templateId
            if (tOfData != null) {
                int dataRecordLen = tOfData.getTypeOffset(-1); // 
                // packetOffset+4 flowsetId  length
                for (int idx = 0, p = packetOffset + 4; (p - packetOffset + dataRecordLen) < flowsetLength; //consider padding
                        idx++, p += dataRecordLen) { //+5 makes OK
                    // IP?v9v5
                    V5_Flow f;
                    try {
                        f = new V5_Flow(RouterIP, buf, p, tOfData);
                        flows.add(f);
                    } catch (DoneException e) {
                        if (Params.DEBUG) {
                            e.printStackTrace();
                        }
                        if ((e.toString() != null) && (!e.toString().equals(""))) {
                            if (e.toString().startsWith("savePacket")) {
                                try {
                                    ObjectOutputStream fOut;
                                    fOut = new ObjectOutputStream(
                                            new FileOutputStream("./" + e.toString() + ".cache.tmp"));
                                    fOut.writeObject(buf);
                                    fOut.writeObject(new Integer(len));
                                    fOut.flush();
                                    fOut.close();
                                    System.err.println("Saved ");
                                } catch (FileNotFoundException e2) {
                                    e2.printStackTrace();
                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                }
                            } else {
                                System.err.println(e.toString());
                            }
                        }
                    }
                }
            } else { //options packet, should refer to option template, not in use now
                continue;
                //                    OptionTemplate otOfData = OptionTemplateManager
                //                                              .getOptionTemplateManager().
                //                                              getOptionTemplate(
                //                            this.routerIP, (int) flowsetId);
                //                    if (otOfData != null) {
                //                        int dataRecordLen = otOfData.getTypeOffset( -1); // 
                //                        // packetOffset+4 flowsetId  length
                //                        for (int idx = 0, p = packetOffset + 4; p
                //                                              - packetOffset < flowsetLength;
                //                                              idx++, p += dataRecordLen) {
                //                            OptionFlow of;
                //                            try {
                //                                of = new OptionFlow(RouterIP, buf, p, otOfData);
                ////                                optionFlows.add(of); // Vector
                //                            } catch (DoneException e) {
                //                                if (Params.DEBUG) {
                //                                    e.printStackTrace();
                //                                }
                //                                System.err.println(e.toString());
                //                            }
                //                        }
                //                    } else {
                //                        System.err.println(this.routerIP + "" + flowsetId
                //                                           + "template");
                //                    }
            }
        }
    }
}

From source file:de.forsthaus.example.TestCtrl.java

public void onClick$BtnSerializeFC(Event event) throws InterruptedException {

    FieldComparator fcOld;//from  ww w .  j a v a2  s .c  o  m
    FieldComparator fcNew;

    fcOld = new FieldComparator("TestColumn", false);

    // Serialize the original class object
    try {
        final FileOutputStream fo = new FileOutputStream("cde.tmp");
        final ObjectOutputStream so = new ObjectOutputStream(fo);
        so.writeObject(fcOld);
        so.flush();
        so.close();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

    // Deserialize in to new class object
    try {
        final FileInputStream fi = new FileInputStream("cde.tmp");
        final ObjectInputStream si = new ObjectInputStream(fi);
        fcNew = (FieldComparator) si.readObject();
        System.out.println(fcNew.getOrderBy());
        si.close();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

    final String longString1 = "Hello. I'm a long string\n\n Hello i'm the second line.\n hjdgf hgjhdgsfhsd jhgjd sfjgj gfdsfg\n\n kjdsds fjk jdsh fjdhfdjsh djsfh jkhjdsf jds jds f ";
    final String longString2 = "Hello. I'm a long string\n\n Hello i'm the second line.\n hjdgf hgjhdgsfhsd jhgjd sfjgj gfdsfg ooiji ojre iorjioj girirjgijr griojgiorjg iorjgir ";
    final String longString3 = "Hello. I'm a long string\n\n Hello i'm the second line.\n hjdgf hgjhdgsfhsd jhgjd sfjgj gfdsfg rok reok kre grigoirejg eopijsj jgioe gjiojg rei re";
    final String longString4 = "Hello. I'm a long string\n\n Hello i'm the second line.\n hjdgf hgjhdgsfhsd jhgjd sfjgj gfdsfg rpokg orkeopkg ok rkropk gpor oprek grekopg kropkpor ";
    final String longString5 = "Hello. I'm a long string\n\n Hello i'm the second line.\n hjdgf hgjhdgsfhsd jhgjd sfjgj gfdsfg rplg reo ropekpo rekerop ok orek oprek porkeop re ";
    final String longString6 = "Hello. I'm a long string\n\n Hello i'm the second line.\n hjdgf hgjhdgsfhsd jhgjd sfjgj gfdsfg pork oprkk opre opkrepok oprek kopre oprekpo rkeop rke ";
    final String message = longString1 + longString2 + longString3 + longString4 + longString5 + longString6;
    final String title = Labels.getLabel("message.Information");
    MultiLineMessageBox.doSetTemplate();
    MultiLineMessageBox.show(message, title, MultiLineMessageBox.OK, "INFORMATION", true);

}