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

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this JSON reader and the underlying java.io.Reader .

Usage

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 . j  a va  2s. c  om*/
 * @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.meltmedia.cadmium.core.history.HistoryManager.java

License:Apache License

private void readHistoryFile() throws Exception {
    if (contentRoot != null) {
        String path = FileSystemManager.getFileIfCanRead(contentRoot, HISTORY_FILE_NAME);

        if (path != null) {
            Gson gson = new Gson();
            JsonReader reader = null;
            try {
                reader = new JsonReader(new FileReader(path));
                reader.setLenient(true);
                List<HistoryEntry> entries = gson.fromJson(reader, new TypeToken<List<HistoryEntry>>() {
                }.getType());//from  www  .jav  a  2 s.co m

                if (entries != null) {
                    history.addAll(entries);
                }
            } finally {
                log.info("Read in {} history entries", history.size());
                if (reader != null) {
                    reader.close();
                }
            }
        }
    }
}

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

/**
 * Cette methode permet de renvoyer une liste de map contenant pour chaque map, les attributs(pass en parametre) et leurs valeurs concernant un objet de la liste(liste d'objet resultant de l'url)
 * @param urlwebservice url du webservice (faire reference  un renvoie
 * d'une liste d'objet)/*from   www. j  ava 2 s. c om*/
 * @param listeAttribut une liste des attributs a chercher dans le Json
 * @return une liste de Map
 */
public List<Map<String, String>> getListeLectureJsonFromUrl(String urlwebservice, List<String> listeAttribut) {
    try {
        if (!listeAttribut.isEmpty()) {
            String json = MikiWsTools.get(urlwebservice);
            List<Map<String, String>> resultat3 = null;
            final JsonReader reader = new JsonReader(new StringReader(json));
            MikiWsJsonTools classe = new MikiWsJsonTools();
            resultat3 = classe.lectureJson(listeAttribut, reader);
            reader.close();
            return resultat3;
        } else {
            return null;
        }

    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("Echec de l'opration");
        return null;
    }
}

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

/**
 * Cette methode permet de renvoyer une liste de map contenant pour chaque map, les attributs(pass en parametre) et leurs valeurs concernant un objet de la liste( liste d'objet dans le json passe en parametre)
 * @param json les donnes en format json
 * d'une liste d'objet)/*w  w  w  .j  av a  2 s  .  co  m*/
 * @param listeAttribut une liste des attributs a chercher dans le Json
 * @return une liste de Map
 */
public List<Map<String, String>> getListeLectureJson(String json, List<String> listeAttribut) {
    try {
        if (!listeAttribut.isEmpty()) {
            List<Map<String, String>> resultat3 = null;
            final JsonReader reader = new JsonReader(new StringReader(json));
            MikiWsJsonTools classe = new MikiWsJsonTools();
            resultat3 = classe.lectureJson(listeAttribut, reader);
            reader.close();
            return resultat3;
        } else {
            return null;
        }

    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("Echec de l'opration");
        return null;
    }
}

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

/**
 * Cette methode permet de retourner une liste d'objet (type d'objet pass en parametre  la classe) resultants de l'url pass en parametre
 * @param urlWebservice url du webservice (pas besoin de paramtre path)
 * @return liste de l'objet pass en parametre au constructeur de la classe
 * MikiWsTools ou null s'il ya erreur//  w  w w .j a va2s.  com
 */
