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

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

Introduction

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

Prototype

public JsonReader(Reader in) 

Source Link

Document

Creates a new instance that reads a JSON-encoded stream from in .

Usage

From source file:com.hichinaschool.flashcards.libanki.importer.Anki2Importer.java

License:Open Source License

public int run() {
    publishProgress(false, 0, 0, false);
    try {//from  w w  w. ja  v a 2 s . c om
        // extract the deck from the zip file
        String tempDir = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpzip";
        // from anki2.py
        String colFile = tempDir + "/collection.anki2";
        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().getDir();
        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) {
        Log.e(AnkiDroidApp.TAG, "RuntimeException while importing ", e);
        return -1;
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "IOException while importing ", e);
        return -1;
    }
}

From source file:com.huguesjohnson.hapsby.Hapsby.java

License:Open Source License

private void loadDefinitions() throws Exception {
    String defFilePath = System.getProperty("user.dir") + File.separator + "hsd";
    File f = new File(defFilePath);
    String[] defList = f.list(new SaveDefFilter());
    int length = defList.length;
    this.gameDefinitions = new ArrayList<>();
    Gson gson = new Gson();
    for (int index = 0; index < length; index++) {
        try (JsonReader reader = new JsonReader(
                new FileReader(defFilePath + File.separator + defList[index]))) {
            this.gameDefinitions.add((SaveGameDefinition) gson.fromJson(reader, SaveGameDefinition.class));
        }/*w w w.ja  va 2s  .  c om*/
    }
}

From source file:com.ibm.watson.developer_cloud.util.ResponseUtil.java

License:Open Source License

/**
 * Parses the response into the POJO representation
 * /* ww w  .  j a va 2  s  . c  o  m*/
 * @param <T> the generic type to use when parsing the response
 * @param response the HTTP response
 * @param type the type of the response
 * @return the POJO
 */
public static <T extends GenericModel> T getObject(Response response, Class<T> type) {
    try {
        Reader bodyCharStream = response.body().charStream();
        //      PrintingReaderWrapper printingReaderWrapper = new PrintingReaderWrapper(bodyCharStream);
        final T model = GsonSingleton.getGson().fromJson(new JsonReader(bodyCharStream), type);
        return model;
    } catch (IOException e) {
        log.log(Level.SEVERE, ERROR_MESSAGE, e);
        throw new RuntimeException(ERROR_MESSAGE, e);
    } finally {
        try {
            response.body().close();
        } catch (IOException e) {
            log.log(Level.SEVERE, "Error closing the HTTP Response", e);
        }
    }
}

From source file:com.ibm.watson.developer_cloud.util.ResponseUtils.java

License:Open Source License

/**
 * Parses the {@link Response} into the POJO representation.
 *
 * @param <T> the generic type to use when parsing the response
 * @param response the HTTP response/*w w  w  . ja  v a 2  s  .com*/
 * @param type the type of the response
 * @return the POJO
 */
public static <T extends GenericModel> T getObject(Response response, Class<? extends T> type) {
    JsonReader reader;
    try {
        reader = new JsonReader(response.body().charStream());
        return GsonSingleton.getGsonWithoutPrettyPrinting().fromJson(reader, type);
    } finally {
        response.body().close();
    }
}

From source file:com.ibm.watson.discovery.v1.query.AggregationDeserializer.java

License:Open Source License

/**
 * Deserializes JSON and converts it to the appropriate {@link QueryAggregation} subclass.
 *
 * @param json the JSON data being deserialized
 * @param typeOfT the type to deserialize to, which should be {@link QueryAggregation}
 * @param context additional information about the deserialization state
 * @return the appropriate {@link QueryAggregation} subclass
 * @throws JsonParseException signals that there has been an issue parsing the JSON
 *///from   w  ww  .  j a  va 2  s .  c om
