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.google.gdt.googleapi.core.ApiDirectoryListingJsonCodec.java

License:Open Source License

public Map<String, String> toIconCacheMap(InputStream in) {
    try {//from   w  w w  .jav a 2 s .c om
        JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
        return gson.fromJson(reader, Map.class);
    } catch (UnsupportedEncodingException e) {
        return Collections.emptyMap();
    }
}

From source file:com.google.gerrit.httpd.restapi.RestApiServlet.java

License:Apache License

private Object parseRequest(HttpServletRequest req, Type type) throws IOException, BadRequestException,
        SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException,
        InstantiationException, InvocationTargetException, MethodNotAllowedException {
    if (isType(JSON_TYPE, req.getContentType())) {
        try (BufferedReader br = req.getReader(); JsonReader json = new JsonReader(br)) {
            json.setLenient(true);//  w w  w  . j  a v a 2s  . c  o m

            JsonToken first;
            try {
                first = json.peek();
            } catch (EOFException e) {
                throw new BadRequestException("Expected JSON object");
            }
            if (first == JsonToken.STRING) {
                return parseString(json.nextString(), type);
            }
            return OutputFormat.JSON.newGson().fromJson(json, type);
        }
    } else if (("PUT".equals(req.getMethod()) || "POST".equals(req.getMethod())) && acceptsRawInput(type)) {
        return parseRawInput(req, type);
    } else if ("DELETE".equals(req.getMethod()) && hasNoBody(req)) {
        return null;
    } else if (hasNoBody(req)) {
        return createInstance(type);
    } else if (isType("text/plain", req.getContentType())) {
        try (BufferedReader br = req.getReader()) {
            char[] tmp = new char[256];
            StringBuilder sb = new StringBuilder();
            int n;
            while (0 < (n = br.read(tmp))) {
                sb.append(tmp, 0, n);
            }
            return parseString(sb.toString(), type);
        }
    } else if ("POST".equals(req.getMethod()) && isType(FORM_TYPE, req.getContentType())) {
        return OutputFormat.JSON.newGson().fromJson(ParameterParser.formToJson(req), type);
    } else {
        throw new BadRequestException("Expected Content-Type: " + JSON_TYPE);
    }
}

From source file:com.google.iosched.input.fetcher.RemoteJsonHelper.java

License:Open Source License

public static JsonObject fetchJsonFromPublicURL(String urlStr) throws IOException {
    URL url = new URL(urlStr);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setReadTimeout(1000 * 30); // 30 seconds
    int response = connection.getResponseCode();
    if (response < 200 || response >= 300) {
        throw new IllegalArgumentException("Unexpected HTTP response [" + response + "] at URL: " + urlStr);
    }/*from   w  w  w.j ava  2  s.co  m*/

    InputStream stream = connection.getInputStream();
    JsonReader reader = new JsonReader(new InputStreamReader(stream, Charset.forName("UTF-8")));
    return (JsonObject) new JsonParser().parse(reader);
}

From source file:com.google.javascript.jscomp.AbstractCommandLineRunner.java

License:Apache License

public List<JsonFileSpec> parseJsonFilesFromInputStream() throws IOException {
    List<JsonFileSpec> jsonFiles = new ArrayList<>();
    try (JsonReader reader = new JsonReader(new InputStreamReader(this.in, inputCharset))) {
        reader.beginArray();//from  w  w  w  .j  a va 2s.  co  m
        while (reader.hasNext()) {
            JsonFileSpec jsonFile = gson.fromJson(reader, JsonFileSpec.class);
            jsonFiles.add(jsonFile);
        }
        reader.endArray();
    }
    return jsonFiles;
}

From source file:com.google.samples.apps.iosched.server.schedule.input.fetcher.VendorAPIEntityFetcher.java

License:Open Source License

@Override
public JsonElement fetch(Enum<?> entityType, Map<String, String> params) throws IOException {
    StringBuilder urlStr = new StringBuilder(BASE_URL);
    urlStr.append(entityType.name());/*  w w w  . j  av  a  2s .  c  om*/
    if (params != null && !params.isEmpty()) {
        urlStr.append("?");
        for (Map.Entry<String, String> param : params.entrySet()) {
            urlStr.append(param.getKey()).append("=").append(param.getValue()).append("&");

        }
        urlStr.deleteCharAt(urlStr.length() - 1);
    }

    URL url = new URL(urlStr.toString());
    if (LOG.isLoggable(Level.INFO)) {
        LOG.info("URL requested: " + url);
    }

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setReadTimeout(1000 * 30); // 30 seconds
    connection.setRequestProperty("code", Config.CMS_API_CODE);
    connection.setRequestProperty("apikey", Config.CMS_API_KEY);

    InputStream stream = connection.getInputStream();
    JsonReader reader = new JsonReader(new InputStreamReader(stream, Charset.forName("UTF-8")));
    return new JsonParser().parse(reader);
}

