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

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

Introduction

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

Prototype

public String nextName() throws IOException 

Source Link

Document

Returns the next token, a com.google.gson.stream.JsonToken#NAME property name , and consumes it.

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. j  a  v a2s .  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().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.ibasco.agql.protocols.valve.dota2.webapi.adapters.Dota2TeamInfoAdapter.java

License:Open Source License

@Override
public Dota2MatchTeamInfo read(JsonReader in) throws IOException {
    in.beginObject();//from  ww  w .  jav  a  2  s  .  co  m
    Dota2MatchTeamInfo teamInfo = new Dota2MatchTeamInfo();
    while (in.hasNext()) {
        String name = in.nextName();
        if (name.startsWith("league_id_")) {
            teamInfo.getLeagueIds().add(in.nextInt());
        } else if (name.startsWith("player_")) {
            teamInfo.getPlayerAccountIds().add(in.nextLong());
        } else {
            switch (name) {
            case "name":
                teamInfo.setName(in.nextString());
                break;
            case "tag":
                teamInfo.setTag(in.nextString());
                break;
            case "time_created":
                teamInfo.setTimeCreated(in.nextLong());
                break;
            case "calibration_games_remaining":
                teamInfo.setCalibrationGamesRemaining(in.nextInt());
                break;
            case "logo":
                teamInfo.setLogo(in.nextLong());
                break;
            case "logo_sponsor":
                teamInfo.setLogoSponsor(in.nextLong());
                break;
            case "country_code":
                teamInfo.setCountryCode(in.nextString());
                break;
            case "url":
                teamInfo.setUrl(in.nextString());
                break;
            case "games_played":
                teamInfo.setGamesPlayed(in.nextInt());
                break;
            case "admin_account_id":
                teamInfo.setAdminAccountId(in.nextLong());
                break;
            default:
                break;
            }
        }
    }
    in.endObject();
    return teamInfo;
}

From source file:com.ibm.watson.developer_cloud.alchemy.v1.model.TypedEntitiesAdapter.java

License:Open Source License

