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:SaveYourDrawingToFile.java

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == clearBtn) {
        displayList = new Vector();
        repaint();/*from ww  w. j av a 2s  .c om*/
    } else if (e.getSource() == saveBtn) {
        try {
            FileOutputStream fos = new FileOutputStream(pathname);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(displayList);
            oos.flush();
            oos.close();
            fos.close();
        } catch (Exception ex) {
            System.out.println("Trouble writing display list vector");
        }
    } else if (e.getSource() == restoreBtn) {
        try {
            FileInputStream fis = new FileInputStream(pathname);
            ObjectInputStream ois = new ObjectInputStream(fis);
            displayList = (Vector) (ois.readObject());
            ois.close();
            fis.close();
            repaint();
        } catch (Exception ex) {
            System.out.println("Trouble reading display list vector");
        }
    } else if (e.getSource() == quitBtn) {
        setVisible(false);
        dispose();
        System.exit(0);
    }
}

From source file:com.googlecode.jeeunit.example.test.spring.AuthorTest.java

/**
 * Test case for Glassfish <a/*ww w  . jav a  2s  .c o m*/
 * href="https://glassfish.dev.java.net/issues/show_bug.cgi?id=12599">bug #12599</a>.
 * 
 * @throws IOException
 * @throws ClassNotFoundException
 */
@Test
@Ignore
public void serialization() throws IOException, ClassNotFoundException {
    long expectedNumBooks = libraryService.getNumBooks();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(libraryService);
    oos.close();

    byte[] bytes = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    ObjectInputStream ois = new ObjectInputStream(bais);
    Object obj = ois.readObject();
    assertTrue(obj instanceof LibraryService);

    // the deserialized proxy throws a NullPointerException on method invocation
    long numBooks = ((LibraryService) obj).getNumBooks();
    assertEquals(expectedNumBooks, numBooks);
}

From source file:org.ambraproject.model.article.ArticleTypeTest.java

@Test
public void testDeserializedArticleTypeEquality() throws Exception {
    ArticleType art1 = ArticleType/* w  w w  .ja  va  2s .c om*/
            .getArticleTypeForURI(new URI("http://rdf.plos.org/RDF/articleType/Interview"), false);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bout);

    out.writeObject(art1);
    out.flush();

    ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
    ObjectInputStream in = new ObjectInputStream(bin);

    ArticleType art2 = (ArticleType) in.readObject();

    assertTrue(art1 == art2, "Article 1 == Article 2");
    assertTrue(art1.equals(art2), "Article 1 should .equals() Article 2");
}

From source file:com.adobe.acs.commons.httpcache.keys.AbstractCacheKey.java

protected void parentWriteObject(ObjectOutputStream o) throws IOException {
    o.writeObject(authenticationRequirement);
    o.writeObject(uri);/*from   w  w w . ja  v  a 2s  .  com*/
    o.writeObject(resourcePath);
    o.writeObject(hierarchyResourcePath);
}

From source file:net.sf.ehcache.distribution.EventMessageTest.java

/**
 * test serialization and deserialization of EventMessage.
 *//*from w w w  . j  a  v  a2 s .com*/
public void testSerialization() throws IOException, ClassNotFoundException {

    EventMessage eventMessage = new EventMessage(EventMessage.PUT, "key", new Element("key", "element"));

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bout);
    oos.writeObject(eventMessage);
    byte[] serializedValue = bout.toByteArray();
    oos.close();
    EventMessage eventMessage2 = null;
    ByteArrayInputStream bin = new ByteArrayInputStream(serializedValue);
    ObjectInputStream ois = new ObjectInputStream(bin);
    eventMessage2 = (EventMessage) ois.readObject();
    ois.close();

    //Check after Serialization
    assertEquals("key", eventMessage2.getSerializableKey());
    assertEquals("element", eventMessage2.getElement().getObjectValue());
    assertEquals(EventMessage.PUT, eventMessage2.getEvent());
    assertTrue(eventMessage2.isValid());

}

From source file:com.adobe.acs.commons.httpcache.config.impl.keys.KeyValueCacheKey.java

/** For Serialization **/
private void writeObject(ObjectOutputStream o) throws IOException {
    parentWriteObject(o);//from w  w  w  .  j a  v  a2s.com
    o.writeObject(allowedKeyValues);
}

From source file:gnomezgrave.gsyncj.auth.ProfileSettings.java

public void saveSettings() throws IOException, ClassNotFoundException {
    ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(filePath));
    oo.writeObject(this);
    oo.close();/*from w ww  . j  a v a  2s . co  m*/
}

From source file:it.acubelab.smaph.SmaphAnnotator.java

/**
 * Flushes the cache of the Bing api./* w w w.  j  av a  2  s . c om*/
 * 
 * @throws FileNotFoundException
 *             if the file exists but is a directory rather than a regular
 *             file, does not exist but cannot be created, or cannot be
 *             opened for any other reason.
 * @throws IOException
 *             if an I/O error occurred.
 */
public static synchronized void flush() throws FileNotFoundException, IOException {
    if (flushCounter > 0 && resultsCacheFilename != null) {
        SmaphAnnotatorDebugger.out.print("Flushing Bing cache... ");
        new File(resultsCacheFilename).createNewFile();
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(resultsCacheFilename));
        oos.writeObject(url2jsonCache);
        oos.close();
        SmaphAnnotatorDebugger.out.println("Flushing Bing cache Done.");
    }
}

