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.twinsoft.convertigo.engine.util.XMLUtils.java

public static Node writeObjectToXml(Document document, Object object, Object compiledValue) throws Exception {
    if (object == null)
        return null;

    if (object instanceof Enum) {
        object = ((Enum<?>) object).name();
    }// w w  w.java  2  s  . c o m

    // Simple objects
    if ((object instanceof Boolean) || (object instanceof Integer) || (object instanceof Double)
            || (object instanceof Float) || (object instanceof Character) || (object instanceof Long)
            || (object instanceof Short) || (object instanceof Byte)) {
        Element element = document.createElement(object.getClass().getName());
        element.setAttribute("value", object.toString());
        if (compiledValue != null)
            element.setAttribute("compiledValue", compiledValue.toString());
        return element;
    }
    // Strings
    else if (object instanceof String) {
        Element element = document.createElement(object.getClass().getName());
        element.setAttribute("value", object.toString());
        if (compiledValue != null) {
            element.setAttribute("compiledValueClass", compiledValue.getClass().getCanonicalName());
            element.setAttribute("compiledValue", compiledValue.toString());
        }
        return element;
    }
    // Arrays
    else if (object.getClass().getName().startsWith("[")) {
        String arrayClassName = object.getClass().getName();
        int i = arrayClassName.lastIndexOf('[');

        String itemClassName = arrayClassName.substring(i + 1);
        char c = itemClassName.charAt(itemClassName.length() - 1);
        switch (c) {
        case ';':
            itemClassName = itemClassName.substring(1, itemClassName.length() - 1);
            break;
        case 'B':
            itemClassName = "byte";
            break;
        case 'C':
            itemClassName = "char";
            break;
        case 'D':
            itemClassName = "double";
            break;
        case 'F':
            itemClassName = "float";
            break;
        case 'I':
            itemClassName = "int";
            break;
        case 'J':
            itemClassName = "long";
            break;
        case 'S':
            itemClassName = "short";
            break;
        case 'Z':
            itemClassName = "boolean";
            break;
        }

        Element element = document.createElement("array");
        element.setAttribute("classname", itemClassName);

        int len = Array.getLength(object);
        element.setAttribute("length", Integer.toString(len));

        Node subNode;
        for (int k = 0; k < len; k++) {
            subNode = writeObjectToXml(document, Array.get(object, k));
            if (subNode != null) {
                element.appendChild(subNode);
            }
        }

        return element;
    }
    // XMLization
    else if (object instanceof XMLizable) {
        Element element = document.createElement("xmlizable");
        element.setAttribute("classname", object.getClass().getName());
        element.appendChild(((XMLizable) object).writeXml(document));
        return element;
    }
    // Default serialization
    else {
        Element element = document.createElement("serializable");
        element.setAttribute("classname", object.getClass().getName());

        String objectBytesEncoded = null;
        byte[] objectBytes = null;

        // We write the object to a bytes array
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.flush();
        outputStream.close();

        // Now, we retrieve the object bytes
        objectBytes = outputStream.toByteArray();
        objectBytesEncoded = org.apache.commons.codec.binary.Base64.encodeBase64String(objectBytes);

        CDATASection cDATASection = document.createCDATASection(new String(objectBytesEncoded));
        element.appendChild(cDATASection);

        return element;
    }
}

From source file:jfs.sync.encryption.JFSEncryptedStream.java

