List of usage examples for com.google.gson.stream JsonReader close
public void close() throws IOException
From source file:com.nridge.ds.solr.SolrSchemaJSON.java
License:Open Source License
private DataTable createSchemaFieldTable(String aSchemaString, String aFieldName, String aTitle) throws IOException { String jsonName;/*from w w w . j av a 2 s. c o m*/ DataField dataField; DataTable dataTable = new DataTable(aTitle); DataBag dataBag = dataTable.getColumnBag(); StringReader stringReader = new StringReader(aSchemaString); JsonReader jsonReader = new JsonReader(stringReader); jsonReader.beginObject(); while (jsonReader.hasNext()) { jsonName = jsonReader.nextName(); if (StringUtils.equals(jsonName, OBJECT_SCHEMA)) { jsonReader.beginObject(); while (jsonReader.hasNext()) { jsonName = jsonReader.nextName(); if (StringUtils.equals(jsonName, aFieldName)) { jsonReader.beginArray(); while (jsonReader.hasNext()) { jsonReader.beginObject(); while (jsonReader.hasNext()) { jsonName = jsonReader.nextName(); dataField = dataBag.getFieldByName(jsonName); if (dataField == null) { dataField = new DataTextField(jsonName, Field.nameToTitle(jsonName)); dataField.addFeature(Field.FEATURE_IS_STORED, StrUtl.STRING_TRUE); dataBag.add(dataField); } jsonReader.skipValue(); } jsonReader.endObject(); } jsonReader.endArray(); ; } else jsonReader.skipValue(); } jsonReader.endObject(); } else jsonReader.skipValue(); } jsonReader.endObject(); jsonReader.close(); return dataTable; }
From source file:com.nridge.ds.solr.SolrSchemaJSON.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.// www .j a v a 2 s.c om * * @param aSchemaString JSON string representation of the Solr schema. * * @return Document instance containing the parsed data. * * @throws java.io.IOException I/O related exception. */ public Document loadDocument(String aSchemaString) throws IOException { String jsonName, jsonValue; Document schemaDocument = new Document(Solr.DOCUMENT_SCHEMA_TYPE); DataBag schemaBag = schemaDocument.getBag(); // Parse a subset of the JSON payload to identify the table columns before fully processing it. SolrSchema solrSchema = new SolrSchema(mAppMgr); DataTable fieldsTable = new DataTable(solrSchema.createFieldsBag()); DataTable dynamicFieldsTable = createSchemaFieldTable(aSchemaString, OBJECT_SCHEMA_DYNAMIC_FIELDS, "Solr Schema Dynamic Fields"); DataTable copyFieldsTable = createSchemaFieldTable(aSchemaString, OBJECT_SCHEMA_COPY_FIELDS, "Solr Schema Copy Fields"); StringReader stringReader = new StringReader(aSchemaString); 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); headerDocument.setName(jsonName); 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(); schemaDocument.addRelationship(Solr.RESPONSE_SCHEMA_HEADER, headerDocument); } else if (StringUtils.equals(jsonName, OBJECT_SCHEMA)) { jsonReader.beginObject(); while (jsonReader.hasNext()) { jsonName = jsonReader.nextName(); if (StringUtils.equals(jsonName, "name")) { jsonValue = nextValueAsString(jsonReader); schemaBag.add(jsonName, Field.nameToTitle(jsonName), jsonValue); } else if (StringUtils.equals(jsonName, "version")) { jsonValue = nextValueAsString(jsonReader); schemaBag.add(jsonName, Field.nameToTitle(jsonName), jsonValue); } else if (StringUtils.equals(jsonName, "uniqueKey")) { jsonValue = nextValueAsString(jsonReader); schemaBag.add(jsonName, Field.nameToTitle(jsonName), jsonValue); } else if (StringUtils.equals(jsonName, OBJECT_SCHEMA_FIELD_TYPES)) { populateSchemaFieldTypes(jsonReader, schemaDocument); } else if (StringUtils.equals(jsonName, OBJECT_SCHEMA_FIELDS)) { populateSchemaFieldTable(jsonReader, fieldsTable); Document fieldsDocument = new Document(Solr.RESPONSE_SCHEMA_FIELD_NAMES, fieldsTable); schemaDocument.addRelationship(Solr.RESPONSE_SCHEMA_FIELD_NAMES, fieldsDocument); } else if (StringUtils.equals(jsonName, OBJECT_SCHEMA_DYNAMIC_FIELDS)) { populateSchemaFieldTable(jsonReader, dynamicFieldsTable); Document dynamicFieldsDocument = new Document(Solr.RESPONSE_SCHEMA_DYNAMIC_FIELDS, dynamicFieldsTable); schemaDocument.addRelationship(Solr.RESPONSE_SCHEMA_DYNAMIC_FIELDS, dynamicFieldsDocument); } else if (StringUtils.equals(jsonName, OBJECT_SCHEMA_COPY_FIELDS)) { populateSchemaFieldTable(jsonReader, copyFieldsTable); Document copyFieldsDocument = new Document(Solr.RESPONSE_SCHEMA_COPY_FIELDS, copyFieldsTable); schemaDocument.addRelationship(Solr.RESPONSE_SCHEMA_COPY_FIELDS, copyFieldsDocument); } else jsonReader.skipValue(); } jsonReader.endObject(); } else jsonReader.skipValue(); } jsonReader.endObject(); jsonReader.close(); return schemaDocument; }
From source file:com.oscarsalguero.smartystreetsautocomplete.json.GsonSmartyStreetsApiJsonParser.java
License:Apache License
@Override public List<Address> readHistoryJson(final InputStream in) throws JsonParsingException { try {/* ww w.j av a 2 s .c o m*/ 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); } }
From source file:com.pearson.pdn.learningstudio.helloworld.OAuth2AssertionServlet.java
License:Apache License
@Override public Map<String, String> getOAuthHeaders(String resourceUrl, String httpMethod, String httpBody) throws IOException { // you would just reuse these values in the real world, // but we'll recreate them on every call here for simplicity. String username = resources.getString("username"); final String grantType = "assertion"; final String assertionType = "urn:ecollege:names:moauth:1.0:assertion"; final String url = LS_API_URL + "/token"; final String applicationId = resources.getString("applicationId"); final String applicationName = resources.getString("applicationName"); final String consumerKey = resources.getString("consumerKey"); final String clientString = resources.getString("clientString"); final String consumerSecret = resources.getString("consumerSecret"); HttpsURLConnection httpConn = null; JsonReader in = null; try {// w ww .j a va 2 s. co m // Create the Assertion String String assertion = buildAssertion(applicationName, consumerKey, applicationId, clientString, username, consumerSecret); // Create the data to send StringBuilder data = new StringBuilder(); data.append("grant_type=").append(URLEncoder.encode(grantType, "UTF-8")); data.append("&assertion_type=").append(URLEncoder.encode(assertionType, "UTF-8")); data.append("&assertion=").append(URLEncoder.encode(assertion, "UTF-8")); // Create a byte array of the data to be sent byte[] byteArray = data.toString().getBytes("UTF-8"); // Setup the Request URL request = new URL(url); httpConn = (HttpsURLConnection) request.openConnection(); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("User-Agent", "LS-HelloWorld-Java-V1"); httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConn.setRequestProperty("Content-Length", "" + byteArray.length); httpConn.setDoOutput(true); // Write data OutputStream postStream = httpConn.getOutputStream(); postStream.write(byteArray, 0, byteArray.length); postStream.close(); long creationTime = System.currentTimeMillis(); // Send Request & Get Response in = new JsonReader(new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"))); // Parse the Json response and retrieve the Access Token Gson gson = new Gson(); Type mapTypeAccess = new TypeToken<Map<String, String>>() { }.getType(); Map<String, String> ser = gson.fromJson(in, mapTypeAccess); String accessToken = ser.get("access_token"); if (accessToken == null || accessToken.length() == 0) { throw new IOException("Missing Access Token"); } Map<String, String> headers = new TreeMap<String, String>(); headers.put("X-Authorization", "Access_Token access_token=" + accessToken); return headers; } finally { // Be sure to close out any resources or connections if (in != null) in.close(); if (httpConn != null) httpConn.disconnect(); } }
From source file:com.pearson.pdn.learningstudio.oauth.OAuth2AssertionService.java
License:Apache License
/** * Generates OAuth2 Assertion Request/*from w w w .j av a 2 s. co m*/ * * @param username Username for request * @return OAuth2 request with assertion * @throws IOException */ public OAuth2Request generateOAuth2AssertionRequest(String username) throws IOException { final String grantType = "assertion"; final String assertionType = "urn:ecollege:names:moauth:1.0:assertion"; final String url = API_DOMAIN + "/token"; final String applicationId = configuration.getApplicationId(); final String applicationName = configuration.getApplicationName(); final String consumerKey = configuration.getConsumerKey(); final String clientString = configuration.getClientString(); final String consumerSecret = configuration.getConsumerSecret(); OAuth2Request oauthRequest = null; HttpsURLConnection httpConn = null; JsonReader in = null; try { // Create the Assertion String String assertion = buildAssertion(applicationName, consumerKey, applicationId, clientString, username, consumerSecret); // Create the data to send StringBuilder data = new StringBuilder(); data.append("grant_type=").append(URLEncoder.encode(grantType, "UTF-8")); data.append("&assertion_type=").append(URLEncoder.encode(assertionType, "UTF-8")); data.append("&assertion=").append(URLEncoder.encode(assertion, "UTF-8")); // Create a byte array of the data to be sent byte[] byteArray = data.toString().getBytes("UTF-8"); // Setup the Request URL request = new URL(url); httpConn = (HttpsURLConnection) request.openConnection(); httpConn.setRequestMethod("POST"); httpConn.addRequestProperty("User-Agent", "LS-Library-OAuth-Java-V1"); httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConn.setRequestProperty("Content-Length", "" + byteArray.length); httpConn.setDoOutput(true); // Write data OutputStream postStream = httpConn.getOutputStream(); postStream.write(byteArray, 0, byteArray.length); postStream.close(); long creationTime = System.currentTimeMillis(); // Send Request & Get Response in = new JsonReader(new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"))); // Parse the Json response and retrieve the Access Token Gson gson = new Gson(); Type mapTypeAccess = new TypeToken<Map<String, String>>() { }.getType(); Map<String, String> ser = gson.fromJson(in, mapTypeAccess); String accessToken = ser.get("access_token"); if (accessToken == null || accessToken.length() == 0) { throw new IOException("Missing Access Token"); } oauthRequest = new OAuth2Request(); oauthRequest.setAccessToken(accessToken); oauthRequest.setExpiresInSeconds(new Integer(ser.get("expires_in"))); oauthRequest.setCreationTime(creationTime); Map<String, String> headers = new TreeMap<String, String>(); headers.put("X-Authorization", "Access_Token access_token=" + accessToken); oauthRequest.setHeaders(headers); } finally { // Be sure to close out any resources or connections if (in != null) in.close(); if (httpConn != null) httpConn.disconnect(); } return oauthRequest; }
From source file:com.pearson.pdn.learningstudio.oauth.OAuth2PasswordService.java
License:Apache License
private OAuth2Request doRequest(byte[] byteArray) throws IOException { final String url = API_DOMAIN + "/token"; OAuth2Request oauthRequest = null; HttpsURLConnection httpConn = null; JsonReader in = null; try {/*from w ww . j a v a 2 s .c o m*/ // Setup the Request URL request = new URL(url); httpConn = (HttpsURLConnection) request.openConnection(); httpConn.setRequestMethod("POST"); httpConn.addRequestProperty("User-Agent", "LS-Library-OAuth-Java-V1"); httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConn.setRequestProperty("Content-Length", "" + byteArray.length); httpConn.setDoOutput(true); // Write data OutputStream postStream = httpConn.getOutputStream(); postStream.write(byteArray, 0, byteArray.length); postStream.close(); long creationTime = System.currentTimeMillis(); // Send Request & Get Response in = new JsonReader(new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"))); // Parse the Json response and retrieve the Access Token Gson gson = new Gson(); Type mapType = new TypeToken<Map<String, String>>() { }.getType(); Map<String, String> ser = gson.fromJson(in, mapType); String accessToken = ser.get("access_token"); if (accessToken == null || accessToken.length() == 0) { throw new IOException("Missing Access Token"); } oauthRequest = new OAuth2Request(); oauthRequest.setAccessToken(accessToken); oauthRequest.setExpiresInSeconds(new Integer(ser.get("expires_in"))); oauthRequest.setRefreshToken(ser.get("refresh_token")); oauthRequest.setCreationTime(creationTime); Map<String, String> headers = new TreeMap<String, String>(); headers.put("X-Authorization", "Access_Token access_token=" + accessToken); oauthRequest.setHeaders(headers); } finally { // Be sure to close out any resources or connections if (in != null) in.close(); if (httpConn != null) httpConn.disconnect(); } return oauthRequest; }
From source file:com.pocketbeer.presentation.flow.GsonParceler.java
License:Apache License
private Object decode(String json) throws IOException { JsonReader reader = new JsonReader(new StringReader(json)); try {// ww w . ja v a2 s. c o m reader.beginObject(); Class<?> type = Class.forName(reader.nextName()); return mGson.fromJson(reader, type); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } finally { reader.close(); } }
From source file:com.ptapp.sync.PTAppDataHandler.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 java.io.IOException If there is an error parsing the data. *//*from w w w. j a va 2 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 "educators", "courses", "students", "events" 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 ptapp data json: " + key); reader.skipValue(); } } reader.endObject(); } finally { reader.close(); } }
From source file:com.quarterfull.newsAndroid.reader.owncloud.OwnCloudReaderMethods.java
License:Open Source License
/** * can parse json like {"items":[{"id":6782}]} * @param in/* www . ja va 2 s . c o m*/ * @param iJoBj * @return count all, count new items * @throws IOException */ public static int[] readJsonStreamV2(InputStream in, IHandleJsonObject iJoBj) throws IOException { List<String> allowedArrays = Arrays.asList("feeds", "folders", "items"); int count = 0; int newItemsCount = 0; JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); reader.beginObject(); String currentName; while (reader.hasNext() && (currentName = reader.nextName()) != null) { if (allowedArrays.contains(currentName)) break; else reader.skipValue(); } reader.beginArray(); while (reader.hasNext()) { JSONObject e = getJSONObjectFromReader(reader); if (iJoBj.performAction(e)) newItemsCount++; count++; } if (iJoBj instanceof InsertItemIntoDatabase) ((InsertItemIntoDatabase) iJoBj).performDatabaseBatchInsert(); //Save pending buffer //reader.endArray(); //reader.endObject(); reader.close(); return new int[] { count, newItemsCount }; }
From source file:com.quarterfull.newsAndroid.reader.owncloud.OwnCloudReaderMethods.java
License:Open Source License
/** * can parse json like {"items":[{"id":6782}]} * @param in//from w w w .ja v a 2 s . com * @param iJoBj * @return new int[] { count, newItemsCount } * @throws IOException */ public static int[] readJsonStreamV1(InputStream in, IHandleJsonObject iJoBj) throws IOException { int count = 0; int newItemsCount = 0; JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); reader.beginObject();//{ reader.nextName();//"ocs" reader.beginObject();//{ reader.nextName();//meta getJSONObjectFromReader(reader);//skip status etc. reader.nextName();//data reader.beginObject();//{ reader.nextName();//folders etc.. reader.beginArray(); while (reader.hasNext()) { //reader.beginObject(); JSONObject e = getJSONObjectFromReader(reader); if (iJoBj.performAction(e)) newItemsCount++; //reader.endObject(); count++; } if (iJoBj instanceof InsertItemIntoDatabase) ((InsertItemIntoDatabase) iJoBj).performDatabaseBatchInsert(); //Save pending buffer //reader.endArray(); //reader.endObject(); reader.close(); return new int[] { count, newItemsCount }; }