@Override
public QueryAggregation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonReader in = new JsonReader(new StringReader(GsonSingleton.getGson().toJson(json)));
    HashMap<String, Object> aggregationMap = null;

    try {
        aggregationMap = getAggregationMap(in);
    } catch (IOException e) {
        e.printStackTrace();
    }

    QueryAggregation aggregation;
    String aggregationType = (String) aggregationMap.get(TYPE);

    if (aggregationType.equals(AggregationType.HISTOGRAM.getName())) {
        aggregation = GsonSerializationHelper.serializeDynamicModelProperty(aggregationMap, Histogram.class);
    } else if (aggregationType.equals(AggregationType.MAX.getName())
            || aggregationType.equals(AggregationType.MIN.getName())
            || aggregationType.equals(AggregationType.AVERAGE.getName())
            || aggregationType.equals(AggregationType.SUM.getName())
            || aggregationType.equals(AggregationType.UNIQUE_COUNT.getName())) {
        aggregation = GsonSerializationHelper.serializeDynamicModelProperty(aggregationMap, Calculation.class);
    } else if (aggregationType.equals(AggregationType.TERM.getName())) {
        aggregation = GsonSerializationHelper.serializeDynamicModelProperty(aggregationMap, Term.class);
    } else if (aggregationType.equals(AggregationType.FILTER.getName())) {
        aggregation = GsonSerializationHelper.serializeDynamicModelProperty(aggregationMap, Filter.class);
    } else if (aggregationType.equals(AggregationType.NESTED.getName())) {
        aggregation = GsonSerializationHelper.serializeDynamicModelProperty(aggregationMap, Nested.class);
    } else if (aggregationType.equals(AggregationType.TIMESLICE.getName())) {
        aggregation = GsonSerializationHelper.serializeDynamicModelProperty(aggregationMap, Timeslice.class);
    } else if (aggregationType.equals(AggregationType.TOP_HITS.getName())) {
        aggregation = GsonSerializationHelper.serializeDynamicModelProperty(aggregationMap, TopHits.class);
    } else {
        aggregation = GsonSerializationHelper.serializeDynamicModelProperty(aggregationMap,
                QueryAggregation.class);
    }

    return aggregation;
}

From source file:com.ichi2.anki.AnkiDroidProxy.java

License:Open Source License

/**
 * Parses a JSON InputStream to a list of SharedDecks efficiently 
 * @param is InputStream to parse and convert. It only works with the reply from
 *        getSharedDecks request//from   ww w .  ja  v a 2s.c om
 * @return List of SharedDecks that were parsed
 * @throws Exception 
 */
public static List<SharedDeck> parseGetSharedDecksResponce(InputStream is) throws Exception {
    BufferedReader rd = new BufferedReader(new InputStreamReader(is), 409600);
    JsonReader reader = new JsonReader(rd);
    List<SharedDeck> sharedDecks = new ArrayList<SharedDeck>();
    try {
        reader.beginArray();
        int count = 0;
        while (reader.hasNext()) {
            SharedDeck sd = new SharedDeck();
            reader.beginArray();
            sd.setId(reader.nextInt()); // SD_ID
            reader.skipValue(); // SD_USERNAME
            sd.setTitle(reader.nextString()); // SD_TITLE
            reader.skipValue(); // SD_DESCRIPTION
            reader.skipValue(); // SD_TAGS
            reader.skipValue(); // SD_VERSION
            sd.setFacts(reader.nextInt()); // SD_FACTS
            sd.setSize(reader.nextInt()); // SD_SIZE
            reader.skipValue(); // SD_COUNT
            reader.skipValue(); // SD_MODIFIED
            reader.skipValue(); // SD_FNAME
            reader.endArray();
            sharedDecks.add(sd);
            count++;
        }
        reader.endArray();
        reader.close();
        Log.d(AnkiDroidApp.TAG, "parseGetSharedDecksResponce: found " + count + " shared decks");
    } catch (Exception e) {
        Log.e(AnkiDroidApp.TAG, Log.getStackTraceString(e));
        sharedDecks.clear();
        throw e;
    }

    return sharedDecks;
}

From source file:com.ichi2.async.DeckTask.java

License:Open Source License

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

    // extract the deck from the zip file
    String fileDir = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpzip";
    File dir = new File(fileDir);
    if (dir.exists()) {
        BackupManager.removeDir(dir);/*from   www  .j a  v  a2s . c  o  m*/
    }

    publishProgress(new TaskData(res.getString(R.string.import_unpacking)));
    // from anki2.py
    String colFile = fileDir + "/collection.anki2";
    ZipFile zip;
    try {
        zip = new ZipFile(new File(path), ZipFile.OPEN_READ);
    } catch (IOException e) {
        Timber.e(e, "doInBackgroundImportReplace - Error while unzipping");
        AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace0");
        return new TaskData(false);
    }
    if (!Utils.unzipFiles(zip, fileDir, 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)));
    String colPath;
    if (col != null) {
        // unload collection and trigger a backup
        colPath = col.getPath();
        AnkiDroidApp.closeCollection(true);
        BackupManager.performBackupInBackground(colPath, true);
    }
    // overwrite collection
    colPath = AnkiDroidApp.getCollectionPath();
    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 {
        // open using force close of old collection, as background loader may have reopened the col
        col = AnkiDroidApp.openCollection(colPath, true);

        // 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(fileDir, "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);

        publishProgress(new TaskData(res.getString(R.string.import_update_counts)));
        // Update the counts
        DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col));
        if (result == null) {
            return null;
        }
        return new TaskData(addedCount, result.getObjArray(), true);
    } catch (RuntimeException e) {
        Timber.e(e, "doInBackgroundImportReplace - RuntimeException");
        AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace1");
        return new TaskData(false);
    } catch (FileNotFoundException e) {
        Timber.e(e, "doInBackgroundImportReplace - FileNotFoundException");
        AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace2");
        return new TaskData(false);
    } catch (IOException e) {
        Timber.e(e, "doInBackgroundImportReplace - IOException");
        AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace3");
        return new TaskData(false);
    }
}

