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.gelakinetic.mtgfam.helpers.updaters.CardAndSetParser.java

License:Open Source License

/**
 * Parses the legality file and populates the database with the different formats, their respective sets, and their
 * banned and restricted lists/*from   ww w . ja  v  a  2 s. c o  m*/
 *
 * @param prefAdapter The preference adapter is used to get the last update time
 * @return An object with all of the legal info, to be added to the database in one fell swoop
 * @throws IOException                                                 Thrown if something goes wrong with the InputStream
 * @throws com.gelakinetic.mtgfam.helpers.database.FamiliarDbException Thrown if something goes wrong with database writing
 */
public LegalInfo readLegalityJsonStream(PreferenceAdapter prefAdapter) throws IOException, FamiliarDbException {

    LegalInfo legalInfo = new LegalInfo();

    String legalSet;
    String bannedCard;
    String restrictedCard;
    String formatName;
    String jsonArrayName;
    String jsonTopLevelName;

    URL legal = new URL(LEGALITY_URL);
    InputStream in = new BufferedInputStream(legal.openStream());

    JsonReader reader = new JsonReader(new InputStreamReader(in, "ISO-8859-1"));

    reader.beginObject();
    while (reader.hasNext()) {

        jsonTopLevelName = reader.nextName();
        if (jsonTopLevelName.equalsIgnoreCase("Date")) {
            mCurrentRulesDate = reader.nextString();

            /* compare date, maybe return, update shared prefs */
            String spDate = prefAdapter.getLegalityDate();
            if (spDate != null && spDate.equals(mCurrentRulesDate)) {
                reader.close();
                return null; /* dates match, nothing new here. */
            }

        } else if (jsonTopLevelName.equalsIgnoreCase("Formats")) {

            reader.beginObject();
            while (reader.hasNext()) {
                formatName = reader.nextName();

                legalInfo.formats.add(formatName);

                reader.beginObject();
                while (reader.hasNext()) {
                    jsonArrayName = reader.nextName();

                    if (jsonArrayName.equalsIgnoreCase("Sets")) {
                        reader.beginArray();
                        while (reader.hasNext()) {
                            legalSet = reader.nextString();
                            legalInfo.legalSets.add(new NameAndMetadata(legalSet, formatName));
                        }
                        reader.endArray();
                    } else if (jsonArrayName.equalsIgnoreCase("Banlist")) {
                        reader.beginArray();
                        while (reader.hasNext()) {
                            bannedCard = reader.nextString();
                            legalInfo.bannedCards.add(new NameAndMetadata(bannedCard, formatName));
                        }
                        reader.endArray();
                    } else if (jsonArrayName.equalsIgnoreCase("Restrictedlist")) {
                        reader.beginArray();
                        while (reader.hasNext()) {
                            restrictedCard = reader.nextString();
                            legalInfo.restrictedCards.add(new NameAndMetadata(restrictedCard, formatName));
                        }
                        reader.endArray();
                    }
                }
                reader.endObject();
            }
            reader.endObject();
        }
    }
    reader.endObject();

    reader.close();

    return legalInfo;
}

From source file:com.gelakinetic.mtgfam.helpers.updaters.CardAndSetParser.java

License:Open Source License

/**
 * This method parses the mapping between set codes and the names TCGPlayer.com uses
 *
 * @param prefAdapter The preference adapter is used to get the last update time
 * @param tcgNames    A place to store tcg names before adding to the database
 * @throws IOException Thrown if something goes wrong with the InputStream
 *///w  w w. j a  v  a2s .  c o  m
public void readTCGNameJsonStream(PreferenceAdapter prefAdapter, ArrayList<NameAndMetadata> tcgNames)
        throws IOException {
    URL update;
    String label;
    String label2;
    String name = null, code = null;

    update = new URL(TCG_NAMES_URL);
    InputStreamReader isr = new InputStreamReader(update.openStream(), "ISO-8859-1");
    JsonReader reader = new JsonReader(isr);

    reader.beginObject();
    while (reader.hasNext()) {
        label = reader.nextName();

        if (label.equals("Date")) {
            String lastUpdate = prefAdapter.getLastTCGNameUpdate();
            mCurrentTCGNamePatchDate = reader.nextString();
            if (lastUpdate.equals(mCurrentTCGNamePatchDate)) {
                reader.close();
                return;
            }
        } else if (label.equals("Sets")) {
            reader.beginArray();
            while (reader.hasNext()) {
                reader.beginObject();
                while (reader.hasNext()) {
                    label2 = reader.nextName();
                    if (label2.equals("Code")) {
                        code = reader.nextString();
                    } else if (label2.equals("TCGName")) {
                        name = reader.nextString();
                    }
                }
                tcgNames.add(new NameAndMetadata(name, code));
                reader.endObject();
            }
            reader.endArray();
        }
    }
    reader.endObject();
    reader.close();
}