private void internalClose() throws IOException {
    delegate.close();/*from w  ww  . ja v a 2s  .  c  o  m*/
    byte[] bytes = delegate.toByteArray();
    final byte[] originalBytes = bytes;
    long l = bytes.length;

    byte marker = COMPRESSION_NONE;

    if (log.isDebugEnabled()) {
        log.debug("close() checking for compressions for");
    } // if

    CompressionThread dt = new CompressionThread(originalBytes) {

        @Override
        public void run() {
            try {
                ByteArrayOutputStream deflaterStream = new ByteArrayOutputStream();
                Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION, true);
                OutputStream dos = new DeflaterOutputStream(deflaterStream, deflater, COMPRESSION_BUFFER_SIZE);
                dos.write(originalBytes);
                dos.close();
                compressedValue = deflaterStream.toByteArray();
            } catch (Exception e) {
                log.error("run()", e);
            } // try/catch
        } // run()

    };

    CompressionThread bt = new CompressionThread(originalBytes) {

        @Override
        public void run() {
            try {
                if (originalBytes.length > BZIP_MAX_LENGTH) {
                    compressedValue = originalBytes;
                } else {
                    ByteArrayOutputStream bzipStream = new ByteArrayOutputStream();
                    OutputStream bos = new BZip2CompressorOutputStream(bzipStream);
                    bos.write(originalBytes);
                    bos.close();
                    compressedValue = bzipStream.toByteArray();
                } // if
            } catch (Exception e) {
                log.error("run()", e);
            } // try/catch
        } // run()

    };

    CompressionThread lt = new CompressionThread(originalBytes) {

        /*
         * // "  -a{N}:  set compression mode - [0, 1], default: 1 (max)\n" +
         * "  -d{N}:  set dictionary - [0,28], default: 23 (8MB)\n"
         * +"  -fb{N}: set number of fast bytes - [5, 273], default: 128\n"
         * +"  -lc{N}: set number of literal context bits - [0, 8], default: 3\n"
         * +"  -lp{N}: set number of literal pos bits - [0, 4], default: 0\n"
         * +"  -pb{N}: set number of pos bits - [0, 4], default: 2\n"
         * +"  -mf{MF_ID}: set Match Finder: [bt2, bt4], default: bt4\n"+"  -eos:   write End Of Stream marker\n");
         */
        private int dictionarySize = 1 << 23;

        private int lc = 3;

        private int lp = 0;

        private int pb = 2;

        private int fb = 128;

        public int algorithm = 2;

        public int matchFinderIndex = 1; // 0, 1, 2

        @Override
        public void run() {
            try {
                Encoder encoder = new Encoder();
                encoder.SetEndMarkerMode(false);
                encoder.SetAlgorithm(algorithm); // Whatever that means
                encoder.SetDictionarySize(dictionarySize);
                encoder.SetNumFastBytes(fb);
                encoder.SetMatchFinder(matchFinderIndex);
                encoder.SetLcLpPb(lc, lp, pb);

                ByteArrayOutputStream lzmaStream = new ByteArrayOutputStream();
                ByteArrayInputStream inStream = new ByteArrayInputStream(originalBytes);

                encoder.WriteCoderProperties(lzmaStream);
                encoder.Code(inStream, lzmaStream, -1, -1, null);
                compressedValue = lzmaStream.toByteArray();
            } catch (Exception e) {
                log.error("run()", e);
            } // try/catch
        } // run()

    };

    dt.start();
    bt.start();
    lt.start();

    try {
        dt.join();
        bt.join();
        lt.join();
    } catch (InterruptedException e) {
        log.error("run()", e);
    } // try/catch

    if (dt.compressedValue.length < l) {
        marker = COMPRESSION_DEFLATE;
        bytes = dt.compressedValue;
        l = bytes.length;
    } // if

    if (lt.compressedValue.length < l) {
        marker = COMPRESSION_LZMA;
        bytes = lt.compressedValue;
        l = bytes.length;
    } // if

    if (bt.compressedValue.length < l) {
        marker = COMPRESSION_BZIP2;
        bytes = bt.compressedValue;
        if (log.isWarnEnabled()) {
            log.warn("close() using bzip2 and saving " + (l - bytes.length) + " bytes.");
        } // if
        l = bytes.length;
    } // if

    if (log.isInfoEnabled()) {
        if (marker == COMPRESSION_NONE) {
            if (log.isInfoEnabled()) {
                log.info("close() using no compression");
            } // if
        } // if
        if (marker == COMPRESSION_LZMA) {
            if (log.isInfoEnabled()) {
                log.info("close() using lzma");
            } // if
        } // if
    } // if

    ObjectOutputStream oos = new ObjectOutputStream(baseOutputStream);
    oos.writeByte(marker);
    oos.writeLong(originalBytes.length);
    oos.flush();
    OutputStream out = baseOutputStream;
    if (cipher != null) {
        out = new CipherOutputStream(out, cipher);
    } // if
    out.write(bytes);
    out.close();
    delegate = null;
    baseOutputStream = null;
}

From source file:maui.main.MauiModelBuilder.java

/** 
 * Saves the extraction model to the file.
 *//*from   ww w.j  a v a  2  s.  c  o m*/
public void saveModel() throws Exception {

    BufferedOutputStream bufferedOut = new BufferedOutputStream(new FileOutputStream(modelName));
    ObjectOutputStream out = new ObjectOutputStream(bufferedOut);
    out.writeObject(mauiFilter);
    out.flush();
    out.close();
}

From source file:com.joliciel.jochre.lexicon.TextFileLexicon.java

