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:jfs.sync.meta.AbstractMetaStorageAccess.java

protected Map<String, FileInfo> getMetaData(String rootPath, String relativePath) {
    if (directoryCache.containsKey(relativePath)) {
        return directoryCache.get(relativePath);
    } // if/* w ww.j  a v a2 s  . c  om*/
    Map<String, FileInfo> result = new HashMap<>();
    ObjectInputStream ois = null;
    try {
        InputStream inputStream = getInputStream(rootPath, getMetaDataPath(relativePath));
        byte[] credentials = getCredentials(relativePath);
        Cipher cipher = SecurityUtils.getCipher(getCipherSpec(), Cipher.DECRYPT_MODE, credentials);
        inputStream = new CipherInputStream(inputStream, cipher);
        if (LOG.isDebugEnabled()) {
            LOG.debug("getMetaData() reading infos for " + relativePath);
        } // if
        ois = new ObjectInputStream(inputStream);
        Object o;
        while ((o = ois.readObject()) != null) {
            if (o instanceof FileInfo) {
                FileInfo fi = (FileInfo) o;
                if (fi.isDirectory()) {
                    String date;
                    synchronized (FORMATTER) {
                        date = FORMATTER.format(new Date(fi.getModificationDate()));
                    }
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(
                                "getMetaData() " + relativePath + getSeparator() + fi.getName() + ": " + date);
                    } // if
                } // if
                result.put(fi.getName(), fi);
            } // if
        } // while
        ois.close();
    } catch (FileNotFoundException | EOFException e) {
        // empty directory or - who cares?
    } catch (Exception e) {
        if (LOG.isInfoEnabled()) {
            LOG.info("getMetaData() possible issue while reading infos " + e, e);
        } // if
    } finally {
        try {
            if (ois != null) {
                ois.close();
            } // if
        } catch (Exception ex) {
            // who cares?
        } // try/catch
    } // try/catch
    directoryCache.put(relativePath, result);
    return result;
}

From source file:ru.org.linux.auth.UserDetailsServiceImpl.java

private Profile readProfile(String username) {
    Storage storage = new FileStorage(configuration.getPathPrefix() + "linux-storage/");
    InputStream df = null;/* w  w  w . j  a  v a2s  .c  o  m*/
    Map<String, Object> userProfile = null;
    try {
        df = storage.getReadStream("profile", username);
        ObjectInputStream dof = null;
        try {
            dof = new ObjectInputStream(df);
            userProfile = (Map<String, Object>) dof.readObject();
            dof.close();
            df.close();
        } catch (IOException e) {
            logger.info("Bad profile for user " + username);
        } finally {
            if (dof != null) {
                try {
                    dof.close();
                } catch (IOException e) {
                    logger.info("Bad profile for user " + username);
                }
            }
        }
    } catch (StorageException e) {
        logger.info("Bad profile for user " + username);
    } catch (ClassNotFoundException e) {
        logger.info("Bad profile for user " + username);
    } finally {
        if (df != null) {
            try {
                df.close();
            } catch (IOException e) {
                logger.info("Bad profile for user " + username);
            }
        }
    }
    ProfileProperties properties;
    if (userProfile != null) {
        properties = new ProfileProperties(
                new ProfileHashtable(DefaultProfile.getDefaultProfile(), userProfile));
    } else {
        properties = new ProfileProperties(
                new ProfileHashtable(DefaultProfile.getDefaultProfile(), new HashMap<String, Object>()));
    }
    return new Profile(properties, false);
}

From source file:com.amazon.sqs.javamessaging.message.SQSObjectMessage.java

/**
 * Deserialize the <code>String</code> into <code>Serializable</code>
 * object.//from  w ww.  ja v a 2 s.  co  m
 */