From source file:com.healthmarketscience.rmiio.RemoteStreamServerTest.java

/**
 * Returns the result of serializing and deserializing the given, exported
 * RemoteStub.//  w w  w .j  a v a 2 s  .  co m
 * <p>
 * Note, i'm leaving the paragraph below because i believe it is related to
 * the problem, however, adding the serialization cycle did <b>not</b> solve
 * the hard ref problem (hence that code is still in place).
 * <p>
 * Evidently, something special happens to a RemoteStub when it is
 * serialized.  There were previously issues during testing where
 * RemoteStubs were throwing NoSuchObjectException on the first remote call.
 * In these cases, the server objects were being garbage collected before
 * ever being used.  Eventually, I realized that this was because the
 * RemoteStubs were not being serialized in the test code (because both the
 * client and server are in the same VM).  There was initially a hack in the
 * RemoteStreamServer to get around this problem by temporarily maintaining
 * a hard reference to the server object until the client makes the first
 * successful call (which could cause leaks if the client dies before making
 * the first call).  After determining that the issue was due to
 * serialization, I was able to make the problem disappear by forcing a
 * serialize/deserialize cycle on the RemoteStub in the test code before
 * handing it to the client thread.
 *
 * @param obj RMI stub to force into "remote" mode
 */
@SuppressWarnings("unchecked")
public static <T> T simulateRemote(T obj) throws IOException {
    PipeBuffer.InputStreamAdapter istream = new PipeBuffer.InputStreamAdapter();
    PipeBuffer.OutputStreamAdapter ostream = new PipeBuffer.OutputStreamAdapter();
    istream.connect(ostream);
    ObjectOutputStream objOstream = new ObjectOutputStream(ostream);
    objOstream.writeObject(obj);
    objOstream.close();

    ObjectInputStream objIstream = new ObjectInputStream(istream);
    try {
        obj = (T) objIstream.readObject();
    } catch (ClassNotFoundException e) {
        throw (IOException) ((new IOException()).initCause(e));
    }
    objIstream.close();

    return obj;
}

From source file:com.winvector.logistic.demo.MapReduceLogisticTrain.java

public double run(final String trainFileName, final String formulaStr, final String weightKey,
        final String resultFileName, final int maxNewtonRounds) throws Exception {
    final Log log = LogFactory.getLog(MapReduceLogisticTrain.class);
    log.info("start");
    final Formula formula = new Formula(formulaStr); // force an early parse error if wrong
    final Random rand = new Random();
    final String tmpPrefix = "TMPLR_" + rand.nextLong();
    final Configuration mrConfig = getConf();
    final Path trainFile = new Path(trainFileName);
    final Path resultFile = new Path(resultFileName);
    final String headerLine = WritableUtils.readFirstLine(mrConfig, trainFile);
    final Pattern sepPattern = Pattern.compile("\t");
    final LineBurster burster = new HBurster(sepPattern, headerLine, false);
    mrConfig.set(MapRedScan.BURSTERSERFIELD, SerialUtils.serializableToString(burster));
    final WritableVariableList lConfig = MapRedScan.initialScan(tmpPrefix, mrConfig, trainFile, formulaStr);
    log.info("formula:\t" + formulaStr + "\n" + lConfig.formatState());
    final VariableEncodings defs = new VariableEncodings(lConfig, true, weightKey);
    //final WritableSigmoidLossBinomial underlying = new WritableSigmoidLossBinomial(defs.dim());
    final SigmoidLossMultinomial underlying = new SigmoidLossMultinomial(defs.dim(), defs.noutcomes());
    final MapRedFn f = new MapRedFn(underlying, lConfig, defs.useIntercept(), tmpPrefix, mrConfig, trainFile);
    final ArrayList<VectorFn> fns = new ArrayList<VectorFn>();
    fns.add(f);//from w  w  w  .  j a v a2 s . c  o m
    fns.add(new NormPenalty(f.dim(), 1.0e-5, defs.adaptions));
    final VectorFn sl = new SumFn(fns);
    final VectorOptimizer nwt = new Newton();
    final VEval opt = nwt.maximize(sl, null, maxNewtonRounds);
    log.info("done training");
    log.info("soln vector:\n" + LinUtil.toString(opt.x));
    log.info("soln details:\n" + defs.formatSoln(opt.x));
    {
        final Model model = new Model();
        model.config = defs;
        model.coefs = opt.x;
        model.origFormula = formula;
        log.info("writing " + resultFile);
        final FSDataOutputStream fdo = resultFile.getFileSystem(mrConfig).create(resultFile, true);
        final ObjectOutputStream oos = new ObjectOutputStream(fdo);
        oos.writeObject(model);
        oos.close();
    }
    final MapRedAccuracy sc = new MapRedAccuracy(underlying, lConfig, defs.useIntercept(), tmpPrefix, mrConfig,
            trainFile);
    final long[] trainAccuracy = sc.score(opt.x);
    final double accuracy = trainAccuracy[0] / (double) trainAccuracy[1];
    log.info("train accuracy: " + trainAccuracy[0] + "/" + trainAccuracy[1] + "\t" + accuracy);
    return accuracy;
}