Java Code Examples for com.google.gson.stream.JsonReader#close()

The following examples show how to use com.google.gson.stream.JsonReader#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SizeWeightReader.java    From TFC2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void process(JsonReader reader)
{
	try 
	{
		reader.beginArray();

		while(reader.hasNext())
		{
			list.add(read(reader));
		}
		reader.endArray();
		reader.close();

	} catch (IOException e) 
	{
		e.printStackTrace();
	}
}
 
Example 2
Source File: GsonPlacesApiJsonParser.java    From android-PlacesAutocompleteTextView with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public List<Place> readHistoryJson(final InputStream in) throws JsonParsingException {
    try {
        JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
        List<Place> places = new ArrayList<>();
        reader.beginArray();
        while (reader.hasNext()) {
            Place message = gson.fromJson(reader, Place.class);
            places.add(message);
        }
        reader.endArray();
        reader.close();
        return places;
    } catch (Exception e) {
        throw new JsonParsingException(e);
    }
}
 
Example 3
Source File: TapchatService.java    From tapchat-android with Apache License 2.0 6 votes vote down vote up
private void oobInclude(String path) throws Exception {
    mLoadingOobBacklog = true;

    Response response = mAPI.oobInclude(path.substring(1));

    JsonReader reader = new JsonReader(new InputStreamReader(response.getBody().in()));
    reader.beginArray();
    while (reader.hasNext()) {
        Message message = mGson.fromJson(reader, Message.class);
        handleMessage(message);
    }
    reader.endArray();
    reader.close();

    mLoadingOobBacklog = false;
    handleMessageCache();
}
 
Example 4
Source File: TestJSONObj.java    From nuls-v2 with MIT License 6 votes vote down vote up
/**
 * alpha3
 */
public List<AccountData> readStream() {
    List<AccountData> accountDataList = new ArrayList<>();
    try {
        //方式一:将文件放入Transaction模块test的resources中,json格式 只保留list部分
        InputStream inputStream = getClass().getClassLoader().getResource("alpha2.json").openStream();
        //方式二:定义文件目录
        //InputStream inputStream = new FileInputStream("E:/IdeaProjects/nuls_2.0/module/nuls-transaction/src/test/resources/alpha2.json");
        JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
        Gson gson = new GsonBuilder().create();
        reader.beginArray();
        while (reader.hasNext()) {
            AccountData accountData = gson.fromJson(reader, AccountData.class);
            accountDataList.add(accountData);
        }
        reader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return accountDataList;
}
 
Example 5
Source File: EmptyDataTest.java    From restcountries with Mozilla Public License 2.0 6 votes vote down vote up
@Before
public void before() throws IOException {
    InputStream is = this.getClass().getClassLoader()
            .getResourceAsStream("countriesV2.json");
    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
    countries = new ArrayList<>();
    reader.beginArray();
    while (reader.hasNext()) {
        BaseCountry country = gson.fromJson(reader, BaseCountry.class);
        countries.add(country);
    }
    reader.endArray();
    reader.close();
}
 
Example 6
Source File: GsonSmartyStreetsApiJsonParser.java    From Smarty-Streets-AutoCompleteTextView with Apache License 2.0 6 votes vote down vote up
@Override
public List<Address> readHistoryJson(final InputStream in) throws JsonParsingException {
    try {
        JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
        List<Address> addresses = new ArrayList<>();
        reader.beginArray();
        while (reader.hasNext()) {
            Address message = gson.fromJson(reader, Address.class);
            addresses.add(message);
        }
        reader.endArray();
        reader.close();
        return addresses;
    } catch (Exception e) {
        throw new JsonParsingException(e);
    }
}
 
Example 7
Source File: CoincheckContext.java    From cryptotrader with GNU Affero General Public License v3.0 6 votes vote down vote up
@OnMessage
public void onWebSocketMessage(Reader message) throws IOException {

    // [id, pair, price, size, side]
    JsonReader reader = gson.newJsonReader(message);
    reader.beginArray();
    reader.skipValue();
    String pair = reader.nextString();
    String price = reader.nextString();
    String size = reader.nextString();
    reader.skipValue();
    reader.endArray();
    reader.close();

    appendCache(pair, CoincheckTrade.builder()
            .timestamp(getNow())
            .price(new BigDecimal(price))
            .size(new BigDecimal(size))
            .build());

}
 
Example 8
Source File: URLTools.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
public static JsonElement extractJson(String url) throws IOException
{
	HttpURLConnection con = openConnection(url);
	JsonReader reader = new JsonReader(new InputStreamReader(con.getInputStream()));
	JsonElement e= JsonParser.parseReader(reader);
	reader.close();
	close(con);
	return e;
}
 
Example 9
Source File: FileStore.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
private static <T> T parseEncryptedJsonFile(String fileName, CheckedFunction<JsonReader, T> parser) throws Exception {
    SecretKeySpec sks = new SecretKeySpec(StringHelper.hexStringToByteArray(Config.ENCRYPTION_KEY), "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, sks);

    try (InputStream is = Files.newInputStream(Paths.get(fileName))) {
        CipherInputStream in = new CipherInputStream(is, cipher);
        JsonReader reader = new JsonReader(new InputStreamReader(in));
        T result = parser.apply(reader);
        reader.close();
        in.close();
        return result;
    }
}
 
Example 10
Source File: JsonParser.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Parses a json string, returning either a {@code Map<String, ?>}, {@code List<?>},
 * {@code String}, {@code Double}, {@code Boolean}, or {@code null}.
 */
public static Object parse(String raw) throws IOException {
  JsonReader jr = new JsonReader(new StringReader(raw));
  try {
    return parseRecursive(jr);
  } finally {
    try {
      jr.close();
    } catch (IOException e) {
      logger.log(Level.WARNING, "Failed to close", e);
    }
  }
}
 
Example 11
Source File: MixedStreamTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testReadClosed() throws IOException {
  Gson gson = new Gson();
  JsonReader jsonReader = new JsonReader(new StringReader(CARS_JSON));
  jsonReader.close();
  try {
    gson.fromJson(jsonReader, new TypeToken<List<Car>>() {}.getType());
    fail();
  } catch (JsonParseException expected) {
  }
}
 
Example 12
Source File: GsonParcer.java    From EventApp with Apache License 2.0 5 votes vote down vote up
private static <T> T decode(String json) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(json));
    try {
        reader.beginObject();
        Class<?> type = Class.forName(reader.nextName());
        return gson.fromJson(reader, type);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    } finally {
        reader.close();
    }
}
 
