Example usage for com.google.gson.stream JsonReader close

List of usage examples for com.google.gson.stream JsonReader close

Introduction

In this page you can find the example usage for com.google.gson.stream JsonReader close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this JSON reader and the underlying java.io.Reader .

Usage

From source file:vogar.OutcomeStore.java

License:Apache License

private void loadOutcomes(Map<String, AnnotatedOutcome> map, File file, long fileDate) throws IOException {
    JsonReader in = new JsonReader(new FileReader(file));
    in.beginObject();//from  w  w w .jav  a2s . com
    while (in.hasNext()) {
        String outcomeName = in.nextName();
        AnnotatedOutcome annotatedOutcome = map.get(outcomeName);
        if (annotatedOutcome == null) {
            in.skipValue();
            continue;
        }

        Result result = null;
        in.beginObject();
        while (in.hasNext()) {
            String fieldName = in.nextName();
            if (fieldName.equals("result")) {
                result = Result.valueOf(in.nextString());
            } else {
                in.skipValue();
            }
        }
        in.endObject();

        annotatedOutcome.add(fileDate, new Outcome(outcomeName, result, Collections.<String>emptyList()));
    }
    in.endObject();
    in.close();
}

From source file:website.openeng.async.DeckTask.java

License:Open Source License

private TaskData doInBackgroundImportReplace(TaskData... params) {
    Timber.d("doInBackgroundImportReplace");
    Collection col = CollectionHelper.getInstance().getCol(mContext);
    String path = params[0].getString();
    Resources res = KanjiDroidApp.getInstance().getBaseContext().getResources();

    // extract the deck from the zip file
    String colPath = col.getPath();
    File dir = new File(new File(colPath).getParentFile(), "tmpzip");
    if (dir.exists()) {
        BackupManager.removeDir(dir);//from w  w  w  .  j  av  a2  s .  co m
    }

    publishProgress(new TaskData(res.getString(R.string.import_unpacking)));
    // from anki2.py
    String colFile = new File(dir, "collection.anki2").getAbsolutePath();
    ZipFile zip;
    try {
        zip = new ZipFile(new File(path), ZipFile.OPEN_READ);
    } catch (IOException e) {
        Timber.e(e, "doInBackgroundImportReplace - Error while unzipping");
        KanjiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace0");
        return new TaskData(false);
    }
    if (!Utils.unzipFiles(zip, dir.getAbsolutePath(), new String[] { "collection.anki2", "media" }, null)
            || !(new File(colFile)).exists()) {
        return new TaskData(-2, null, false);
    }

    Collection tmpCol = null;
    try {
        tmpCol = Storage.Collection(colFile);
        if (!tmpCol.validCollection()) {
            tmpCol.close();
            return new TaskData(-2, null, false);
        }
    } catch (Exception e) {
        Timber.e("Error opening new collection file... probably it's invalid");
        try {
            tmpCol.close();
        } catch (Exception e2) {
            // do nothing
        }
        return new TaskData(-2, null, false);
    } finally {
        if (tmpCol != null) {
            tmpCol.close();
        }
    }

    publishProgress(new TaskData(res.getString(R.string.importing_collection)));
    if (col != null) {
        // unload collection and trigger a backup
        CollectionHelper.getInstance().closeCollection(true);
        CollectionHelper.getInstance().lockCollection();
        BackupManager.performBackupInBackground(colPath, true);
    }
    // overwrite collection
    File f = new File(colFile);
    if (!f.renameTo(new File(colPath))) {
        // Exit early if this didn't work
        return new TaskData(-2, null, false);
    }
    int addedCount = -1;
    try {
        col = CollectionHelper.getInstance().reopenCollection();
        CollectionHelper.getInstance().unlockCollection();

        // because users don't have a backup of media, it's safer to import new
        // data and rely on them running a media db check to get rid of any
        // unwanted media. in the future we might also want to duplicate this step
        // import media
        HashMap<String, String> nameToNum = new HashMap<String, String>();
        HashMap<String, String> numToName = new HashMap<String, String>();
        File mediaMapFile = new File(dir.getAbsolutePath(), "media");
        if (mediaMapFile.exists()) {
            JsonReader jr = new JsonReader(new FileReader(mediaMapFile));
            jr.beginObject();
            String name;
            String num;
            while (jr.hasNext()) {
                num = jr.nextName();
                name = jr.nextString();
                nameToNum.put(name, num);
                numToName.put(num, name);
            }
            jr.endObject();
            jr.close();
        }
        String mediaDir = col.getMedia().dir();
        int total = nameToNum.size();
        int i = 0;
        for (Map.Entry<String, String> entry : nameToNum.entrySet()) {
            String file = entry.getKey();
            String c = entry.getValue();
            File of = new File(mediaDir, file);
            if (!of.exists()) {
                Utils.unzipFiles(zip, mediaDir, new String[] { c }, numToName);
            }
            ++i;
            publishProgress(new TaskData(res.getString(R.string.import_media_count, (i + 1) * 100 / total)));
        }
        zip.close();
        // delete tmp dir
        BackupManager.removeDir(dir);
        return new TaskData(true);
    } catch (RuntimeException e) {
        Timber.e(e, "doInBackgroundImportReplace - RuntimeException");
        KanjiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace1");
        return new TaskData(false);
    } catch (FileNotFoundException e) {
        Timber.e(e, "doInBackgroundImportReplace - FileNotFoundException");
        KanjiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace2");
        return new TaskData(false);
    } catch (IOException e) {
        Timber.e(e, "doInBackgroundImportReplace - IOException");
        KanjiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace3");
        return new TaskData(false);
    }
}

