Example usage for java.io ObjectInputStream ObjectInputStream

List of usage examples for java.io ObjectInputStream ObjectInputStream

Introduction

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

Prototype

public ObjectInputStream(InputStream in) throws IOException 

Source Link

Document

Creates an ObjectInputStream that reads from the specified InputStream.

Usage

From source file:de.tudarmstadt.ukp.dkpro.tc.ml.report.BatchPredictionReport.java

@Override
public void execute() throws Exception {
    StorageService store = getContext().getStorageService();

    FlexTable<String> table = FlexTable.forClass(String.class);

    for (TaskContextMetadata subcontext : getSubtasks()) {
        // FIXME this is a bad hack
        if (subcontext.getType().contains("ExtractFeaturesAndPredictTask")) {

            Map<String, String> discriminatorsMap = store
                    .retrieveBinary(subcontext.getId(), Task.DISCRIMINATORS_KEY, new PropertiesAdapter())
                    .getMap();// ww  w. ja  v  a 2  s.  c  o m

            // deserialize file
            FileInputStream f = new FileInputStream(
                    store.getStorageFolder(subcontext.getId(), PREDICTION_MAP_FILE_NAME));
            ObjectInputStream s = new ObjectInputStream(f);
            Map<String, List<String>> resultMap = (Map<String, List<String>>) s.readObject();
            s.close();

            // write one file per batch
            // in files: one line per instance

            for (String id : resultMap.keySet()) {
                Map<String, String> row = new HashMap<String, String>();
                row.put(predicted_value, StringUtils.join(resultMap.get(id), ","));
                table.addRow(id, row);
            }
            // create a separate output folder for each execution of
            // ExtractFeaturesAndPredictTask, 36 is the length of the UUID hash
            File contextFolder = store.getStorageFolder(getContext().getId(),
                    subcontext.getId().substring(subcontext.getId().length() - 36));
            // Excel cannot cope with more than 255 columns
            if (table.getColumnIds().length <= 255) {
                getContext().storeBinary(contextFolder.getName() + System.getProperty("file.separator")
                        + report_name + SUFFIX_EXCEL, table.getExcelWriter());
            }
            getContext().storeBinary(
                    contextFolder.getName() + System.getProperty("file.separator") + report_name + SUFFIX_CSV,
                    table.getCsvWriter());
            getContext().storeBinary(
                    contextFolder.getName() + System.getProperty("file.separator") + Task.DISCRIMINATORS_KEY,
                    new PropertiesAdapter(discriminatorsMap));
        }
    }

    // output the location of the batch evaluation folder
    // otherwise it might be hard for novice users to locate this
    File dummyFolder = store.getStorageFolder(getContext().getId(), "dummy");
    // TODO can we also do this without creating and deleting the dummy folder?
    getContext().getLoggingService().message(getContextLabel(),
            "Storing detailed results in:\n" + dummyFolder.getParent() + "\n");
    dummyFolder.delete();
}

From source file:hugonicolau.openbrailleinput.wordcorrection.mafsa.MAFSA.java

/**
 * Factory method.  Creates a new Dawg entry by reading in data from the given InputStream.  Once the data is read,
 * the stream remains open./*from ww  w.ja  va 2s .co  m*/
 *
 * @param is the stream with the data to create the Dawg instance.
 * @return a new Dawg instance with the data loaded
 * @throws DataFormatException if the InputStream doesn't contain the proper data format for loading a Dawg instance
 * @throws IOException if reading from the stream casues an IOException.
 */
public static MAFSA load(InputStream is) throws IOException {
    BufferedInputStream bis = new BufferedInputStream(is, 8 * 1024);
    ObjectInputStream ois = new ObjectInputStream(bis);

    long[] longs;

    try {
        longs = (long[]) ois.readObject();
    } catch (ClassNotFoundException cnfe) {
        throw new DataFormatException("Bad file.  Not valid for loading com.icantrap.collections.dawg.Dawg",
                cnfe);
    }

    return new MAFSA(longs);
}

From source file:io.dstream.hadoop.TypeAwareWritable.java

/**
 * //from w  ww .j av a  2s.  c o m
 */
@Override
public void readFields(DataInput in) throws IOException {
    this.valueType = in.readByte();
    switch (this.valueType) {
    case INTEGER:
        this.value = (T) Integer.valueOf(in.readInt());
        break;
    case LONG:
        this.value = (T) Long.valueOf(in.readLong());
        break;
    case NULL:
        this.value = null;
        break;
    case OBJECT:
        try {
            ObjectInputStream ois = new ObjectInputStream((DataInputStream) in);
            T value = (T) ois.readObject();
            this.value = (T) value;
        } catch (Exception e) {
            throw new IllegalStateException("Failed to deserialize value", e);
        }
        break;
    default:
        throw new IllegalStateException("Unsupported or unrecognized value type: " + this.valueType);
    }
}

