Example usage for java.io ObjectInputStream close

List of usage examples for java.io ObjectInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the input stream.

Usage

From source file:com.floreantpos.model.MenuItem.java

public MenuItem clone(MenuItem source) throws Exception {
    MenuItem menuItem = null;/*from   w w  w. j a  v a 2 s .  c o m*/
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(source);
        out.flush();
        out.close();

        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
        menuItem = (MenuItem) in.readObject();
        in.close();
    } catch (Exception ex) {
        throw ex;
    }
    return menuItem;
}

From source file:at.treedb.backup.Import.java

/**
 * Full restore of a database//from   w w  w  .j ava  2 s.  com
 * 
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public void fullRestore() throws Exception {
    archiveMap = readEntries();
    archiveInfo = new String(readData("dbinfo.xml"), "UTF8");
    xstream = new XStream();
    DBexportInfo dbInfo = (DBexportInfo) xstream.fromXML(archiveInfo);
    serialization = dbInfo.getSerialization();
    switch (serialization) {
    case JSON:
        gson = new Gson();
        break;
    case XML:
        if (xstream == null) {
            xstream = new XStream();
        }
        break;
    default:
        break;
    }

    DAOiface dao = DAO.getDAO();
    // dummy array for binary data
    byte[] dummyArray = new byte[1];
    // first loop - restore data without detached data
    for (Class<?> c : DBentities.getClasses()) {
        if (ignoreClass(c)) {
            continue;
        }
        HashMap<Integer, Integer> idMap = new HashMap<Integer, Integer>();
        classIdMap.put(c, idMap);
        HashMap<Integer, Integer> detachMap = new HashMap<Integer, Integer>();
        detachIdMap.put(c, detachMap);
        HashMap<Integer, Integer> historicMap = new HashMap<Integer, Integer>();
        historicIdMap.put(c, historicMap);
        int dataBlockCounter = 0;
        while (true) {
            String path = "treeDB/" + c.getSimpleName() + "/" + dataBlockCounter;
            if (!archiveMap.containsKey(path)) {
                break; // not entities available of this class
            }
            byte[] data = readData(path);
            // detached binary data available?
            ArrayList<Field> fieldList = new ArrayList<Field>();
            for (Field f : c.getDeclaredFields()) {
                if (f.getAnnotation(Detach.class) != null) {
                    f.setAccessible(true);
                    fieldList.add(f);
                }

            }
            // data de-serialization
            List<Base> list = null;
            switch (serialization) {
            case JSON:
                ParameterizedTypeImpl pti = new ParameterizedTypeImpl(List.class, new Type[] { c }, null);
                list = gson.fromJson(new String(data), pti);
                break;
            case XML:
                list = (List<Base>) xstream.fromXML(new String(data));
                break;
            case BINARY:
                ByteArrayInputStream is = new ByteArrayInputStream(data);
                ObjectInputStream input = new ObjectInputStream(is);
                list = (List<Base>) input.readObject();
                input.close();
                break;
            default:
                break;
            }
            // traverse entities
            for (Base b : list) {
                if (!fieldList.isEmpty()) {
                    for (Field f : fieldList) {
                        // set a dummy binary array to avoid
                        // @Column(nullable = false) conflicts
                        f.set(b, dummyArray);
                    }
                }
                int oldDBid = b.getDBid();
                dao.beginTransaction();
                Base.restore(dao, b);
                dao.endTransaction();
                // store the pair old DB ID / new DB ID
                idMap.put(oldDBid, b.getDBid());
                if (historicMap.get(b.getHistId()) == null) {
                    historicMap.put(b.getHistId(), b.getDBid());
                }
                if (!fieldList.isEmpty()) {
                    // store the pair new DB ID / old DB ID
                    detachMap.put(b.getDBid(), oldDBid);
                }
                if (c.equals(DBfile.class)) {
                    fileIdMap.put(b.getDBid(), oldDBid);
                }
            }
            ++dataBlockCounter;
        }
    }
    // second loop - adjust DB IDs
    for (Class<?> c : DBentities.getClasses()) {
        if (ignoreClass(c)) {
            continue;
        }
        dao.beginTransaction();
        Iterator iter = new Iterator(dao, c, null, null, entityFetchThreshold);
        adjustFields(dao, c, iter);
        dao.endTransaction();
    }
}

From source file:jhttpp2.Jhttpp2Launcher.java

@SuppressWarnings("unchecked")
public void restoreSettings()// throws Exception
{
    if (server.getServerProperties() == null) {
        log.warn("server propertie where not set will not save them");
        return;//from  ww  w  .  j  a  v a2  s  . c om
    }

    try {

        // Restore the WildcardDioctionary and the URLActions with the
        // ObjectInputStream (settings.dat)...
        ObjectInputStream obj_in;
        File file = new File(DATA_FILE);
        if (!file.exists()) {
            if (!file.createNewFile() || !file.canWrite()) {
                log.warn("Can't create or write to file " + file.toString());
            } else
                saveServerSettings();
        }

        obj_in = new ObjectInputStream(new FileInputStream(file));
        server.setWildcardDictionary((WildcardDictionary) obj_in.readObject());
        server.setURLActions((List<OnURLAction>) obj_in.readObject());
        obj_in.close();
    } catch (IOException e) {
        log.warn("restoreSettings(): " + e.getMessage());
    } catch (ClassNotFoundException e_class_not_found) {
    }
}

From source file:com.radicaldynamic.groupinform.services.InformOnlineService.java

private void restoreSession() {
    // Restore any serialized session information
    File sessionCache = new File(getCacheDir(), FileUtilsExtended.SESSION_CACHE_FILE);

    if (sessionCache.exists()) {
        if (Collect.Log.DEBUG)
            Log.d(Collect.LOGTAG, t + "restoring cached session");

        try {/*  w  w  w.  ja va  2  s.  c  om*/
            InformOnlineSession session = new InformOnlineSession();

            FileInputStream fis = new FileInputStream(sessionCache);
            ObjectInputStream ois = new ObjectInputStream(fis);
            session = (InformOnlineSession) ois.readObject();
            ois.close();
            fis.close();

            Collect.getInstance().getInformOnlineState().setSession(new BasicCookieStore());
            Iterator<InformOnlineSession> cookies = session.getCookies().iterator();

            if (cookies.hasNext()) {
                InformOnlineSession ios = cookies.next();

                BasicClientCookie bcc = new BasicClientCookie(ios.getName(), ios.getValue());
                bcc.setDomain(ios.getDomain());
                bcc.setExpiryDate(ios.getExpiryDate());
                bcc.setPath(ios.getPath());
                bcc.setVersion(ios.getVersion());

                Collect.getInstance().getInformOnlineState().getSession().addCookie(bcc);
            }
        } catch (Exception e) {
            if (Collect.Log.WARN)
                Log.w(Collect.LOGTAG, t + "problem restoring cached session " + e.toString());
            e.printStackTrace();

            // Don't leave a broken file hanging
            new File(getCacheDir(), FileUtilsExtended.SESSION_CACHE_FILE).delete();

            // Clear the session
            Collect.getInstance().getInformOnlineState().setSession(null);
        }
    } else {
        if (Collect.Log.DEBUG)
            Log.d(Collect.LOGTAG, t + "no session to restore");
    }
}