public List<T> ListeObjetFromUrl(String urlWebservice) {
    final Gson gson = new GsonBuilder().create();
    final List<T> values = new ArrayList<T>();
    try {

        URL url = new URL(urlWebservice);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Erreur -> HTTP code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        String output2 = "";
        while ((output = br.readLine()) != null) {
            output2 += output;
        }

        final JsonReader jsonReader = new JsonReader(new StringReader(output2));
        final JsonParser jsonParser = new JsonParser();
        final JsonArray jsonArray = jsonParser.parse(jsonReader).getAsJsonArray();

        for (final JsonElement element : jsonArray) {
            final T value = gson.fromJson(element, type);
            values.add(value);
        }

        jsonReader.close();

        conn.disconnect();

        return values;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;

    } catch (RuntimeException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

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

/**
 * Cette methode permet de retourner une liste d'objet (type d'objet pass en parametre  la classe) resultants du json pass en paramtre
 * @param json String contenant le json pass en paramtre(le json en question doit renferm une liste de l'objet)
 * @return liste de l'objet pass en parametre au constructeur de la classe
 * MikiWsTools ou null s'il ya erreur/*from www  .  j ava 2s  . c  om*/
 */
public List<T> ListeObjet(String json) {
    final Gson gson = new GsonBuilder().create();
    final List<T> values = new ArrayList<T>();
    try {

        final JsonReader jsonReader = new JsonReader(new StringReader(json));
        final JsonParser jsonParser = new JsonParser();
        final JsonArray jsonArray = jsonParser.parse(jsonReader).getAsJsonArray();

        for (final JsonElement element : jsonArray) {
            final T value = gson.fromJson(element, type);
            values.add(value);
        }

        jsonReader.close();

        return values;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.netease.flume.taildirSource.ReliableTaildirEventReader.java

License:Apache License

/**
 * Load a position file which has the last read position of each file. If the position file exists, update tailFiles
 * mapping./* w  w  w  .  ja  v a 2  s  .c  o m*/
 */
public void loadPositionFile(String filePath) {
    Long inode, pos;
    String path;
    FileReader fr = null;
    JsonReader jr = null;
    try {
        fr = new FileReader(filePath);
        jr = new JsonReader(fr);
        jr.beginArray();
        while (jr.hasNext()) {
            inode = null;
            pos = null;
            path = null;
            jr.beginObject();
            while (jr.hasNext()) {
                switch (jr.nextName()) {
                case "inode":
                    inode = jr.nextLong();
                    break;
                case "pos":
                    pos = jr.nextLong();
                    break;
                case "file":
                    path = jr.nextString();
                    break;
                }
            }
            jr.endObject();

            for (Object v : Arrays.asList(inode, pos, path)) {
                Preconditions.checkNotNull(v, "Detected missing value in position file. " + "inode: " + inode
                        + ", pos: " + pos + ", path: " + path);
            }
            TailFile tf = tailFiles.get(inode);
            if (tf != null && tf.updatePos(path, inode, pos)) {
                tailFiles.put(inode, tf);
            } else {
                logger.info("Missing file: " + path + ", inode: " + inode + ", pos: " + pos);
            }
        }
        jr.endArray();
    } catch (FileNotFoundException e) {
        logger.info("File not found: " + filePath + ", not updating position");
    } catch (IOException e) {
        logger.error("Failed loading positionFile: " + filePath, e);
    } finally {
        try {
            if (fr != null)
                fr.close();
            if (jr != null)
                jr.close();
        } catch (IOException e) {
            logger.error("Error: " + e.getMessage(), e);
        }
    }
}

From source file:com.nit.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);//from w  w w .  j a va  2  s  .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));
    } 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);
    }
}

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

License:Open Source License

