List of usage examples for com.google.gson.stream JsonReader JsonReader
public JsonReader(Reader in)
From source file:com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginsAdvertiser.java
License:Apache License
public static List<PluginId> retrieve(UnknownFeature unknownFeature) { final String featureType = unknownFeature.getFeatureType(); final String implementationName = unknownFeature.getImplementationName(); final String buildNumber = ApplicationInfo.getInstance().getBuild().asString(); final String pluginRepositoryUrl = FEATURE_IMPLEMENTATIONS_URL + "featureType=" + featureType + "&implementationName=" + implementationName.replaceAll("#", "%23") + "&build=" + buildNumber; try {// www. java 2s . c om HttpURLConnection connection = HttpConfigurable.getInstance().openHttpConnection(pluginRepositoryUrl); connection.connect(); final InputStreamReader streamReader = new InputStreamReader(connection.getInputStream()); try { final JsonReader jsonReader = new JsonReader(streamReader); jsonReader.setLenient(true); final JsonElement jsonRootElement = new JsonParser().parse(jsonReader); final List<PluginId> result = new ArrayList<PluginId>(); for (JsonElement jsonElement : jsonRootElement.getAsJsonArray()) { final JsonObject jsonObject = jsonElement.getAsJsonObject(); final JsonElement pluginId = jsonObject.get("pluginId"); result.add(PluginId.getId(StringUtil.unquoteString(pluginId.toString()))); } return result; } finally { streamReader.close(); } } catch (IOException e) { LOG.info(e); return null; } }
From source file:com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginsAdvertiser.java
License:Apache License
private static Map<String, Set<PluginId>> loadSupportedExtensions() { final String pluginRepositoryUrl = FEATURE_IMPLEMENTATIONS_URL + "featureType=" + FileTypeFactory.FILE_TYPE_FACTORY_EP.getName(); try {//from w ww. j a v a 2s . c o m HttpURLConnection connection = HttpConfigurable.getInstance().openHttpConnection(pluginRepositoryUrl); connection.connect(); final InputStreamReader streamReader = new InputStreamReader(connection.getInputStream()); try { final JsonReader jsonReader = new JsonReader(streamReader); jsonReader.setLenient(true); final JsonElement jsonRootElement = new JsonParser().parse(jsonReader); final Map<String, Set<PluginId>> result = new HashMap<String, Set<PluginId>>(); for (JsonElement jsonElement : jsonRootElement.getAsJsonArray()) { final JsonObject jsonObject = jsonElement.getAsJsonObject(); final JsonElement ext = jsonObject.get("implementationName"); final String extension = StringUtil.unquoteString(ext.toString()); Set<PluginId> pluginIds = result.get(extension); if (pluginIds == null) { pluginIds = new HashSet<PluginId>(); result.put(extension, pluginIds); } pluginIds.add(PluginId.getId(StringUtil.unquoteString(jsonObject.get("pluginId").toString()))); } saveExtensions(result); return result; } finally { streamReader.close(); } } catch (IOException e) { LOG.info(e); return null; } }
From source file:com.inverseinnovations.VBulletinAPI.VBulletinAPI.java
License:Apache License
/** * Calls a method through the API.// w ww . ja v a2 s.c om * * @param methodname * the name of the method to call * @param params * the parameters as a map * @param sign * if the request should be signed or not. Generally, you want this to be true * @return the array returned by the server * @throws IOException * If the URL is wrong, or a connection is unable to be made for * whatever reason. */ private LinkedTreeMap<String, Object> callMethod(String methodname, Map<String, String> params, boolean sign) {// throws IOException{ LinkedTreeMap<String, Object> map = new LinkedTreeMap<String, Object>(); try { StringBuffer queryStringBuffer = new StringBuffer("api_m=" + methodname); SortedSet<String> keys = new TreeSet<String>(params.keySet()); for (String key : keys) {// ' " \ are unsafe String value = Functions.querySafeString(params.get(key)); queryStringBuffer.append("&" + key + "=" + URLEncoder.encode(value, "UTF-8")); } if (sign) { queryStringBuffer.append("&api_sig=" + Functions.MD5((queryStringBuffer.toString() + getAPIAccessToken() + apiClientID + getSecret() + getAPIkey())).toLowerCase()); if (DEBUG) { System.out.println("encoded: " + queryStringBuffer.toString()); } } queryStringBuffer.append("&api_c=" + apiClientID); queryStringBuffer.append("&api_s=" + getAPIAccessToken()); String queryString = queryStringBuffer.toString(); queryString = queryString.replace(" ", "%20"); URL apiUrl = new URL(apiURL + "?" + queryString); HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(10000); //set timeout to 10 seconds conn.setReadTimeout(10000);//set timeout to 10 seconds conn.setDoOutput(true); conn.setDoInput(true); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(queryString); InputStream is = null; try { is = conn.getInputStream(); } finally { if (is != null) { String json = Functions.inputStreamToString(is); //need to remove everything before { if (json.contains("{")) { json = json.substring(json.indexOf("{")); } Gson gson = new Gson(); JsonReader reader = new JsonReader(new StringReader(json)); reader.setLenient(true); try { map = gson.fromJson(reader, new TypeToken<Map<String, Object>>() { }.getType()); } catch (Exception e) {//TODO need to check what kind of errors... System.out.println(json); e.printStackTrace(); map = new LinkedTreeMap<String, Object>(); map.put("custom", new String("IllegalStateException")); } } } conn.disconnect(); } catch (java.net.SocketTimeoutException e) { map = new LinkedTreeMap<String, Object>(); map.put("custom", new String("SocketTimeoutException")); } catch (IOException e) { map = new LinkedTreeMap<String, Object>(); map.put("custom", new String("IOException")); } return map; }
From source file:com.junichi11.netbeans.php.enhancements.editor.completion.Parameters.java
License:Open Source License
private static void buildParameters() { Gson gson = new Gson(); for (Map.Entry<String, List<Parameter>> entry : PARAMETER_MAP.entrySet()) { String target = entry.getKey(); List<Parameter> list = entry.getValue(); list.clear();/*from ww w . ja v a2 s . c o m*/ String filePath = String.format("resources/%s.json", target); // NOI18N URL resource = Function.class.getResource(filePath); if (resource == null) { continue; } try { InputStream inputStream = resource.openStream(); JsonReader jsonReader = new JsonReader( new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))); // NOI18N try { Type type = new TypeToken<ArrayList<Parameter>>() { }.getType(); ArrayList<Parameter> parameters = gson.fromJson(jsonReader, type); list.addAll(parameters); } finally { inputStream.close(); jsonReader.close(); } } catch (IOException ex) { LOGGER.log(Level.WARNING, ex.getMessage()); } } }
From source file:com.jzsec.broker.okgo.callback.JsonConvert.java
License:Apache License
private T parseClass(Response response, Class<?> rawType) throws Exception { if (rawType == null) return null; ResponseBody body = response.body(); if (body == null) return null; JsonReader jsonReader = new JsonReader(body.charStream()); if (rawType == String.class) { //noinspection unchecked return (T) body.string(); } else if (rawType == JSONObject.class) { //noinspection unchecked return (T) new JSONObject(body.string()); } else if (rawType == JSONArray.class) { //noinspection unchecked return (T) new JSONArray(body.string()); } else {/*from w w w .j a v a 2 s . c o m*/ T t = Convert.fromJson(jsonReader, rawType); response.close(); return t; } }
From source file:com.jzsec.broker.okgo.callback.JsonConvert.java
License:Apache License
private T parseType(Response response, Type type) throws Exception { if (type == null) return null; ResponseBody body = response.body(); if (body == null) return null; JsonReader jsonReader = new JsonReader(body.charStream()); // ? new JsonCallback<?JavaBean>(this) T t = Convert.fromJson(jsonReader, type); response.close();/* w w w .ja v a 2s . c o m*/ return t; }
From source file:com.jzsec.broker.okgo.callback.JsonConvert.java
License:Apache License
private T parseParameterizedType(Response response, ParameterizedType type) throws Exception { if (type == null) return null; ResponseBody body = response.body(); if (body == null) return null; JsonReader jsonReader = new JsonReader(body.charStream()); Type rawType = type.getRawType(); // Type typeArgument = type.getActualTypeArguments()[0]; // ? if (rawType != DataResponse.class) { // ? new JsonCallback<BaseBean<JavaBean>>(this) T t = Convert.fromJson(jsonReader, type); response.close();// w w w . ja v a2 s .c o m return t; } else { if (typeArgument == Void.class) { // ? new JsonCallback<DataResponse<Void>>(this) SimpleResponse simpleResponse = Convert.fromJson(jsonReader, SimpleResponse.class); response.close(); //noinspection unchecked return (T) simpleResponse.toLzyResponse(); } else { // ? new JsonCallback<DataResponse<JavaBean>>(this) DataResponse lzyResponse = Convert.fromJson(jsonReader, type); response.close(); int code = lzyResponse.code; //0?? //???? if (code == 0) { //noinspection unchecked return (T) lzyResponse; } else if (code == 104) { throw new IllegalStateException("??"); } else if (code == 105) { throw new IllegalStateException("??"); } else { //??onError?? throw new IllegalStateException( "?" + code + "?" + lzyResponse.msg); } } } }
From source file:com.kyloth.serleena.synchronization.kylothcloud.inbound.CloudJSONInboundStreamParser.java
License:Open Source License
/** * Dato un InboundStream, lo legge e ne restituisce * una rappresentazione intermedia agnostica. * * @return Una collezione di IDataEntity che costituiscono una * rappresentazione agnostica dei dati forniti dal servizio. *///from w w w .j a v a 2 s . co m @Override public InboundRootEntity parse() { if (stream instanceof CloudJSONInboundStream) { Gson gson = new GsonBuilder() .registerTypeAdapter(InboundRootEntity.class, new InboundRootEntityDeserializer()).create(); InputStreamReader reader = new InputStreamReader(stream); JsonReader jsr = new JsonReader(reader); InboundRootEntity root = gson.fromJson(jsr, InboundRootEntity.class); return root; } else { throw new RuntimeException(); } }
From source file:com.lwx.ysnewdemo.callback.JsonConvert.java
License:Apache License
private T parseParameterizedType(Response response, ParameterizedType type) throws Exception { if (type == null) return null; ResponseBody body = response.body(); if (body == null) return null; JsonReader jsonReader = new JsonReader(body.charStream()); Type rawType = type.getRawType(); // Type typeArgument = type.getActualTypeArguments()[0]; // ? if (rawType != LwxResponse.class) { // ? new JsonCallback<BaseBean<JavaBean>>(this) T t = Convert.fromJson(jsonReader, type); response.close();/*from w w w .j a va 2 s . c o m*/ return t; } else { if (typeArgument == Void.class) { // ? new JsonCallback<LzyResponse<Void>>(this) SimpleResponse simpleResponse = Convert.fromJson(jsonReader, SimpleResponse.class); response.close(); //noinspection unchecked return (T) simpleResponse.toLwxResponse(); } else { // ? new JsonCallback<LzyResponse<JavaBean>>(this) LwxResponse lzyResponse = Convert.fromJson(jsonReader, type); response.close(); int code = lzyResponse.errcode; //0?? //???? if (code == 0) { //noinspection unchecked return (T) lzyResponse; } else if (code == 104) { throw new IllegalStateException("??"); } else if (code == 105) { throw new IllegalStateException("??"); } else { //??onError?? throw new IllegalStateException( "?" + code + "?" + lzyResponse.message); } } } }
From source file:com.lzy.demo.supercache.NewsCallback.java
License:Apache License
/** * ??? http://gank.io/api/data/Android/10/1 ?? * ,?????,??,?//from w ww .jav a2 s . com */ @Override public T convertResponse(Response response) throws Throwable { //???, Type genType = getClass().getGenericSuperclass(); Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); Type type = params[0]; if (!(type instanceof ParameterizedType)) throw new IllegalStateException("?"); JsonReader jsonReader = new JsonReader(response.body().charStream()); Type rawType = ((ParameterizedType) type).getRawType(); if (rawType == GankResponse.class) { GankResponse gankResponse = Convert.fromJson(jsonReader, type); if (!gankResponse.error) { response.close(); //noinspection unchecked return (T) gankResponse; } else { response.close(); throw new IllegalStateException("??"); } } else { response.close(); throw new IllegalStateException("?!"); } }