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.glom.web.server.Utils.java

static public Object deepCopy(final Object oldObj) {
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;

    try {/* w ww.j  ava2s.c o  m*/
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(bos);
        // serialize and pass the object
        oos.writeObject(oldObj);
        oos.flush();
        final ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray());
        ois = new ObjectInputStream(bin);

        // return the new object
        return ois.readObject();
    } catch (final Exception e) {
        System.out.println("Exception in deepCopy:" + e);
        return null;
    } finally {
        try {
            oos.close();
            ois.close();
        } catch (final IOException e) {
            System.out.println("Exception in deepCopy during finally: " + e);
            return null;
        }
    }
}

From source file:org.apache.lens.ml.impl.ModelLoader.java

/**
 * Save test report./*from w w w.  j  av  a  2 s . c  o  m*/
 *
 * @param conf   the conf
 * @param report the report
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void saveTestReport(Configuration conf, MLTestReport report) throws IOException {
    Path reportDir = new Path(conf.get(TEST_REPORT_BASE_DIR, TEST_REPORT_BASE_DIR_DEFAULT));
    FileSystem fs = reportDir.getFileSystem(conf);

    if (!fs.exists(reportDir)) {
        log.info("Creating test report dir {}", reportDir.toUri().toString());
        fs.mkdirs(reportDir);
    }

    Path algoDir = new Path(reportDir, report.getAlgorithm());

    if (!fs.exists(algoDir)) {
        log.info("Creating algorithm report dir {}", algoDir.toUri().toString());
        fs.mkdirs(algoDir);
    }

    ObjectOutputStream reportOutputStream = null;
    Path reportSaveLocation;
    try {
        reportSaveLocation = new Path(algoDir, report.getReportID());
        reportOutputStream = new ObjectOutputStream(fs.create(reportSaveLocation));
        reportOutputStream.writeObject(report);
        reportOutputStream.flush();
    } catch (IOException ioexc) {
        log.error("Error saving test report {}", report.getReportID(), ioexc);
        throw ioexc;
    } finally {
        IOUtils.closeQuietly(reportOutputStream);
    }
    log.info("Saved report {} at location {}", report.getReportID(), reportSaveLocation.toUri());
}

From source file:org.apache.lens.ml.ModelLoader.java

/**
 * Save test report./* w ww.java  2  s.com*/
 *
 * @param conf   the conf
 * @param report the report
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void saveTestReport(Configuration conf, MLTestReport report) throws IOException {
    Path reportDir = new Path(conf.get(TEST_REPORT_BASE_DIR, TEST_REPORT_BASE_DIR_DEFAULT));
    FileSystem fs = reportDir.getFileSystem(conf);

    if (!fs.exists(reportDir)) {
        LOG.info("Creating test report dir " + reportDir.toUri().toString());
        fs.mkdirs(reportDir);
    }

    Path algoDir = new Path(reportDir, report.getAlgorithm());

    if (!fs.exists(algoDir)) {
        LOG.info("Creating algorithm report dir " + algoDir.toUri().toString());
        fs.mkdirs(algoDir);
    }

    ObjectOutputStream reportOutputStream = null;
    Path reportSaveLocation;
    try {
        reportSaveLocation = new Path(algoDir, report.getReportID());
        reportOutputStream = new ObjectOutputStream(fs.create(reportSaveLocation));
        reportOutputStream.writeObject(report);
        reportOutputStream.flush();
    } catch (IOException ioexc) {
        LOG.error("Error saving test report " + report.getReportID(), ioexc);
        throw ioexc;
    } finally {
        IOUtils.closeQuietly(reportOutputStream);
    }
    LOG.info("Saved report " + report.getReportID() + " at location " + reportSaveLocation.toUri());
}

From source file:com.kellerkindt.scs.utilities.Utilities.java

/**
 * Serializes the MetaData of an ItemStack
 * and marshals it then in a String/*  w ww .  ja  v  a2  s  . c o  m*/
 * @param itemMeta The MetaData so save
 * @return The marshaled ItemStack as String
 * @throws IOException On any internal Exception
 */
public static String toHexString(ItemMeta itemMeta) throws IOException {

    // create streams
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);

    // write map
    oos.writeObject(itemMeta.serialize());
    oos.flush();

    // toHexString
    return new HexBinaryAdapter().marshal(baos.toByteArray());
}

From source file:org.mule.transport.jms.JmsMessageUtils.java

/**
 * @param message the message to receive the bytes from. Note this only works for
 *                TextMessge, ObjectMessage, StreamMessage and BytesMessage.
 * @param jmsSpec indicates the JMS API version, either
 *                {@link JmsConstants#JMS_SPECIFICATION_102B} or
 *                {@link JmsConstants#JMS_SPECIFICATION_11}. Any other value
 *                including <code>null</code> is treated as fallback to
 *                {@link JmsConstants#JMS_SPECIFICATION_102B}.
 * @return a byte array corresponding with the message payload
 * @throws JMSException        if the message can't be read or if the message passed is
 *                             a MapMessage
 * @throws java.io.IOException if a failure occurs while reading the stream and
 *                             converting the message data
 *///  ww w  . j  ava2  s  .c o m
