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.github.stephanarts.cas.ticket.registry.provider.AddMethod.java

/**
 * Execute the JSONRPCFunction.//from   ww  w . ja v a2 s .  co m
 *
 * @param params    JSONRPC Method Parameters.
 *
 * @return          JSONRPC result object
 *
 * @throws JSONRPCException implementors can throw JSONRPCExceptions containing the error.
 */
public JSONObject execute(final JSONObject params) throws JSONRPCException {

    JSONObject result = new JSONObject();

    String ticketId = null;
    String serializedTicket = null;

    Ticket ticket = null;

    logger.debug("Add Ticket");
    if (params.length() != 2) {
        throw new JSONRPCException(-32602, "Invalid Params");
    }
    if (!(params.has("ticket-id") && params.has("ticket"))) {
        throw new JSONRPCException(-32602, "Invalid Params");
    }
    try {
        ticketId = params.getString("ticket-id");
        serializedTicket = params.getString("ticket");

        ByteArrayInputStream bi = new ByteArrayInputStream(
                DatatypeConverter.parseBase64Binary(serializedTicket));
        ObjectInputStream si = new ObjectInputStream(bi);

        ticket = (Ticket) si.readObject();
    } catch (final Exception e) {
        throw new JSONRPCException(-32501, "Could not decode Ticket");
    }

    if (this.map.containsKey(ticketId.hashCode())) {
        logger.error("Duplicate Key {}", ticketId);
        throw new JSONRPCException(-32502, "Duplicate Ticket");
    } else {
        this.map.put(ticketId.hashCode(), ticket);
    }

    logger.debug("Ticket-ID '{}'", ticketId);

    return result;
}

From source file:com.linkedin.pinot.common.utils.DataTableJavaSerDe.java

/**
 * Helper method to de-serialize an object using Java ser/de.
 * @param bytes Java serialized byte-array of the object.
 * @param <T> Type of the object/*w  ww .  ja  va2s.c  om*/
 * @return De-serialized object
 */
@SuppressWarnings("unchecked")
public static <T extends Serializable> T deserializeJavaObject(@Nonnull byte[] bytes) {

    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    ObjectInputStream objectInputStream = null;
    Object readObject;

    try {
        try {
            objectInputStream = new ObjectInputStream(byteArrayInputStream);
            readObject = objectInputStream.readObject();
        } catch (final Exception e) {
            throw new RuntimeException("Caught exception while deserializing DataTable: " + e);
        }
    } finally {
        IOUtils.closeQuietly(objectInputStream);
        IOUtils.closeQuietly(byteArrayInputStream);
    }

    return (T) readObject;
}

From source file:com.cyberway.issue.crawler.datamodel.CrawlURITest.java

/**
 * Test serialization/deserialization works.
 * /*from   www .  j a v a  2  s .  c o  m*/
 * @throws IOException
 * @throws ClassNotFoundException
 */
final public void testSerialization() throws IOException, ClassNotFoundException {
    File serialize = new File(getTmpDir(), this.getClass().getName() + ".serialize");
    try {
        FileOutputStream fos = new FileOutputStream(serialize);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(this.seed);
        oos.reset();
        oos.writeObject(this.seed);
        oos.reset();
        oos.writeObject(this.seed);
        oos.close();
        // Read in the object.
        FileInputStream fis = new FileInputStream(serialize);
        ObjectInputStream ois = new ObjectInputStream(fis);
        CrawlURI deserializedCuri = (CrawlURI) ois.readObject();
        deserializedCuri = (CrawlURI) ois.readObject();
        deserializedCuri = (CrawlURI) ois.readObject();
        assertTrue("Deserialized not equal to original",
                this.seed.toString().equals(deserializedCuri.toString()));
        String host = this.seed.getUURI().getHost();
        assertTrue("Deserialized host not null", host != null && host.length() >= 0);
    } finally {
        serialize.delete();
    }
}

From source file:de.rnd7.urlcache.URLCacheLoader.java

private Optional<CachedElement> loadFromDisk(final URLCacheKey key) throws IOException {
    final File localFile = this.toLocalFile(key);

    Optional<CachedElement> result = Optional.empty();

    if (localFile.exists()) {
        try (final InputStream in = new FileInputStream(localFile);
                final ObjectInputStream objIn = new ObjectInputStream(in);) {

            final CachedElement element = (CachedElement) objIn.readObject();
            result = Optional.of(element);
        } catch (final ClassNotFoundException e) {
            throw new IOException(e);
        }/* w w w. j ava2 s .  c  o  m*/
    }

    if (result.isPresent()) {
        if (!result.get().isValid()) {
            localFile.delete();
            result = Optional.empty();
        }
    }

    return result;
}

From source file:com.ikon.util.Serializer.java

/**
 * @param obj/*from   ww  w  .ja  v a  2s  .c om*/
 */
public static Object read(byte[] data) throws IOException, ClassNotFoundException {
    ByteArrayInputStream bais = null;
    ObjectInputStream ois = null;

    try {
        bais = new ByteArrayInputStream(data);
        ois = new ObjectInputStream(bais);
        return ois.readObject();
    } finally {
        IOUtils.closeQuietly(ois);
        IOUtils.closeQuietly(bais);
    }
}