public int run(boolean currDeckImport) {
    publishProgress(false, 0, 0, false);
    try {/*from ww w  .ja  va  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(currDeckImport);
        } 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.nridge.ds.solr.SolrConfigJSON.java

License:Open Source License

/**
 * Parses an JSON string representing the Solr schema and loads it into a document
 * and returns an instance to it./*  w  w w .j  a  va  2  s . co  m*/
 *
 * @param aConfigString JSON string representation of the Solr schema.
 *
 * @return Document instance containing the parsed data.
 *
 * @throws IOException I/O related exception.
 */
public Document loadDocument(String aConfigString) throws IOException {
    String jsonName, jsonValue;
    Document componentDocument;

    Document configDocument = new Document(Solr.DOCUMENT_SCHEMA_TYPE);
    DataBag configBag = configDocument.getBag();

    StringReader stringReader = new StringReader(aConfigString);
    JsonReader jsonReader = new JsonReader(stringReader);

    jsonReader.beginObject();
    while (jsonReader.hasNext()) {
        jsonName = jsonReader.nextName();
        if (StringUtils.equals(jsonName, OBJECT_RESPONSE_HEADER)) {
            Document headerDocument = new Document(Solr.RESPONSE_SCHEMA_HEADER);
            DataBag headerBag = headerDocument.getBag();
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                jsonName = jsonReader.nextName();
                jsonValue = nextValueAsString(jsonReader);
                headerBag.add(new DataTextField(jsonName, Field.nameToTitle(jsonName), jsonValue));
            }
            jsonReader.endObject();
            configDocument.addRelationship(Solr.RESPONSE_SCHEMA_HEADER, headerDocument);
        } else if (StringUtils.equals(jsonName, OBJECT_RESPONSE_CONFIG)) {
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                jsonName = jsonReader.nextName();
                if (StringUtils.equals(jsonName, OBJECT_RESPONSE_CONFIG_UPDATE_HANDLER))
                    populateCfgUpdateHandler(jsonReader, configDocument, Solr.RESPONSE_CONFIG_UPDATE_HANDLER);
                else if (StringUtils.equals(jsonName, OBJECT_RESPONSE_CONFIG_QUERY))
                    populateCfgQuery(jsonReader, configDocument, Solr.RESPONSE_CONFIG_QUERY);
                else if (StringUtils.equals(jsonName, OBJECT_RESPONSE_CONFIG_REQUEST_HANDLER))
                    populateCfgRequestHandler(jsonReader, configDocument, Solr.RESPONSE_CONFIG_REQUEST_HANDLER);
                else if (StringUtils.equals(jsonName, OBJECT_RESPONSE_CONFIG_RESPONSE_WRITER))
                    populateQueryResponseWriterHandler(jsonReader, configDocument,
                            Solr.RESPONSE_CONFIG_QUERY_RESPONSE_WRITER);
                else if (StringUtils.equals(jsonName, OBJECT_RESPONSE_CONFIG_SEARCH_COMPONENT))
                    populateSearchComponent(jsonReader, configDocument, Solr.RESPONSE_CONFIG_SEARCH_COMPONENT);
                else if (StringUtils.equals(jsonName, OBJECT_RESPONSE_CONFIG_INIT_PARAMS)) {
                    componentDocument = new Document(Solr.RESPONSE_CONFIG_INIT_PARAMS);
                    addObjectToDocument(jsonReader, componentDocument, Solr.RESPONSE_CONFIG_INIT_PARAMETERS,
                            jsonName);
                    configDocument.addRelationship(Solr.RESPONSE_CONFIG_INIT_PARAMS, componentDocument);
                } else if (StringUtils.equals(jsonName, OBJECT_RESPONSE_CONFIG_LISTENER)) {
                    componentDocument = new Document(Solr.RESPONSE_CONFIG_LISTENER);
                    jsonReader.beginArray();
                    while (jsonReader.hasNext())
                        addObjectToDocument(jsonReader, componentDocument, Solr.RESPONSE_CONFIG_LISTENER_EVENTS,
                                jsonName);
                    jsonReader.endArray();
                    configDocument.addRelationship(Solr.RESPONSE_CONFIG_LISTENER, componentDocument);
                } else if (StringUtils.equals(jsonName, OBJECT_RESPONSE_CONFIG_DIRECTORY_FACTORY)) {
                    componentDocument = new Document(Solr.RESPONSE_CONFIG_DIRECTORY_FACTORY);
                    addObjectToDocument(jsonReader, componentDocument, Solr.RESPONSE_CONFIG_DIRECTORY_ENTRIES,
                            jsonName);
                    configDocument.addRelationship(Solr.RESPONSE_CONFIG_DIRECTORY_FACTORY, componentDocument);
                } else if (StringUtils.equals(jsonName, OBJECT_RESPONSE_CONFIG_CODEC_FACTORY)) {
                    componentDocument = new Document(Solr.RESPONSE_CONFIG_CODEC_FACTORY);
                    addObjectToDocument(jsonReader, componentDocument, Solr.RESPONSE_CONFIG_CODEC_ENTRIES,
                            jsonName);
                    configDocument.addRelationship(Solr.RESPONSE_CONFIG_CODEC_FACTORY, componentDocument);
                } else if (StringUtils.equals(jsonName, OBJECT_RESPONSE_CONFIG_UPDATE_HU_LOG)) {
                    componentDocument = new Document(Solr.RESPONSE_CONFIG_UPDATE_HANDLER_ULOG);
                    addObjectToDocument(jsonReader, componentDocument, Solr.RESPONSE_CONFIG_UHUL_ENTRIES,
                            jsonName);
                    configDocument.addRelationship(Solr.RESPONSE_CONFIG_UPDATE_HANDLER_ULOG, componentDocument);
                } else if (StringUtils.equals(jsonName, OBJECT_RESPONSE_CONFIG_REQUEST_DISPATCHER)) {
                    componentDocument = new Document(Solr.RESPONSE_CONFIG_REQUEST_DISPATCHER);
                    addObjectToDocument(jsonReader, componentDocument, Solr.RESPONSE_CONFIG_RD_ENTRIES,
                            jsonName);
                    configDocument.addRelationship(Solr.RESPONSE_CONFIG_REQUEST_DISPATCHER, componentDocument);
                } else if (StringUtils.equals(jsonName, OBJECT_RESPONSE_CONFIG_INDEX_CONFIG)) {
                    componentDocument = new Document(Solr.RESPONSE_CONFIG_REQUEST_DISPATCHER);
                    addObjectToDocument(jsonReader, componentDocument, Solr.RESPONSE_CONFIG_INDEX_CONFIG,
                            jsonName);
                    configDocument.addRelationship(Solr.RESPONSE_CONFIG_IC_ENTRIES, componentDocument);
                } else if (StringUtils.equals(jsonName, OBJECT_RESPONSE_CONFIG_PEER_SYNC)) {
                    componentDocument = new Document(Solr.RESPONSE_CONFIG_PEER_SYNC);
                    addObjectToDocument(jsonReader, componentDocument, Solr.RESPONSE_CONFIG_PS_ENTRIES,
                            jsonName);
                    configDocument.addRelationship(Solr.RESPONSE_CONFIG_PEER_SYNC, componentDocument);
                } else {
                    jsonValue = nextValueAsString(jsonReader);
                    addBagTextField(configBag, jsonName, jsonValue);
                }
            }
            jsonReader.endObject();
        } else
            jsonReader.skipValue();
    }
    jsonReader.endObject();
    jsonReader.close();

    return configDocument;
}