@Override
public List<TypedEntity> read(JsonReader reader) throws IOException {
    List<TypedEntity> es = new ArrayList<TypedEntity>();

    reader.beginArray(); // arguments
    while (reader.hasNext()) {
        reader.beginObject(); // argument
        while (reader.hasNext()) {
            String name = reader.nextName();
            if ("entities".equals(name)) {
                reader.beginArray();/* w  ww.  j  a va2  s  .  co m*/
                while (reader.hasNext()) {
                    TypedEntity e = new TypedEntity();
                    reader.beginObject();
                    while (reader.hasNext()) {
                        String name1 = reader.nextName();
                        if ("text".equals(name1)) {
                            e.setText(reader.nextString());
                        } else if ("type".equals(name1)) {
                            e.setType(reader.nextString());
                        } else if ("id".equals(name1)) {
                            e.setId(reader.nextString());
                        } else {
                            reader.skipValue();
                        }
                    }
                    reader.endObject();
                    es.add(e);
                }
                reader.endArray();
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
    }
    reader.endArray();

    return es;
}

From source file:com.ibm.watson.developer_cloud.alchemy.v1.util.ImageKeywordTypeAdapter.java

License:Open Source License

@Override
public ImageKeyword read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();//from ww w.  j a  va  2  s .c  om
        return null;
    }

    final ImageKeyword ImageKeyword = new ImageKeyword();
    reader.beginObject();
    while (reader.hasNext()) {
        final String name = reader.nextName();

        if (name.equals("text")) {
            final String text = reader.nextString();
            ImageKeyword.setText(text);
        } else if (name.equals("score")) {
            final String score = reader.nextString();
            if (score != null && !score.isEmpty())
                ImageKeyword.setScore(Double.valueOf(score));
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
    return ImageKeyword;
}

From source file:com.ibm.watson.developer_cloud.alchemy.v1.util.PublicationDateTypeAdapter.java

License:Open Source License

@Override
public PublicationDate read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();/*from   w w w .  j a v  a  2 s  .c o  m*/
        return null;
    }

    final PublicationDate publicationDate = new PublicationDate();
    publicationDate.setConfident(true);
    reader.beginObject();
    while (reader.hasNext()) {
        final String name = reader.nextName();

        if (name.equals("confident")) {
            final String confidentAsString = reader.nextString();
            publicationDate.setConfident(confidentAsString == null || !confidentAsString.equals("no"));
        } else if (name.equals("date")) {
            final String dateAsString = reader.nextString();
            if (dateAsString != null && !dateAsString.isEmpty())
                try {
                    publicationDate.setDate(df.parse(dateAsString));
                } catch (final ParseException e) {
                    log.log(Level.SEVERE, "Error parsing: " + dateAsString, e);
                }
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
    return publicationDate;
}

From source file:com.ibm.watson.developer_cloud.alchemy.v1.util.TaxonomyTypeAdapter.java

License:Open Source License

@Override
public Taxonomy read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();// w  w  w.  ja  va2  s.c o m
        return null;
    }

    final Taxonomy taxonomy = new Taxonomy();
    taxonomy.setConfident(true);

    reader.beginObject();
    while (reader.hasNext()) {
        final String name = reader.nextName();

        if (name.equals("confident")) {
            final String confidentAsString = reader.nextString();
            taxonomy.setConfident(confidentAsString == null || !confidentAsString.equals("no"));
        } else if (name.equals("label")) {
            final String label = reader.nextString();
            taxonomy.setLabel(label);
        } else if (name.equals("score")) {
            final Double score = reader.nextDouble();
            taxonomy.setScore(score);
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
    return taxonomy;
}

From source file:com.ibm.watson.developer_cloud.conversation.v1.model.util.PaginationResponseTypeAdapter.java

License:Open Source License

@Override
public PaginationResponse read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();/*from   w  ww  . jav a 2  s .c  om*/
        return null;
    }
    reader.beginObject();
    PaginationResponse pagination = new PaginationResponse();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals(REFRESH_URL)) {
            pagination.setRefreshUrl(reader.nextString());
        } else if (name.equals(NEXT_URL)) {
            String nextUrl = reader.nextString();
            HttpUrl url = HttpUrl.parse(RequestUtils.DEFAULT_ENDPOINT + nextUrl);
            pagination.setCursor(url.queryParameter(CURSOR));
            pagination.setNextUrl(nextUrl);
        } else if (name.equals(TOTAL)) {
            pagination.setTotal(reader.nextLong());
        } else if (name.equals(MATCHED)) {
            pagination.setMatched(reader.nextLong());
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();

    return pagination;
}

From source file:com.ibm.watson.developer_cloud.tradeoff_analytics.v1.util.ColumnTypeAdapter.java

License:Open Source License