protected static Serializable deserialize(String serialized) throws JMSException {
    if (serialized == null) {
        return null;
    }
    Serializable deserializedObject;
    ObjectInputStream objectInputStream = null;
    try {
        byte[] bytes = Base64.decode(serialized);
        objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
        deserializedObject = (Serializable) objectInputStream.readObject();
    } catch (IOException e) {
        LOG.error("IOException: Message cannot be written", e);
        throw convertExceptionToMessageFormatException(e);
    } catch (Exception e) {
        LOG.error("Unexpected exception: ", e);
        throw convertExceptionToMessageFormatException(e);
    } finally {
        if (objectInputStream != null) {
            try {
                objectInputStream.close();
            } catch (IOException e) {
                LOG.warn(e.getMessage());
            }
        }
    }
    return deserializedObject;
}

From source file:aptgraph.server.JsonRpcServer.java

/**
 * Start the server, blocking. This method will only return if the server
 * crashed.../*from   w w w. j a  v  a2s  .c  om*/
 * @throws java.io.IOException if the graph file cannot be read
 * @throws java.lang.ClassNotFoundException if the Graph class is not found
 * @throws java.lang.Exception if the server cannot start...
 */
public final void start() throws IOException, ClassNotFoundException, Exception {

    LOGGER.info("Reading graphs from disk...");
    ObjectInputStream input = new ObjectInputStream(new BufferedInputStream(input_file));
    HashMap<String, LinkedList<Graph<Request>>> user_graphs = (HashMap<String, LinkedList<Graph<Request>>>) input
            .readObject();
    input.close();

    Map.Entry<String, LinkedList<Graph<Request>>> entry_set = user_graphs.entrySet().iterator().next();
    String first_key = entry_set.getKey();
    LOGGER.log(Level.INFO, "Graph has {0} features", user_graphs.get(first_key).size());
    LOGGER.log(Level.INFO, "k-NN Graph : k = {0}", user_graphs.get(first_key).getFirst().getK());
    LOGGER.log(Level.INFO, "Starting JSON-RPC server at http://{0}:{1}",
            new Object[] { config.getServerHost(), config.getServerPort() });

    RequestHandler request_handler = new RequestHandler(user_graphs);

    ObjectMapper object_mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Graph.class, new GraphSerializer());
    module.addSerializer(Domain.class, new DomainSerializer());
    module.addSerializer(Neighbor.class, new NeighborSerializer());
    object_mapper.registerModule(module);

    com.googlecode.jsonrpc4j.JsonRpcServer jsonrpc_server = new com.googlecode.jsonrpc4j.JsonRpcServer(
            object_mapper, request_handler);

    QueuedThreadPool thread_pool = new QueuedThreadPool(config.getMaxThreads(), config.getMinThreads(),
            config.getIdleTimeout(), new ArrayBlockingQueue<Runnable>(config.getMaxPendingRequests()));

    http_server = new org.eclipse.jetty.server.Server(thread_pool);
    //http_server = new org.eclipse.jetty.server.Server();

    ServerConnector http_connector = new ServerConnector(http_server);
    http_connector.setHost(config.getServerHost());
    http_connector.setPort(config.getServerPort());

    http_server.setConnectors(new Connector[] { http_connector });
    http_server.setHandler(new JettyHandler(jsonrpc_server));

    http_server.start();
}

From source file:com.hs.mail.imap.processor.fetch.BodyStructureBuilder.java