From source file:website.openeng.libanki.importer.Anki2Importer.java

License:Open Source License

public int run() {
    publishProgress(false, 0, 0, false);
    try {/*from  w  w w  .  ja  va2 s  .c o m*/
        // extract the deck from the zip file
        String tempDir = new File(new File(mCol.getPath()).getParentFile(), "tmpzip").getAbsolutePath();
        // from anki2.py
        String colFile = new File(tempDir, "collection.anki2").getAbsolutePath();
        if (!Utils.unzipFiles(mZip, tempDir, new String[] { "collection.anki2", "media" }, null)
                || !(new File(colFile)).exists() || !Storage.Collection(colFile).validCollection()) {
            return -2;
        }

        // we need the media dict in advance, and we'll need a map of fname number to use during the import
        File mediaMapFile = new File(tempDir, "media");
        HashMap<String, String> numToName = new HashMap<String, String>();
        if (mediaMapFile.exists()) {
            JsonReader jr = new JsonReader(new FileReader(mediaMapFile));
            jr.beginObject();
            String name;
            String num;
            while (jr.hasNext()) {
                num = jr.nextName();
                name = jr.nextString();
                nameToNum.put(name, num);
                numToName.put(num, name);
            }
            jr.endObject();
            jr.close();
        }

        _prepareFiles(colFile);
        publishProgress(true, 0, 0, false);
        int cnt = -1;
        try {
            cnt = _import();
        } finally {
            // do not close collection but close only db (in order not to confuse access counting in storage.java
            // Note that the media database is still open and needs to be closed below.
            AnkiDatabaseManager.closeDatabase(mSrc.getPath());
        }
        // import static media
        String mediaDir = mCol.getMedia().dir();
        if (nameToNum.size() != 0) {
            for (Map.Entry<String, String> entry : nameToNum.entrySet()) {
                String file = entry.getKey();
                String c = entry.getValue();
                if (!file.startsWith("_") && !file.startsWith("latex-")) {
                    continue;
                }
                File of = new File(mediaDir, file);
                if (!of.exists()) {
                    Utils.unzipFiles(mZip, mediaDir, new String[] { c }, numToName);
                }
            }
        }
        mZip.close();
        mSrc.getMedia().close();
        // delete tmp dir
        File dir = new File(tempDir);
        BackupManager.removeDir(dir);
        publishProgress(true, 100, 100, true);
        return cnt;
    } catch (RuntimeException e) {
        Timber.e(e, "RuntimeException while importing");
        return -1;
    } catch (IOException e) {
        Timber.e(e, "IOException while importing");
        return -1;
    }
}

From source file:yong.dealer.shopping.ShoppingActivity.java

License:Apache License

public void fetchAndParseData() {

    JsonReader reader;
    InputStream inputStream = null;
    try {/*w  w w .  ja v  a2  s .c om*/
        inputStream = getResources()
                .openRawResource(getResources().getIdentifier("raw/itemlist", "raw", getPackageName()));
    } catch (Exception e) {

    }
    if (inputStream != null) {
        try {
            Gson gson = new Gson();

            reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
            reader.beginArray();
            while (reader.hasNext()) {
                ShoppingItem product = gson.fromJson(reader, ShoppingItem.class);
                //log.info("COINAPTYPE::" + Product.getType());
                products.add(product);
            }
            reader.endArray();
            reader.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            return; //this means the network connection is not good or IO
        }
    }
}