public void serialize(File memoryBaseFile) {
    LOG.debug("serialize");
    boolean isZip = false;
    if (memoryBaseFile.getName().endsWith(".zip"))
        isZip = true;//from  w w  w .j  a v a  2s .c  om

    FileOutputStream fos = null;
    ObjectOutputStream out = null;
    ZipOutputStream zos = null;
    try {
        fos = new FileOutputStream(memoryBaseFile);
        if (isZip) {
            zos = new ZipOutputStream(fos);
            zos.putNextEntry(new ZipEntry("lexicon.obj"));
            out = new ObjectOutputStream(zos);
        } else {
            out = new ObjectOutputStream(fos);
        }

        try {
            out.writeObject(this);
        } finally {
            out.flush();
            out.close();
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:com.googlecode.clearnlp.component.AbstractStatisticalComponent.java

protected void saveWeightVector(ZipOutputStream zout, String entryName) throws Exception {
    int i, size = s_models.length;
    ObjectOutputStream oout;

    for (i = 0; i < size; i++) {
        zout.putNextEntry(new ZipEntry(entryName + i));
        oout = new ObjectOutputStream(new BufferedOutputStream(zout));
        s_models[i].saveWeightVector(oout);
        oout.flush();
        zout.closeEntry();//from  w w w . ja v a 2s  . c  o  m
    }
}

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

public void testSaveAndRestore() throws Exception {
    File theFile = null;/*from  ww  w . j  a v a 2s.c  o  m*/
    String theFilename = null;
    boolean saved = false;
    boolean restored = false;
    boolean done = false;
    boolean comparesOk = false;

    AxisConfiguration axisConfiguration = new AxisConfiguration();
    ConfigurationContext configurationContext = new ConfigurationContext(axisConfiguration);

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

    // ---------------------------------------------------------
    // setup an options object to use
    // ---------------------------------------------------------
    Options options = new Options();

    options.setSoapVersionURI(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    options.setExceptionToBeThrownOnSOAPFault(true);
    options.setTimeOutInMilliSeconds(5000L);
    options.setUseSeparateListener(false);
    options.setAction("SoapAction");
    options.setFaultTo(new EndpointReference("http://ws.apache.org/axis2/faultTo"));
    options.setFrom(new EndpointReference("http://ws.apache.org/axis2/from"));
    options.setTo(new EndpointReference("http://ws.apache.org/axis2/to"));
    options.setReplyTo(new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL));

    TransportOutDescription transportOut = new TransportOutDescription("null");
    TransportOutDescription transportOut2 = new TransportOutDescription("happy");
    TransportOutDescription transportOut3 = new TransportOutDescription("golucky");
    transportOut.setSender(new CommonsHTTPTransportSender());
    transportOut2.setSender(new CommonsHTTPTransportSender());
    transportOut3.setSender(new CommonsHTTPTransportSender());
    options.setTransportOut(transportOut);
    axisConfiguration.addTransportOut(transportOut3);
    axisConfiguration.addTransportOut(transportOut2);
    axisConfiguration.addTransportOut(transportOut);

    TransportInDescription transportIn = new TransportInDescription("null");
    TransportInDescription transportIn2 = new TransportInDescription("always");
    TransportInDescription transportIn3 = new TransportInDescription("thebest");
    transportIn.setReceiver(new SimpleHTTPServer());
    transportIn2.setReceiver(new SimpleHTTPServer());
    transportIn3.setReceiver(new SimpleHTTPServer());
    options.setTransportIn(transportIn);
    axisConfiguration.addTransportIn(transportIn2);
    axisConfiguration.addTransportIn(transportIn);
    axisConfiguration.addTransportIn(transportIn3);

    options.setMessageId("msgId012345");

    options.setProperty("key01", "value01");
    options.setProperty("key02", "value02");
    options.setProperty("key03", "value03");
    options.setProperty("key04", "value04");
    options.setProperty("key05", "value05");
    options.setProperty("key06", "value06");
    options.setProperty("key07", "value07");
    options.setProperty("key08", "value08");
    options.setProperty("key09", "value09");
    options.setProperty("key10", "value10");

    // TODO: setup a parent

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

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

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

            long filesize = theFile.length();
            log.debug("OptionsSaveTest:testSaveAndRestore(): file size after save [" + filesize
                    + "]   temp file = [" + theFilename + "]");
        } catch (Exception ex2) {
            if (saved != true) {
                log.debug("OptionsSaveTest:testSaveAndRestore(): error during save [" + ex2.getClass().getName()
                        + " : " + ex2.getMessage() + "]");
                ex2.printStackTrace();
            } else {
                log.debug("OptionsSaveTest:testSaveAndRestore(): error during restore ["
                        + 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("OptionsSaveTest:testSaveAndRestore(): restoring .....");
            restored = false;
            Options options_restored = (Options) inObjStream.readObject();
            inObjStream.close();
            inStream.close();

            options_restored.activate(configurationContext);

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

            comparesOk = options_restored.isEquivalent(options);
            log.debug("OptionsSaveTest:testSaveAndRestore():   Options equivalency [" + comparesOk + "]");
        } catch (Exception ex2) {
            log.debug("OptionsSaveTest:testSaveAndRestore(): error during restore [" + ex2.getClass().getName()
                    + " : " + ex2.getMessage() + "]");
            ex2.printStackTrace();
        }

        assertTrue(restored);

        assertTrue(comparesOk);

        // if the save/restore of the object 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("OptionsSaveTest:testSaveAndRestore():  END ---------------");
}

From source file:org.codehaus.wadi.core.store.DiscStore.java

public void insert(Motable motable) throws Exception {
    File file = new File(sessionStoreDir, motable.getId() + streamer.getSuffixWithDot());

    ObjectOutputStream oos = null;
    FileOutputStream fos = null;//from   w  w  w.  j  av  a 2  s  .co  m
    try {
        fos = new FileOutputStream(file);
        oos = new ObjectOutputStream(fos);

        oos.writeLong(motable.getCreationTime());
        oos.writeLong(motable.getLastAccessedTime());
        oos.writeInt(motable.getMaxInactiveInterval());
        oos.writeObject(motable.getId());
        byte[] bodyAsByteArray = motable.getBodyAsByteArray();
        oos.writeInt(bodyAsByteArray.length);
        oos.flush();
        if (bodyAsByteArray.length > 0) {
            fos.write(bodyAsByteArray);
        }
        if (log.isTraceEnabled()) {
            log.trace("stored disc motable): " + file + ": " + bodyAsByteArray.length + " bytes");
        }
    } catch (Exception e) {
        log.warn("store exclusive disc failed. File [" + file + "]", e);
        throw e;
    } finally {
        try {
            if (oos != null) {
                oos.close();
            }
        } catch (IOException e) {
            log.warn("store exclusive disc) problem. File [" + file + "]", e);
        }
    }
}

From source file:org.nuxeo.ecm.core.redis.contribs.RedisTransientStore.java

protected byte[] serialize(Serializable value) {
    try {//  w  w  w  .j a  va 2  s . c  o  m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(baos);
        out.writeObject(value);
        out.flush();
        out.close();
        return baos.toByteArray();
    } catch (IOException e) {
        throw new NuxeoException(e);
    }
}

From source file:com.splicemachine.derby.serialization.ActivationSerializerTest.java

@Test
public void canSerdeStatementTextLargerThanUTF8Limit() throws Exception {
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    try {//  w  w w .  jav a 2  s .  c  o m
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 65535 + 1; i++) {
            sb.append('A');
        }
        SpliceObserverInstructions.ActivationContext context = new SpliceObserverInstructions.ActivationContext(
                null, true, true, sb.toString(), false, 100, "foo".getBytes());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        context.writeExternal(oos);
        oos.flush();
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        ois = new ObjectInputStream(bais);
        SpliceObserverInstructions.ActivationContext context2 = new SpliceObserverInstructions.ActivationContext();
        context2.readExternal(ois);
        Assert.assertEquals("Serde Incorrect", context.getStatementTxt(), context2.getStatementTxt());
    } finally {
        if (oos != null)
            oos.close();
        if (ois != null)
            ois.close();
    }

}

From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java

public final void encryptObjToOutputStream(final Serializable obj, final OutputStream outputStream)
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidAlgorithmParameterException, IOException {
    if (outputStream instanceof ObjectOutputStream)
        throw new IOException(
                "encryptObjToOutputStream already wraps the outputStream in an ObjectOutputStream, so only pass-in a non-ObjectOutputStream wrapped stream");

    ready();//  w  w  w  . jav  a  2 s.co m
    activecrypts++;
    try {
        final Cipher ecipher = crypter.getEcipher();
        final byte[] salt = ecipher.getIV();
        if (salt == null) {
            outputStream.write(0);
        } else {
            outputStream.write(salt.length);
            for (byte s : salt)
                outputStream.write(s);
        }
        final CipherOutputStream cos = new CipherOutputStream(outputStream, ecipher) {
            /*
             * WebSphere 7 has a known bug with it's implementation of ibmjceprovider.jar
             * concerning writing byte-arrays in a serialized object when the byte-array length
             * is zero.
             * see: http://www.ibm.com/developerworks/forums/thread.jspa?messageID=14597510
             * 
             * Added an override of the CipherOutputStream write method so that it is only called when
             * the byte array has length > 0
             */
            @Override
            public void write(final byte[] b, final int off, final int len) throws IOException {
                if (len > 0) {
                    super.write(b, off, len);
                    //super.flush();
                }
            }
        };
        final ObjectOutputStream oos = new ObjectOutputStream(cos);
        oos.writeObject(obj);
        oos.flush();
        oos.close();
    } finally {
        activecrypts--;
    }
}