List of usage examples for com.google.gson JsonParser parse
@Deprecated public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException
From source file:co.cask.cdap.passport.http.client.PassportClient.java
License:Apache License
/** * Get List of VPC for the apiKey./*from w w w . jav a2 s . c om*/ * @return List of VPC Names */ public List<String> getVPCList(String apiKey) { Preconditions.checkNotNull(apiKey, "ApiKey cannot be null"); List<String> vpcList = Lists.newArrayList(); try { String data = responseCache.getIfPresent(apiKey); if (data == null) { data = httpGet(API_BASE + "vpc/list", apiKey); if (data != null) { responseCache.put(apiKey, data); } } if (data != null) { JsonParser parser = new JsonParser(); JsonElement element = parser.parse(data); JsonArray jsonArray = element.getAsJsonArray(); for (JsonElement elements : jsonArray) { JsonObject vpc = elements.getAsJsonObject(); if (vpc.get("vpc_name") != null) { vpcList.add(vpc.get("vpc_name").getAsString()); } } } } catch (Exception e) { throw Throwables.propagate(e); } return vpcList; }
From source file:co.cask.cdap.security.tools.AccessTokenClient.java
License:Apache License
private String getAuthenticationServerAddress() throws IOException { HttpClient client = new DefaultHttpClient(); String baseUrl = "http"; // ssl settings if (useSsl) { baseUrl = "https"; if (disableCertCheck) { try { client = getHTTPClient(); } catch (Exception e) { errorDebugExit("Could not create HTTP Client with SSL enabled", e); System.exit(1);//w w w .j av a 2 s . c o m } } } HttpGet get = new HttpGet(String.format("%s://%s:%d", baseUrl, host, port)); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { System.out.println("Security is not enabled. No Access Token may be acquired"); System.exit(0); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteStreams.copy(response.getEntity().getContent(), bos); String responseBody = bos.toString("UTF-8"); bos.close(); JsonParser parser = new JsonParser(); JsonObject responseJson = (JsonObject) parser.parse(responseBody); JsonArray addresses = responseJson.get("auth_uri").getAsJsonArray(); ArrayList<String> list = new ArrayList<String>(); for (JsonElement e : addresses) { list.add(e.getAsString()); } return list.get(new Random().nextInt(list.size())); }
From source file:co.cask.cdap.security.tools.AccessTokenClient.java
License:Apache License
public String execute0(String[] args) { buildOptions();/* www . ja v a2 s . c o m*/ parseArguments(args); if (help) { return ""; } String baseUrl; try { baseUrl = getAuthenticationServerAddress(); } catch (IOException e) { errorDebugExit("Could not find Authentication service to connect to.", e); return null; } System.out.println(String.format("Authentication server address is: %s", baseUrl)); System.out.println(String.format("Authenticating as: %s", username)); HttpClient client = new DefaultHttpClient(); if (useSsl && disableCertCheck) { try { client = getHTTPClient(); } catch (Exception e) { errorDebugExit("Could not create HTTP Client with SSL enabled", e); return null; } } // construct the full URL and verify its well-formedness try { URI.create(baseUrl); } catch (IllegalArgumentException e) { System.err.println( "Invalid base URL '" + baseUrl + "'. Check the validity of --host or --port arguments."); return null; } HttpGet get = new HttpGet(baseUrl); String auth = Base64.encodeBase64String(String.format("%s:%s", username, password).getBytes()); auth = auth.replaceAll("(\r|\n)", ""); get.addHeader("Authorization", String.format("Basic %s", auth)); HttpResponse response; try { response = client.execute(get); } catch (IOException e) { errorDebugExit("Error sending HTTP request: " + e.getMessage(), e); return null; } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.out.println( "Authentication failed. Please ensure that the username and password provided are correct."); return null; } else { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteStreams.copy(response.getEntity().getContent(), bos); String responseBody = bos.toString("UTF-8"); bos.close(); JsonParser parser = new JsonParser(); JsonObject responseJson = (JsonObject) parser.parse(responseBody); String token = responseJson.get(ExternalAuthenticationServer.ResponseFields.ACCESS_TOKEN) .getAsString(); PrintWriter writer = new PrintWriter(filePath, "UTF-8"); writer.write(token); writer.close(); System.out.println("Your Access Token is:" + token); System.out.println("Access Token saved to file " + filePath); } catch (Exception e) { System.err.println("Could not parse response contents."); e.printStackTrace(System.err); return null; } } client.getConnectionManager().shutdown(); return "OK."; }
From source file:co.edu.uniandes.csw.miso4204.reward.service.RewardService.java
License:MIT License
@POST @Path("/save") public RewardDTO saveReward(@Context HttpHeaders httpHeaders, RewardDTO reward) { try {/*from w ww .j a v a 2 s . c om*/ String path = new File(".").getCanonicalPath(); } catch (Exception e) { } String token = httpHeaders.getRequestHeader("X_REST_USER").get(0); ClientConfig config = new ClientConfig(); Client client = ClientBuilder.newClient(config); String entity = client.target(URL_SERVICIO).path(reward.getBuyerId().toString()) .request(MediaType.APPLICATION_JSON).header("X_REST_USER", token).get(String.class); System.out.println(entity); JsonParser parser = new JsonParser(); JsonObject object = (JsonObject) parser.parse(entity); JsonElement column = object.get("id"); String id = column.getAsString(); System.out.println(id); reward.setBuyerId(Long.parseLong(id)); createReward(reward); return reward; }
From source file:co.mitro.keyczar.KeyczarJsonReader.java
License:Open Source License
public KeyczarJsonReader(String json) { JsonParser parser = new JsonParser(); parsed = parser.parse(json).getAsJsonObject(); }
From source file:cocacola.cocacola.controller.MemberController.java
License:Apache License
public void gerarVideos() throws Exception { CocaCola coca = new CocaCola(); Calendar cal = Calendar.getInstance(); Date date = cal.getTime();//w w w . j av a 2 s. co m CocaCola c = new CocaCola(cal, "asdasdasdasd", "url1", "Paul", Status.RECEBIDA); ClientRequest request = new ClientRequest( "http://festivaldomeujeito.com.br/server/index.php/festival/user/format/json"); ClientResponse<String> response = request.get(String.class); try { Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonArray jArray = parser.parse(response.getEntity()).getAsJsonArray(); for (JsonElement obj : jArray) { JsonElement jelem = gson.fromJson(obj, JsonElement.class); JsonObject jobj = jelem.getAsJsonObject(); System.out.println(jobj.get("mon_pergunta_1")); ClasseJsonCoca cocaJson = gson.fromJson(obj, ClasseJsonCoca.class); cocaJson.setMonPergunta1("decarrao"); cocaJson.setUsuGender("female"); c.setJsonCoca(cocaJson); VideoManager vm = new VideoManager(); vm.gerarVideos(c); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:cocacola.cocacola.controller.MemberController.java
License:Apache License
public void testarRestCoca() { try {/* w w w. ja v a 2 s. c o m*/ Calendar cal = Calendar.getInstance(); Date date = cal.getTime(); CocaCola c = new CocaCola(cal, "asdasdasdasd", "url1", "Paul", Status.RECEBIDA); c.setCor(cocaCola.getCor()); c.setNome(cocaCola.getNome()); c.setSexo(cocaCola.getSexo()); System.out.println(cocaCola.toString()); VideoGerado vg = new VideoGerado(); VideoManager vm = new VideoManager(); ClientRequest request = new ClientRequest( "http://festivaldomeujeito.com.br/server/index.php/festival/user/format/json"); ClientResponse<String> response = request.get(String.class); Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonArray jArray = parser.parse(response.getEntity()).getAsJsonArray(); for (JsonElement obj : jArray) { System.out.println(obj.toString()); JsonElement jelem = gson.fromJson(obj, JsonElement.class); JsonObject jobj = jelem.getAsJsonObject(); System.out.println(jobj.get("mon_pergunta_1")); ClasseJsonCoca coca = gson.fromJson(obj, ClasseJsonCoca.class); System.out.println(coca.getMonPergunta1()); c.setJsonCoca(coca); vg.setCocaCola(c); System.out.println(vg.getUrlCena2()); System.out.println(vg.getUrlCena3()); System.out.println(vg.getUrlCena4()); System.out.println(vg.getUrlCena5()); System.out.println(vg.getUrlCena6()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.adkdevelopment.jokesactivity.JokesActivityFragment.java
License:Open Source License
/** * Method to parse JSON string and return String[] with a link and a title * * @param jokesJson JSON string with info about comics, link, etc. * @return String[] with a link and a title *///w ww .ja va2 s . com public static String[] getJokesInfo(String jokesJson) { String[] reviews = new String[2]; JsonParser parser = new JsonParser(); JsonElement element = parser.parse(jokesJson); if (element.isJsonObject()) { JsonObject results = element.getAsJsonObject(); JsonElement title = results.getAsJsonPrimitive("title"); JsonElement linkToImage = results.getAsJsonPrimitive("img"); reviews[0] = title.getAsString(); reviews[1] = linkToImage.getAsString(); return reviews; } return null; }
From source file:com.adobe.acs.commons.adobeio.service.impl.EndpointServiceImpl.java
License:Apache License
private JsonObject responseAsJson(@NotNull final HttpResponse response) throws IOException { String result = IOUtils.toString(response.getEntity().getContent(), CharEncoding.UTF_8); JsonParser parser = new JsonParser(); JsonObject resultJson = new JsonObject(); try {//w w w . j a v a2s .co m LOGGER.debug("Call result = {}", result); resultJson = parser.parse(result).getAsJsonObject(); } catch (Exception e) { resultJson.addProperty(RESULT_ERROR, result); } LOGGER.debug("JSON result from Service: {}", resultJson); return resultJson; }
From source file:com.adobe.acs.commons.adobeio.service.impl.IntegrationServiceImpl.java
License:Apache License
private String fetchAccessToken() { String token = StringUtils.EMPTY; try (CloseableHttpClient client = helper.getHttpClient(getTimeoutinMilliSeconds())) { HttpPost post = new HttpPost(jwtServiceConfig.endpoint()); post.addHeader(CACHE_CONTRL, NO_CACHE); post.addHeader(CONTENT_TYPE, CONTENT_TYPE_URL_ENCODED); List<BasicNameValuePair> params = Lists.newArrayList(); params.add(new BasicNameValuePair(CLIENT_ID, jwtServiceConfig.clientId())); params.add(new BasicNameValuePair(CLIENT_SECRET, jwtServiceConfig.clientSecret())); params.add(new BasicNameValuePair(JWT_TOKEN, getJwtToken())); post.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() != 200) { LOGGER.info("response code {} ", response.getStatusLine().getStatusCode()); }/*from w w w. jav a 2 s . c o m*/ String result = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); LOGGER.info("JSON Response : {}", result); JsonParser parser = new JsonParser(); JsonObject json = parser.parse(result).getAsJsonObject(); if (json.has(JSON_ACCESS_TOKEN)) { token = json.get(JSON_ACCESS_TOKEN).getAsString(); } else { LOGGER.error("JSON does not contain an access_token"); } } catch (Exception e) { LOGGER.error(e.getMessage()); } LOGGER.info("JWT Access Token : {}", token); return token; }