From source file:com.jpeterson.littles3.bo.BucketTest.java

/**
 * Test that an instance is serializable.
 *//*  w  w  w .  j a  va 2s  .  c om*/
public void test_serialization() {
    Bucket bucket, reconstitutedBucket;
    ByteArrayInputStream bais;
    ByteArrayOutputStream baos;
    ObjectInputStream ois;
    ObjectOutputStream oos;
    Date now = new Date();

    bucket = new Bucket();

    bucket.setName("test");
    bucket.setCreated(now);

    try {
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);

        oos.writeObject(bucket);

        bais = new ByteArrayInputStream(baos.toByteArray());
        ois = new ObjectInputStream(bais);

        reconstitutedBucket = (Bucket) ois.readObject();

        assertEquals("Unexpected value", "test", reconstitutedBucket.getName());
        assertEquals("Unexpected value", now, reconstitutedBucket.getCreated());
    } catch (IOException e) {
        e.printStackTrace();
        fail("Unexpected exception");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        fail("Unexpected exception");
    }
}

From source file:edu.stanford.muse.lens.LensPrefs.java

public LensPrefs(String cacheDir) {
    pathToPrefsFile = cacheDir + File.separatorChar + PREFS_FILENAME;
    String pathToPrefsFileTxt = pathToPrefsFile + ".txt";
    log.info("Trying to load lens prefs from: " + pathToPrefsFileTxt);
    // read serialized state from file
    try {//from   w ww. jav a  2  s. c  o m
        log.info("Trying to load lens prefs from: " + pathToPrefsFileTxt);
        loadPrefs(pathToPrefsFile + ".txt");
    } catch (IOException ioe) {
        log.info("Unable to load text lens prefs from " + pathToPrefsFileTxt);
        try {
            log.info("Trying to load lens prefs from: " + pathToPrefsFileTxt);
            FileInputStream fis = new FileInputStream(pathToPrefsFile);
            ObjectInputStream ois = new ObjectInputStream(fis);
            prefs = (Map<String, Map<String, Float>>) ois.readObject();
            ois.close();
        } catch (FileNotFoundException e) {
            // hilitePrefs = new ArrayList<BrowserPrefs>();
            log.info("No existing browser preferences file: " + pathToPrefsFile);
        } catch (Exception e) {
            log.warn("exception reading " + pathToPrefsFile + ": " + Util.stackTrace(e));
        }
    }
    log.info(prefs.size() + " terms have user-specified weights");
    if (log.isDebugEnabled())
        log.debug(" User prefs are : " + this);
}

From source file:com.aionemu.gameserver.cache.HTMLCache.java

@SuppressWarnings("unchecked")
public synchronized void reload(boolean deleteCacheFile) {
    cache.clear();//from w  w w.j a  v a 2 s  .c  o  m
    loadedFiles = 0;
    size = 0;

    final File cacheFile = getCacheFile();

    if (deleteCacheFile && cacheFile.exists()) {
        log.info("Cache[HTML]: Deleting cache file... OK.");

        cacheFile.delete();
    }

    log.info("Cache[HTML]: Caching started... OK.");

    if (cacheFile.exists()) {
        log.info("Cache[HTML]: Using cache file... OK.");

        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(getCacheFile())));

            cache = (FastMap<String, String>) ois.readObject();

            for (String html : cache.values()) {
                loadedFiles++;
                size += html.length();
            }
        } catch (Exception e) {
            log.warn("", e);

            reload(true);
            return;
        } finally {
            IOUtils.closeQuietly(ois);
        }
    } else {
        parseDir(HTML_ROOT);
    }

    log.info(String.valueOf(this));

    if (cacheFile.exists()) {
        log.info("Cache[HTML]: Compaction skipped!");
    } else {
        log.info("Cache[HTML]: Compacting htmls... OK.");

        final StringBuilder sb = new StringBuilder(8192);

        for (Entry<String, String> entry : cache.entrySet()) {
            try {
                final String oldHtml = entry.getValue();
                final String newHtml = compactHtml(sb, oldHtml);

                size -= oldHtml.length();
                size += newHtml.length();

                entry.setValue(newHtml);
            } catch (RuntimeException e) {
                log.warn("Cache[HTML]: Error during compaction of " + entry.getKey(), e);
            }
        }

        log.info(String.valueOf(this));
    }

    if (!cacheFile.exists()) {
        log.info("Cache[HTML]: Creating cache file... OK.");

        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(getCacheFile())));

            oos.writeObject(cache);
        } catch (IOException e) {
            log.warn("", e);
        } finally {
            IOUtils.closeQuietly(oos);
        }
    }
}

From source file:com.facebook.infrastructure.utils.FBUtilities.java