Example 13
Source File: KafkaTopicConfigProvider.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void loadClusterConfigs(String clusterConfigsFile) throws FileNotFoundException {
  JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(clusterConfigsFile), StandardCharsets.UTF_8));
  try {
    Gson gson = new Gson();
    _clusterConfigs = gson.fromJson(reader, Properties.class);
  } finally {
    try {
      reader.close();
    } catch (IOException e) {
      // let it go.
    }
  }
}
 
Example 14
Source File: QuerySolrIT.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testStats() throws IOException {
    SolrClient solrClient = createSolrClient();
    TestRunner runner = createRunnerWithSolrClient(solrClient);

    runner.setProperty("stats", "true");
    runner.setProperty("stats.field", "integer_single");

    runner.enqueue(new ByteArrayInputStream(new byte[0]));
    runner.run();

    runner.assertTransferCount(QuerySolr.STATS, 1);
    JsonReader reader = new JsonReader(new InputStreamReader(new ByteArrayInputStream(
            runner.getContentAsByteArray(runner.getFlowFilesForRelationship(QuerySolr.STATS).get(0)))));
    reader.beginObject();
    assertEquals(reader.nextName(), "stats_fields");
    reader.beginObject();
    assertEquals(reader.nextName(), "integer_single");
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        switch (name) {
            case "min": assertEquals(reader.nextString(), "0.0"); break;
            case "max": assertEquals(reader.nextString(), "9.0"); break;
            case "count": assertEquals(reader.nextInt(), 10); break;
            case "sum": assertEquals(reader.nextString(), "45.0"); break;
            default: reader.skipValue(); break;
        }
    }
    reader.endObject();
    reader.endObject();
    reader.endObject();

    reader.close();
    solrClient.close();
}
 