public static byte[] toByteArray(Message message, String jmsSpec, String encoding)
        throws JMSException, IOException {
    if (message instanceof BytesMessage) {
        BytesMessage bMsg = (BytesMessage) message;
        bMsg.reset();

        if (JmsConstants.JMS_SPECIFICATION_11.equals(jmsSpec)) {
            long bmBodyLength = bMsg.getBodyLength();
            if (bmBodyLength > Integer.MAX_VALUE) {
                throw new JMSException("Size of BytesMessage exceeds Integer.MAX_VALUE; "
                        + "please consider using JMS StreamMessage instead");
            }

            if (bmBodyLength > 0) {
                byte[] bytes = new byte[(int) bmBodyLength];
                bMsg.readBytes(bytes);
                return bytes;
            } else {
                return ArrayUtils.EMPTY_BYTE_ARRAY;
            }
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
            byte[] buffer = new byte[4096];
            int len;

            while ((len = bMsg.readBytes(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }

            if (baos.size() > 0) {
                return baos.toByteArray();
            } else {
                return ArrayUtils.EMPTY_BYTE_ARRAY;
            }
        }
    } else if (message instanceof StreamMessage) {
        StreamMessage sMsg = (StreamMessage) message;
        sMsg.reset();

        ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
        byte[] buffer = new byte[4096];
        int len;

        while ((len = sMsg.readBytes(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }

        return baos.toByteArray();
    } else if (message instanceof ObjectMessage) {
        ObjectMessage oMsg = (ObjectMessage) message;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(baos);
        os.writeObject(oMsg.getObject());
        os.flush();
        os.close();
        return baos.toByteArray();
    } else if (message instanceof TextMessage) {
        TextMessage tMsg = (TextMessage) message;
        String tMsgText = tMsg.getText();

        if (null == tMsgText) {
            // Avoid creating new instances of byte arrays, even empty ones. The
            // load on this part of the code can be high.
            return ArrayUtils.EMPTY_BYTE_ARRAY;
        } else {
            return tMsgText.getBytes(encoding);
        }
    } else {
        throw new JMSException("Cannot get bytes from Map Message");
    }
}

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

public static OutputStream createOutputStream(long compressionLimit, OutputStream baseOutputStream, long length,
        Cipher cipher) throws IOException {
    OutputStream result = null;//w  w w  .  j a  v  a 2 s . com
    Runtime runtime = Runtime.getRuntime();
    long freeMem = runtime.totalMemory() / SPACE_RESERVE;
    if (length >= freeMem) {
        if (log.isWarnEnabled()) {
            log.warn("JFSEncryptedStream.createOutputStream() GC " + freeMem + "/" + runtime.maxMemory());
        } // if
        runtime.gc();
        freeMem = runtime.totalMemory() / SPACE_RESERVE;
    } // if
    if ((length < compressionLimit) && (length < freeMem)) {
        result = new JFSEncryptedStream(baseOutputStream, cipher);
    } else {
        if (length < freeMem) {
            if (log.isInfoEnabled()) {
                log.info("JFSEncryptedStream.createOutputStream() not compressing");
            } // if
        } else {
            if (log.isWarnEnabled()) {
                log.warn("JFSEncryptedStream.createOutputStream() due to memory constraints (" + length + "/"
                        + freeMem + ") not compressing");
            } // if
        } // if
        ObjectOutputStream oos = new ObjectOutputStream(baseOutputStream);
        oos.writeByte(COMPRESSION_NONE);
        oos.writeLong(length);
        oos.flush();
        result = baseOutputStream;
        if (cipher != null) {
            result = new CipherOutputStream(result, cipher);
        } // if
    } // if
    return result;
}

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' /*from   w  w w  .  j av a2 s. 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:org.openml.weka.algorithm.WekaAlgorithm.java

public static File classifierSerializedToFile(Classifier cls, Integer task_id) throws IOException {
    File file = File.createTempFile("WekaSerialized_" + cls.getClass().getName(), ".model");
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
    oos.writeObject(cls);/*www .j  av  a2 s. c om*/
    oos.flush();
    oos.close();
    file.deleteOnExit();
    return file;
}

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.ibm.pi.beacon.PIBeaconSensor.java

private static void savePIAPIAdapter(Context context, PIAPIAdapter adapter) {
    ObjectOutputStream adapterStream = null;
    try {/*w w w.ja v a  2  s  . co m*/
        adapterStream = new ObjectOutputStream(
                context.openFileOutput("piapiadapter.data", Context.MODE_PRIVATE));
        adapterStream.writeObject(adapter);
        adapterStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (adapterStream != null) {
            try {
                adapterStream.flush();
                adapterStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}