public MimeDescriptor readBodyStructure(File file) {
    if (file.exists()) {
        ObjectInputStream is = null;
        try {/*from  w  w  w.ja  v  a  2 s . com*/
            InputStream in = new BufferedInputStream(new FileInputStream(file));
            is = new ObjectInputStream(in);
            return (MimeDescriptor) is.readObject();
        } catch (Exception ex) {
            // TODO - remove this file
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    return null;
}

From source file:com.izforge.izpack.uninstaller.resource.RootScripts.java

/**
 * Returns the root scripts.//from   w w w.  j  av a2s. c o m
 *
 * @return the root scripts
 * @throws IzPackException if a resource cannot be read
 */
private List<String> getRootScripts(Resources resources) {
    List<String> result = new ArrayList<String>();
    for (int index = 0;; ++index) {
        try {
            String name = UninstallData.ROOTSCRIPT + Integer.toString(index);
            ObjectInputStream in = null;
            try {
                InputStream inputStream = resources.getInputStream(name);
                in = new ObjectInputStream(inputStream);
                result.add(in.readUTF());
            } catch (IOException exception) {
                throw new IzPackException("Failed to read resource: " + name, exception);
            } finally {
                IOUtils.closeQuietly(in);
            }
        } catch (ResourceNotFoundException ignore) {
            break;
        }
    }
    return result;
}

From source file:com.cedarsoft.crypt.HashTest.java

License:asdf

@Test
public void testSerialization() throws IOException, ClassNotFoundException {
    Hash hash = Hash.fromHex(Algorithm.SHA256, "1234");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    new ObjectOutputStream(out).writeObject(hash);

    Hash deserialized = (Hash) new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())).readObject();
    assertEquals(deserialized, hash);/*  w w w .  java 2 s  . c  om*/
}

From source file:com.mnt.base.util.SerializeUtil.java

public static Object deSerialize(byte[] source) {

    Object result;//from   w w w  .  j a  va2  s.com

    if (CommonUtil.isEmpty(source)) {
        result = null;
    } else {
        ByteArrayInputStream bais = new ByteArrayInputStream(source);
        try {
            ObjectInputStream ois = new ObjectInputStream(bais);
            result = ois.readObject();
            ois.close();
        } catch (Exception e) {
            log.error("error while open byte array input stream.", e);
            result = null;
        }
    }

    return result;
}

From source file:com.l2jfree.gameserver.cache.HtmCache.java

@SuppressWarnings("unchecked")
public synchronized void reload(boolean deleteCacheFile) {
    _cache.clear();//from w ww .  j ava 2  s  . c om
    _loadedFiles = 0;
    _size = 0;

    final File cacheFile = getCacheFile();

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

        cacheFile.delete();
    }

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

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

        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(Config.DATAPACK_ROOT);
    }

    _log.info(this);

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

        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(this);
    }

    if (cacheFile.exists()) {
        _log.info("Cache[HTML]: Validation skipped!");
    } else {
        _log.info("Cache[HTML]: Validating htmls...");

        validate();
    }

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

        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:calendarioSeries.vistas.MainViewController.java

public MainViewController() {
    mesActual = new Mes();
    Calendar cal = Calendar.getInstance();
    this.hoy = cal.get(Calendar.DAY_OF_MONTH);
    this.esteMes = mesActual.getNumMes();
    this.esteAno = mesActual.getNumAno();

    File file = new File("data.db");
    FileInputStream fis;/*  ww  w .  j a  va2s.c om*/
    ObjectInputStream ois;
    try {
        fis = new FileInputStream(file);
        ois = new ObjectInputStream(fis);
        this.series = (ArrayList<Serie>) ois.readObject();
        ois.close();
    } catch (IOException ex) {
        ex.printStackTrace();
        this.series = new ArrayList<>();
        try {
            File datos = new File("seriesUsuario.json");
            Scanner in = new Scanner(datos);
            String toJson = "";
            while (in.hasNext()) {
                toJson += in.nextLine();
            }
            JSONObject sesion = new JSONObject(toJson);
            Set<String> ids = sesion.keySet();
            for (String id : ids) {
                Serie aux = new Serie(id);
                if (series.contains(aux)) {
                    JSONArray lastVisto = sesion.getJSONArray(id).getJSONArray(1);
                    aux.setVistosHasta(lastVisto.getInt(0), lastVisto.getInt(1));
                    int i = 0;
                    for (Serie serie : series) {
                        if (serie.equals(aux)) {
                            this.series.set(i, aux);
                        }
                        i++;
                    }
                } else {
                    this.series.add(aux);
                }
            }

        } catch (FileNotFoundException e) {

        }
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    }

}