From source file:com.google.samples.apps.iosched.sync.ConferenceDataHandler.java

License:Open Source License

/**
 * Processes a conference data body and calls the appropriate data type handlers
 * to process each of the objects represented therein.
 *
 * @param dataBody The body of data to process
 * @throws IOException If there is an error parsing the data.
 *///from   w  ww .j  av a2  s.  c  o m
private void processDataBody(String dataBody) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(dataBody));
    JsonParser parser = new JsonParser();
    try {
        reader.setLenient(true); // To err is human

        // the whole file is a single JSON object
        reader.beginObject();

        while (reader.hasNext()) {
            // the key is "rooms", "speakers", "tracks", etc.
            String key = reader.nextName();
            if (mHandlerForKey.containsKey(key)) {
                // pass the value to the corresponding handler
                mHandlerForKey.get(key).process(parser.parse(reader));
            } else {
                LOGW(TAG, "Skipping unknown key in conference data json: " + key);
                reader.skipValue();
            }
        }
        reader.endObject();
    } finally {
        reader.close();
    }
}

From source file:com.google.samples.apps.iosched.sync.userdata.util.UserActionHelper.java

License:Open Source License

public static List<UserAction> deserializeUserActions(String str) {
    try {/*from   w w w. ja  va  2  s  .  c  o m*/
        ArrayList<UserAction> actions = new ArrayList<UserAction>();
        JsonReader reader = new JsonReader(new StringReader(str));
        reader.beginArray();
        while (reader.hasNext()) {
            reader.beginObject();
            UserAction action = new UserAction();
            while (reader.hasNext()) {
                String key = reader.nextName();
                if ("type".equals(key)) {
                    action.type = UserAction.TYPE.valueOf(reader.nextString());
                } else if ("id".equals(key)) {
                    action.sessionId = reader.nextString();
                } else {
                    throw new RuntimeException("Invalid key " + key + " in serialized UserAction: " + str);
                }
            }
            reader.endObject();
            actions.add(action);
        }
        reader.endArray();
        return actions;
    } catch (IOException ex) {
        throw new RuntimeException("Error deserializing UserActions: " + str, ex);
    }
}

From source file:com.google.samples.apps.iosched.sync.userdata.util.UserDataHelper.java

License:Open Source License

static public Set<String> fromString(String str) {
    TreeSet<String> result = new TreeSet<String>();
    if (str == null || str.isEmpty()) {
        return result;
    }/*from  w w  w  .j  a v  a2s. c om*/
    try {
        JsonReader reader = new JsonReader(new StringReader(str));
        reader.beginObject();
        while (reader.hasNext()) {
            String key = reader.nextName();
            if (JSON_STARRED_SESSIONS_KEY.equals(key)) {
                reader.beginArray();
                while (reader.hasNext()) {
                    result.add(reader.nextString());
                }
                reader.endArray();
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
        reader.close();
    } catch (Exception ex) {
        Log.w(TAG, "Ignoring invalid remote content.", ex);
        return null;
    }
    return result;
}

From source file:com.google.security.wycheproof.JsonUtil.java

License:Apache License

/**
 * Reads a set of test vectors from a file.
 * @param filename the name of the file, local to the directory with the
 *        the test vectors./*from ww w  .  j a v a  2s .  c  om*/
 * @return a JsonObject with a test
 * @throws IOException if the test vectors could not be read.
 * @throws JsonParseException if the file is not valid JSON.
 */
public static JsonObject getTestVectors(String filename) throws IOException {
    // The directory where the test vectors are.
    String testVectorsDir = "testvectors/";
    FileInputStream is = new FileInputStream(testVectorsDir + filename);
    JsonReader reader = new JsonReader(new InputStreamReader(is, UTF_8));
    JsonParser parser = new JsonParser();
    JsonElement elem = parser.parse(reader);
    return elem.getAsJsonObject();
}

From source file:com.hichinaschool.flashcards.async.DeckTask.java

License:Open Source License

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);/*  w w  w . j  ava  2s.co  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) {
        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);
    }
}