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.alta189.deskbin.util.CryptUtils.java

private static boolean writeKey(SecretKey key) {
    FileOutputStream fos = null;//from  w  ww .  j  a  va2s .  c  om
    ObjectOutputStream out = null;
    try {
        if (keyFile.getParentFile() != null) {
            keyFile.getParentFile().mkdirs();
        }
        fos = new FileOutputStream(keyFile);
        out = new ObjectOutputStream(fos);
        out.writeObject(key);
        out.flush();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(out);
    }
    return false;
}

From source file:at.ac.tuwien.dsg.comot.m.common.Utils.java

public static Object deepCopy(Object oldObj) throws IOException, ClassNotFoundException {

    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;

    try {//from   ww  w  .  j  a v  a 2 s . c o m
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        oos = new ObjectOutputStream(bos);
        oos.writeObject(oldObj);
        oos.flush();

        ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));

        return ois.readObject();

    } finally {
        if (oos != null)
            oos.close();
        if (ois != null)
            ois.close();
    }
}

From source file:com.cooksys.postmaster.PostmasterModelSingleton.java

public static void writeToFile() {
    if (_instance != null) { //make sure there is an instance first
        File file = new File(POSTMASTER_DATA_FILE);
        try {/*from   w  w  w. ja va  2s . c  o  m*/
            //convert messageConsole to serializable format
            _instance.messageConsoleSerializable = _instance.messageConsole.getValue();

            //serialize the object to a file
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(_instance);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(PostmasterModelSingleton.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PostmasterModelSingleton.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:io.hops.experiments.results.compiler.InterleavedBMResultsAggregator.java

public static InterleavedBMResults processInterleavedResults(Collection<Object> responses, Configuration args)
        throws FileNotFoundException, IOException, InterruptedException {
    Map<BenchmarkOperations, double[][]> allOpsPercentiles = new HashMap<BenchmarkOperations, double[][]>();
    System.out.println("Processing the results ");
    DescriptiveStatistics successfulOps = new DescriptiveStatistics();
    DescriptiveStatistics failedOps = new DescriptiveStatistics();
    DescriptiveStatistics speed = new DescriptiveStatistics();
    DescriptiveStatistics duration = new DescriptiveStatistics();
    DescriptiveStatistics opsLatency = new DescriptiveStatistics();
    DescriptiveStatistics noOfNNs = new DescriptiveStatistics();
    for (Object obj : responses) {
        if (!(obj instanceof InterleavedBenchmarkCommand.Response)) {
            throw new IllegalStateException("Wrong response received from the client");
        } else {//  w  w  w . j  a  va2 s. c om
            InterleavedBenchmarkCommand.Response response = (InterleavedBenchmarkCommand.Response) obj;
            successfulOps.addValue(response.getTotalSuccessfulOps());
            failedOps.addValue(response.getTotalFailedOps());
            speed.addValue(response.getOpsPerSec());
            duration.addValue(response.getRunTime());
            opsLatency.addValue(response.getAvgOpLatency());
            noOfNNs.addValue(response.getNnCount());
        }
    }

    //write the response objects to files. 
    //these files are processed by CalculatePercentiles.java
    int responseCount = 0;
    for (Object obj : responses) {
        if (!(obj instanceof InterleavedBenchmarkCommand.Response)) {
            throw new IllegalStateException("Wrong response received from the client");
        } else {
            String filePath = args.getResultsDir();
            if (!filePath.endsWith("/")) {
                filePath += "/";
            }
            InterleavedBenchmarkCommand.Response response = (InterleavedBenchmarkCommand.Response) obj;
            filePath += "ResponseRawData" + responseCount++ + ConfigKeys.RAW_RESPONSE_FILE_EXT;
            System.out.println("Writing Rwaw results to " + filePath);
            FileOutputStream fout = new FileOutputStream(filePath);
            ObjectOutputStream oos = new ObjectOutputStream(fout);
            oos.writeObject(response);
            oos.close();
        }
    }

    InterleavedBMResults result = new InterleavedBMResults(args.getNamenodeCount(),
            (int) Math.floor(noOfNNs.getMean()), args.getNdbNodesCount(), args.getInterleavedBmWorkloadName(),
            (successfulOps.getSum() / ((duration.getMean() / 1000))), (duration.getMean() / 1000),
            (successfulOps.getSum()), (failedOps.getSum()), allOpsPercentiles, opsLatency.getMean());

    //    // failover testing
    //    if(args.testFailover()){
    //      if(responses.size() != 1){
    //        throw new UnsupportedOperationException("Currently we only support failover testing for one slave machine");
    //      }
    //
    //      String prefix = args.getBenchMarkFileSystemName().toString();
    //      if(args.getBenchMarkFileSystemName() == BenchMarkFileSystemName.HopsFS){
    //        prefix+="-"+args.getNameNodeSelectorPolicy();
    //      }
    //
    //      final String outputFolder = args.getResultsDir();
    //      InterleavedBenchmarkCommand.Response response = (InterleavedBenchmarkCommand.Response)responses.iterator().next();
    //
    //
    //      StringBuilder sb = new StringBuilder();
    //      for(String data : response.getFailOverLog()){
    //        sb.append(data).append("\n");
    //      }
    //
    //      String datFile = prefix+"-failover.dat";
    //      CompileResults.writeToFile(outputFolder+"/"+datFile, sb.toString(), false);
    //
    //
    //      StringBuilder plot = new StringBuilder("set terminal postscript eps enhanced color font \"Helvetica,18\"  #monochrome\n");
    //      plot.append( "set output '| ps2pdf - failover.pdf'\n");
    //      plot.append( "#set size 1,0.75 \n ");
    //      plot.append( "set ylabel \"ops/sec\" \n");
    //      plot.append( "set xlabel \"Time (sec)\" \n");
    //      plot.append( "set format y \"%.0s%c\"\n");
    //
    //
    //      StringBuilder sbx = new StringBuilder();
    //      String oldPt = "";
    //      for(String data : response.getFailOverLog()){
    //
    //        if(data.startsWith("#")) {
    //          StringTokenizer st = new StringTokenizer(oldPt);
    //          long time = Long.parseLong(st.nextToken());
    //          long spd = Long.parseLong(st.nextToken());
    //          sbx.append("set label 'NN-Restart' at "+time+","+spd+" rotate by 270").append("\n");
    //        }
    //        oldPt = data;
    //      }
    //      plot.append(sbx.toString());
    //
    //
    //      plot.append( "plot '"+datFile+"' with linespoints ls 1");
    //      CompileResults.writeToFile(outputFolder+"/"+prefix+"-failover.gnu", plot.toString(), false);
    //
    //    }

    return result;
}

From source file:com.amazon.sqs.javamessaging.message.SQSObjectMessage.java

/**
 * Serialize the <code>Serializable</code> object to <code>String</code>.
 *//* ww w.j  av  a 2  s  . c o m*/
protected static String serialize(Serializable serializable) throws JMSException {
    if (serializable == null) {
        return null;
    }
    String serializedString;
    ObjectOutputStream objectOutputStream = null;
    try {
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        objectOutputStream = new ObjectOutputStream(bytesOut);
        objectOutputStream.writeObject(serializable);
        objectOutputStream.flush();
        serializedString = Base64.encodeAsString(bytesOut.toByteArray());
    } catch (IOException e) {
        LOG.error("IOException: cannot serialize objectMessage", e);
        throw convertExceptionToMessageFormatException(e);
    } finally {
        if (objectOutputStream != null) {
            try {
                objectOutputStream.close();
            } catch (IOException e) {
                LOG.warn(e.getMessage());
            }
        }
    }
    return serializedString;
}

From source file:com.yahoo.bullet.record.AvroBulletRecordTest.java

public static byte[] getRecordBytes(AvroBulletRecord record) {
    try {/*from  ww  w.j  av  a  2 s  . co  m*/
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        ObjectOutputStream outputStream = new ObjectOutputStream(byteStream);
        outputStream.writeObject(record);
        outputStream.close();
        return byteStream.toByteArray();
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);

    }
}

From source file:Main.java

/**
 * Serialises a <code>Paint</code> object.
 *
 * @param paint  the paint 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 w w  w . j  a  v a  2 s  .c o m
public static void writePaint(final Paint paint, final ObjectOutputStream stream) throws IOException {

    if (stream == null) {
        throw new IllegalArgumentException("Null 'stream' argument.");
    }
    if (paint != null) {
        stream.writeBoolean(false);
        stream.writeObject(paint.getClass());
        if (paint instanceof Serializable) {
            stream.writeObject(paint);
        } else if (paint instanceof GradientPaint) {
            final GradientPaint gp = (GradientPaint) paint;
            stream.writeFloat((float) gp.getPoint1().getX());
            stream.writeFloat((float) gp.getPoint1().getY());
            stream.writeObject(gp.getColor1());
            stream.writeFloat((float) gp.getPoint2().getX());
            stream.writeFloat((float) gp.getPoint2().getY());
            stream.writeObject(gp.getColor2());
            stream.writeBoolean(gp.isCyclic());
        }
    } else {
        stream.writeBoolean(true);
    }

}

From source file:com.couchbase.client.java.transcoder.TranscoderUtils.java

/**
 * Serializes the input into a ByteBuf.//from   w  ww  . j a  v a2 s .  c  o  m
 *
 * @param serializable the object to serialize.
 * @return the serialized object.
 * @throws Exception if something goes wrong during serialization.
 */
public static ByteBuf serialize(final Serializable serializable) throws Exception {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ;
    ObjectOutputStream os = new ObjectOutputStream(bos);
    os.writeObject(serializable);

    byte[] serialized = bos.toByteArray();
    os.close();
    bos.close();
    return Unpooled.buffer().writeBytes(serialized);
}

From source file:com.ery.ertc.estorm.util.ToolUtil.java

public static String serialObject(Object obj, boolean isGzip, boolean urlEnCode) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
    objectOutputStream.writeObject(obj);
    String serStr = null;/*from w  ww .  j a v a  2s  .co  m*/
    byte[] bts = null;
    if (isGzip) {
        bts = GZIPUtils.zip(byteArrayOutputStream.toByteArray());
    } else {
        bts = byteArrayOutputStream.toByteArray();
    }
    if (urlEnCode) {
        serStr = new String(org.apache.commons.codec.binary.Base64.encodeBase64(bts), "ISO-8859-1");
    } else {
        serStr = new String(bts, "ISO-8859-1");
    }
    objectOutputStream.close();
    byteArrayOutputStream.close();
    return serStr;
}

From source file:com.fengduo.bee.commons.util.ObjectUtils.java

/**
 * ?/*from   ww  w.  java 2  s . c  om*/
 * 
 * @param object
 * @return
 */
public static byte[] serialize(Object object) {
    ObjectOutputStream oos = null;
    ByteArrayOutputStream baos = null;
    try {
        if (object != null) {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            return baos.toByteArray();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}