From source file:com.getperka.flatpack.fast.JavaDialect.java

License:Apache License

/**
 * If {@value #concreteTypeMapFile} is defined, load the file into {@link #concreteTypeMap}.
 *//*from   w w  w .ja v a2  s.com*/
private void loadConcreteTypeMap() throws IOException {
    if (baseTypeArrayFile != null) {
        JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(baseTypeArrayFile), UTF8));
        reader.setLenient(true);
        reader.beginArray();
        while (reader.hasNext()) {
            baseTypes.add(reader.nextString());
        }
        reader.endArray();
        reader.close();
    }
}

From source file:com.getperka.flatpack.Unpacker.java

License:Apache License

private <T> FlatPackEntity<T> unpack(Type returnType, JsonReader reader, Principal principal)
        throws IOException {
    // Hold temporary state for deserialization
    DeserializationContext context = contexts.get();

    /*//from   w w  w .  j  a v a  2  s. c om
     * Decoding is done as a two-pass operation since the runtime type of an allocated object cannot
     * be swizzled. The per-entity data is held as a semi-reified JsonObject to be passed off to a
     * Codex.
     */
    Map<HasUuid, JsonObject> entityData = FlatPackCollections.mapForIteration();
    // Used to populate the entityData map
    JsonParser jsonParser = new JsonParser();
    /*
     * The reader is placed in lenient mode as an aid to developers, however all output will be
     * strictly formatted.
     */
    reader.setLenient(true);

    // The return value
    @SuppressWarnings("unchecked")
    FlatPackEntity<T> toReturn = (FlatPackEntity<T>) FlatPackEntity.create(returnType, null, principal);
    // Stores the single, top-level value in the payload for two-pass reification
    JsonElement value = null;

    if (reader.peek().equals(JsonToken.NULL)) {
        return toReturn;
    }

    reader.beginObject();

    while (JsonToken.NAME.equals(reader.peek())) {
        String name = reader.nextName();
        if ("data".equals(name)) {
            // data : { "fooEntity" : [ { ... }, { ... } ]
            reader.beginObject();
            while (JsonToken.NAME.equals(reader.peek())) {
                // Turn "fooEntity" into the actual FooEntity class
                String simpleName = reader.nextName();
                Class<? extends HasUuid> clazz = typeContext.getClass(simpleName);
                if (clazz == null) {
                    if (ignoreUnresolvableTypes) {
                        reader.skipValue();
                        continue;
                    } else {
                        throw new UnsupportedOperationException("Cannot resolve type " + simpleName);
                    }
                } else if (Modifier.isAbstract(clazz.getModifiers())) {
                    throw new UnsupportedOperationException(
                            "A subclass of " + simpleName + " must be used instead");
                }
                context.pushPath("allocating " + simpleName);
                try {
                    // Find the Codex for the requested entity type
                    EntityCodex<?> codex = (EntityCodex<?>) typeContext.getCodex(clazz);

                    // Take the n-many property objects and stash them for later decoding
                    reader.beginArray();
                    while (!JsonToken.END_ARRAY.equals(reader.peek())) {
                        JsonObject chunk = jsonParser.parse(reader).getAsJsonObject();
                        HasUuid entity = codex.allocate(chunk, context);
                        toReturn.addExtraEntity(entity);
                        entityData.put(entity, chunk.getAsJsonObject());
                    }
                    reader.endArray();
                } finally {
                    context.popPath();
                }
            }
            reader.endObject();
        } else if ("errors".equals(name)) {
            // "errors" : { "path" : "problem", "path2" : "problem2" }
            reader.beginObject();
            while (JsonToken.NAME.equals(reader.peek())) {
                String path = reader.nextName();
                if (JsonToken.STRING.equals(reader.peek()) || JsonToken.NUMBER.equals(reader.peek())) {
                    toReturn.addError(path, reader.nextString());
                } else {
                    reader.skipValue();
                }
            }
            reader.endObject();
        } else if ("metadata".equals(name)) {
            reader.beginArray();

            while (!JsonToken.END_ARRAY.equals(reader.peek())) {
                EntityMetadata meta = new EntityMetadata();
                JsonObject metaElement = jsonParser.parse(reader).getAsJsonObject();
                metaCodex.get().readProperties(meta, metaElement, context);
                toReturn.addMetadata(meta);
            }

            reader.endArray();
        } else if ("value".equals(name)) {
            // Just stash the value element in case it occurs first
            value = jsonParser.parse(reader);
        } else if (JsonToken.STRING.equals(reader.peek()) || JsonToken.NUMBER.equals(reader.peek())) {
            // Save off any other simple properties
            toReturn.putExtraData(name, reader.nextString());
        } else {
            // Ignore random other entries
            reader.skipValue();
        }
    }

    reader.endObject();
    reader.close();

    for (Map.Entry<HasUuid, JsonObject> entry : entityData.entrySet()) {
        HasUuid entity = entry.getKey();
        EntityCodex<HasUuid> codex = (EntityCodex<HasUuid>) typeContext.getCodex(entity.getClass());
        codex.readProperties(entity, entry.getValue(), context);
    }

    @SuppressWarnings("unchecked")
    Codex<T> returnCodex = (Codex<T>) typeContext.getCodex(toReturn.getType());
    toReturn.withValue(returnCodex.read(value, context));

    for (Map.Entry<UUID, String> entry : context.getWarnings().entrySet()) {
        toReturn.addWarning(entry.getKey().toString(), entry.getValue());
    }

    // Process metadata
    for (EntityMetadata meta : toReturn.getMetadata()) {
        if (meta.isPersistent()) {
            HasUuid entity = context.getEntity(meta.getUuid());
            if (entity instanceof PersistenceAware) {
                ((PersistenceAware) entity).markPersistent();
            }
        }
    }

    context.runPostWork();
    context.close();

    return toReturn;
}