public static Object deserializeFromStream(byte[] bytes) {
    Object o = null;//w ww  .j  ava  2s.  c  om
    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    try {
        ObjectInputStream ois = new ObjectInputStream(bis);
        try {
            o = ois.readObject();
        } catch (ClassNotFoundException e) {
        }
        ois.close();
        bis.close();
    } catch (IOException e) {
        LogUtil.getLogger(FBUtilities.class.getName()).info(LogUtil.throwableToString(e));
    }
    return o;
}

From source file:com.limegroup.gnutella.licenses.WeedLicenseTest.java

public void testSerializeAndDeserialize() throws Exception {
    License l = new StubWeedLicense("3", "4", "page");
    assertEquals(null, l.getLicense());//from  w  w  w.j a  va  2  s .c o  m
    assertEquals("http://weedshare.com/company/policies/summary_usage_rights.aspx",
            l.getLicenseDeed(null).toString());
    assertEquals("http://www.weedshare.com/license/verify_usage_rights.aspx?versionid=4&contentid=3",
            l.getLicenseURI().toString());
    assertEquals("Details unknown.", l.getLicenseDescription(null));
    assertFalse(l.isVerified());
    assertFalse(l.isValid(null));

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bout);
    out.writeObject(l);

    ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
    ObjectInputStream in = new ObjectInputStream(bin);
    l = (License) in.readObject();
    assertEquals(null, l.getLicense()); // CHANGE -- not serialized (but unused anyway)
    assertEquals("http://weedshare.com/company/policies/summary_usage_rights.aspx",
            l.getLicenseDeed(null).toString());
    assertEquals(null, l.getLicenseURI()); // CHANGE -- not serialized
    assertEquals("Details unknown.", l.getLicenseDescription(null));
    assertTrue(l.isVerified()); // CHANGE -- becomes verified
    assertFalse(l.isValid(null));

    // Now try with a full out parsed License.
    l = new StubWeedLicense("3", "4", xml(true, "Sammy B", "Blues In G", "$4.20"));
    l.verify(null);
    assertEquals(null, l.getLicense());
    assertTrue(l.isVerified());
    assertTrue(l.isValid(null));
    assertEquals("http://weedshare.com/company/policies/summary_usage_rights.aspx",
            l.getLicenseDeed(null).toString());
    assertEquals("Artist: Sammy B\nTitle: Blues In G\nPrice: $4.20", l.getLicenseDescription(null));

    bout = new ByteArrayOutputStream();
    out = new ObjectOutputStream(bout);
    out.writeObject(l);

    bin = new ByteArrayInputStream(bout.toByteArray());
    in = new ObjectInputStream(bin);
    l = (License) in.readObject();
    assertEquals(null, l.getLicense()); // CHANGE -- not serialized (but unused)
    assertTrue(l.isVerified());
    assertTrue(l.isValid(null));
    assertEquals("http://weedshare.com/company/policies/summary_usage_rights.aspx",
            l.getLicenseDeed(null).toString());
    assertEquals("Artist: Sammy B\nTitle: Blues In G\nPrice: $4.20", l.getLicenseDescription(null));
}

From source file:com.code.savemarks.utils.Utils.java

/**
 * Deserialize an object from a byte array. Does not throw any exceptions;
 * instead, exceptions are logged and null is returned.
 * //from www .  java  2s  . c o  m
 * @param bytesIn A byte array containing a previously serialized object.
 * @return An object instance, or null if an exception occurred.
 */
public static Object deserialize(byte[] bytesIn) {
    ObjectInputStream objectIn = null;
    try {
        bytesIn = decodeBase64(bytesIn);
        objectIn = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(bytesIn)));
        return objectIn.readObject();
    } catch (Exception e) {
        log.log(Level.SEVERE, "Error deserializing task", e);
        return null; // don't retry task
    } finally {
        try {
            if (objectIn != null) {
                objectIn.close();
            }
        } catch (IOException ignore) {
        }
    }
}

From source file:io.dstream.tez.io.TypeAwareWritable.java

/**
 *
 *///from w w w. j  a v a  2  s  . c o m
@Override
public void readFields(DataInput in) throws IOException {
    this.valueType = in.readByte();
    switch (this.valueType) {
    case INTEGER:
        this.value = (T) Integer.valueOf(in.readInt());
        break;
    case LONG:
        this.value = (T) Long.valueOf(in.readLong());
        break;
    case NULL:
        this.value = null;
        break;
    case OBJECT:
        try {
            ObjectInputStream ois = new ObjectInputStream((DataInputStream) in);
            T value = (T) ois.readObject();
            this.value = value;
        } catch (Exception e) {
            throw new IllegalStateException("Failed to deserialize value", e);
        }
        break;
    default:
        throw new IllegalStateException("Unsupported or unrecognized value type: " + this.valueType);
    }
}