List of usage examples for com.google.gson.stream JsonReader JsonReader
public JsonReader(Reader in)
From source file:com.oscarsalguero.smartystreetsautocomplete.json.GsonSmartyStreetsApiJsonParser.java
License:Apache License
@Override public List<Address> readHistoryJson(final InputStream in) throws JsonParsingException { try {/*from w w w . j a v a2s . com*/ 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.ovrhere.android.currencyconverter.model.parsers.AbstractJsonParser.java
License:Apache License
/** Parses the JSON stream and returns it described return type. * Note that this method initializes and closes the reader. * @param reader The input reading/*from ww w .j av a 2s . co m*/ * @return R1, the parsed data. * @throws IOException Re-thrown exception from reader */ public R1 parseJsonStream(Reader reader) throws IOException { checkPause(); jsonReader = new JsonReader(reader); checkPause(); try { return parseJsonToReturnData(); } finally { try { jsonReader.close(); } catch (IOException e) { } } }
From source file:com.ovrhere.android.currencyconverter.model.parsers.AbstractJsonParser.java
License:Apache License
/** Parses the JSON stream and returns it described return type. * Note that this method initializes and closes the reader. * @param in The input stream//from www .j a va 2 s. co m * @return R1, the parsed data. * @throws IOException Re-thrown exception from reader */ public R1 parseJsonStream(InputStream in) throws IOException { checkPause(); InputStreamReader reader = new InputStreamReader(in); jsonReader = new JsonReader(reader); checkPause(); try { return parseJsonToReturnData(); } finally { try { jsonReader.close(); } catch (IOException e) { } } }
From source file:com.pcloud.sdk.internal.RealApiClient.java
License:Apache License
private <T> T deserializeResponseBody(Response response, Class<? extends T> bodyType) throws IOException { try {/*www .j a va2 s .co m*/ if (!response.isSuccessful()) { throw new APIHttpException(response.code(), response.message()); } JsonReader reader = new JsonReader( new BufferedReader(new InputStreamReader(response.body().byteStream()))); try { return gson.fromJson(reader, bodyType); } catch (JsonSyntaxException e) { throw new IOException("Malformed JSON response.", e); } finally { closeQuietly(reader); } } finally { closeQuietly(response); } }
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;/*from w ww.j a v a 2 s. c o m*/ 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.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/*w w w . ja va2 s . c om*/ * * @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;/* w ww . ja va2 s .co m*/ try { // 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.persistencia.PersistenciaJson.java
public List<TablaDePago> tablasDepago(String ruta) throws FileNotFoundException, IOException { List<TablaDePago> result = null; System.out.println("Ruta de la tabla de pagos: " + ruta); if (ruta == null) { return null; }/*w w w .j a va 2 s . c o m*/ if (ruta.isEmpty()) { return null; } if (!new File(ruta).exists()) { ruta = "tablasDePago.json"; try (Writer writer = new FileWriter(ruta)) { List<TablaDePago> tabla = new ArrayList<>(); for (int i = 0; i < 10; i++) { TablaDePago t = new TablaDePago(FiguraPagoFactoria.cartones()); t.setNumero(i); tabla.add(t); } Gson gson = new GsonBuilder().create(); gson.toJson(tabla, writer); } } Gson gson = new Gson(); Type tipo = new TypeToken<List<TablaDePago>>() { }.getType(); JsonReader reader = new JsonReader(new FileReader(ruta)); result = gson.fromJson(reader, tipo); // Lista cargada return result; }
From source file:com.persistencia.PersistenciaJson.java
/** * Crea la configuracion de acceso a la base de datos JSON */// w w w. ja v a 2s . c o m private void crearConfiguracion() throws IOException { if (new File("config.db").exists()) { System.out.println("Existe el archivo config.db"); Gson gson = new Gson(); JsonReader reader = new JsonReader(new FileReader("config.db")); config = gson.fromJson(reader, ConfiguracionPersistencia.class); // Configuracion cargada } else { //No existe el archivo, crearlo System.out.println("No existe el archivo config.db, creando..."); try (Writer writer = new FileWriter("config.db")) { //Bonus por defecto Map<Integer, Integer> premiosFijosBonusMap = new HashMap<>(); Map<Integer, Integer> premiosVariablesBonusMap = new HashMap<>(); //Bonus fijo premiosFijosBonusMap.put(10, 4); premiosFijosBonusMap.put(50, 4); premiosFijosBonusMap.put(100, 4); //Premios variables premiosVariablesBonusMap.put(2, 4); premiosVariablesBonusMap.put(4, 4); premiosVariablesBonusMap.put(8, 4); config = new ConfiguracionPersistencia(); config.setRutaDeLasTablasDePago("tablasDePago.json"); config.setLimiteMaximoGratis(10); config.setLimiteMinimoGratis(0); config.setUtilizarUmbral(false); config.setUmbralParaLiberarBolasExtra(10); config.setFactorDePorcentajeDeCostoDeBolaExtraSegunElPremioMayor(0.1); config.setUtilizarPremiosFijosBonus(true); config.setPremiosFijosBonus(premiosFijosBonusMap); config.setUtilizarPremiosVariablesBonus(false); config.setPremiosVariablesBonus(premiosVariablesBonusMap); config.setCantidadDePremiosEnBonus(16); config.setIndiceConfiguracionJugadores(0); config.setProbabilidadDeApostarPorPerfil(new Double[] { .3, .6, .95 }); config.setProbabilidadDeComprarBolasExtra(new Double[] { .3, .6, .95 }); config.setCreditosMaximosPorPerfil(new Integer[] { 100, 250, 500 }); config.setIndiceConfiguracionCostoBolaExtra(0); Gson gson = new GsonBuilder().create(); gson.toJson(config, writer); writer.flush(); writer.close(); } } }
From source file:com.persistencia.PersistenciaJson.java
private ConfiguracionPersistencia leerConfiguracion() throws FileNotFoundException { ConfiguracionPersistencia result;/*from www . j av a2s .co m*/ Gson gson = new Gson(); JsonReader reader = new JsonReader(new FileReader("config.db")); result = gson.fromJson(reader, ConfiguracionPersistencia.class); // Lista cargada return result; }