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

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

Introduction

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

Prototype

public boolean hasNext() throws IOException 

Source Link

Document

Returns true if the current array or object has another element.

Usage

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 a v  a  2s.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  . j ava 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.javacreed.examples.gson.part3.BookTypeAdapter.java

License:Apache License

@Override
public Book read(final JsonReader in) throws IOException {
    final Book book = new Book();

    in.beginArray();/*from  w  w w. j  a  va  2  s .co m*/
    book.setIsbn(in.nextString());
    book.setTitle(in.nextString());
    final List<Author> authors = new ArrayList<>();
    while (in.hasNext()) {
        final int id = in.nextInt();
        final String name = in.nextString();
        authors.add(new Author(id, name));
    }
    book.setAuthors(authors.toArray(new Author[authors.size()]));
    in.endArray();

    return book;
}

From source file:com.javacreed.examples.gson.part4.BookTypeAdapter.java

License:Apache License

@Override
public Book read(final JsonReader in) throws IOException {
    final Book book = new Book();

    in.beginObject();//from w  w  w  .  jav a  2 s.  c o  m
    while (in.hasNext()) {
        switch (in.nextName()) {
        case "isbn":
            book.setIsbn(in.nextString());
            break;
        case "title":
            book.setTitle(in.nextString());
            break;
        case "authors":
            in.beginArray();
            final List<Author> authors = new ArrayList<>();
            while (in.hasNext()) {
                in.beginObject();
                final Author author = new Author();
                while (in.hasNext()) {
                    switch (in.nextName()) {
                    case "id":
                        author.setId(in.nextInt());
                        break;
                    case "name":
                        author.setName(in.nextString());
                        break;
                    }
                }
                authors.add(author);
                in.endObject();
            }
            book.setAuthors(authors.toArray(new Author[authors.size()]));
            in.endArray();
            break;
        }
    }
    in.endObject();

    return book;
}

From source file:com.magnet.android.mms.request.GenericResponseParser.java

License:Open Source License

private Collection fromJsonToPojoCollection(JsonReader jr, Class<?> bclass) throws IOException {
    List result = new ArrayList();
    // process each element in the array
    jr.beginArray();//  w  w w  .j  a  va2s .com
    try {
        while (jr.hasNext()) {
            Object obj = genericGson.fromJson(jr, bclass);
            ((ArrayList) result).add(obj);
        }
    } finally {
        jr.endArray();
    }
    return result;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.apns.APNSPayloadInfo.java

License:Apache License

/**
 * Parse payload json string to extract specific properties from the APNS Payload json.
 *
 * @param payloadJSON//from   w w  w  .  ja va  2  s.  com
 * @return
 */
public static APNSPayloadInfo parse(String payloadJSON) {
    JsonReader reader = new JsonReader(new StringReader(payloadJSON));
    try {
        APNSPayloadInfo rv = null;
        reader.beginObject();
        while (reader.hasNext()) {
            String name = reader.nextName();
            if (name.equalsIgnoreCase(Constants.PAYLOAD_MMX_KEY)) {
                rv = readMMXObject(reader);
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
        return rv;
    } catch (Throwable t) {
        LOGGER.warn("Exception in parsing payloadJSON:{}", payloadJSON, t);
        return null;
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.apns.APNSPayloadInfo.java

License:Apache License

private static APNSPayloadInfo readMMXObject(JsonReader reader) throws IOException {
    APNSPayloadInfo info = new APNSPayloadInfo();
    reader.beginObject();/* w w w . j ava  2s.  c  o  m*/
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals(Constants.PAYLOAD_ID_KEY)) {
            info.messageId = reader.nextString();
        } else if (name.equals(Constants.PAYLOAD_TYPE_KEY)) {
            info.type = reader.nextString();
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
    return info;
}

From source file:com.magnet.plugin.models.ExamplesManifest.java

License:Open Source License

public ExamplesManifest(String json) throws IOException {
    this.examples = new HashMap<String, ExampleResource>();

    JsonReader reader = new JsonReader(new StringReader(json));
    reader.beginObject();/*from  w  ww. j a v a 2  s  . co  m*/
    while (reader.hasNext()) {
        String name = reader.nextName();

        // single example
        reader.beginObject();
        String file = null;
        String description = null;
        while (reader.hasNext()) {
            String key = reader.nextName();
            if (key.equals(FILE_KEY)) {
                file = reader.nextString();
            } else if (key.equals(DESCRIPTION_KEY)) {
                description = reader.nextString();
            }
        }
        reader.endObject();
        examples.put(name, new ExampleResource(name, file, description));
    }

}

From source file:com.miki.webapp.webservicerestful.MikiWsJsonTools.java

public Map<String, String> lecture(List<String> listeAttribut, final JsonReader reader) throws IOException {
    Map<String, String> resultat = new HashMap<>();
    reader.beginObject();//from   w w  w  .  ja v a2s .c  om
    while (reader.hasNext()) {
        final String name = reader.nextName();
        int iter = 0;
        for (String attribut : listeAttribut) {
            if (name.equals(attribut)) {
                if (reader.peek() == JsonToken.NULL) {
                    reader.nextNull();
                    resultat.put(attribut, null);
                } else {
                    resultat.put(attribut, reader.nextString());
                }
            } else {
                iter++;
            }
        }

        if (iter == listeAttribut.size()) {
            reader.skipValue();
        }
    }
    reader.endObject();
    return resultat;
}

From source file:com.miki.webapp.webservicerestful.MikiWsJsonTools.java

public List<Map<String, String>> lectureJson(List<String> listeAttribut, final JsonReader reader)
        throws IOException {
    List<Map<String, String>> resultat2 = new ArrayList<>();
    reader.setLenient(true);/*from   ww w.ja v  a 2 s  .  c o  m*/
    reader.beginArray();
    while (reader.hasNext()) {
        resultat2.add(lecture(listeAttribut, reader));
    }
    reader.endArray();
    return resultat2;
}