Example 15
Source File: TestQuerySolr.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testStats() throws IOException {
    SolrClient solrClient = createSolrClient();
    TestRunner runner = createRunnerWithSolrClient(solrClient);

    runner.setProperty("stats", "true");
    runner.setProperty("stats.field", "integer_single");

    runner.enqueue(new ByteArrayInputStream(new byte[0]));
    runner.run();

    runner.assertTransferCount(QuerySolr.STATS, 1);
    JsonReader reader = new JsonReader(new InputStreamReader(new ByteArrayInputStream(
            runner.getContentAsByteArray(runner.getFlowFilesForRelationship(QuerySolr.STATS).get(0)))));
    reader.beginObject();
    assertEquals(reader.nextName(), "stats_fields");
    reader.beginObject();
    assertEquals(reader.nextName(), "integer_single");
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        switch (name) {
            case "min": assertEquals(reader.nextString(), "0.0"); break;
            case "max": assertEquals(reader.nextString(), "9.0"); break;
            case "count": assertEquals(reader.nextInt(), 10); break;
            case "sum": assertEquals(reader.nextString(), "45.0"); break;
            default: reader.skipValue(); break;
        }
    }
    reader.endObject();
    reader.endObject();
    reader.endObject();

    reader.close();
    solrClient.close();
}
 
