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.joliciel.talismane.lexicon.LexiconDeserializer.java

public PosTaggerLexicon deserializeLexiconFile(File lexiconFile) {
    MONITOR.startTask("deserializeLexiconFile(File)");
    try {//from   w  w  w  . jav  a2  s.  c  om
        LOG.debug("deserializing " + lexiconFile.getName());
        boolean isZip = false;
        if (lexiconFile.getName().endsWith(".zip"))
            isZip = true;

        PosTaggerLexicon lexicon = null;
        ZipInputStream zis = null;
        FileInputStream fis = null;
        ObjectInputStream in = null;

        try {
            fis = new FileInputStream(lexiconFile);
            if (isZip) {
                zis = new ZipInputStream(fis);
                lexicon = this.deserializeLexiconFile(zis);
            } else {
                in = new ObjectInputStream(fis);
                lexicon = (PosTaggerLexicon) in.readObject();
                in.close();
            }
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        } catch (ClassNotFoundException cnfe) {
            throw new RuntimeException(cnfe);
        }

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

From source file:LessonSaver.ServerBridge.java

public ServerBridge() {
    // ?    ? ? ? 
    if (new File("frameQueue.dat").exists()) //?  ?? ?   ?     
    {//from w  ww  . j  a  v a2 s. c om
        try {
            FileInputStream FIS = new FileInputStream("frameQueue.dat");
            try {
                ObjectInputStream OIS = new ObjectInputStream(FIS);
                try {
                    this.frameQueue = (ConcurrentLinkedQueue<ServerBridge.Frame>) OIS.readObject();
                } catch (ClassNotFoundException ex) {
                }
                OIS.close();
            } catch (IOException ex) {
            }
        } catch (FileNotFoundException ex) {
        }
    } else //?  ??  ?  
    {
        this.frameQueue = new ConcurrentLinkedQueue<>();
    }

    this.bridge = new Bridge();
    Thread T = new Thread(this.bridge);
    T.setDaemon(true);
    T.start();
}

From source file:edu.stanford.muse.email.JarDocCache.java

public Map<Integer, Document> getAllHeaders(String prefix) throws IOException, ClassNotFoundException {
    Map<Integer, Document> result = new LinkedHashMap<Integer, Document>();
    JarFile jarFile = null;/*from  w w w.  j av  a 2 s.c o  m*/
    String fname = baseDir + File.separator + prefix + ".headers";
    try {
        jarFile = new JarFile(fname);
    } catch (Exception e) {
        log.info("No Jar file exists: " + fname);
    }
    if (jarFile == null)
        return result;

    Enumeration<JarEntry> entries = jarFile.entries();
    String suffix = ".header";
    while (entries.hasMoreElements()) {
        JarEntry je = entries.nextElement();
        String s = je.getName();
        if (!s.endsWith(suffix))
            continue;
        String idx_str = s.substring(0, s.length() - suffix.length());
        int index = -1;
        try {
            index = Integer.parseInt(idx_str);
        } catch (Exception e) {
            log.error("Funny file in header: " + index);
        }

        ObjectInputStream ois = new ObjectInputStream(jarFile.getInputStream(je));
        Document ed = (Document) ois.readObject();
        ois.close();
        result.put(index, ed);
    }
    return result;
}

From source file:de.scoopgmbh.copper.persistent.StandardJavaSerializer.java

private Serializable deserialize(String _data, final WorkflowRepository wfRepo)
        throws IOException, ClassNotFoundException, DataFormatException {
    if (_data == null)
        return null;
    boolean isCompressed = _data.charAt(0) == 'C';
    byte[] data = Base64.decodeBase64(_data.substring(1));
    if (isCompressed) {
        data = compressorTL.get().uncompress(data);
    }/*  ww w  .  j  av  a 2s .  co  m*/
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    ObjectInputStream ois = wfRepo != null ? new ObjectInputStream(bais) {
        @Override
        protected java.lang.Class<?> resolveClass(java.io.ObjectStreamClass desc)
                throws java.io.IOException, ClassNotFoundException {
            return wfRepo.resolveClass(desc);
        };
    } : new ObjectInputStream(bais);
    Serializable o = (Serializable) ois.readObject();
    ois.close();
    return o;
}

From source file:cascading.util.Util.java

public static Object deserializeBase64(String string, boolean decompress) throws IOException {
    if (string == null || string.length() == 0)
        return null;

    ObjectInputStream in = null;

    try {//  w  ww .j  a  v a  2  s  .  c  o  m
        ByteArrayInputStream bytes = new ByteArrayInputStream(Base64.decodeBase64(string.getBytes()));

        in = new ObjectInputStream(decompress ? new GZIPInputStream(bytes) : bytes) {
            @Override
            protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                try {
                    return Class.forName(desc.getName(), false, Thread.currentThread().getContextClassLoader());
                } catch (ClassNotFoundException exception) {
                    return super.resolveClass(desc);
                }
            }
        };

        return in.readObject();
    } catch (ClassNotFoundException exception) {
        throw new FlowException("unable to deserialize data", exception);
    } finally {
        if (in != null)
            in.close();
    }
}

From source file:io.seldon.api.state.ZkABTestingUpdater.java

@Override
public void run() {
    logger.info("Starting");
    try {/*from   ww  w .  j  a  v a 2 s. co m*/
        while (keepRunning) {
            boolean error = false;
            try {

                CuratorFramework client = null;
                boolean ok = false;
                for (int attempts = 0; attempts < 4 && !ok; attempts++) {
                    client = curatorHandler.getCurator().usingNamespace(clientName);
                    logger.info("Waiting until zookeeper connected");
                    ok = client.getZookeeperClient().blockUntilConnectedOrTimedOut();
                    if (ok)
                        logger.info("zookeeper connected on attempt " + attempts);
                    else {
                        logger.error("Timed out waiting for zookeeper connect : attempt " + attempts);
                    }
                }
                if (!ok) {
                    logger.error("Failed to connect to zookeeper after multiple attempts - STOPPING");
                    return;
                }
                queue = new LinkedBlockingQueue<>();
                Watcher watcher = new Watcher() {
                    boolean expired;

                    @Override
                    public void process(WatchedEvent event) {
                        try {
                            if (event.getPath() != null)
                                queue.put(event.getPath());
                            else {
                                logger.warn("Unexpected event " + event.getType().name() + " -> "
                                        + event.toString());
                                switch (event.getState()) {
                                case SyncConnected: {
                                }
                                    break;
                                case Expired: {
                                    queue.put("");
                                }
                                    break;
                                case Disconnected: {
                                }
                                    break;
                                }
                            }
                        } catch (InterruptedException e) {
                            throw new Error(e);
                        }
                    }
                };

                logger.info("Checking path " + DYNAMIC_PARAM_PATH + " exists");
                if (client.checkExists().forPath(DYNAMIC_PARAM_PATH) == null) {
                    logger.warn("Path " + DYNAMIC_PARAM_PATH + " does not exist for client " + clientName
                            + " creating...");
                    client.create().forPath(DYNAMIC_PARAM_PATH);
                }

                logger.info("Checking path " + AB_ALG_PATH + " exists");
                if (client.checkExists().forPath(AB_ALG_PATH) == null) {
                    logger.warn("Path " + AB_ALG_PATH + " does not exist for client " + clientName
                            + " creating...");
                    client.create().forPath(AB_ALG_PATH);
                }

                client.getData().usingWatcher(watcher).forPath(DYNAMIC_PARAM_PATH);
                client.getData().usingWatcher(watcher).forPath(AB_ALG_PATH);

                boolean restart = false;
                while (keepRunning && !restart) {

                    String path = queue.take();
                    if (!StringUtils.isEmpty(path)) {
                        logger.info("Alg Path changed " + path);

                        System.out.println("Alg Path changed " + path);

                        if (path.endsWith(DYNAMIC_PARAM_PATH)) {
                            try {
                                byte[] bytes = client.getData().forPath(DYNAMIC_PARAM_PATH);
                                ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
                                DynamicParameterBean bean = (DynamicParameterBean) in.readObject();
                                in.close();
                                logger.info("Updating dynamic parameter: " + bean.getName()
                                        + " and setting to value: " + bean.getValue() + " for client "
                                        + clientName);
                                DynamicParameterServer.setParameterBean(clientName, bean);
                                numUpdates++;
                            } catch (ClassNotFoundException e) {
                                logger.error("Can't find class ", e);
                            } catch (IOException e) {
                                logger.error("Failed to deserialize algorithm for client " + clientName, e);
                            } finally {
                                client.getData().usingWatcher(watcher).forPath(DYNAMIC_PARAM_PATH);
                            }

                        } else if (path.endsWith(AB_ALG_PATH)) {
                            try {
                                byte[] bytes = client.getData().forPath(AB_ALG_PATH);

                                ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
                                ABTest abTest = (ABTest) in.readObject();
                                in.close();
                                logger.info("Updating Algorithm percentage for client " + clientName + " to "
                                        + abTest.toString());
                                ABTestingServer.setABTest(clientName, abTest);
                                numUpdates++;
                            } catch (ClassNotFoundException e) {
                                logger.error("Can't find class ", e);
                            } catch (IOException e) {
                                logger.error("Failed to deserialize algorithm for client " + clientName, e);
                            } finally {
                                client.getData().usingWatcher(watcher).forPath(AB_ALG_PATH);
                            }
                        } else {
                            logger.error("Unknown path " + path + " changed so reseting watchers");
                        }
                    } else {
                        //client.getData().usingWatcher(watcher).forPath(DYNAMIC_PARAM_PATH);
                        //client.getData().usingWatcher(watcher).forPath(AB_ALG_PATH);
                        logger.warn("Will try to restart");
                        restart = true;
                    }

                }

            } catch (IOException e) {
                logger.error("Exception trying to create sk client ", e);
                error = true;
            } catch (Exception e) {
                logger.error("Exception from zookeeper client ", e);
                error = true;
            } finally {

            }

            if (keepRunning && error) {
                logger.info("Sleeping " + sleepTime);
                Thread.sleep(sleepTime);
                if (sleepTime * 2 < maxSleepTime)
                    sleepTime = sleepTime * 2;
                error = false;
            }

        }
    } catch (InterruptedException e) {
        logger.warn("Sleep interuppted ", e);
    }
    logger.info("Stopping");
}

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

@Test
public void testGoogleDictionary() throws Exception {

    FileUtils.deleteQuietly(new File(output));

    GoogleDictionary dictionary = new GoogleDictionary(path, needed_mentions);
    Assert.assertNotNull(dictionary);/*  www.  j  a  v a 2  s . c  o m*/

    ObjectOutputStream dictionaryWriter = new ObjectOutputStream(
            new BZip2CompressorOutputStream(new FileOutputStream(output)));
    dictionaryWriter.writeObject(dictionary);
    dictionaryWriter.close();

    Assert.assertTrue(new File(output).exists());

    ObjectInputStream dictionaryReader = new ObjectInputStream(
            new BZip2CompressorInputStream(new FileInputStream(output)));

    dictionary = null;
    dictionary = (GoogleDictionary) dictionaryReader.readObject();

    Assert.assertNotNull(dictionary);
    System.out.println(dictionary.getNumberOfMentionEntityPairs());
    System.out.println(dictionary.getTargetSize());
    Assert.assertEquals(3, dictionary.getTargetValuePairs("claude_monet").size());

    dictionaryReader.close();

}

From source file:models.TopicModel.java

protected InstanceList getDocumentVectors() throws IOException, ClassNotFoundException {
    if (currentInstanceList == null) {
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(featureSequence));
        currentInstanceList = (InstanceList) ois.readObject();
        ois.close();
    }//from  w ww  .j  ava2  s.  co m
    return currentInstanceList;
}

