Example usage for java.io ObjectInputStream readObject

List of usage examples for java.io ObjectInputStream readObject

Introduction

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

Prototype

public final Object readObject() throws IOException, ClassNotFoundException 

Source Link

Document

Read an object from the ObjectInputStream.

Usage

From source file:com.taobao.metamorphosis.utils.codec.impl.JavaDeserializer.java

/**
 * @see com.taobao.notify.codec.Deserializer#decodeObject(byte[])
 *///w w w.  java  2  s.com
@Override
public Object decodeObject(final byte[] objContent) throws IOException {
    Object obj = null;
    ByteArrayInputStream bais = null;
    ObjectInputStream ois = null;
    try {
        bais = new ByteArrayInputStream(objContent);
        ois = new ObjectInputStream(bais);
        obj = ois.readObject();
    } catch (final IOException ex) {
        throw ex;
    } catch (final ClassNotFoundException ex) {
        this.logger.warn("Failed to decode object.", ex);
    } finally {
        if (ois != null) {
            try {
                ois.close();
                bais.close();
            } catch (final IOException ex) {
                this.logger.error("Failed to close stream.", ex);
            }
        }
    }
    return obj;
}

From source file:net.fizzl.redditengine.impl.PersistentCookieStore.java

/**
 * Load Cookies from a file//from ww w.ja  v a  2 s .  com
 */
