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:com.enonic.cms.core.portal.instruction.PostProcessInstruction.java

public final String serialize() throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream dout = new ObjectOutputStream(out);

    writeExternal(dout);//w w w  .ja va  2  s.  c  o m

    dout.close();
    out.close();

    return new String(Base64.encodeBase64(out.toByteArray()));
}

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 ww .  j ava  2  s  .co  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;
}

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  a2 s.c  om*/
 * <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.twosigma.beaker.cpp.utils.CppKernel.java

public int execute(String mainCell, String type, ArrayList<String> otherCells) {
    String tmpDir = System.getenv("beaker_tmp_dir");

    for (String cell : otherCells) {
        cLoad(tmpDir + "/lib" + cell + ".so");
    }/*from w w  w.j  a v a  2s .c  om*/

    Object ret = cLoadAndRun(tmpDir + "/lib" + mainCell + ".so", type);

    try {
        FileOutputStream file = new FileOutputStream(tmpDir + "/" + mainCell + ".result");
        BufferedOutputStream buffer = new BufferedOutputStream(file);
        ObjectOutputStream output = new ObjectOutputStream(buffer);
        output.writeObject(ret);
        output.close();
    } catch (IOException ex) {
        logger.warn("Could not load file");
        return 1;
    }

    return 0;
}

From source file:com.servioticy.queueclient.SimpleQueueClient.java

void writeQueue(LinkedList<Object> queue) throws IOException {
    File file = new File(filePath);
    file.delete();/*  ww w .  j a va2s. c o  m*/
    file.createNewFile();
    FileOutputStream fileOut = new FileOutputStream(file);
    ObjectOutputStream out = new ObjectOutputStream(fileOut);
    out.writeObject(queue);
    out.close();
    fileOut.close();
}

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

/**
 * Flushes the cache of the Bing api.//w ww  . j  av a  2s .c o m
 * 
 * @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.googlecode.DownloadCache.java

private void saveIndex() throws Exception {
    if (this.basedir.exists() && !this.basedir.isDirectory()) {
        throw new Exception("Cannot use " + this.basedir + " as cache directory: file exists");
    }/*www.  jav a2 s  .c  om*/
    if (!this.basedir.exists()) {
        this.basedir.mkdirs();
    }
    if (!this.indexFile.exists()) {
        this.indexFile.createNewFile();
    }
    FileOutputStream out = new FileOutputStream(this.indexFile);
    ObjectOutputStream res = new ObjectOutputStream(out);
    res.writeObject(index);
    res.close();
}

From source file:SaveYourDrawingToFile.java

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == clearBtn) {
        displayList = new Vector();
        repaint();/*from  ww  w.j a  v  a2 s . co m*/
    } 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.scoredev.scores.HighScore.java

public void setHighScore(final int score) throws IOException {
    //check permission first
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new HighScorePermission(gameName));
    }/*w  ww.ja  va2s . co m*/

    // need a doPrivileged block to manipulate the file
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IOException {
                Hashtable scores = null;
                // try to open the existing file. Should have a locking
                // protocol (could use File.createNewFile).
                try {
                    FileInputStream fis = new FileInputStream(highScoreFile);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    scores = (Hashtable) ois.readObject();
                } catch (Exception e) {
                    // ignore, try and create new file
                }

                // if scores is null, create a new hashtable
                if (scores == null)
                    scores = new Hashtable(13);

                // update the score and save out the new high score
                scores.put(gameName, new Integer(score));
                FileOutputStream fos = new FileOutputStream(highScoreFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(scores);
                oos.close();
                return null;
            }
        });
    } catch (PrivilegedActionException pae) {
        throw (IOException) pae.getException();
    }
}

From source file:com.jaspersoft.jasperserver.core.util.TolerantObjectWrapper.java

/**
 * tests whether an object is serializable
 *
 * return boolean representing if it is serializable
 *
 * *///w  w  w. j a  va 2 s.  c om
private boolean testIsSerializable(Object obj) throws IOException {

    NullOutputStream nos = new NullOutputStream();
    ObjectOutputStream oos = null;

    try {
        oos = new ObjectOutputStream(nos);
        oos.writeObject(obj);
        oos.close();
        nos.close();

    } catch (Exception err) {
        return false;
    }
    return true;
}