From source file:com.aurel.track.exchange.excel.ExcelFieldMatchAction.java

/**
 * Render the field match: first time and after a sheet change
 *//*from  w w w.  j  ava2  s . c  om*/
@Override
public String execute() {
    File fileOnDisk = new File(excelMappingsDirectory, fileName);
    workbook = ExcelFieldMatchBL.loadWorkbook(excelMappingsDirectory, fileName);
    if (workbook == null) {
        JSONUtility.encodeJSON(servletResponse,
                JSONUtility.encodeJSONFailure(getText("admin.actions.importExcel.err.noWorkbook")), false);
        fileOnDisk.delete();
        return null;
    }
    if (selectedSheet == null) {
        //first rendering (not submit because of sheet change)
        selectedSheet = Integer.valueOf(0);
    }
    //get the previous field mappings
    Map<String, Integer> columNameToFieldIDMap = null;
    Set<Integer> lastSavedIdentifierFieldIDIsSet = null;
    try {
        FileInputStream fis = new FileInputStream(new File(excelMappingsDirectory, mappingFileName));

        ObjectInputStream objectInputStream = new ObjectInputStream(fis);
        columNameToFieldIDMap = (Map<String, Integer>) objectInputStream.readObject();
        lastSavedIdentifierFieldIDIsSet = (Set<Integer>) objectInputStream.readObject();
        objectInputStream.close();
    } catch (FileNotFoundException e) {
        LOGGER.info("Creating the input stream for mapping failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (IOException e) {
        LOGGER.warn("Saving the mapping failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (ClassNotFoundException e) {
        LOGGER.warn("Class not found for  the mapping " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    //get the column index to header names from the excel sheet
    SortedMap<Integer, String> columnIndexToColumNameMap = ExcelFieldMatchBL.getFirstRowHeaders(workbook,
            selectedSheet);

    SortedSet<String> excelColumnNames = new TreeSet<String>();
    excelColumnNames.addAll(columnIndexToColumNameMap.values());
    //prepare the best field matching
    if (columNameToFieldIDMap == null) {
        columNameToFieldIDMap = new HashMap<String, Integer>();
    }
    ExcelFieldMatchBL.prepareBestMatchByLabel(excelColumnNames, columNameToFieldIDMap, locale);
    columnIndexToFieldIDMap = ExcelFieldMatchBL.getColumnIndexToFieldIDMap(columNameToFieldIDMap,
            columnIndexToColumNameMap);
    columnIndexIsIdentifierMap = new HashMap<Integer, Boolean>();
    //the saved identifier columns
    if (lastSavedIdentifierFieldIDIsSet != null && !lastSavedIdentifierFieldIDIsSet.isEmpty()) {
        for (Integer columnIndex : columnIndexToFieldIDMap.keySet()) {
            Integer fieldID = columnIndexToFieldIDMap.get(columnIndex);
            columnIndexIsIdentifierMap.put(columnIndex,
                    new Boolean(lastSavedIdentifierFieldIDIsSet.contains(fieldID)));
        }
    }
    //if issueNo is present it is always identifier (first time it should be preselected and any time when mapped also preselected)
    if (columnIndexToFieldIDMap.values().contains(SystemFields.INTEGER_ISSUENO)) {
        for (Integer columnIndex : columnIndexToFieldIDMap.keySet()) {
            Integer fieldID = columnIndexToFieldIDMap.get(columnIndex);
            if (SystemFields.INTEGER_ISSUENO.equals(fieldID)) {
                columnIndexIsIdentifierMap.put(columnIndex, new Boolean(true));
            }
        }
    }
    List<IntegerStringBean> sheetNames = ExcelFieldMatchBL.loadSheetNames(workbook);
    List<IntegerStringBean> matchableFieldsList = ExcelFieldMatchBL.getFieldConfigs(personID, locale);
    Map<Integer, String> columnIndexNumericToLetter = ExcelFieldMatchBL.getFirstRowNumericToLetter(workbook,
            selectedSheet);
    Set<Integer> possibleIdentifiersSet = ExcelFieldMatchBL.getPossibleIdentifierFields();
    Set<Integer> mandatoryIdentifiersSet = ExcelFieldMatchBL.getMandatoryIdentifierFields();
    JSONUtility.encodeJSON(servletResponse,
            ExcelImportJSON.getExcelFieldMatcherJSON(fileName, selectedSheet, sheetNames, matchableFieldsList,
                    columnIndexToColumNameMap, columnIndexNumericToLetter, columnIndexToFieldIDMap,
                    columnIndexIsIdentifierMap, possibleIdentifiersSet, mandatoryIdentifiersSet),
            false);
    return null;
}

From source file:Main.java

@SuppressWarnings("unchecked")
static boolean loadSharedPreferencesFromFile(Context context, File src) {
    boolean res = false;
    ObjectInputStream input = null;
    try {// w  w  w  .  ja  v a 2s.  c  om
        GZIPInputStream inputGZIP = new GZIPInputStream(new FileInputStream(src));
        input = new ObjectInputStream(inputGZIP);
        Editor prefEdit = PreferenceManager.getDefaultSharedPreferences(context).edit();
        prefEdit.clear();
        Map<String, Object> entries = (Map<String, Object>) input.readObject();
        for (Entry<String, ?> entry : entries.entrySet()) {
            Object v = entry.getValue();
            String key = entry.getKey();

            if (v instanceof Boolean)
                prefEdit.putBoolean(key, ((Boolean) v).booleanValue());
            else if (v instanceof Float)
                prefEdit.putFloat(key, ((Float) v).floatValue());
            else if (v instanceof Integer)
                prefEdit.putInt(key, ((Integer) v).intValue());
            else if (v instanceof Long)
                prefEdit.putLong(key, ((Long) v).longValue());
            else if (v instanceof String)
                prefEdit.putString(key, ((String) v));
        }
        prefEdit.commit();
        res = true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return res;
}