From source file:com.ichi2.libanki.importer.Anki2Importer.java

License:Open Source License

public int run() {
    publishProgress(false, 0, 0, false);
    try {/*from   w  w  w.j ava 2  s.  c  o  m*/
        // extract the deck from the zip file
        String tempDir = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpzip";
        // from anki2.py
        String colFile = tempDir + "/collection.anki2";
        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:com.ichi2.libanki.importer.AnkiPackageImporter.java

License:Open Source License

@Override
public void run() {
    publishProgress(0, 0, 0);/*from w ww .ja  va  2 s.  c  o m*/
    File tempDir = new File(new File(mCol.getPath()).getParent(), "tmpzip");
    Collection tmpCol;
    try {
        // We extract the zip contents into a temporary directory and do a little more
        // validation than the desktop client to ensure the extracted collection is an apkg.
        try {
            // extract the deck from the zip file
            mZip = new ZipFile(new File(mFile), ZipFile.OPEN_READ);
            Utils.unzipFiles(mZip, tempDir.getAbsolutePath(), new String[] { "collection.anki2", "media" },
                    null);
        } catch (IOException e) {
            Timber.e(e, "Failed to unzip apkg.");
            mLog.add(getRes().getString(R.string.import_log_no_apkg));
            return;
        }
        String colpath = new File(tempDir, "collection.anki2").getAbsolutePath();
        if (!(new File(colpath)).exists()) {
            mLog.add(getRes().getString(R.string.import_log_no_apkg));
            return;
        }
        tmpCol = Storage.Collection(mContext, colpath);
        try {
            if (!tmpCol.validCollection()) {
                mLog.add(getRes().getString(R.string.import_log_no_apkg));
                return;
            }
        } finally {
            if (tmpCol != null) {
                tmpCol.close();
            }
        }
        mFile = colpath;
        // 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");
        mNameToNum = new HashMap<>();
        // We need the opposite mapping in AnkiDroid since our extraction method requires it.
        Map<String, String> numToName = new HashMap<>();
        try {
            JsonReader jr = new JsonReader(new FileReader(mediaMapFile));
            jr.beginObject();
            String name;
            String num;
            while (jr.hasNext()) {
                num = jr.nextName();
                name = jr.nextString();
                mNameToNum.put(name, num);
                numToName.put(num, name);
            }
            jr.endObject();
            jr.close();
        } catch (FileNotFoundException e) {
            Timber.e("Apkg did not contain a media dict. No media will be imported.");
        } catch (IOException e) {
            Timber.e("Malformed media dict. Media import will be incomplete.");
        }
        // run anki2 importer
        super.run();
        // import static media
        for (Map.Entry<String, String> entry : mNameToNum.entrySet()) {
            String file = entry.getKey();
            String c = entry.getValue();
            if (!file.startsWith("_") && !file.startsWith("latex-")) {
                continue;
            }
            File path = new File(mCol.getMedia().dir(), Utils.nfcNormalized(file));
            if (!path.exists()) {
                try {
                    Utils.unzipFiles(mZip, mCol.getMedia().dir(), new String[] { c }, numToName);
                } catch (IOException e) {
                    Timber.e("Failed to extract static media file. Ignoring.");
                }
            }
        }
    } finally {
        // Clean up our temporary files
        if (tempDir.exists()) {
            BackupManager.removeDir(tempDir);
        }
    }
    publishProgress(100, 100, 100);
}

From source file:com.ikanow.infinit.e.data_model.custom.InfiniteFileInputJsonParser.java

License:Apache License

@Override
public InfiniteFileInputParser initialize(InputStream inStream, SourceFileConfigPojo fileConfig)
        throws IOException {

    this.primaryKey = fileConfig.XmlPrimaryKey;
    this.sourceName = fileConfig.XmlSourceName;
    if (null != fileConfig.XmlRootLevelValues) {
        for (String objectId : fileConfig.XmlRootLevelValues) {
            if (objectId.startsWith("*")) {
                this.bRecurse = true;
                this.recursiveObjectIdentifiers.add(objectId.substring(1).toLowerCase());
                throw new RuntimeException("JSON metadata parser: Don't currently support recursive parsing.");
                //TODO (INF-2469): Not currently supported, it gets a bit tricky?
            } //TESTED
            this.objectIdentifiers.add(objectId.toLowerCase());
        }//  w ww . ja  v  a2 s.c o m
    }
    if (null != fileConfig.XmlIgnoreValues) {
        this.fieldsThatNeedToExist.addAll(fileConfig.XmlIgnoreValues);
    }
    reader = new JsonReader(new InputStreamReader(inStream, "UTF-8"));
    reader.setLenient(true);
    parser = new JsonParser();

    return this;
}