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:de.loercher.geomodule.cloudant.CloudantGeoSearchStream.java

private void extractEntities(BufferedReader bufferedReader) throws JSONParseException {
    JsonReader reader = new JsonReader(bufferedReader);
    try {//from   w ww  . j  a va  2s  . com
        reader.beginObject();

        String arrayName = null;
        while (reader.hasNext() && !("features".equals(arrayName))) {
            arrayName = reader.nextName();
            if ("bookmark".equals(arrayName)) {
                bookmark = reader.nextString();
            } else if (!("features".equals(arrayName))) {
                reader.skipValue();
            }
        }

        if ("features".equals(arrayName)) {
            reader.beginArray();

            while (reader.hasNext()) {
                Gson gson = new Gson();
                CloudantArticleEntity entity = gson.fromJson(reader, CloudantArticleEntity.class);

                // Duplicates should not be returned
                if (!(alreadyAvailableIds.contains(entity.getId()))) {
                    bufferedEntities.add(entity);
                }

                alreadyAvailableIds.add(entity.getId());
            }

            reader.endArray();
            reader.endObject();
            reader.close();
        } else {
            JSONParseException e = new JSONParseException(
                    "Parsing of cloudant response failed. Tag 'features' not found. ");
            log.error(e.getLoggingString());
            throw e;
        }
    } catch (IOException ex) {
        JSONParseException e = new JSONParseException("Parsing of cloudant response failed.", ex);
        log.error(e.getLoggingString());
        throw e;
    }
}

From source file:de.qaware.chronix.converter.serializer.json.JsonMetricTimeSeriesSerializer.java

License:Apache License

/**
 * Deserialize the given json to a collection of metric data points
 *
 * @param json       the json representation of collection holding metric data points
 * @param queryStart the start of the query
 * @param queryEnd   the end of the query
 * @param builder    the builder for the time series
 */// www  .ja va2  s.c  o m
public void fromJson(byte[] json, final long queryStart, final long queryEnd,
        MetricTimeSeries.Builder builder) {
    if (queryStart <= 0 && queryEnd <= 0) {
        return;
    }

    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(json);
        JsonReader reader = new JsonReader(new InputStreamReader(bais, UTF_8));
        List[] timestampsValues = gson.fromJson(reader, List[].class);
        reader.close();

        List<Double> times = (List<Double>) timestampsValues[0];
        List<Double> values = (List<Double>) timestampsValues[1];

        for (int i = 0; i < times.size(); i++) {
            if (times.get(i) > queryEnd) {
                break;
            }

            if (times.get(i) >= queryStart && times.get(i) <= queryEnd) {
                builder.point(times.get(i).longValue(), values.get(i));
            }
        }

    } catch (IOException | JsonSyntaxException | JsonIOException e) {
        LOGGER.error("Could not deserialize json data. Returning empty lists.", e);
    }

}

From source file:de.sabian.objectstore.ObjectStoreRaw.java

License:Apache License

public <T> boolean fillCollection(String identifier, Class<T> clazz, Collection<T> collection)
        throws IOException {
    if (contains(identifier)) {
        JsonReader jReader = new JsonReader(new StringReader(mJsonStorage.getJson(identifier)));
        jReader.beginArray();/*from  w ww .j  a v  a 2 s .  co  m*/
        while (jReader.hasNext()) {
            T object = mGson.fromJson(jReader, clazz);
            collection.add(object);
        }
        jReader.endArray();
        jReader.close();
        return true;
    } else
        return false;
}

From source file:de.sabian.objectstore.ObjectStoreRaw.java

License:Apache License

public <T, X> boolean fillMap(String identifier, Class<T> classOfKeys, Class<X> classOfValues, Map<T, X> map)
        throws IOException {
    if (contains(identifier)) {
        JsonReader jReader = new JsonReader(new StringReader(mJsonStorage.getJson(identifier)));
        jReader.beginArray();/*from  w  w w  .ja va2  s .com*/
        while (jReader.hasNext()) {
            jReader.beginObject();
            String name = jReader.nextName();
            if (!name.equals("key"))
                throw new IOException("expected name key but found: " + name);
            T key = mGson.fromJson(jReader, classOfKeys);
            name = jReader.nextName();
            if (!name.equals("value"))
                throw new IOException("expected name value but found: " + name);
            X value = mGson.fromJson(jReader, classOfValues);
            jReader.endObject();
            map.put(key, value);
        }
        jReader.endArray();
        jReader.close();
        return true;
    } else
        return false;
}