Example 16
Source File: JsonFileReader.java    From neodymium-library with MIT License 4 votes vote down vote up
public static List<Map<String, String>> readFile(InputStream inputStream)
{
    List<Map<String, String>> data = new LinkedList<>();
    try
    {
        BufferedInputStream bufferedStream = new BufferedInputStream(inputStream);
        InputStreamReader streamReader = new InputStreamReader(new BufferedInputStream(bufferedStream), Charset.forName("UTF-8"));
        JsonReader jsonReader = new JsonReader(streamReader);

        JsonArray asJsonArray = new JsonParser().parse(jsonReader).getAsJsonArray();

        for (int i = 0; i < asJsonArray.size(); i++)
        {
            JsonObject dataSet = asJsonArray.get(i).getAsJsonObject();
            Map<String, String> newDataSet = new HashMap<>();
            for (Entry<String, JsonElement> entry : dataSet.entrySet())
            {
                JsonElement element = entry.getValue();
                if (element.isJsonNull())
                {
                    newDataSet.put(entry.getKey(), null);
                }
                else if (element.isJsonArray() || element.isJsonObject())
                {
                    newDataSet.put(entry.getKey(), element.toString());
                }
                else
                {
                    newDataSet.put(entry.getKey(), element.getAsString());
                }
            }
            data.add(newDataSet);
        }

        jsonReader.close();
        streamReader.close();
        bufferedStream.close();

        return data;
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}
 
Example 17
Source File: JSONPListParser.java    From tm4e with Eclipse Public License 1.0 4 votes vote down vote up
public T parse(InputStream contents) throws Exception {
	PList<T> pList = new PList<T>(theme);
	JsonReader reader = new JsonReader(new InputStreamReader(contents, StandardCharsets.UTF_8));
	// reader.setLenient(true);
	boolean parsing = true;
	while (parsing) {
		JsonToken nextToken = reader.peek();
		switch (nextToken) {
		case BEGIN_ARRAY:
			pList.startElement(null, "array", null, null);
			reader.beginArray();
			break;
		case END_ARRAY:
			pList.endElement(null, "array", null);
			reader.endArray();
			break;
		case BEGIN_OBJECT:
			pList.startElement(null, "dict", null, null);
			reader.beginObject();
			break;
		case END_OBJECT:
			pList.endElement(null, "dict", null);
			reader.endObject();
			break;
		case NAME:
			String lastName = reader.nextName();
			pList.startElement(null, "key", null, null);
			pList.characters(lastName.toCharArray(), 0, lastName.length());
			pList.endElement(null, "key", null);
			break;
		case NULL:
			reader.nextNull();
			break;
		case BOOLEAN:
			reader.nextBoolean();
			break;
		case NUMBER:
			reader.nextLong();
			break;
		case STRING:
			String value = reader.nextString();
			pList.startElement(null, "string", null, null);
			pList.characters(value.toCharArray(), 0, value.length());
			pList.endElement(null, "string", null);
			break;
		case END_DOCUMENT:
			parsing = false;
			break;
		default:
			break;
		}
	}
	reader.close();
	return pList.getResult();
}
 
Example 18
Source File: QuerySolrIT.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testRecordResponse() throws IOException, InitializationException {
    SolrClient solrClient = createSolrClient();
    TestRunner runner = createRunnerWithSolrClient(solrClient);

    runner.setProperty(QuerySolr.RETURN_TYPE, QuerySolr.MODE_REC.getValue());
    runner.setProperty(QuerySolr.SOLR_PARAM_FIELD_LIST, "id,created,integer_single");
    runner.setProperty(QuerySolr.SOLR_PARAM_ROWS, "10");

    final String outputSchemaText = new String(Files.readAllBytes(Paths.get("src/test/resources/test-schema.avsc")));

    final JsonRecordSetWriter jsonWriter = new JsonRecordSetWriter();
    runner.addControllerService("writer", jsonWriter);
    runner.setProperty(jsonWriter, SchemaAccessUtils.SCHEMA_ACCESS_STRATEGY, SchemaAccessUtils.SCHEMA_TEXT_PROPERTY);
    runner.setProperty(jsonWriter, SchemaAccessUtils.SCHEMA_TEXT, outputSchemaText);
    runner.setProperty(jsonWriter, "Pretty Print JSON", "true");
    runner.setProperty(jsonWriter, "Schema Write Strategy", "full-schema-attribute");
    runner.enableControllerService(jsonWriter);
    runner.setProperty(SolrUtils.RECORD_WRITER, "writer");

    runner.setNonLoopConnection(false);

    runner.run(1);
    runner.assertQueueEmpty();
    runner.assertTransferCount(QuerySolr.RESULTS, 1);

    JsonReader reader = new JsonReader(new InputStreamReader(new ByteArrayInputStream(
            runner.getContentAsByteArray(runner.getFlowFilesForRelationship(QuerySolr.RESULTS).get(0)))));
    reader.beginArray();
    int controlScore = 0;
    while (reader.hasNext()) {
        reader.beginObject();
        while (reader.hasNext()) {
            if (reader.nextName().equals("integer_single")) {
                controlScore += reader.nextInt();
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
    }
    reader.close();
    solrClient.close();

    assertEquals(controlScore, 45);
}
 
Example 19
Source File: SettingService.java    From webapp-hardware-bridge with MIT License 4 votes vote down vote up
private void loadFile(String filename) throws IOException {
    JsonReader reader = new JsonReader(new FileReader(filename));
    Gson gson = new Gson();
    setting = gson.fromJson(reader, Setting.class);
    reader.close();
}
 
Example 20
Source File: QuerySolrIT.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testAllFacetCategories() throws IOException {
    SolrClient solrClient = createSolrClient();
    TestRunner runner = createRunnerWithSolrClient(solrClient);

    runner.setProperty("facet", "true");
    runner.setProperty("facet.field", "integer_multi");
    runner.setProperty("facet.interval", "integer_single");
    runner.setProperty("facet.interval.set.1", "[4,7]");
    runner.setProperty("facet.interval.set.2", "[5,7]");
    runner.setProperty("facet.range", "created");
    runner.setProperty("facet.range.start", "NOW/MINUTE");
    runner.setProperty("facet.range.end", "NOW/MINUTE+1MINUTE");
    runner.setProperty("facet.range.gap", "+20SECOND");
    runner.setProperty("facet.query.1", "*:*");
    runner.setProperty("facet.query.2", "integer_multi:2");
    runner.setProperty("facet.query.3", "integer_multi:3");

    runner.enqueue(new ByteArrayInputStream(new byte[0]));
    runner.run();
    runner.assertTransferCount(QuerySolr.FACETS, 1);

    JsonReader reader = new JsonReader(new InputStreamReader(new ByteArrayInputStream(
            runner.getContentAsByteArray(runner.getFlowFilesForRelationship(QuerySolr.FACETS).get(0)))));
    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("facet_queries")) {
            assertEquals(30, returnCheckSumForArrayOfJsonObjects(reader));
        } else if (name.equals("facet_fields")) {
            reader.beginObject();
            assertEquals(reader.nextName(), "integer_multi");
            assertEquals(returnCheckSumForArrayOfJsonObjects(reader), 30);
            reader.endObject();
        } else if (name.equals("facet_ranges")) {
            reader.beginObject();
            assertEquals(reader.nextName(), "created");
            assertEquals(returnCheckSumForArrayOfJsonObjects(reader), 10);
            reader.endObject();
        } else if (name.equals("facet_intervals")) {
            reader.beginObject();
            assertEquals(reader.nextName(), "integer_single");
            assertEquals(returnCheckSumForArrayOfJsonObjects(reader), 7);
            reader.endObject();
        }
    }
    reader.endObject();
    reader.close();
    solrClient.close();
}