@Override
public Column read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();//from  w  ww  .  j ava  2s  . c o  m
        return null;
    }

    ColumnType type = ColumnType.TEXT;
    Goal goal = null;
    Boolean objective = null;

    String key = null, format = null, description = null, fullName = null, low = null, high = null;
    Double significantGain = null, significantLoss = null, insignificantLoss = null;

    List<String> categoricalRange = null, categoricalPreference = null;

    reader.beginObject();

    while (reader.hasNext()) {
        String name = reader.nextName();

        if (name.equals(TYPE2)) {
            type = ColumnType.fromString(reader.nextString());
        } else if (name.equals(KEY)) {
            key = reader.nextString();
        } else if (name.equals(GOAL)) {
            goal = Goal.fromString(reader.nextString());
        } else if (name.equals(IS_OBJECTIVE)) {
            objective = reader.nextBoolean();
        } else if (name.equals(FORMAT)) {
            format = reader.nextString();
        } else if (name.equals(DESCRIPTION)) {
            description = reader.nextString();
        } else if (name.equals(FULL_NAME)) {
            fullName = reader.nextString();
        } else if (name.equals(SIGNIFICANT_GAIN)) {
            significantGain = reader.nextDouble();
        } else if (name.equals(SIGNIFICANT_LOSS)) {
            significantLoss = reader.nextDouble();
        } else if (name.equals(INSIGNIFICANT_LOSS)) {
            insignificantLoss = reader.nextDouble();
        } else if (name.equals("preference")) {
            reader.beginArray();
            categoricalPreference = new ArrayList<String>();
            while (reader.hasNext()) {
                categoricalPreference.add(reader.nextString());
            }
            reader.endArray();
        } else if (name.equals(RANGE)) {
            if (reader.peek().equals(JsonToken.BEGIN_ARRAY)) {
                reader.beginArray();
                categoricalRange = new ArrayList<String>();
                while (reader.hasNext()) {
                    categoricalRange.add(reader.nextString());
                }
                reader.endArray();
            } else {
                reader.beginObject();
                while (reader.hasNext()) {
                    name = reader.nextName();
                    if (name.equals(LOW)) {
                        low = reader.nextString();
                    } else if (name.equals(HIGH)) {
                        high = reader.nextString();
                    } else {
                        reader.skipValue();
                    }
                }
                reader.endObject();
            }
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();

    Column column;
    if (type == ColumnType.CATEGORICAL) {
        column = new CategoricalColumn();
        if (categoricalRange != null) {
            ((CategoricalColumn) column).setRange(categoricalRange);
        }
        if (categoricalPreference != null) {
            ((CategoricalColumn) column).setRange(categoricalPreference);
        }
    } else if (type == ColumnType.DATETIME) {
        column = new DateColumn();
        if (low != null) {
            try {
                ((DateColumn) column).withRange(DATE_FORMATTER.parse(low), DATE_FORMATTER.parse(high));
            } catch (final ParseException e) {
                LOG.log(Level.SEVERE, "Error parsing the date", e);
            }
        }
    } else if (type == ColumnType.NUMERIC) {
        column = new NumericColumn();
        if (low != null) {
            ((NumericColumn) column).range(Double.valueOf(low), Double.valueOf(high));
        }
    } else {
        column = new TextColumn();
    }

    column.setKey(key);

    if (description != null) {
        column.setDescription(description);
    }

    if (format != null) {
        column.setFormat(format);
    }

    if (objective != null) {
        column.setObjective(objective);
    }

    if (fullName != null) {
        column.setFullName(fullName);
    }

    if (goal != null) {
        column.setGoal(goal);
    }

    if (key != null) {
        column.setKey(key);
    }

    if (significantGain != null) {
        column.setSignificantGain(significantGain);
    }

    if (significantLoss != null) {
        column.setSignificantLoss(insignificantLoss);
    }

    if (insignificantLoss != null) {
        column.setInsignificantLoss(insignificantLoss);
    }

    return column;
}

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

License:Open Source License

/**
 * Checks the next {@link JsonToken} to decide the next appropriate parsing method.
 *
 * @param in {@link JsonReader} object used for parsing
 * @param objMap Map used to build the structure for the resulting {@link QueryAggregation} object
 * @throws IOException signals that there has been an IO exception
 *//*w ww .j a  v a2 s.  co m*/
private void parseNext(JsonReader in, HashMap<String, Object> objMap) throws IOException {
    JsonToken token = in.peek();

    String lastName = "";
    if (token == JsonToken.NAME) {
        lastName = in.nextName();
        token = in.peek();
    }

    switch (token) {
    case BEGIN_ARRAY:
        parseArray(in, objMap, lastName);
        break;
    case BEGIN_OBJECT:
        parseObject(in, objMap, lastName);
        break;
    case STRING:
        objMap.put(lastName, in.nextString());
        break;
    case NUMBER:
        objMap.put(lastName, in.nextDouble());
        break;
    case BOOLEAN:
        objMap.put(lastName, in.nextBoolean());
        break;
    default:
        throw new IOException("Unexpected JSON token encountered");
    }

    collapseMap(objMap);
}

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 w ww  . j a  va  2  s . c om*/
    }

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