List of usage examples for com.google.gson JsonParser parse
@Deprecated public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException
From source file:com.apothesource.pillfill.service.drug.impl.DefaultDrugServiceImpl.java
License:Open Source License
/** * <a href="http://rxnav.nlm.nih.gov/RxNormAPIs.html#">NIH Service</a>: Get avaliable RxNorm IDs associated with an 11 digit National Drug Code (NDC). * * @param ndc The 11-digit NDC without dashes or spaces * @return A list of RxNorm IDs associated with this NDC (should normally return 0 or 1) */// w w w .ja v a2s . c o m @Override public Observable<String> getRxNormIdForDrugNdc(String ndc) { return subscribeIoObserveImmediate(subscriber -> { String urlStr = String.format(URL_RXNORM_BRAND_NAME_BY_NDC, ndc); try { String responseStr = PFNetworkManager.doPinnedGetForUrl(urlStr); JsonParser parser = new JsonParser(); JsonObject response = parser.parse(responseStr).getAsJsonObject().get("idGroup").getAsJsonObject(); if (response.has("rxnormId")) { JsonArray array = response.getAsJsonArray("rxnormId"); for (JsonElement e : array) { subscriber.onNext(e.getAsString()); } subscriber.onCompleted(); } else { Timber.e("No rxnormIds found for NDC: %s", ndc); subscriber.onError(new RuntimeException("Could not find NDC->RxNorm for NDC.")); } } catch (IOException e) { e.printStackTrace(); } }); }
From source file:com.apothesource.pillfill.service.drug.impl.DefaultDrugServiceImpl.java
License:Open Source License
/** * An experimental method to enable a list of generic concepts to be retrieved without a method-specific implementation. Use with caution. * @param type The {@link Type} of class to be returned. Must be mapped in the <code>/src/main/resources/PFResourceMapping.properties</code> file or a RuntimeException will occur. * @param ids The list of IDs to retrieve * @return An observable that emits instances of the provided type based on the requested IDs *///from w w w . j a v a2 s . c o m protected <T> Observable<T> getConceptList(Class<T> type, String... ids) { if (ids == null || ids.length == 0) return Observable.empty(); String urlTemplate = getUrlForType(type); String url = String.format(urlTemplate, Joiner.on(",").join(ids)); String typeName = type.getSimpleName(); Timber.d("Requesting %s list from URL: %s", typeName, url); return subscribeIoObserveImmediate(subscriber -> { try { String listJson = PFNetworkManager.doPinnedGetForUrl(url); JsonParser parser = new JsonParser(); JsonArray array = parser.parse(listJson).getAsJsonArray(); for (JsonElement elem : array) { subscriber.onNext(gson.fromJson(elem, type)); } subscriber.onCompleted(); } catch (IOException e) { Timber.e("Error retrieving %s list with ids %s - %s", typeName, ids, e.getMessage()); subscriber.onError(e); } }); }
From source file:com.appunity.ant.Utils.java
License:Apache License
protected static ProjectProfile getProfile(Task task, String profilePath) { ProjectProfile profile = null;/* w w w .j a va2s .c o m*/ try { Gson gson = new Gson(); JsonParser parser = new JsonParser(); InputStreamReader reader = new InputStreamReader( new FileInputStream(obtainValidPath(task, profilePath, "project.profile")), "UTF-8"); JsonReader jsonReader = new JsonReader(reader); JsonObject asJsonObject = parser.parse(jsonReader).getAsJsonObject(); profile = gson.fromJson(asJsonObject.get("project"), ProjectProfile.class); } catch (FileNotFoundException ex) { Logger.getLogger(InitProjectTask.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(InitProjectTask.class.getName()).log(Level.SEVERE, null, ex); } catch (JsonIOException ex) { Logger.getLogger(InitProjectTask.class.getName()).log(Level.SEVERE, null, ex); } catch (JsonSyntaxException ex) { Logger.getLogger(InitProjectTask.class.getName()).log(Level.SEVERE, null, ex); } return profile; }
From source file:com.arangodb.BaseArangoDriver.java
License:Apache License
/** * Checks the Http response for database or server errors * @param res the response of the database * @return The Http status code/*www. j av a2s . c o m*/ * @throws ArangoException if any error happened */ private int checkServerErrors(HttpResponseEntity res) throws ArangoException { int statusCode = res.getStatusCode(); if (statusCode >= 400) { // always throws ArangoException DefaultEntity defaultEntity = new DefaultEntity(); if (res.getText() != null && !res.getText().equalsIgnoreCase("") && statusCode != 500) { JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(res.getText()); JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonElement errorMessage = jsonObject.get("errorMessage"); defaultEntity.setErrorMessage(errorMessage.getAsString()); JsonElement errorNumber = jsonObject.get("errorNum"); defaultEntity.setErrorNumber(errorNumber.getAsInt()); } else { String statusPhrase = ""; switch (statusCode) { case 400: statusPhrase = "Bad Request"; break; case 401: statusPhrase = "Unauthorized"; break; case 403: statusPhrase = "Forbidden"; break; case 404: statusPhrase = "Not Found"; break; case 405: statusPhrase = "Method Not Allowed"; break; case 406: statusPhrase = "Not Acceptable"; break; case 407: statusPhrase = "Proxy Authentication Required"; break; case 408: statusPhrase = "Request Time-out"; break; case 409: statusPhrase = "Conflict"; break; case 500: statusPhrase = "Internal Server Error"; break; default: statusPhrase = "unknown error"; break; } defaultEntity.setErrorMessage(statusPhrase); if (statusCode == 500) { defaultEntity.setErrorMessage(statusPhrase + ": " + res.getText()); } } defaultEntity.setCode(statusCode); defaultEntity.setStatusCode(statusCode); defaultEntity.setError(true); ArangoException arangoException = new ArangoException(defaultEntity); arangoException.setCode(statusCode); throw arangoException; } return statusCode; }
From source file:com.arangodb.BaseArangoDriver.java
License:Apache License
/** * Gets the raw JSON string with results, from the Http response * @param res the response of the database * @return A valid JSON string with the results * @throws ArangoException// w ww . j ava 2 s . c om */ protected String getJSONResponseText(HttpResponseEntity res) throws ArangoException { if (res == null) { return null; } checkServerErrors(res); // no errors, return results as a JSON string JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(res.getText()); JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonElement result = jsonObject.get("result"); return result.toString(); }
From source file:com.arangodb.entity.EntityFactory.java
License:Apache License
public static <T> String toJsonString(T obj, boolean includeNullValue) { if (obj != null && obj.getClass().equals(BaseDocument.class)) { String tmp = includeNullValue ? gsonNull.toJson(obj) : gson.toJson(obj); JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(tmp); JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonObject result = jsonObject.getAsJsonObject("properties"); JsonElement keyObject = jsonObject.get("_key"); if (keyObject != null && keyObject.getClass() != JsonNull.class) { result.add("_key", jsonObject.get("_key")); }/*from ww w . j a va2s .c o m*/ JsonElement handleObject = jsonObject.get("_id"); if (handleObject != null && handleObject.getClass() != JsonNull.class) { result.add("_id", jsonObject.get("_id")); } // JsonElement revisionValue = jsonObject.get("documentRevision"); // result.add("_rev", revisionValue); return result.toString(); } return includeNullValue ? gsonNull.toJson(obj) : gson.toJson(obj); }
From source file:com.ardhi.businessgame.services.BusinessGameService.java
public String loadInstallmentDetails(HttpServletRequest req) { String val = "0"; ArrayList<InstallmentEmployee> employees = new ArrayList<InstallmentEmployee>(); ArrayList<InstallmentEquipment> equipments = new ArrayList<InstallmentEquipment>(); ArrayList<String> data = new ArrayList<String>(); SqlRowSet srs1 = db.getJdbc().queryForRowSet( "select installment_employee.id,employee,quality,operational,draw from installment_employee,list_employee,desc_employee,info_employee where installment='" + req.getParameter("id") + "' and installment_employee.id=list_employee.id and list_employee.[desc]=desc_employee.id and name=employee"), srs2;/*from ww w. ja va 2 s . c om*/ while (srs1.next()) { employees.add(new InstallmentEmployee(srs1.getString("id"), srs1.getString("employee"), srs1.getInt("quality"), srs1.getDouble("operational"), srs1.getString("draw"))); } srs1 = db.getJdbc().queryForRowSet( "select installment_equipment.id,equipment,quality,durability,size,operational,draw from installment_equipment,desc_equipment,list_equipment,info_equipment where installment='" + req.getParameter("id") + "' and installment_equipment.id=list_equipment.id and list_equipment.[desc]=desc_equipment.id and name=equipment"); while (srs1.next()) { equipments.add(new InstallmentEquipment(srs1.getString("id"), srs1.getString("equipment"), srs1.getInt("quality"), srs1.getDouble("durability"), srs1.getDouble("size"), srs1.getDouble("operational"), srs1.getString("draw"))); } ArrayList<String> installmentIOdata = calculateInstallmentAndIOByIdInstallment(req.getParameter("id")); data.add(installmentIOdata.get(0)); data.add(installmentIOdata.get(1)); data.add(installmentIOdata.get(2)); data.add(installmentIOdata.get(3)); data.add(installmentIOdata.get(4)); data.add(installmentIOdata.get(5)); data.add(installmentIOdata.get(6)); data.add(installmentIOdata.get(7)); data.add(gson.toJson(equipments)); data.add(gson.toJson(employees)); if (installmentIOdata.get(0).equals("Petrol Power Plant")) { srs1 = db.getJdbc().queryForRowSet( "select subscription,tariff from installment where id='" + req.getParameter("id") + "'"); double tariff, subscription; if (srs1.next()) { subscription = srs1.getDouble("subscription"); tariff = srs1.getDouble("tariff"); } else return "0"; srs1 = db.getJdbc() .queryForRowSet("select id,type,[user],planned_supply from installment where supply='" + req.getParameter("id") + "'"); ArrayList<String> types = new ArrayList<String>(), users = new ArrayList<String>(), idSupplies = new ArrayList<String>(); ArrayList<Double> supplies = new ArrayList<Double>(); while (srs1.next()) { idSupplies.add(srs1.getString("id")); types.add(srs1.getString("type")); users.add(srs1.getString("user")); supplies.add(srs1.getDouble("planned_supply")); } data.add(gson.toJson(subscription)); data.add(gson.toJson(tariff)); data.add(gson.toJson(types)); data.add(gson.toJson(users)); data.add(gson.toJson(supplies)); data.add(gson.toJson(idSupplies)); val = gson.toJson(data); types = null; users = null; supplies = null; idSupplies = null; } else { srs1 = db.getJdbc().queryForRowSet( "select supply,planned_supply from installment where id='" + req.getParameter("id") + "'"); ArrayList<String> idSupplies = new ArrayList<String>(), users = new ArrayList<String>(), tmpSupplies; ArrayList<Double> subscriptions = new ArrayList<Double>(), tariffs = new ArrayList<Double>(), availables = new ArrayList<Double>(); JsonParser parser = new JsonParser(); JsonArray array1; int tmp; double available, currentKwh; String currentSupply; if (srs1.next()) { currentKwh = srs1.getDouble("planned_supply"); currentSupply = srs1.getString("supply"); } else return "0"; srs1 = db.getJdbc().queryForRowSet( "select id,[user],subscription,tariff from installment where type='Petrol Power Plant'"); while (srs1.next()) { tmp = 0; tmpSupplies = calculateInstallmentAndIOByIdInstallment(srs1.getString("id")); array1 = parser.parse(tmpSupplies.get(5)).getAsJsonArray(); for (int i = 0; i < array1.size(); i++) { if ((new Gson().fromJson(array1.get(i), String.class)).equals("Energy")) { tmp = i; break; } } array1 = parser.parse(tmpSupplies.get(6)).getAsJsonArray(); available = new Gson().fromJson(array1.get(tmp), Double.class); srs2 = db.getJdbc().queryForRowSet( "select planned_supply from installment where supply='" + srs1.getString("id") + "'"); while (srs2.next()) available -= srs2.getDouble("planned_supply"); idSupplies.add(srs1.getString("id")); users.add(srs1.getString("user")); subscriptions.add(srs1.getDouble("subscription")); tariffs.add(srs1.getDouble("tariff")); availables.add(new BigDecimal(Double.valueOf(available)).setScale(2, BigDecimal.ROUND_HALF_EVEN) .doubleValue()); tmpSupplies = null; } data.add(gson.toJson(idSupplies)); data.add(gson.toJson(users)); data.add(gson.toJson(subscriptions)); data.add(gson.toJson(tariffs)); data.add(gson.toJson(availables)); data.add(gson.toJson(currentKwh)); data.add(gson.toJson(currentSupply)); val = gson.toJson(data); idSupplies = null; users = null; tariffs = null; availables = null; currentSupply = null; } installmentIOdata = null; employees = null; equipments = null; data = null; srs1 = null; srs2 = null; gc(); return val; }
From source file:com.arvato.thoroughly.util.RestTemplateUtil.java
License:Open Source License
/** * @param url/* w ww . j av a 2s . c o m*/ * @param content * It must be json format data * @return Results <br> * code : http status <br> * responseBody : http response body */ public JsonObject post(String url, String content) throws TmallAppException { LOGGER.trace("Post url:" + url); HttpEntity<String> request = new HttpEntity<String>(content, createHeaders()); ResponseEntity<String> entity = null; try { entity = restTemplate.postForEntity(url, request, String.class); } catch (RestClientException e) { LOGGER.error(e.getMessage(), e); throw new TmallAppException(ResponseCode.CONNECTION_REFUSED.getCode(), "Connection refused:unknown URL content:" + url); } LOGGER.trace("Post data :" + content); LOGGER.trace("Response status:" + entity.getStatusCode().value()); LOGGER.trace("Response body:" + entity.getBody()); JsonObject responseObject = new JsonObject(); if (entity.getStatusCode().value() == 200) { String responseBody = entity.getBody(); JsonParser parser = new JsonParser(); responseObject = parser.parse(responseBody).getAsJsonObject(); } else { responseObject.addProperty("code", entity.getStatusCode().toString()); responseObject.addProperty("msg", entity.getBody()); } return responseObject; }
From source file:com.asakusafw.yaess.jobqueue.client.HttpJobClient.java
License:Apache License
private <T> T extractContent(Class<T> type, HttpUriRequest request, HttpResponse response) throws IOException { assert request != null; assert response != null; HttpEntity entity = response.getEntity(); if (entity == null) { throw new IOException(MessageFormat.format("Response message was invalid (empty): {0} ({1})", request.getURI(), response.getStatusLine())); }//from ww w.j ava 2 s . co m try (Reader reader = new BufferedReader(new InputStreamReader(entity.getContent(), ENCODING));) { JsonParser parser = new JsonParser(); JsonElement element = parser.parse(reader); if ((element instanceof JsonObject) == false) { throw new IOException( MessageFormat.format("Response message was not a valid json object: {0} ({1})", request.getURI(), response.getStatusLine())); } if (LOG.isTraceEnabled()) { LOG.trace("response: {}", new Object[] { element }); } return GSON_BUILDER.create().fromJson(element, type); } catch (RuntimeException e) { throw new IOException(MessageFormat.format("Response message was invalid (not JSON): {0} ({1})", request.getURI(), response.getStatusLine()), e); } }
From source file:com.auction.servlet.RequestServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww. ja v a 2 s.c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.addHeader("Access-Control-Allow-Origin", "*"); Gson gson = new GsonBuilder().create(); PrintWriter out = response.getWriter(); try { request.setCharacterEncoding("UTF-8"); JsonParser parser = new JsonParser(); //JsonObject jsonObject = (JsonObject)parser.parse(request.getReader()); JsonElement packetHeaderText = parser.parse(request.getParameter("packetHeader")); String packetBody = request.getParameter("packetBody"); if (packetHeaderText == null) { ClientResponse cr = new ClientFailedResponse(); cr.setMessage(ClientMessages.PACKET_HEADER_MISSING); out.println(gson.toJson(cr)); return; } /* TODO output your page here. You may use following sample code. */ IPacketHeader packetHeader = gson.fromJson(packetHeaderText, PacketHeaderImpl.class); IPacket packet = new RequestPacketImpl(packetHeader, packetBody, request.getRemoteAddr(), request.getRemotePort()); ClientResponse clientResponse = (ClientResponse) ClientRequestHandler.getInstance() .executeRequest(packet); if (clientResponse != null) { out.println(gson.toJson(clientResponse)); } else { ClientResponse cr = new ClientFailedResponse(); cr.setMessage(ClientMessages.REQUEST_DID_NOT_PROCESSED_SUCCESSFULLY); out.println(gson.toJson(cr)); } } catch (Throwable ex) { ex.printStackTrace(); ClientResponse cr = new ClientFailedResponse(); cr.setMessage(ClientMessages.REQUEST_DID_NOT_PROCESSED_SUCCESSFULLY); out.println(gson.toJson(cr)); } }