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:com.winvector.logistic.demo.MapReduceScore.java

public double run(final String modelFileName, final String testFileName, final String resultFileName)
        throws Exception {
    final Log log = LogFactory.getLog(MapReduceScore.class);
    final Random rand = new Random();
    final String tmpPrefix = "TMPAC_" + rand.nextLong();
    final Configuration mrConfig = getConf();
    log.info("start");
    log.info("reading model: " + modelFileName);
    final Model model;
    {// w w  w .  ja v a  2 s .  c  o m
        final Path modelPath = new Path(modelFileName);
        final FSDataInputStream fdi = modelPath.getFileSystem(mrConfig).open(modelPath);
        final ObjectInputStream ois = new ObjectInputStream(fdi);
        model = (Model) ois.readObject();
        ois.close();
    }
    log.info("model:\n" + model.config.formatSoln(model.coefs));
    final Path testFile = new Path(testFileName);
    final Path resultFile = new Path(resultFileName);
    log.info("scoring data: " + testFile);
    log.info("writing: " + resultFile);
    final SigmoidLossMultinomial underlying = new SigmoidLossMultinomial(model.config.dim(),
            model.config.noutcomes());
    final WritableVariableList lConfig = WritableVariableList.copy(model.config.def());
    final String headerLine = WritableUtils.readFirstLine(mrConfig, testFile);
    final Pattern sepPattern = Pattern.compile("\t");
    final LineBurster burster = new HBurster(sepPattern, headerLine, false);
    mrConfig.set(MapRedScan.BURSTERSERFIELD, SerialUtils.serializableToString(burster));
    final StringBuilder b = new StringBuilder();
    b.append("predict" + "." + model.config.def().resultColumn + "\t");
    b.append("predict" + "." + model.config.def().resultColumn + "." + "score" + "\t");
    for (int i = 0; i < model.config.noutcomes(); ++i) {
        final String cat = model.config.outcome(i);
        b.append("predict" + "." + model.config.def().resultColumn + "." + cat + "." + "score" + "\t");
    }
    b.append(headerLine);
    mrConfig.set(MapRedScore.IDEALHEADERFIELD, b.toString());
    final MapRedScore sc = new MapRedScore(underlying, lConfig, model.config.useIntercept(), mrConfig,
            testFile);
    sc.score(model.coefs, resultFile);
    final MapRedAccuracy ac = new MapRedAccuracy(underlying, lConfig, model.config.useIntercept(), tmpPrefix,
            mrConfig, testFile);
    final long[] testAccuracy = ac.score(model.coefs);
    final double accuracy = testAccuracy[0] / (double) testAccuracy[1];
    log.info("test accuracy: " + testAccuracy[0] + "/" + testAccuracy[1] + "\t" + accuracy);
    log.info("done");
    return accuracy;
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.si.dictionary.UkbDocumentDependentDictionaryInventory.java

public UkbDocumentDependentDictionaryInventory(String inputPath, String serializiblePath,
        String neededMentionsPath) throws FileNotFoundException, IOException {
    // Open the serialized version or create it from scratch
    try {/*from  w w  w. ja  v a  2  s  . c  o m*/
        // System.out.println("Trying to load dictionary from serializable.");
        ObjectInputStream dictionaryReader = new ObjectInputStream(
                new BZip2CompressorInputStream(new FileInputStream(serializiblePath)));
        dictionary = (UkbDictionary) dictionaryReader.readObject();
        dictionaryReader.close();
        // System.out.println("Loaded dictionary from serializable.");
    } catch (Exception e) {
        // System.out.println("Trying to load dictionary from input.");
        dictionary = new UkbDictionary(inputPath, neededMentionsPath);
        System.out.println("Loaded dictionary from input.");

        ObjectOutputStream dictionaryWriter = new ObjectOutputStream(
                new BZip2CompressorOutputStream(new FileOutputStream(serializiblePath)));
        dictionaryWriter.writeObject(dictionary);
        dictionaryWriter.close();
        // System.out.println("Stored dictionary in serializable.");
    }

}

From source file:com.cloudera.kitten.util.LocalDataHelper.java

public static <T> Map<String, T> deserialize(String serialized) {
    byte[] data = Base64.decodeBase64(serialized);
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    Map<String, T> mapping = null;
    try {//from ww  w  . java 2 s. com
        ObjectInputStream ois = new ObjectInputStream(bais);
        mapping = (Map<String, T>) ois.readObject();
        ois.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return mapping;
}

From source file:jp.queuelinker.system.util.SerializeUtil.java

/**
 * @param file//from  w  w  w .  j  a v  a2 s .  c om
 * @return
 * @throws IOException
 * @throws ClassNotFoundException
 */
public static Object restoreObject(final File file) throws IOException, ClassNotFoundException {
    ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
    return input.readObject();
}

From source file:net.nicholaswilliams.java.licensing.TestObjectSerializer.java

@Test
public void testWriteObject1() throws Exception {
    MockTestObject1 object = new MockTestObject1();

    byte[] data = this.serializer.writeObject(object);

    assertNotNull("The array should not be null.", data);
    assertTrue("The array shoudl not be empty.", data.length > 0);

    ByteArrayInputStream bytes = new ByteArrayInputStream(data);
    ObjectInputStream stream = new ObjectInputStream(bytes);

    Object input = stream.readObject();

    assertNotNull("The object should not be null.", input);
    assertEquals("The object is not the right kind of object.", MockTestObject1.class, input.getClass());

    MockTestObject1 actual = (MockTestObject1) input;
    assertFalse("The objects should not be the same object.", actual == object);
    assertEquals("The object is not correct.", object, actual);
}

From source file:com.brianjmelton.apcs.api.BasicCookieStoreSerializer.java

@SuppressWarnings("unchecked")
@Override//from   w w  w.ja  va 2s.c o m
public Map<URI, List<SerializableCookie>> restore() throws PersistenceException {
    try {
        Map<URI, List<SerializableCookie>> map = null;
        if (cookieFile.exists()) {
            InputStream in = new FileInputStream(cookieFile);
            ObjectInputStream ois = new ObjectInputStream(in);
            map = (Map<URI, List<SerializableCookie>>) ois.readObject();
            IOUtils.closeQuietly(ois);
        }
        return map;
    } catch (Throwable t) {
        throw new PersistenceException(t);
    }
}

From source file:license.TestWakeLicense.java

/**
 * ?/*  ww  w. j a v a 2s  .  com*/
 * @return
 * @throws Exception
 */
static PublicKey readPublicKeyFromFile() throws Exception {
    ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(KeyData.publicKey));
    try {
        BigInteger m = (BigInteger) oin.readObject();
        BigInteger e = (BigInteger) oin.readObject();
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        return fact.generatePublic(keySpec);
    } finally {
        oin.close();
    }
}

From source file:com.haulmont.cuba.core.sys.serialization.StandardSerialization.java

@Override
public Object deserialize(InputStream is) {
    try {/*from w w  w. j  av  a  2  s  . c  o  m*/
        ObjectInputStream ois;
        boolean isObjectStream = is instanceof ObjectInputStream;
        if (isObjectStream) {
            ois = (ObjectInputStream) is;
        } else {
            ois = new ObjectInputStream(is) {
                @Override
                protected Class<?> resolveClass(ObjectStreamClass desc)
                        throws IOException, ClassNotFoundException {
                    return ClassUtils.getClass(StandardSerialization.class.getClassLoader(), desc.getName());
                }
            };
        }
        return ois.readObject();
    } catch (IOException ex) {
        throw new IllegalArgumentException("Failed to deserialize object", ex);
    } catch (ClassNotFoundException ex) {
        throw new IllegalStateException("Failed to deserialize object type", ex);
    }
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.clustering.entropy.ClusterSentencesCollector.java

@Override
@SuppressWarnings("unchecked")
public void initialize(UimaContext context) throws ResourceInitializationException {
    super.initialize(context);

    try {/*from   w  ww. ja va  2  s. c o m*/
        // load centroids
        centroids = (TreeMap<Integer, Vector>) new ObjectInputStream(new FileInputStream(centroidsFile))
                .readObject();
    } catch (IOException | ClassNotFoundException e) {
        throw new ResourceInitializationException(e);
    }
}

From source file:com.conwet.silbops.model.ContextFunctionTest.java

@Test
public void shouldExternalize() throws Exception {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutput output = new ObjectOutputStream(baos);

    output.writeObject(function);//www.j a  v a2 s .  com
    output.close();

    ObjectInput input = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));

    ContextFunction cxtFun = (ContextFunction) input.readObject();
    assertThat(cxtFun).isEqualTo(function);
}