From source file:com.all.client.itunes.ByteObject.java

public Serializable readObject() {
    if (compressed) {
        throw new IllegalStateException(
                "The byte content is compressed. Uncompress the content before reading an Object.");
    }/*from  w  w w. j a v  a 2 s.co m*/
    if (content == null) {
        return null;
    }
    ByteArrayInputStream bais = new ByteArrayInputStream(content);
    ObjectInputStream ois;
    Serializable result = null;
    try {
        ois = new ObjectInputStream(bais);
        result = (Serializable) ois.readObject();
        ois.close();
    } catch (Exception e) {
        return null;
    }
    return result;
}

From source file:de.tudarmstadt.ukp.dkpro.lexsemresource.graph.PersistentAdjacencyMatrix.java

@SuppressWarnings("unchecked")
public void loadIndices() {

    logger.info("Loading the indices...");

    FileInputStream finEntIndex = null;
    ObjectInputStream inEntIndex = null;

    FileInputStream finIndexEnt = null;
    ObjectInputStream inIndexEnt = null;

    try {//from w  ww  .j  av a  2s  .  c  o m
        finEntIndex = new FileInputStream("EntityIndexSer" + "_" + resourceName);
        inEntIndex = new ObjectInputStream(finEntIndex);
        entityIndex = (Map<Entity, Integer>) inEntIndex.readObject();
        inEntIndex.close();

        finIndexEnt = new FileInputStream("IndexToEntitySer" + "_" + resourceName);
        inIndexEnt = new ObjectInputStream(finIndexEnt);
        indexToEntity = (Map<Integer, Entity>) inIndexEnt.readObject();
        inIndexEnt.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    logger.info("Indices loaded.");

}

From source file:com.izforge.izpack.installer.multiunpacker.MultiVolumeUnpackerTest.java

/**
 * Verifies that there are multiple volumes of the expected size.
 *
 * @param dir                the directory to find the volumes in
 * @param resources          the resources used to determine the volume name and count
 * @param maxFirstVolumeSize the maximum size of the first volume
 * @param maxVolumeSize      the maximum volume size for subsequent volumes
 * @throws IOException for any I/O error
 *///from  w  w  w  .  jav a 2s.  c o m
private void checkVolumes(File dir, Resources resources, long maxFirstVolumeSize, long maxVolumeSize)
        throws IOException {
    // get the volume information
    ObjectInputStream info = new ObjectInputStream(resources.getInputStream(MultiVolumeUnpacker.VOLUMES_INFO));
    int count = info.readInt();
    String name = info.readUTF();
    info.close();
    assertTrue(count >= 1);

    // verify the primary volume exists, with the expected size
    File volume = new File(dir, name);
    assertTrue(volume.exists());
    assertEquals(maxFirstVolumeSize, volume.length());

    // check the existence and size of the remaining volumes
    for (int i = 1; i < count; ++i) {
        volume = new File(dir, name + "." + i);
        assertTrue(volume.exists());
        if (i < count - 1) {
            // can't check the size of the last volume
            assertEquals(maxVolumeSize, volume.length());
        }
    }
}

From source file:edu.umd.cs.submitServer.servlets.HandleBuildServerLogMessage.java

/**
 * The doPost method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to
 * post./*  w w  w .  ja  v a2s. c o  m*/
 *
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
    FileItem fileItem = null;
    LoggingEvent loggingEvent = null;
    ObjectInputStream in = null;
    try {
        fileItem = multipartRequest.getFileItem();
        byte[] data = fileItem.get();

        in = new ObjectInputStream(new ByteArrayInputStream(data));
        loggingEvent = (LoggingEvent) in.readObject();

        buildServerLogger.callAppenders(loggingEvent);
    } catch (ClassNotFoundException e) {
        throw new ServletException("Cannot find class: " + e.getMessage(), e);
    } finally {
        if (fileItem != null)
            fileItem.delete();
        if (in != null)
            in.close();
    }
}

From source file:PSOResultFileReader.java

/**
 * Returns the variable represented by the Base64 encoded string.
 * // w  ww  .  j  a v a2  s .  c  o m
 * @param string the Base64 encoded representation of the variable
 * @return the variable represented by the Base64 encoded string
 * @throws IOException if the variable could not be deserialized
 * @throws ClassNotFoundException if the class of the deserialized variable
 *         could not be found
 */
private Variable deserialize(String string) throws IOException, ClassNotFoundException {
    ObjectInputStream ois = null;

    try {
        byte[] encoding = Base64.decodeBase64(string);
        ByteArrayInputStream baos = new ByteArrayInputStream(encoding);
        ois = new ObjectInputStream(baos);

        return (Variable) ois.readObject();
    } finally {
        if (ois != null) {
            ois.close();
        }
    }
}