List of usage examples for com.google.gson.stream JsonReader JsonReader
public JsonReader(Reader in)
From source file:illarion.client.util.translation.mymemory.MyMemoryProvider.java
License:Open Source License
@Nullable @Override//from w w w .j av a 2s . c o m public String getTranslation(@Nonnull String original, @Nonnull TranslationDirection direction) { StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append(serviceUrl).append('?'); try { queryBuilder.append("q=").append(URLEncoder.encode(original, "UTF-8")); queryBuilder.append('&').append("langpair=").append(getLangPair(direction)); queryBuilder.append('&').append("of=json"); queryBuilder.append('&').append("de=").append(URLEncoder.encode("webmaster@illarion.org", "UTF-8")); URL queryUrl = new URL(queryBuilder.toString()); try (JsonReader rd = new JsonReader( new InputStreamReader(queryUrl.openStream(), Charset.forName("UTF-8")))) { Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); Response response = gson.fromJson(rd, Response.class); if ((response != null) && (response.getResponseData() != null) && (response.getResponseData().getMatch() > 0.75)) { return response.getResponseData().getTranslatedText(); } } catch (IOException e) { log.error("Error while reading from the service.", e); } catch (JsonParseException e) { log.error("Unexpected error while decoding json", e); } } catch (UnsupportedEncodingException e) { log.error("Error while encoding the text for transfer to the MyMemory provider.", e); } catch (MalformedURLException e) { log.error("Generated URL for the query to MyMemory appears to have a invalid format.", e); } // The provider is not working anymore. That either happens because the provider is unreachable or because // the provider is not accepting any more requests. Either way to reduce overhead the provider may shut down for // this session to reduce the overhead. operational = false; return null; }
From source file:illarion.client.util.translation.yandex.YandexProvider.java
License:Open Source License
@Nullable @Override//from ww w . j a v a 2s .com public String getTranslation(@Nonnull String original, @Nonnull TranslationDirection direction) { if (!isProviderWorking()) { return null; } StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append(serviceUrl).append('?'); try { queryBuilder.append("text=").append(URLEncoder.encode(original, "UTF-8")); queryBuilder.append('&').append("lang=").append(getLang(direction)); queryBuilder.append("&srv=tr-text"); URL queryUrl = new URL(queryBuilder.toString()); URLConnection connection = queryUrl.openConnection(); connection.addRequestProperty("User-Agent", userAgent); try (JsonReader rd = new JsonReader( new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")))) { Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); Response response = gson.fromJson(rd, Response.class); if (response != null) { List<String> result = response.getTexts(); if (result.size() == 1) { return result.get(0); } else if (result.size() > 1) { StringBuilder resultBuilder = new StringBuilder(); for (String text : result) { resultBuilder.append(text).append(' '); } return resultBuilder.toString().trim(); } } } catch (IOException e) { log.error("Error while reading from the service.", e); } catch (JsonParseException e) { log.error("Unexpected error while decoding json", e); } } catch (UnsupportedEncodingException e) { log.error("Error while encoding the text for transfer to the Yandex provider.", e); } catch (MalformedURLException e) { log.error("Generated URL for the query to Yandex appears to have a invalid format.", e); } catch (IOException e) { log.error("Failed to open connection for Yandex provider.", e); } // The provider is not working anymore. That either happens because the provider is unreachable or because // the provider is not accepting any more requests. Either way to reduce overhead the provider may shut down for // this session to reduce the overhead. operational = false; return null; }
From source file:imapi.OnlineDatabaseActions.java
License:Apache License
private int readJsonUriVals(InputStream inputStream, Vector<String> uriVals) { try {/*from w w w . jav a 2 s . c o m*/ JsonReader rdr = new JsonReader(new InputStreamReader(inputStream)); JsonParser parser = new JsonParser(); JsonElement jElement = parser.parse(rdr); if (jElement.isJsonObject() == false) { showContentsOfInputStream(inputStream); return ApiConstants.IMAPIFailCode; } // read head/vars from json in order to get the names of the // select clause in the order that they were declared. // Store in headVarNames vector Vector<String> headVarNames = new Vector<String>(); JsonObject jRootObject = jElement.getAsJsonObject(); JsonArray jHeadVarsArray = jRootObject.get("head").getAsJsonObject().get("vars").getAsJsonArray(); Iterator<JsonElement> jVarsIter = jHeadVarsArray.iterator(); while (jVarsIter.hasNext()) { JsonElement jVarElement = jVarsIter.next(); if (jVarElement.isJsonPrimitive()) { headVarNames.add(jVarElement.getAsString()); } } if (jRootObject.has("results") == false || jRootObject.get("results").getAsJsonObject().has("bindings") == false) { return ApiConstants.IMAPIFailCode; } // loop over all json bindings JsonArray jBindingsArray = jRootObject.get("results").getAsJsonObject().get("bindings") .getAsJsonArray(); Iterator<JsonElement> jBindingsIter = jBindingsArray.iterator(); while (jBindingsIter.hasNext()) { // of the binding String uri = ""; JsonElement jBindingElement = jBindingsIter.next(); if (jBindingElement.isJsonObject() == false) { continue; } JsonObject jBindingObject = jBindingElement.getAsJsonObject(); for (int k = 0; k < headVarNames.size(); k++) { String currentPropertyName = headVarNames.get(k); if (jBindingObject.has(currentPropertyName)) { JsonObject jObj = jBindingObject.get(currentPropertyName).getAsJsonObject(); String valStr = ""; if (jObj.has("value")) { valStr = jObj.get("value").getAsString(); } if (k == 0) { uri = valStr; } } } if (uri.length() > 0 && uriVals.contains(uri) == false) { uriVals.add(uri); } // end of asking for all predicates of select clause head/vars names } // edn of while llop that iters across all bindings } catch (Exception ex) { Utilities.handleException(ex); return ApiConstants.IMAPIFailCode; } return ApiConstants.IMAPISuccessCode; }
From source file:imapi.OnlineDatabaseActions.java
License:Apache License
private int readJsonStartingUriAndValuePairs(InputStream inputStream, String startingUriName, String valueName, boolean checkForLang, Vector<DataRecord[]> returnVals) { try {/*from www .jav a 2s . co m*/ JsonReader rdr = new JsonReader(new InputStreamReader(inputStream)); JsonParser parser = new JsonParser(); JsonElement jElement = parser.parse(rdr); if (jElement.isJsonObject() == false) { showContentsOfInputStream(inputStream); return ApiConstants.IMAPIFailCode; } // read head/vars from json in order to get the names of the // select clause in the order that they were declared. // Store in headVarNames vector Vector<String> headVarNames = new Vector<String>(); JsonObject jRootObject = jElement.getAsJsonObject(); JsonArray jHeadVarsArray = jRootObject.get("head").getAsJsonObject().get("vars").getAsJsonArray(); Iterator<JsonElement> jVarsIter = jHeadVarsArray.iterator(); while (jVarsIter.hasNext()) { JsonElement jVarElement = jVarsIter.next(); if (jVarElement.isJsonPrimitive()) { headVarNames.add(jVarElement.getAsString()); } } if (jRootObject.has("results") == false || jRootObject.get("results").getAsJsonObject().has("bindings") == false) { return ApiConstants.IMAPIFailCode; } // loop over all json bindings JsonArray jBindingsArray = jRootObject.get("results").getAsJsonObject().get("bindings") .getAsJsonArray(); Iterator<JsonElement> jBindingsIter = jBindingsArray.iterator(); while (jBindingsIter.hasNext()) { // of the binding DataRecord start = null; DataRecord end = null; JsonElement jBindingElement = jBindingsIter.next(); if (jBindingElement.isJsonObject() == false) { continue; } JsonObject jBindingObject = jBindingElement.getAsJsonObject(); for (int k = 0; k < headVarNames.size(); k++) { String currentPropertyName = headVarNames.get(k); if (jBindingObject.has(currentPropertyName)) { JsonObject jObj = jBindingObject.get(currentPropertyName).getAsJsonObject(); String valStr = ""; String langStr = ""; if (jObj.has("value")) { valStr = jObj.get("value").getAsString(); } if (checkForLang) { //read lang if type is literal if (jObj.has("xml:lang")) { langStr = jObj.get("xml:lang").getAsString(); } } if (valStr == null || valStr.trim().length() == 0) { continue; } if (currentPropertyName.equals(startingUriName)) { start = new DataRecord(valStr, ""); } if (currentPropertyName.equals(valueName)) { end = new DataRecord(valStr, langStr); } } } if (start != null && end != null) { DataRecord[] newVal = { start, end }; returnVals.add(newVal); } // end of asking for all predicates of select clause head/vars names } // edn of while llop that iters across all bindings } catch (Exception ex) { Utilities.handleException(ex); return ApiConstants.IMAPIFailCode; } return ApiConstants.IMAPISuccessCode; }
From source file:Implement.DAO.CommonDAOImpl.java
@Override public boolean insertNewLanguage() { String language = "JSON String"; Gson gson = new Gson(); JsonReader reader = new JsonReader(new StringReader(language)); reader.setLenient(true);//w ww .j ava 2s . com JsonObject myobject = gson.fromJson(reader, JsonObject.class); int flag = 0; for (Map.Entry<String, JsonElement> entry : myobject.entrySet()) { String name = entry.getValue().getAsJsonObject().get("name").toString(); if (!name.equals( "\"Old Church Slavonic, Church Slavic, Church Slavonic, Old Bulgarian, Old Slavonic\"")) { String sql = "INSERT INTO Language" + " VALUES (?)"; jdbcTemplate.update(sql, name.replaceAll("\"", "")); } } return true; }
From source file:info.hieule.framework.laravel.github.GithubTagBase.java
License:Open Source License
private void init() { isNetworkError = false;/* w w w . jav a 2 s .co m*/ tags = new ArrayList<GithubTag>(); try { // JSON -> Object Gson gson = new Gson(); URL tagsJson = new URL(getUrl()); BufferedReader reader = new BufferedReader(new InputStreamReader(tagsJson.openStream(), "UTF-8")); try { JsonReader jsonReader = new JsonReader(reader); Type type = new TypeToken<ArrayList<GithubTag>>() { }.getType(); tags = gson.fromJson(jsonReader, type); } finally { reader.close(); } } catch (MalformedURLException ex) { Exceptions.printStackTrace(ex); } catch (UnsupportedEncodingException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { isNetworkError = true; } names = new ArrayList<String>(tags.size()); if (isNetworkError) { return; } Filter filter = getFilter(); if (filter == null) { filter = new DefaultFilter(); } for (GithubTag tag : tags) { String name = tag.getName(); if (filter.accept(name)) { names.add(name); } } }
From source file:io.bouquet.v4.GsonFactory.java
License:Apache License
/** * Deserialize the given JSON string to Java object. * * @param <T> Type/* w ww . ja v a2s . co m*/ * @param body The JSON string * @param returnType The type to deserialize inot * @return The deserialized Java object */ @SuppressWarnings("unchecked") public <T> T deserialize(String body, Type returnType) throws ApiException { try { if (getClient().isLenientOnJson()) { JsonReader jsonReader = new JsonReader(new StringReader(body)); // see // https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) jsonReader.setLenient(true); return gson.fromJson(jsonReader, returnType); } else { return gson.fromJson(body, returnType); } } catch (JsonParseException e) { // Fallback processing when failed to parse JSON form response body: // return the response body string directly for the String return // type; // parse response body into date or datetime for the Date return // type. if (returnType.equals(String.class)) return (T) body; else if (returnType.equals(Date.class)) return (T) getClient().parseDateOrDatetime(body); else throw (e); } catch (Exception e) { throw e; } }
From source file:io.cloudex.framework.config.Job.java
License:Apache License
/** * De-serialize a job instance from a json file. * @param jsonFile - a file path//from w w w . j ava 2 s. c om * @return a Job instance * @throws FileNotFoundException if the file is not found * @throws IOException if the json conversion fails */ public static Job fromJsonFile(String jsonFile) throws FileNotFoundException, IOException { try (FileReader reader = new FileReader(jsonFile)) { return ObjectUtils.GSON.fromJson(new JsonReader(reader), Job.class); } }
From source file:io.cloudex.framework.utils.FileUtils.java
License:Apache License
/** * Convert a json file to set/*from ww w. jav a 2 s. c o m*/ * @param filename * @return * @throws IOException */ public static Set<String> jsonFileToSet(String filename) throws IOException { try (FileReader reader = new FileReader(filename)) { return GSON.fromJson(new JsonReader(reader), new TypeToken<Set<String>>() { }.getType()); } catch (Exception e) { log.error("failed to prase json into set", e); throw new IOException(e); } }
From source file:io.cloudex.framework.utils.FileUtils.java
License:Apache License
/** * Convert a json file to map/* w ww . j av a2 s. c om*/ * @param filename * @return * @throws IOException */ public static Map<String, Long> jsonFileToMap(String filename) throws IOException { try (FileReader reader = new FileReader(filename)) { return GSON.fromJson(new JsonReader(reader), new TypeToken<Map<String, Long>>() { }.getType()); } catch (Exception e) { log.error("failed to prase json into map", e); throw new IOException(e); } }