From source file:com.izforge.izpack.event.AntActionUninstallerListener.java

/**
 * Initialises the listener./*from ww w. j a  va2 s.  c  o m*/
 *
 * @throws IzPackException for any error
 */
@Override
public void initialise() {
    String buildResource = getBuildResource();
    List<AntAction> allActions;
    try {
        // Load the defined actions.
        InputStream in = getClass().getResourceAsStream("/antActions");
        if (in == null) { // No actions, nothing todo.
            return;
        }
        ObjectInputStream objIn = new ObjectInputStream(in);
        // The actions are stored at installation time as list of AntAction
        // objects.
        // See AntActionInstallerListener.afterPacks.
        allActions = (List<AntAction>) objIn.readObject();
        objIn.close();
        in.close();
    } catch (Exception exception) {
        throw new IzPackException(exception);
    }
    // There are two possible orders; before and after deletion.
    // Now we assign the actions to two different lists, the
    // local "before" list which we perform after the scan and
    // the class member "antActions" which should contain the
    // "afterdeletion" actions. Additionally we should save needed
    // files like the properties file for this order because if they're
    // part of the pack the'll be lost after the deletion has been
    // performed.
    for (AntAction action : allActions) {
        // See if we need to set the action with the build_resource that
        //  we extracted
        if (null != buildResource) {
            // We do
            action.setBuildFile(new File(buildResource));
        }
        //
        if (action.getUninstallOrder().equals(ActionBase.BEFOREDELETION)) {
            befDel.add(action);
        } else {// We need the build and the properties file(s) outside the
                // install dir.
            if (null == buildResource) {
                // We have not copied a build_resource to a temporary file
                //  so now copy the local build file to a temporary file
                //  and set it as the build file for the action
                File tmpFile;
                try {
                    tmpFile = IoHelper.copyToTempFile(action.getBuildFile(), ".xml");
                } catch (IOException exception) {
                    throw new IzPackException(exception);
                }
                action.setBuildFile(tmpFile);
            }
            List<String> props = action.getPropertyFiles();
            if (props != null) {
                ArrayList<String> newProps = new ArrayList<String>();
                for (String propName : props) {
                    File propFile;
                    try {
                        propFile = IoHelper.copyToTempFile(propName, ".properties");
                        newProps.add(propFile.getCanonicalPath());
                    } catch (IOException exception) {
                        throw new IzPackException(exception);
                    }
                }
                action.setPropertyFiles(newProps);
            }
            antActions.add(action);
        }
    }
}

From source file:de.mpg.escidoc.services.aa.crypto.RSAEncoder.java

public static Key readKeyFromFile(String keyFileName, boolean publ) throws Exception {
    InputStream in = ResourceUtil.getResourceAsStream(keyFileName, RSAEncoder.class.getClassLoader());
    ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));
    try {/* w w w .j  a  v a 2  s  .co m*/
        BigInteger m = (BigInteger) oin.readObject();
        BigInteger e = (BigInteger) oin.readObject();
        KeySpec keySpec;
        if (publ) {
            keySpec = new RSAPublicKeySpec(m, e);
        } else {
            keySpec = new RSAPrivateKeySpec(m, e);
        }
        KeyFactory fact = KeyFactory.getInstance("RSA");
        if (publ) {
            PublicKey pubKey = fact.generatePublic(keySpec);
            return pubKey;
        } else {
            PrivateKey privKey = fact.generatePrivate(keySpec);
            return privKey;
        }
    } catch (Exception e) {
        throw new RuntimeException("Error reading key from file", e);
    } finally {
        oin.close();
    }
}

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

/**
 * Test that an instance is serializable.
 *///from  w  ww. j  av  a 2 s.co  m
public void test_serialization() {
    AllUsersGroup group, reconstitutedGroup;
    ByteArrayInputStream bais;
    ByteArrayOutputStream baos;
    ObjectInputStream ois;
    ObjectOutputStream oos;

    group = AllUsersGroup.getInstance();

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

        oos.writeObject(group);

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

        reconstitutedGroup = (AllUsersGroup) ois.readObject();

        assertEquals("Unexpected value", group, reconstitutedGroup);
    } catch (IOException e) {
        e.printStackTrace();
        fail("Unexpected exception");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        fail("Unexpected exception");
    }
}

From source file:geva.Main.State.java

/**
 * Load a State//www .  j a va  2s . c om
 * @param fileName Name of file to load
 **/
@SuppressWarnings({ "IOResourceOpenedButNotSafelyClosed" })
public void load(String fileName) {
    FileInputStream fIn;
    ObjectInputStream oIn;
    try {
        fIn = new FileInputStream(fileName);
        oIn = new ObjectInputStream(fIn);

        State emp = (State) oIn.readObject();
        logger.info(emp);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:jedi.util.serialization.Pickle.java

/**
 * Deserializes objects.//  ww w .  jav a  2s  .c o  m
 * 
 * @param f File that holds the serialized objects.
 * @return Object
 */
public static Object load(File f) {
    Object o = null;

    if (f != null) {
        try {
            FileInputStream fis = new FileInputStream(f);

            // The file reader.
            ObjectInputStream ois = new ObjectInputStream(fis);
            o = ois.readObject();
            ois.close();

            fis.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    return o;
}