Example usage for java.io ObjectInputStream close

List of usage examples for java.io ObjectInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the input stream.

Usage

From source file:com.datatorrent.stram.FSRecoveryHandler.java

@Override
public Object restore() throws IOException {
    FileContext fc = FileContext.getFileContext(fs.getUri());

    // recover from wherever it was left
    if (fc.util().exists(snapshotBackupPath)) {
        LOG.warn("Incomplete checkpoint, reverting to {}", snapshotBackupPath);
        fc.rename(snapshotBackupPath, snapshotPath, Rename.OVERWRITE);

        // combine logs (w/o append, create new file)
        Path tmpLogPath = new Path(basedir, "log.combined");
        FSDataOutputStream fsOut = fc.create(tmpLogPath, EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE));
        try {/*ww  w  .java  2 s. com*/
            FSDataInputStream fsIn = fc.open(logBackupPath);
            try {
                IOUtils.copy(fsIn, fsOut);
            } finally {
                fsIn.close();
            }

            fsIn = fc.open(logPath);
            try {
                IOUtils.copy(fsIn, fsOut);
            } finally {
                fsIn.close();
            }
        } finally {
            fsOut.close();
        }

        fc.rename(tmpLogPath, logPath, Rename.OVERWRITE);
        fc.delete(logBackupPath, false);
    } else {
        // we have log backup, but no checkpoint backup
        // failure between log rotation and writing checkpoint
        if (fc.util().exists(logBackupPath)) {
            LOG.warn("Found {}, did checkpointing fail?", logBackupPath);
            fc.rename(logBackupPath, logPath, Rename.OVERWRITE);
        }
    }

    if (!fc.util().exists(snapshotPath)) {
        LOG.debug("No existing checkpoint.");
        return null;
    }

    LOG.debug("Reading checkpoint {}", snapshotPath);
    InputStream is = fc.open(snapshotPath);
    // indeterministic class loading behavior
    // http://stackoverflow.com/questions/9110677/readresolve-not-working-an-instance-of-guavas-serializedform-appears
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    ObjectInputStream ois = new ObjectInputStream(is) {
        @Override
        protected Class<?> resolveClass(ObjectStreamClass objectStreamClass)
                throws IOException, ClassNotFoundException {
            return Class.forName(objectStreamClass.getName(), true, loader);
        }
    };
    //ObjectInputStream ois = new ObjectInputStream(is);
    try {
        return ois.readObject();
    } catch (ClassNotFoundException cnfe) {
        throw new IOException("Failed to read checkpointed state", cnfe);
    } finally {
        ois.close();
    }
}

From source file:com.holycityaudio.SpinCAD.SpinCADFile.java

public SpinCADBank fileReadBank(File fileName) throws IOException, ClassNotFoundException {
    // Object deserialization 
    FileInputStream fis = new FileInputStream(fileName);
    ObjectInputStream ois = new ObjectInputStream(fis);
    SpinCADBank b = (SpinCADBank) ois.readObject();
    ois.close();
    return b;//from  w w w. jav a  2 s. c  o  m
}

From source file:de.forsthaus.example.TestCtrl.java