From source file:de.winniehell.battlebeavers.gameplay.Game.java

License:Open Source License

/** load decisions from file */
public SoldierList getDecisions(final Context pContext, final int pTeam) throws IOException {
    if (!hasDecisions(pContext, pTeam)) {
        return null;
    }//from w  w w. j  ava 2s .c  o  m

    final JsonReader reader = CustomGSON.getReader(pContext, getDecisionsFile(pContext, pTeam));

    try {
        return CustomGSON.getInstance().fromJson(reader, SoldierList.class);
    } finally {
        reader.close();
    }
}

From source file:de.winniehell.battlebeavers.gameplay.Game.java

License:Open Source License

/** load outcome from file */
public Outcome getOutcome(final Context pContext) throws IOException {
    if (!hasOutcome(pContext)) {
        return null;
    }/* w  ww  .  jav a 2  s  . co m*/

    final JsonReader reader = CustomGSON.getReader(pContext, getOutcomeFile(pContext));

    try {
        return CustomGSON.getInstance().fromJson(reader, Outcome.class);
    } finally {
        reader.close();
    }
}

From source file:de.winniehell.battlebeavers.storage.CustomGSON.java

License:Open Source License

/** ensure the next element has the given Name */
public static void assertElement(final JsonReader pReader, final String pName)
        throws IOException, WrongElementException {
    if (!pReader.nextName().equals(pName)) {
        pReader.close();
        throw new WrongElementException("Expected " + pName + "!");
    }/* w  ww  . j  a v a2s  .  c o m*/
}

From source file:de.winniehell.battlebeavers.storage.GameStorage.java

License:Open Source License

/**
 * loads the storage from file/*ww w  . j  av a 2  s  . co  m*/
 * @throws FileNotFoundException
 */
private void loadFromFile() throws FileNotFoundException {

    if (!(new File(getFileName())).exists()) {
        final GameInfo info = GameInfo.fromFile(context, game);

        Log.d(TAG, "Copying maps/" + info.getMapName() + "/setup.json");

        try {
            final InputStream src = context.getAssets().open("maps/" + info.getMapName() + "/setup.json");

            final FileOutputStream dest = new FileOutputStream(getFileName());

            StreamUtils.copyAndClose(src, dest);
        } catch (final IOException e) {
            Log.e(TAG, "Copying map failed!", e);
            return;
        }
    }

    try {
        Log.d(TAG, "loading: " + StreamUtils.readFully(new FileInputStream(getFileName())));
    } catch (final Exception e) {
        Log.e(TAG, e.getMessage());
        return;
    }

    final Gson gson = CustomGSON.getInstance();
    final JsonReader reader = CustomGSON.getReader(context, getFileName());

    // file does not exist
    if (reader == null) {
        throw new FileNotFoundException(getFileName());
    }

    try {
        reader.beginArray();
        while (reader.hasNext()) {
            final Soldier soldier = gson.fromJson(reader, Soldier.class);

            try {
                addSoldier(soldier);
            } catch (final UnexpectedTileContentException e) {
                Log.e(TAG, "Adding soldier failed!", e);
            }
        }
        reader.endArray();
    } catch (final Exception e) {
        Log.e(TAG, "Loading game storage failed!", e);
    } finally {
        try {
            reader.close();
        } catch (final IOException e) {
            Log.e(TAG, "Closing reader failed!", e);
        }
    }
}

From source file:edu.isi.karma.modeling.alignment.GraphUtil.java

License:Apache License

public static DirectedWeightedMultigraph<Node, DefaultLink> importJson(String filename) throws IOException {

    File file = new File(filename);
    if (!file.exists()) {
        logger.error("cannot open the file " + filename);
    }//from www . j  ava2  s. c  o m

    FileInputStream in = new FileInputStream(file);
    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
    try {
        return readGraph(reader);
    } catch (Exception e) {
        logger.error("error in reading the model from json!");
        e.printStackTrace();
        return null;
    } finally {
        reader.close();
    }
}

From source file:edu.isi.karma.modeling.alignment.SemanticModel.java

License:Apache License

public static SemanticModel readJson(String filename) throws IOException {

    File file = new File(filename);
    if (!file.exists()) {
        logger.error("cannot open the file " + filename);
    }/*  w  w  w .  j  a  va  2 s. c  o m*/

    FileInputStream in = new FileInputStream(file);
    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
    try {
        return readModel(reader);
    } catch (Exception e) {
        logger.error("error in reading the model from json!");
        e.printStackTrace();
        return null;
    } finally {
        reader.close();
    }
}