private void load() {
    RedditApi api = DefaultRedditApi.getInstance();
    Context ctx = api.getContext();
    try {
        FileInputStream fis = ctx.openFileInput(cookiestore);
        ObjectInputStream ois = new ObjectInputStream(fis);
        SerializableCookieStore tempStore = (SerializableCookieStore) ois.readObject();

        super.clear();
        for (Cookie c : tempStore.getCookies()) {
            super.addCookie(c);
        }

        ois.close();
        fis.close();
    } catch (FileNotFoundException e) {
        Log.w(getClass().getName(), e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.hp.autonomy.hod.sso.HodAuthenticationTest.java

private <T extends Serializable> T deserializeFromResource(final String resourcePath)
        throws IOException, ClassNotFoundException {
    try (InputStream inputStream = getClass().getResourceAsStream(resourcePath)) {
        final ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);

        //noinspection unchecked
        return (T) objectInputStream.readObject();
    }/*from   www . j  a  va  2  s.  c  om*/
}

From source file:org.hoteia.qalingo.app.business.job.email.AbstractEmailItemProcessor.java

public Email process(CommonProcessIndicatorItemWrapper<Long, Email> wrapper) throws Exception {
    Email email = wrapper.getItem();//from  w  w  w.  j  av a2 s.  c  om
    Blob emailcontent = email.getEmailContent();

    InputStream is = emailcontent.getBinaryStream();
    ObjectInputStream oip = new ObjectInputStream(is);
    Object object = oip.readObject();

    MimeMessagePreparatorImpl mimeMessagePreparator = (MimeMessagePreparatorImpl) object;

    oip.close();
    is.close();

    try {
        // SANITY CHECK
        if (email.getStatus().equals(Email.EMAIl_STATUS_PENDING)) {

            if (mimeMessagePreparator.isMirroringActivated()) {
                String filePathToSave = mimeMessagePreparator.getMirroringFilePath();
                File file = new File(filePathToSave);

                // SANITY CHECK : create folders
                String absoluteFolderPath = file.getParent();
                File absolutePathFile = new File(absoluteFolderPath);
                if (!absolutePathFile.exists()) {
                    absolutePathFile.mkdirs();
                }

                if (!file.exists()) {
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,
                            Constants.UTF8);
                    Writer out = new BufferedWriter(outputStreamWriter);
                    if (StringUtils.isNotEmpty(mimeMessagePreparator.getHtmlContent())) {
                        out.write(mimeMessagePreparator.getHtmlContent());
                    } else {
                        out.write(mimeMessagePreparator.getPlainTextContent());
                    }

                    try {
                        if (out != null) {
                            out.close();
                        }
                    } catch (IOException e) {
                        logger.debug("Cannot close the file", e);
                    }
                } else {
                    logger.debug("File already exists : " + filePathToSave);
                }
            }

            mailSender.send(mimeMessagePreparator);
            email.setStatus(Email.EMAIl_STATUS_SENDED);
        } else {
            logger.warn("Batch try to send email was already sended!");
        }

    } catch (Exception e) {
        logger.error("Fail to send email! Exception is save in database, id:" + email.getId());
        email.setStatus(Email.EMAIl_STATUS_ERROR);
        emailService.handleEmailException(email, e);
    }

    return email;
}

From source file:com.joliciel.talismane.lexicon.LexiconDeserializer.java

public PosTaggerLexicon deserializeLexiconFile(ZipInputStream zis) {
    MONITOR.startTask("deserializeLexiconFile(ZipInputStream)");
    try {//from   w w w.  ja va 2 s.  com
        PosTaggerLexicon lexicon = null;
        try {
            ZipEntry zipEntry;
            if ((zipEntry = zis.getNextEntry()) != null) {
                LOG.debug("Scanning zip entry " + zipEntry.getName());

                ObjectInputStream in = new ObjectInputStream(zis);
                lexicon = (PosTaggerLexicon) in.readObject();
                zis.closeEntry();
                in.close();
            } else {
                throw new RuntimeException("No zip entry in input stream");
            }
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        } catch (ClassNotFoundException cnfe) {
            throw new RuntimeException(cnfe);
        }

        return lexicon;
    } finally {
        MONITOR.endTask("deserializeLexiconFile(ZipInputStream)");
    }
}

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

/**
 * Deserializes an object of the specified type from the provided byte stream.
 *
 * @param expectedType The type that is expected to be retrieved from {@code byteStream} (must implement {@link Serializable})
 * @param byteStream The byte stream to retrieve the object from (it must contain exactly one object, of the exact type passed to {@code expectedType})
 * @return the requested unserialized object, presumably in the stream.
 * @throws ObjectTypeNotExpectedException If the object found in the stream does not match the type {@code expectedType} or if a {@link ClassNotFoundException} or {@link NoClassDefFoundError} occurs
 * @throws ObjectDeserializationException If an I/O exception occurs while deserializing the object from the stream
 *///from w w w . j a v a  2  s. c o m
public final <T extends Serializable> T readObject(Class<T> expectedType, byte[] byteStream)
        throws ObjectDeserializationException {
    ByteArrayInputStream bytes = new ByteArrayInputStream(byteStream);
    ObjectInputStream stream = null;
    try {
        stream = new ObjectInputStream(bytes);
        Object allegedObject = stream.readObject();
        if (!expectedType.isInstance(allegedObject)) {
            throw new ObjectTypeNotExpectedException(expectedType.getName(),
                    allegedObject.getClass().getName());
        }

        return expectedType.cast(allegedObject);
    } catch (IOException e) {
        throw new ObjectDeserializationException(
                "An I/O error occurred while reading the object from the byte array.", e);
    } catch (ClassNotFoundException e) {
        throw new ObjectTypeNotExpectedException(expectedType.getName(), e.getMessage(), e);
    } catch (NoClassDefFoundError e) {
        throw new ObjectTypeNotExpectedException(expectedType.getName(), e.getMessage(), e);
    } finally {
        try {
            if (stream != null)
                stream.close();
        } catch (IOException ignore) {
        }
    }
}

From source file:com.joliciel.lefff.LefffMemoryLoader.java

public LefffMemoryBase deserializeMemoryBase(ZipInputStream zis) {
    LefffMemoryBase memoryBase = null;/*  w  w w. j  a  va 2s.  c  o  m*/
    MONITOR.startTask("deserializeMemoryBase");
    try {
        ZipEntry zipEntry;
        if ((zipEntry = zis.getNextEntry()) != null) {
            LOG.debug("Scanning zip entry " + zipEntry.getName());

            ObjectInputStream in = new ObjectInputStream(zis);
            memoryBase = (LefffMemoryBase) in.readObject();
            zis.closeEntry();
            in.close();
        } else {
            throw new RuntimeException("No zip entry in input stream");
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException(cnfe);
    } finally {
        MONITOR.endTask("deserializeMemoryBase");
    }

    Map<PosTagSet, LefffPosTagMapper> posTagMappers = memoryBase.getPosTagMappers();
    PosTagSet posTagSet = posTagMappers.keySet().iterator().next();
    memoryBase.setPosTagSet(posTagSet);

    return memoryBase;
}

From source file:net.larry1123.util.api.world.blocks.BlockPropertyStorage.java

public BlockPropertyStorage(String json) throws ParseException, ClassNotFoundException {
    // TODO add a bit of validation
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse(json);
    name = (String) jsonObject.get("keyName");
    blockTypeMachineName = (String) jsonObject.get("blockTypeMachineName");
    blockTypeData = (Short) jsonObject.get("blockTypeData");
    try {//from  w w w . j  a v a 2 s  .  c  o  m
        byte[] bytes = Base64.decodeBase64((String) jsonObject.get("value"));
        ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
        value = (Comparable) objectInputStream.readObject();
    } catch (IOException e) {
        throw new Error();
        // Not sure how that could happen but I will see what I may need to do
    }
}

From source file:com.joliciel.talismane.machineLearning.ExternalResourceFinderImpl.java

@Override
public void addExternalResources(File externalResourceFile) {
    try {//from   w w  w  .ja  va  2s.  c om
        if (externalResourceFile.isDirectory()) {
            File[] files = externalResourceFile.listFiles();
            for (File resourceFile : files) {
                LOG.debug("Reading " + resourceFile.getName());
                if (resourceFile.getName().endsWith(".zip")) {
                    ZipInputStream zis = new ZipInputStream(new FileInputStream(resourceFile));
                    zis.getNextEntry();
                    ObjectInputStream ois = new ObjectInputStream(zis);
                    ExternalResource<?> externalResource = (ExternalResource<?>) ois.readObject();
                    this.addExternalResource(externalResource);
                } else {
                    TextFileResource textFileResource = new TextFileResource(resourceFile);
                    this.addExternalResource(textFileResource);
                }
            }
        } else {
            LOG.debug("Reading " + externalResourceFile.getName());
            if (externalResourceFile.getName().endsWith(".zip")) {
                ZipInputStream zis = new ZipInputStream(new FileInputStream(externalResourceFile));
                zis.getNextEntry();
                ObjectInputStream ois = new ObjectInputStream(zis);
                ExternalResource<?> externalResource = (ExternalResource<?>) ois.readObject();
                this.addExternalResource(externalResource);
            } else {
                TextFileResource textFileResource = new TextFileResource(externalResourceFile);
                this.addExternalResource(textFileResource);
            }
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:com.hp.autonomy.hod.sso.HodAuthenticationTest.java

private <T extends Serializable> T writeAndReadObject(final T object)
        throws IOException, ClassNotFoundException {
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    final ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
    objectOutputStream.writeObject(object);
    objectOutputStream.close();//from   ww w . j  av  a 2  s  .com

    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
            byteArrayOutputStream.toByteArray());
    final ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);

    //noinspection unchecked
    return (T) objectInputStream.readObject();
}