Example usage for java.io ObjectOutputStream close

List of usage examples for java.io ObjectOutputStream close

Introduction

In this page you can find the example usage for java.io ObjectOutputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes the stream.

Usage

From source file:it.polito.elite.dog.core.library.model.DeviceStatus.java

/**
 * Serialize a DeviceStatus into a String using a byte encoding
 * @param object/* www. j a  v a  2 s .  c o m*/
 *          a DeviceStatus ready for serialization
 * @return a byte encoded String of a DeviceStatus
 * @throws IOException 
 */
public static String serializeToString(DeviceStatus object) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream encoder = new ObjectOutputStream(baos);
    //serialize the DeviceStatus
    encoder.writeObject(object);
    //flush and close everything
    encoder.flush();
    baos.flush();
    encoder.close();
    baos.close();
    return new String(Base64.encodeBase64(baos.toByteArray()));
}

From source file:com.mirth.connect.connectors.jms.JmsMessageUtils.java

/**
 * @param message//from  w ww .ja  v  a  2 s.co  m
 *            the message to receive the bytes from. Note this only works
 *            for TextMessge, ObjectMessage, StreamMessage and BytesMessage.
 * @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 failiare occurs while stream and converting the message
 *             data
 */
public static byte[] getBytesFromMessage(Message message) throws JMSException, IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024 * 2];
    int len;

    if (message instanceof BytesMessage) {
        BytesMessage bMsg = (BytesMessage) message;
        // put message in read-only mode
        bMsg.reset();
        while ((len = bMsg.readBytes(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
    } else if (message instanceof StreamMessage) {
        StreamMessage sMsg = (StreamMessage) message;
        sMsg.reset();
        while ((len = sMsg.readBytes(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
    } else if (message instanceof ObjectMessage) {
        ObjectMessage oMsg = (ObjectMessage) message;
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(bs);
        os.writeObject(oMsg.getObject());
        os.flush();
        baos.write(bs.toByteArray());
        os.close();
        bs.close();
    } else if (message instanceof TextMessage) {
        TextMessage tMsg = (TextMessage) message;
        baos.write(tMsg.getText().getBytes());
    } else {
        throw new JMSException("Cannot get bytes from Map Message");
    }

    baos.flush();
    byte[] bytes = baos.toByteArray();
    baos.close();
    return bytes;
}

From source file:net.myrrix.common.io.IOUtils.java

/**
 * Serializes an object, with gzip compression, to a given file.
 *//*  w  w  w .ja v a 2  s  .co m*/
public static <T extends Serializable> void writeObjectToFile(File f, T t) throws IOException {
    Preconditions.checkArgument(f.getName().endsWith(".gz"), "File should end in .gz: %s", f);
    ObjectOutputStream out = new ObjectOutputStream(buildGZIPOutputStream(f));
    try {
        out.writeObject(t);
    } finally {
        out.close();
    }
}

From source file:Main.java

public static boolean saveObject(Context cxt, Serializable obj, String file) {
    FileOutputStream fos = null;/*  w w w .ja va 2 s .co  m*/
    ObjectOutputStream oos = null;

    try {
        fos = cxt.openFileOutput(file, Context.MODE_PRIVATE);
        oos = new ObjectOutputStream(fos);
        oos.writeObject(obj);
        oos.flush();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            oos.close();
        } catch (Exception e) {
        }
        try {
            fos.close();
        } catch (Exception e) {
        }
    }
}

From source file:Main.java

public static void put_(String key, Serializable value) {
    ByteArrayOutputStream baos = null;
    ObjectOutputStream oos = null;
    try {//  w w w. ja v  a 2  s . c o m
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(value);
        byte[] data = baos.toByteArray();
        put(key, data);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            oos.close();
        } catch (IOException e) {
        }
    }
}

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  av a 2s.com*/
            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:Main.java

public static boolean saveObject(Context context, Serializable ser, String file) {
    FileOutputStream fos = null;/* w ww. j  a va  2  s .c o  m*/
    ObjectOutputStream oos = null;
    try {
        fos = context.openFileOutput(file, Context.MODE_PRIVATE);
        oos = new ObjectOutputStream(fos);
        oos.writeObject(ser);
        oos.flush();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            oos.close();
        } catch (Exception e) {
        }
        try {
            fos.close();
        } catch (Exception e) {
        }
    }
}

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

public static byte[] getRecordBytes(AvroBulletRecord record) {
    try {//from   w w w .j  ava  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:de.tud.cs.se.flashcards.persistence.Store.java

public static void saveSeries(FlashcardSeries series, File file) throws IOException {

    ObjectOutputStream oout = null;
    try {/*from w  w w  .  j av  a  2 s.  c  o m*/
        oout = new ObjectOutputStream(new FileOutputStream(file));
        oout.writeInt(series.getSize());
        for (int i = series.getSize() - 1; i >= 0; i -= 1) {
            oout.writeObject(series.getElementAt(i));
        }
    } finally {
        if (oout != null)
            oout.close();
    }

}

From source file:Main.java

private static byte[] serializable2Bytes(final Serializable serializable) {
    if (serializable == null)
        return null;
    ByteArrayOutputStream baos;/*from   w ww  .j  av  a  2  s .  com*/
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(baos = new ByteArrayOutputStream());
        oos.writeObject(serializable);
        return baos.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (oos != null) {
                oos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}