Search in sources :

Example 86 with JsonReader

use of com.google.gson.stream.JsonReader in project plaid by nickbutcher.

the class DenvelopingConverter method responseBodyConverter.

@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    // This converter requires an annotation providing the name of the payload in the envelope;
    // if one is not supplied then return null to continue down the converter chain.
    final String payloadName = getPayloadName(annotations);
    if (payloadName == null)
        return null;
    final TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
    return new Converter<ResponseBody, Object>() {

        @Override
        public Object convert(ResponseBody body) throws IOException {
            try (JsonReader jsonReader = gson.newJsonReader(body.charStream())) {
                jsonReader.beginObject();
                while (jsonReader.hasNext()) {
                    if (payloadName.equals(jsonReader.nextName())) {
                        return adapter.read(jsonReader);
                    } else {
                        jsonReader.skipValue();
                    }
                }
                return null;
            } finally {
                body.close();
            }
        }
    };
}
Also used : Converter(retrofit2.Converter) JsonReader(com.google.gson.stream.JsonReader) ResponseBody(okhttp3.ResponseBody)

Example 87 with JsonReader

use of com.google.gson.stream.JsonReader in project json-android-compare by martinadamek.

the class GsonJson method parsePublicTimeline.

public List<Map> parsePublicTimeline(InputStream inputStream) {
    List<Map> result = new ArrayList<Map>();
    try {
        Map map;
        String name;
        String name2;
        JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
        reader.beginArray();
        while (reader.hasNext()) {
            map = new HashMap();
            reader.beginObject();
            while (reader.hasNext()) {
                name = reader.nextName();
                if ("user".equals(name)) {
                    reader.beginObject();
                    while (reader.hasNext()) {
                        name2 = reader.nextName();
                        map.put("user." + name2, getValue(reader));
                    }
                    reader.endObject();
                } else {
                    map.put(name, getValue(reader));
                }
            }
            reader.endObject();
            result.add(map);
        }
        reader.endArray();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
Also used : InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JsonReader(com.google.gson.stream.JsonReader) Map(java.util.Map) HashMap(java.util.HashMap) IOException(java.io.IOException)

Example 88 with JsonReader

use of com.google.gson.stream.JsonReader in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundImportReplace.

private TaskData doInBackgroundImportReplace(TaskData... params) {
    Log.i(AnkiDroidApp.TAG, "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);
    }
    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) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - Error while unzipping: ", e);
        AnkiDroidApp.saveExceptionReportFile(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);
        }
    } 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.performBackup(colPath, true);
    }
    // overwrite collection
    colPath = AnkiDroidApp.getCollectionPath();
    File f = new File(colFile);
    f.renameTo(new File(colPath));
    int addedCount = -1;
    try {
        col = AnkiDroidApp.openCollection(colPath);
        // 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().getDir();
        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) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - RuntimeException: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace1");
        return new TaskData(false);
    } catch (FileNotFoundException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - FileNotFoundException: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace2");
        return new TaskData(false);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - IOException: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace3");
        return new TaskData(false);
    }
}
Also used : HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) ZipFile(java.util.zip.ZipFile) Collection(com.ichi2.libanki.Collection) JsonReader(com.google.gson.stream.JsonReader) FileReader(java.io.FileReader) Resources(android.content.res.Resources) ZipFile(java.util.zip.ZipFile) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 89 with JsonReader

use of com.google.gson.stream.JsonReader in project Anki-Android by Ramblurr.

the class Anki2Importer method run.

public int run() {
    publishProgress(false, 0, 0, false);
    try {
        // 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;
    }
}
Also used : JsonReader(com.google.gson.stream.JsonReader) ZipFile(java.util.zip.ZipFile)

Example 90 with JsonReader

use of com.google.gson.stream.JsonReader in project intellij-community by JetBrains.

the class PluginsAdvertiser method retrieve.

public static List<Plugin> retrieve(UnknownFeature unknownFeature) {
    final String featureType = unknownFeature.getFeatureType();
    final String implementationName = unknownFeature.getImplementationName();
    final String buildNumber = ApplicationInfo.getInstance().getApiVersion();
    final String pluginRepositoryUrl = FEATURE_IMPLEMENTATIONS_URL + "featureType=" + featureType + "&implementationName=" + implementationName.replaceAll("#", "%23") + "&build=" + buildNumber;
    return HttpRequests.request(pluginRepositoryUrl).connect(new HttpRequests.RequestProcessor<List<Plugin>>() {

        @Override
        public List<Plugin> process(@NotNull HttpRequests.Request request) throws IOException {
            final JsonReader jsonReader = new JsonReader(request.getReader());
            jsonReader.setLenient(true);
            final JsonElement jsonRootElement = new JsonParser().parse(jsonReader);
            final List<Plugin> result = new ArrayList<>();
            for (JsonElement jsonElement : jsonRootElement.getAsJsonArray()) {
                final JsonObject jsonObject = jsonElement.getAsJsonObject();
                final JsonElement pluginId = jsonObject.get("pluginId");
                final JsonElement pluginName = jsonObject.get("pluginName");
                final JsonElement bundled = jsonObject.get("bundled");
                result.add(new Plugin(PluginId.getId(StringUtil.unquoteString(pluginId.toString())), pluginName != null ? StringUtil.unquoteString(pluginName.toString()) : null, Boolean.parseBoolean(StringUtil.unquoteString(bundled.toString()))));
            }
            return result;
        }
    }, null, LOG);
}
Also used : JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) HttpRequests(com.intellij.util.io.HttpRequests) JsonElement(com.google.gson.JsonElement) JsonReader(com.google.gson.stream.JsonReader) JsonParser(com.google.gson.JsonParser)

Aggregations

JsonReader (com.google.gson.stream.JsonReader)100 StringReader (java.io.StringReader)38 JsonElement (com.google.gson.JsonElement)31 IOException (java.io.IOException)20 JsonObject (com.google.gson.JsonObject)19 Test (org.junit.Test)19 InputStreamReader (java.io.InputStreamReader)18 JsonParser (com.google.gson.JsonParser)12 HumanReadableException (com.facebook.buck.util.HumanReadableException)10 Gson (com.google.gson.Gson)10 JsonWriter (com.google.gson.stream.JsonWriter)10 TypeToken (com.google.gson.reflect.TypeToken)8 Map (java.util.Map)8 JsonToken (com.google.gson.stream.JsonToken)6 HashMap (java.util.HashMap)6 InputStream (java.io.InputStream)5 StringWriter (java.io.StringWriter)5 Type (java.lang.reflect.Type)5 ArrayList (java.util.ArrayList)5 GsonBuilder (com.google.gson.GsonBuilder)4