From source file:com.github.kevinsawicki.halligan.Resource.java

License:Open Source License

/**
 * Fill this resource by opening a request to the URL and parsing the response
 *
 * @param url//  w w  w  . j ava 2  s  . c o m
 * @return this resource
 * @throws IOException
 */
protected Resource parse(final String url) throws IOException {
    BufferedReader buffer;
    try {
        HttpRequest request = createRequest(url);
        code = request.code();
        buffer = request.bufferedReader();
        prefix = getPrefix(request.getConnection().getURL());
    } catch (HttpRequestException e) {
        throw e.getCause();
    }

    JsonReader reader = new JsonReader(buffer);
    try {
        parse(reader);
    } catch (JsonParseException e) {
        IOException ioException = new IOException("JSON parsing failed");
        ioException.initCause(e);
        throw ioException;
    } finally {
        try {
            reader.close();
        } catch (IOException ignored) {
            // Ignored
        }
    }

    return this;
}

From source file:com.github.lindenb.gatkui.Json2Xml.java

License:Open Source License

public static void main(String[] args) {
    try {//from  w  w w.  j av  a  2s  .  c  o  m
        Json2Xml app = new Json2Xml();
        Reader r = null;
        JsonReader jr = null;
        if (args.length == 0) {
            LOG.info("reading JSON from stdin");
            r = new InputStreamReader(System.in);
        } else if (args.length == 1) {
            r = new FileReader(new File(args[0]));
        } else {
            System.err.println("Illegal Number of args");
            System.exit(-1);
        }

        jr = new JsonReader(r);
        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
        app.w = xof.createXMLStreamWriter(System.out, "UTF-8");
        app.w.setDefaultNamespace(NS);
        app.w.writeStartDocument("UTF-8", "1.0");

        app.parse(null, jr);
        app.w.writeEndDocument();
        app.w.flush();
        jr.close();
        System.exit(0);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }

}

From source file:com.github.rustdt.tooling.RustJsonMessageParser.java

License:Open Source License

public ArrayList2<RustMainMessage> parseStructuredMessages(JsonReader jsonReader) throws CommonException {
    ArrayList2<RustMainMessage> rustMessages = new ArrayList2<>();
    while (true) {
        try {/*from w ww  .  j  a  v a2 s  . c om*/
            RustMainMessage rustMessage = parseStructuredMessage(jsonReader);
            if (rustMessage == null) {
                jsonReader.close();
                break;
            }
            rustMessages.add(rustMessage);
        } catch (IOException ioe) {
            throw new CommonException("Unexpected IO Exception: ", ioe);
        }
    }
    return rustMessages;
}

From source file:com.google.cloud.bigquery.samples.StreamingSample.java

License:Apache License

/**
 * Command line that demonstrates Bigquery streaming.
 *
 * @param args Command line args, should be empty
 * @throws IOException IOexception/*from w  ww. ja  v  a 2  s .  co m*/
 */
// [START main]
public static void main(final String[] args) throws IOException {
    final Scanner scanner = new Scanner(System.in);
    System.out.println("Enter your project id: ");
    String projectId = scanner.nextLine();
    System.out.println("Enter your dataset id: ");
    String datasetId = scanner.nextLine();
    System.out.println("Enter your table id: ");
    String tableId = scanner.nextLine();
    scanner.close();

    System.out.println("Enter JSON to stream to BigQuery: \n" + "Press End-of-stream (CTRL-D) to stop");

    JsonReader fromCli = new JsonReader(new InputStreamReader(System.in));

    Iterator<TableDataInsertAllResponse> responses = run(projectId, datasetId, tableId, fromCli);

    while (responses.hasNext()) {
        System.out.println(responses.next());
    }

    fromCli.close();
}

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 w  w .  j  ava2  s  . c  om*/
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.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 va2 s . com*/
    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;
}