public void onClick$BtnSerializeFC(Event event) throws InterruptedException {

    FieldComparator fcOld;//from  w ww .j a v  a 2 s  .c o  m
    FieldComparator fcNew;

    fcOld = new FieldComparator("TestColumn", false);

    // Serialize the original class object
    try {
        final FileOutputStream fo = new FileOutputStream("cde.tmp");
        final ObjectOutputStream so = new ObjectOutputStream(fo);
        so.writeObject(fcOld);
        so.flush();
        so.close();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

    // Deserialize in to new class object
    try {
        final FileInputStream fi = new FileInputStream("cde.tmp");
        final ObjectInputStream si = new ObjectInputStream(fi);
        fcNew = (FieldComparator) si.readObject();
        System.out.println(fcNew.getOrderBy());
        si.close();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

    final String longString1 = "Hello. I'm a long string\n\n Hello i'm the second line.\n hjdgf hgjhdgsfhsd jhgjd sfjgj gfdsfg\n\n kjdsds fjk jdsh fjdhfdjsh djsfh jkhjdsf jds jds f ";
    final String longString2 = "Hello. I'm a long string\n\n Hello i'm the second line.\n hjdgf hgjhdgsfhsd jhgjd sfjgj gfdsfg ooiji ojre iorjioj girirjgijr griojgiorjg iorjgir ";
    final String longString3 = "Hello. I'm a long string\n\n Hello i'm the second line.\n hjdgf hgjhdgsfhsd jhgjd sfjgj gfdsfg rok reok kre grigoirejg eopijsj jgioe gjiojg rei re";
    final String longString4 = "Hello. I'm a long string\n\n Hello i'm the second line.\n hjdgf hgjhdgsfhsd jhgjd sfjgj gfdsfg rpokg orkeopkg ok rkropk gpor oprek grekopg kropkpor ";
    final String longString5 = "Hello. I'm a long string\n\n Hello i'm the second line.\n hjdgf hgjhdgsfhsd jhgjd sfjgj gfdsfg rplg reo ropekpo rekerop ok orek oprek porkeop re ";
    final String longString6 = "Hello. I'm a long string\n\n Hello i'm the second line.\n hjdgf hgjhdgsfhsd jhgjd sfjgj gfdsfg pork oprkk opre opkrepok oprek kopre oprekpo rkeop rke ";
    final String message = longString1 + longString2 + longString3 + longString4 + longString5 + longString6;
    final String title = Labels.getLabel("message.Information");
    MultiLineMessageBox.doSetTemplate();
    MultiLineMessageBox.show(message, title, MultiLineMessageBox.OK, "INFORMATION", true);

}

From source file:org.bonitasoft.engine.api.HTTPServerAPI.java

@SuppressWarnings("unchecked")
private <T> T fromXML(final String object, final XStream xstream) {
    final StringReader xmlReader = new StringReader(object);
    ObjectInputStream in = null;
    try {//  w ww. j  a  v  a2 s  .  c o  m
        in = xstream.createObjectInputStream(xmlReader);
        try {
            return (T) in.readObject();
        } catch (final IOException e) {
            throw new BonitaRuntimeException("unable to deserialize object " + object, e);
        } catch (final ClassNotFoundException e) {
            throw new BonitaRuntimeException("unable to deserialize object " + object, e);
        } catch (final CannotResolveClassException e) {
            throw new BonitaRuntimeException("unable to deserialize object " + object, e);
        } finally {
            in.close();
            xmlReader.close();
        }
    } catch (final IOException e) {
        throw new BonitaRuntimeException("unable to deserialize object " + object, e);
    }
}

From source file:net.sf.serfj.serializers.Base64Serializer.java

/**
 * Deserialze base 64 encoded string data to Object.
 *//*from www .j a  v  a 2  s  .  c  o  m*/
public Object deserialize(String data) {
    if ((data == null) || (data.length() == 0)) {
        return null;
    }
    ObjectInputStream ois = null;
    ByteArrayInputStream bis = null;
    try {
        bis = new ByteArrayInputStream(Base64.decodeBase64(data.getBytes()));
        ois = new ObjectInputStream(bis);
        return ois.readObject();
    } catch (ClassNotFoundException e) {
        LOGGER.error("Can't deserialize data from Base64", e);
        throw new IllegalArgumentException(e);
    } catch (IOException e) {
        LOGGER.error("Can't deserialize data from Base64", e);
        throw new IllegalArgumentException(e);
    } catch (Exception e) {
        LOGGER.error("Can't deserialize data from Base64", e);
        throw new IllegalArgumentException(e);
    } finally {
        try {
            if (ois != null) {
                ois.close();
            }
        } catch (Exception e) {
            LOGGER.error("Can't close ObjetInputStream used for deserialize data from Base64", e);
        }
    }
}

From source file:fmiquerytest.Coordinates.java

static List<stationData> loadStationsFromFile(File stationFileName) {
    List<stationData> savedStations = new ArrayList<>();
    try {//w ww .  j  a  v  a 2 s . co m
        FileInputStream fin = new FileInputStream(stationFileName);
        ObjectInputStream ois = new ObjectInputStream(fin);
        savedStations = (List<stationData>) ois.readObject();
        fin.close();
        ois.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(FmiQueryTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException | ClassNotFoundException ex) {
        Logger.getLogger(FmiQueryTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return savedStations;
}

From source file:fmiquerytest.Coordinates.java

static List<routeStep> loadSavedRoute(String gQuery) {
    List<routeStep> loadedRoute = new ArrayList<>();
    gQuery = gQuery.replace(FmiQueryTest.gDirectionQuery, "");
    gQuery = gQuery.replace(FmiQueryTest.gKey, "");
    gQuery = gQuery.replace("&key=", "");
    File savedFileName = new File(gQuery.replaceAll("[^A-Za-z0-9 ]", "") + ".txt");
    //Load route//from w ww . j  av a  2s . com
    try {
        FileInputStream fin = new FileInputStream(savedFileName);
        ObjectInputStream ois = new ObjectInputStream(fin);
        loadedRoute = (List<routeStep>) ois.readObject();
        fin.close();
        ois.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(FmiQueryTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException | ClassNotFoundException ex) {
        Logger.getLogger(FmiQueryTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return loadedRoute;
}

From source file:com.ning.metrics.collector.endpoint.resources.ScribeEventRequestHandler.java

private Event extractThriftEnvelopeEvent(final String category, final String message) throws TException {
    Event event;/*from w  ww .j  a  va2  s.c  om*/
    final String[] payload = StringUtils.split(message, ":");

    if (payload == null || payload.length != 2) {
        // Invalid API
        throw new TException("Expected payload separator ':'");
    }

    Long eventDateTime = null;
    try {
        eventDateTime = Long.parseLong(payload[0]);
    } catch (RuntimeException e) {
        log.debug("Event DateTime not specified, defaulting to NOW()");
    }

    // The payload is Base64 encoded
    final byte[] thrift = new Base64().decode(payload[1].getBytes());

    // Assume a ThriftEnvelopeEvent from the eventtracker (uses Java serialization).
    // This is bigger on the wire, but the interface is portable. Serialize using TBinaryProtocol
    // if you care about size (see below).
    ObjectInputStream objectInputStream = null;
    try {
        objectInputStream = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(thrift)));
        event = new ThriftEnvelopeEvent();
        event.readExternal(objectInputStream);

        if (event.getName().equals(category)) {
            return event;
        }
    } catch (Exception e) {
        log.debug(String.format("Payload is not a ThriftEvent: %s", e.getLocalizedMessage()));
    } finally {
        try {
            if (objectInputStream != null) {
                objectInputStream.close();
            }
        } catch (IOException e) {
            log.warn("Unable to close stream when deserializing thrift events", e);
        }
    }

    // Not a ThriftEvent, probably native Thrift serialization (TBinaryProtocol)
    try {
        if (eventDateTime == null) {
            event = ThriftToThriftEnvelopeEvent.extractEvent(category, thrift);
        } else {
            event = ThriftToThriftEnvelopeEvent.extractEvent(category, new DateTime(eventDateTime), thrift);
        }
    } catch (TException e) {
        log.debug("Event doesn't look like a Thrift, assuming plain text");
        if (eventDateTime == null) {
            event = StringToThriftEnvelopeEvent.extractEvent(category, payload[1]);
        } else {
            event = StringToThriftEnvelopeEvent.extractEvent(category, new DateTime(eventDateTime), payload[1]);
        }
    }
    return event;
}

From source file:com.holycityaudio.SpinCAD.SpinCADFile.java

public SpinCADPatch fileReadPatch(String fileName) throws IOException, ClassNotFoundException {
    // Object deserialization 
    FileInputStream fis = new FileInputStream(fileName);
    ObjectInputStream ois = new ObjectInputStream(fis);
    SpinCADPatch p = new SpinCADPatch();

    p = (SpinCADPatch) ois.readObject();

    ois.close();
    return p;//w  w w . j  ava 2s.  c  om
}

From source file:edu.isi.misd.tagfiler.download.FileDownloadImplementation.java

/**
 * Performs the dataset download./*from   w  w w .  java2 s. co  m*/
 * 
 * @param destDir
 *            destination directory for the download
 * @param target
 *            resume or download all
 */
@SuppressWarnings("unchecked")
public boolean downloadFiles(String destDir, String target) {
    if (destDir == null || destDir.length() == 0 || target == null)
        throw new IllegalArgumentException(destDir + ", " + target);
    this.target = target;
    try {
        client.setBaseURL(DatasetUtils.getBaseDownloadUrl(dataset, tagFilerServerURL));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    // the copy is done for performance reasons in the inner loop
    ArrayList<String> tempFiles = new ArrayList<String>(fileNames);

    List<FileWrapper> filesList = new ArrayList<FileWrapper>();
    if (target.equals(RESUME_TARGET)) {
        // resume download
        String filename = destDir + File.separator + TagFilerProperties.getProperty("tagfiler.checkpoint.file");
        File file = new File(filename);
        if (file.exists() && file.isFile() && file.canRead()) {
            // get the download check point status
            try {
                FileInputStream fis = new FileInputStream(filename);
                ObjectInputStream in = new ObjectInputStream(fis);
                Hashtable<String, Long> checkPoint = (Hashtable<String, Long>) in.readObject();
                HashMap<String, String> checksum = (HashMap<String, String>) in.readObject();
                in.close();
                fis.close();
                System.out.println("Check Points Read: " + checkPoint + "\n" + checksum);
                Set<String> keys = checkPoint.keySet();
                for (String key : keys) {
                    if (tempFiles.contains(key)) {
                        tempFiles.remove(key);
                        boolean complete = (long) bytesMap.get(key) == (long) checkPoint.get(key);
                        if (complete && enableChecksum) {
                            complete = checksum.get(key) != null && checksumMap.get(key) != null
                                    && checksum.get(key).equals(checksumMap.get(key));
                        }
                        if (complete) {
                            // file already downloaded
                            bytesMap.remove(key);
                            versionMap.remove(key);
                            checksumMap.remove(key);
                        } else {
                            // file partial downloaded
                            filesList.add(new FileWrapper(key, checkPoint.get(key), versionMap.get(key),
                                    bytesMap.get(key)));
                        }
                    }
                }
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    // add the rest of the files without check points
    for (String filename : tempFiles) {
        filesList.add(new FileWrapper(filename, 0, versionMap.get(filename), bytesMap.get(filename)));
    }

    System.out.println("" + filesList.size() + " file(s) will be downloaded");

    // get the total size of the files to be downloaded and checksum
    long totalSize = 0;
    long tb = 0;
    for (FileWrapper fileWrapper : filesList) {
        tb += fileWrapper.getFileLength() - fileWrapper.getOffset();
        totalSize += fileWrapper.getFileLength() - fileWrapper.getOffset();
        if (enableChecksum) {
            totalSize += fileWrapper.getFileLength();
        }
    }
    fileDownloadListener.notifyLogMessage(
            tb + " total bytes will be transferred\n" + totalSize + " total bytes in the progress bar");
    fileDownloadListener.notifyStart(dataset, totalSize);
    if (!((AbstractTagFilerApplet) applet).allowChunksTransfering()) {
        ClientUtils.disableExpirationWarning(applet);
    }
    start = System.currentTimeMillis();
    cancel = false;
    client.download(filesList, destDir, checksumMap, bytesMap, versionMap);

    return true;
}