List of usage examples for com.google.gson JsonParser JsonParser
@Deprecated
public JsonParser()
From source file:au.com.addstar.SpigetUpdateAbstract.java
License:Open Source License
public void checkForUpdate(final UpdateCallback callback) { dispatch(new Runnable() { @Override//from www.ja v a 2s. c o m public void run() { try { HttpURLConnection connection = (HttpURLConnection) new URL( String.format(RESOURCE_INFO, resourceId, System.currentTimeMillis())).openConnection(); connection.setRequestProperty("User-Agent", getUserAgent()); JsonObject jsonObject = new JsonParser() .parse(new InputStreamReader(connection.getInputStream())).getAsJsonObject(); latestResourceInfo = new Gson().fromJson(jsonObject, ResourceInfo.class); URL url = new URL(String.format(RESOURCE_VERSION, resourceId)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", getUserAgent()); InputStreamReader reader = new InputStreamReader(connection.getInputStream()); jsonObject = new JsonParser().parse(reader).getAsJsonObject(); latestResourceInfo.latestVersion = new Gson().fromJson(jsonObject, ResourceVersion.class); if (isVersionNewer(currentVersion, latestResourceInfo.latestVersion.name)) { callback.updateAvailable(latestResourceInfo, "https://spigotmc.org/" + latestResourceInfo.file.url, !latestResourceInfo.external); } else { callback.upToDate(); } } catch (Exception e) { log.log(Level.WARNING, "Failed to get resource info from spiget.org", e); } } }); }
From source file:au.com.addstar.SpigetUpdater.java
License:Open Source License
@Override public void checkForUpdate(UpdateCallback callback) { dispatch(() -> {// w ww .ja v a 2 s. c o m HttpURLConnection connection; try { connection = (HttpURLConnection) new URL( String.format(RESOURCE_INFO, resourceId, System.currentTimeMillis())).openConnection(); connection.setRequestProperty("User-Agent", getUserAgent()); JsonObject jsonObject = new JsonParser().parse(new InputStreamReader(connection.getInputStream())) .getAsJsonObject(); latestResourceInfo = new Gson().fromJson(jsonObject, ResourceInfo.class); } catch (Exception e) { log.log(Level.WARNING, "Failed to get resource info from spiget.org:" + resourceId); latestResourceInfo = new ResourceInfo(); latestResourceInfo.latestVersion = new ResourceVersion(); latestResourceInfo.latestVersion.name = "MISSING"; latestResourceInfo.external = false; latestResourceInfo.premium = true; latestResourceInfo.id = resourceId; //callback.updateAvailable(info,"UNAVAILABLE", false); } if (!latestResourceInfo.premium) { try { URL url = new URL(String.format(RESOURCE_VERSION, resourceId)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", getUserAgent()); InputStreamReader reader = new InputStreamReader(connection.getInputStream()); JsonElement elem = new JsonParser().parse(reader); JsonObject json = elem.getAsJsonArray().get(0).getAsJsonObject(); latestResourceInfo.latestVersion = new Gson().fromJson(json, ResourceVersion.class); } catch (Exception e) { log.log(Level.WARNING, "Failed to get version info from spiget.org", e); } if (isVersionNewer(currentVersion, latestResourceInfo.latestVersion.name)) { callback.updateAvailable(latestResourceInfo, "https://spigotmc.org/" + latestResourceInfo.file.url, !latestResourceInfo.external); } else { callback.upToDate(); } } else { latestVer = Utilities.readURL("https://api.spigotmc.org/legacy/update.php?resource=" + resourceId); if (isVersionNewer(currentVersion, latestVer)) { if (latestResourceInfo.latestVersion == null) { latestResourceInfo.latestVersion = new ResourceVersion(); } latestResourceInfo.latestVersion.name = latestVer; latestResourceInfo.latestVersion.id = resourceId; callback.updateAvailable(latestResourceInfo, "https://spigotmc.org/" + latestResourceInfo.file.url, !latestResourceInfo.external); } else { callback.upToDate(); } } }); }
From source file:authorization.AuthAPIService.java
License:Open Source License
public AuthorizationResult sendPermissionRequest(boolean isWrite, String body, String subjectInfo, boolean isCertificate) { HttpURLConnection connection = null; try {/* ww w . java 2 s. c o m*/ //Create connection String writeURL = isWrite ? "true" : "false"; String finalURL = authServiceURI + "?ac=true&write=" + writeURL; logger.debug("Sending request. URI:" + finalURL); URL url = new URL(finalURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); if (!isCertificate) connection.setRequestProperty("Cookie", subjectInfo); connection.setUseCaches(false); connection.setDoOutput(true); connection.connect(); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(body); wr.close(); //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+ String line; while ((line = rd.readLine()) != null) { response.append(line); } rd.close(); logger.debug("RESPONSE:" + response.toString()); if (response.toString().equals("false")) { return new Unauthorized(new UserInfo(UserInfo.apply$default$1(), UserInfo.apply$default$2())); } else if (response.toString().equals("true")) { return new Authorized(new UserInfo(UserInfo.apply$default$1(), UserInfo.apply$default$2())); } JsonObject responseObject = new JsonParser().parse(response.toString()).getAsJsonObject();//response.toString(); //reuse variable String isAuthenticated = responseObject.get("result").getAsString(); String userName = responseObject.get("userID").getAsString(); return isAuthenticated.equalsIgnoreCase("ok") ? new Authorized(new UserInfo(UserInfo.apply$default$1(), scala.Option.apply(userName))) : new Unauthorized(new UserInfo(UserInfo.apply$default$1(), scala.Option.apply(userName))); } catch (Exception e) { logger.error("During http request", e); return new Unauthorized(new UserInfo(UserInfo.apply$default$1(), UserInfo.apply$default$2())); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:automatizacionrp.obtenerParametros.java
public static Parametros obtenerParametros() { log.info("Inicia proceso de obtencin de parmetros"); try {//from w ww .j ava 2 s . co m pdi = Servicio.queryapp("SELECT conf.json_config , pe.id_plan_ejecucion , " + "jo.job FROM public.config as conf, public.plan_ejecuciones as pe , " + "public.pasos_plan_ejecucion as ppe , public.jobs as jo WHERE conf.activo=true " + "and elemento='pdi' and pe.id_job=jo.id_job and pe.id_plan_ejecucion=ppe.id_plan_ejecucion " + "and ppe.status_plan='en espera' and ppe.activo=true and pe.timestamp_planificacion in " + "(SELECT min(pe.timestamp_planificacion) FROM public.config as conf, " + "public.plan_ejecuciones as pe , public.pasos_plan_ejecucion as ppe " + "WHERE conf.activo=true and elemento='pdi'and pe.id_plan_ejecucion=ppe.id_plan_ejecucion " + "and ppe.status_plan='en espera' and ppe.activo=true) and pe.timestamp_planificacion::timestamp <= now()::timestamp LIMIT 1;"); } catch (Exception e) { // TODO Auto-generated catch block log.error("Excepcin obteniendo parmetros pdi 1 :"); log.error(e); pdi = ""; } if (pdi.length() <= 2) { log.info("No existe planificacion pendiente"); return param; } aux = ""; pdi = pdi.substring(1, pdi.length() - 1); JsonParser parser = new JsonParser(); JsonElement elementObject; elementObject = parser.parse(pdi); tipo = elementObject.getAsJsonObject().get("job").getAsString(); id = elementObject.getAsJsonObject().get("id_plan_ejecucion").getAsString(); try { cluster = Servicio.queryapp("SELECT conf.json_config , pe.id_plan_ejecucion , " + "jo.job FROM public.config as conf, public.plan_ejecuciones as pe , " + "public.pasos_plan_ejecucion as ppe , public.jobs as jo WHERE conf.activo=true " + "and elemento='cluster' and pe.id_job=jo.id_job and pe.id_plan_ejecucion=ppe.id_plan_ejecucion " + "and ppe.status_plan='en espera' and ppe.activo=true and pe.timestamp_planificacion in " + "(SELECT min(pe.timestamp_planificacion) FROM public.config as conf, " + "public.plan_ejecuciones as pe , public.pasos_plan_ejecucion as ppe " + "WHERE conf.activo=true and elemento='cluster'and pe.id_plan_ejecucion=ppe.id_plan_ejecucion " + "and ppe.status_plan='en espera' and ppe.activo=true) and pe.timestamp_planificacion::timestamp <= now()::timestamp limit 1;"); bd_pys = Servicio.queryapp("SELECT conf.json_config , pe.id_plan_ejecucion , jo.job " + "FROM public.config as conf, public.plan_ejecuciones as pe , public.pasos_plan_ejecucion as ppe, " + "public.jobs as jo WHERE conf.activo=true and elemento='bd_pys' and pe.id_job=jo.id_job " + "and pe.id_plan_ejecucion=ppe.id_plan_ejecucion and ppe.status_plan='en espera' and ppe.activo=true " + "and pe.timestamp_planificacion in (SELECT min(pe.timestamp_planificacion) FROM public.config as conf," + "public.plan_ejecuciones as pe , public.pasos_plan_ejecucion as ppe WHERE conf.activo=true " + "and elemento='bd_pys'and pe.id_plan_ejecucion=ppe.id_plan_ejecucion and ppe.status_plan='en espera' and ppe.activo=true) " + "and pe.timestamp_planificacion::timestamp <= now()::timestamp limit 1;"); tienda = Servicio.queryapp( "SELECT t.tienda,t.host_bd_oracle,t.usuario_bd_oracle,t.pass_usuario_bd_oracle,t.bd_oracle\n" + " FROM public.plan_ejecuciones as pe,public.tiendas as t\n" + " where pe.id_plan_ejecucion=" + id + " and pe.id_tienda=t.id_tienda;"); } catch (Exception e) { log.error("Excepcin obteniendo parmetros cluster , bd_pys y tienda :"); log.error(e); tienda = ""; cluster = ""; bd_pys = ""; } bandera = true; if (pdi.length() > 2) { if (existeCampo.existeCampo(pdi, "valor")) { aux = elementObject.getAsJsonObject().get("valor").getAsString(); param.setTransformaciones(aux); } if (existeCampo.existeCampo(pdi, "timestamp_inicio_ejec")) { aux = elementObject.getAsJsonObject().get("timestamp_inicio_ejec").getAsString(); param.setTimestampIni(aux); } if (existeCampo.existeCampo(pdi, "timestamp_fin_ejec")) { aux = elementObject.getAsJsonObject().get("timestamp_fin_ejec").getAsString(); param.setTimestampFin(aux); } if (existeCampo.existeCampo(pdi, "id_plan_ejecucion")) { aux = elementObject.getAsJsonObject().get("id_plan_ejecucion").getAsString(); param.setIdplanEjec(aux); } pdi = elementObject.getAsJsonObject().get("json_config").getAsString(); elementObject = parser.parse(pdi); if (existeCampo.existeCampo(pdi, "directorio_pdi")) { aux = elementObject.getAsJsonObject().get("directorio_pdi").getAsString(); param.setDirPDI(aux); } if (existeCampo.existeCampo(pdi, "repositorio")) { aux = elementObject.getAsJsonObject().get("repositorio").getAsString(); param.setRepositorio(aux); } if (existeCampo.existeCampo(pdi, "usuario_repositorio")) { aux = elementObject.getAsJsonObject().get("usuario_repositorio").getAsString(); param.setUsuarioRepositorio(aux); } if (existeCampo.existeCampo(pdi, "password")) { aux = elementObject.getAsJsonObject().get("password").getAsString(); param.setPassusuarioRepo(aux); } if (existeCampo.existeCampo(pdi, "directorio_logs")) { aux = elementObject.getAsJsonObject().get("directorio_logs").getAsString(); param.setDirLogs(aux); } if (existeCampo.existeCampo(pdi, "nivel_logs")) { aux = elementObject.getAsJsonObject().get("nivel_logs").getAsString(); param.setNivelLogs(aux); } param.setNombreJob(tipo); if (bandera) { if (existeCampo.existeCampo(pdi, "directorio_job_ci")) { aux = elementObject.getAsJsonObject().get("directorio_job_ci").getAsString(); param.setDirEjecucion(aux); } } else { if (existeCampo.existeCampo(pdi, "directorio_job_m")) { aux = elementObject.getAsJsonObject().get("directorio_job_m").getAsString(); param.setDirEjecucion(aux); } } param.setJobModo("CARGA"); } else { log.warn("No se obtuvieron los valores del PDI"); } if (cluster.length() > 2) { aux = ""; cluster = cluster.substring(1, cluster.length() - 1); elementObject = parser.parse(cluster); cluster = elementObject.getAsJsonObject().get("json_config").getAsString(); if (existeCampo.existeCampo(cluster, "nodos")) { elementObject = parser.parse(cluster); cluster = elementObject.getAsJsonObject().get("nodos").toString(); cluster = cluster.substring(1, cluster.length() - 1); StringTokenizer st = new StringTokenizer(cluster, "}"); cluster = st.nextToken() + "}"; elementObject = parser.parse(cluster); if (existeCampo.existeCampo(cluster, "host")) { aux = elementObject.getAsJsonObject().get("host").getAsString(); param.setHostbdCassandra(aux); } if (existeCampo.existeCampo(cluster, "columnFamily")) { aux = elementObject.getAsJsonObject().get("columnFamily").getAsString(); param.setColumnFamily(aux); } if (existeCampo.existeCampo(cluster, "keyspace")) { aux = elementObject.getAsJsonObject().get("keyspace").getAsString(); param.setKeyspace(aux); } } } else { log.warn("No se obtuvieron los valores del cluster"); } if (bd_pys.length() > 2) { aux = ""; bd_pys = bd_pys.substring(1, bd_pys.length() - 1); elementObject = parser.parse(bd_pys); bd_pys = elementObject.getAsJsonObject().get("json_config").getAsString(); elementObject = parser.parse(bd_pys); if (existeCampo.existeCampo(bd_pys, "host")) { aux = elementObject.getAsJsonObject().get("host").getAsString(); param.setHostbdApp(aux); } if (existeCampo.existeCampo(bd_pys, "bd")) { aux = elementObject.getAsJsonObject().get("bd").getAsString(); param.setBdApp(aux); } if (existeCampo.existeCampo(bd_pys, "usuario")) { aux = elementObject.getAsJsonObject().get("usuario").getAsString(); param.setUsuariobdApp(aux); } if (existeCampo.existeCampo(bd_pys, "password")) { aux = elementObject.getAsJsonObject().get("password").getAsString(); param.setPassusuariobdApp(aux); } } else { log.warn("No se obtuvieron los valores de bd_pys"); } if (tienda.length() > 2) { aux = ""; tienda = tienda.substring(1, tienda.length() - 1); elementObject = parser.parse(tienda); if (existeCampo.existeCampo(tienda, "usuario_bd_oracle")) { aux = elementObject.getAsJsonObject().get("usuario_bd_oracle").getAsString(); param.setUsuariobdOracle(aux); } if (existeCampo.existeCampo(tienda, "pass_usuario_bd_oracle")) { aux = elementObject.getAsJsonObject().get("pass_usuario_bd_oracle").getAsString(); param.setPassusuariobdOracle(aux); } if (existeCampo.existeCampo(tienda, "host_bd_oracle")) { aux = elementObject.getAsJsonObject().get("host_bd_oracle").getAsString(); param.setHostbdOracle(aux); } if (existeCampo.existeCampo(tienda, "bd_oracle")) { aux = elementObject.getAsJsonObject().get("bd_oracle").getAsString(); param.setBdOracle(aux); } } else { log.warn("No se obtuvieron los valores de las tiendas"); } param.setTipo(tipo); return param; }
From source file:badminton.common.Util.JsonUtil.java
License:Open Source License
/** * json?list//from www . j av a 2 s .c om * * @param json * @param tClass * @param <T> * @return */ public static <T> List<T> toList(final String json, final Class<T> tClass) { final List<T> result = Lists.newArrayList(); if (StringUtils.isNotBlank(json)) { final JsonParser parser = new JsonParser(); final JsonArray jsonArray = parser.parse(json).getAsJsonArray(); jsonArray.forEach(node -> { final T cse = GSON.fromJson(node, tClass); result.add(cse); }); } return result; }
From source file:be.iminds.iot.dianne.dataset.DatasetConfigurator.java
License:Open Source License
private void parseDatasetConfiguration(File f) { try {// w w w. j av a2 s.c o m // parse any adapter configurations from JSON and apply config? JsonParser parser = new JsonParser(); JsonObject json = parser.parse(new JsonReader(new FileReader(f))).getAsJsonObject(); String name = json.get("name").getAsString(); if (name == null) return; // should have a name Hashtable<String, Object> props = new Hashtable<>(); String dir = f.getParentFile().getAbsolutePath(); props.put("dir", dir); String pid = null; if (json.has("adapter")) { String adapter = json.get("adapter").getAsString(); pid = adapter.contains(".") ? adapter : "be.iminds.iot.dianne.dataset.adapters." + adapter; // in case of adapter, set Dataset target: the dataset it is adapting String dataset = json.get("dataset").getAsString(); props.put("Dataset.target", "(name=" + dataset + ")"); } else if (json.has("type")) { String type = json.get("type").getAsString(); pid = "be.iminds.iot.dianne.dataset." + type; } else { // some hard coded pids if (name.startsWith("MNIST")) { pid = "be.iminds.iot.dianne.dataset.MNIST"; } else if (name.startsWith("CIFAR-100")) { pid = "be.iminds.iot.dianne.dataset.CIFAR100"; } else if (name.startsWith("CIFAR-10")) { pid = "be.iminds.iot.dianne.dataset.CIFAR10"; } else if (name.startsWith("STL-10")) { pid = "be.iminds.iot.dianne.dataset.STL10"; } else if (name.startsWith("SVHN")) { pid = "be.iminds.iot.dianne.dataset.SVHN"; } else if (name.equalsIgnoreCase("ImageNetValidation")) { pid = "be.iminds.iot.dianne.dataset.ImageNet.validation"; } else if (name.equalsIgnoreCase("ImageNetTraining")) { pid = "be.iminds.iot.dianne.dataset.ImageNet.training"; } else { pid = "be.iminds.iot.dianne.dataset." + name; } } // set an aiolos instance id using the dataset name to treat // equally named datasets as single instance in the network props.put("aiolos.instance.id", name); // combine all offered interfaces (might be SequenceDataset or ExperiencePool) props.put("aiolos.combine", "*"); // TODO use object conversion from JSON here? Configuration config = ca.createFactoryConfiguration(pid, null); json.entrySet().stream().forEach(e -> { if (e.getValue().isJsonArray()) { JsonArray a = e.getValue().getAsJsonArray(); String[] val = new String[a.size()]; for (int i = 0; i < val.length; i++) { val[i] = a.get(i).getAsString(); } props.put(e.getKey(), val); } else { props.put(e.getKey(), e.getValue().getAsString()); } }); config.update(props); } catch (Exception e) { System.err.println("Error parsing Dataset config file: " + f.getAbsolutePath()); e.printStackTrace(); } }
From source file:be.iminds.iot.dianne.jsonrpc.DianneRequestHandler.java
License:Open Source License
@Override public void handleRequest(JsonReader reader, JsonWriter writer) throws IOException { try {//from w w w . j a va 2 s.co m JsonParser parser = new JsonParser(); JsonObject request = parser.parse(reader).getAsJsonObject(); handleRequest(request, writer); } catch (JsonParseException e) { e.printStackTrace(); writeError(writer, null, -32700, "Parse error"); } catch (IllegalStateException e) { // this happens when the client closes the socket and reader returns null throw new IOException(e); } }
From source file:be.jacobsvanroy.LotterDraws.java
License:Open Source License
private List<Integer> mapDrawsToList(String result) { JsonObject root = (JsonObject) new JsonParser().parse(result); JsonArray jsonArray = root.get("d").getAsJsonArray(); List<Integer> draws = new ArrayList<>(); jsonArray.forEach(jsonEl -> draws.add(jsonEl.getAsJsonObject().get("DrawRef").getAsInt())); return draws; }
From source file:be.uantwerpen.dc.studyassistant.StudyAssistant.java
private ArrayList<Environment> getEnvironmentResources() { URL url = null;// ww w. jav a 2 s .c o m try { //url = new URL("https://192.168.2.33:8443/logs"); url = new URL("https://demo3407181.mockable.io/logs"); } catch (MalformedURLException ex) { Logger.getLogger(StudyAssistant.class.getName()).log(Level.SEVERE, null, ex); } String jstring = null; try { jstring = NetworkUtility.request(url, false, false); } catch (Exception ex) { Logger.getLogger(StudyAssistant.class.getName()).log(Level.SEVERE, null, ex); } Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create(); JsonParser parser = new JsonParser(); JsonArray jArray = parser.parse(jstring).getAsJsonArray(); ArrayList<Environment> lcs = new ArrayList<Environment>(); for (JsonElement obj : jArray) { Environment cse = gson.fromJson(obj, Environment.class); lcs.add(cse); } return lcs; }
From source file:be.uantwerpen.dc.studyassistant.StudyAssistant.java
private Environment getLastEnvironmentRecord() { URL url = null;/*from w ww . j a v a 2 s . c om*/ try { //url = new URL("https://192.168.2.33:8443/log"); url = new URL("https://demo3407181.mockable.io/log"); } catch (MalformedURLException ex) { Logger.getLogger(StudyAssistant.class.getName()).log(Level.SEVERE, null, ex); } String jstring = null; try { jstring = NetworkUtility.request(url, false, false); } catch (Exception ex) { Logger.getLogger(StudyAssistant.class.getName()).log(Level.SEVERE, null, ex); } Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create(); JsonParser parser = new JsonParser(); JsonArray jArray = parser.parse(jstring).getAsJsonArray(); ArrayList<Environment> lcs = new ArrayList<Environment>(); for (JsonElement obj : jArray) { Environment cse = gson.fromJson(obj, Environment.class); lcs.add(cse); } return lcs.get(0); }