List of usage examples for com.google.gson JsonParser JsonParser
@Deprecated
public JsonParser()
From source file:com.ARA.DAO.CarDAO.java
/** This method is used to update a specific car with :id. * @param request/*from w w w . j ava 2 s . co m*/ * @param response * @return The car specified with :id. * @throws IOException */ public String updateCar(Request request, Response response) throws IOException { try { String id = request.params(":id"); JsonObject jsonObject = (JsonObject) new JsonParser().parse(request.body()); Car car = getDs().find(Car.class).field("id").equal(id).get(); if (jsonObject.has("make")) { String make = jsonObject.get("make").toString().replaceAll("\"", ""); car.setMake(make); } if (jsonObject.has("model")) { String model = jsonObject.get("model").toString().replaceAll("\"", ""); car.setModel(model); } if (jsonObject.has("license")) { String license = jsonObject.get("license").toString().replaceAll("\"", ""); car.setLicense(license); } if (jsonObject.has("carType")) { String carType = jsonObject.get("carType").toString().replaceAll("\"", ""); car.setCarType(carType); } if (jsonObject.has("maxPassengers")) { Integer maxPassengers = Integer.valueOf(jsonObject.get("maxPassengers").toString()); car.setMaxPassengers(maxPassengers); } if (jsonObject.has("color")) { String color = jsonObject.get("color").toString().replaceAll("\"", ""); car.setColor(color); } if (jsonObject.has("validRideTypes")) { Type listType = new TypeToken<ArrayList<String>>() { }.getType(); List<String> validRideTypes = new Gson().fromJson(jsonObject.get("validRideTypes").getAsJsonArray(), listType); car.setValidRideTypes(validRideTypes); } if (!car.isValidCar()) { response.status(400); return dataToJson.dataToJsonFormat(new Error(400, 2000, "Invalid data type")); } getDs().save(car); response.status(200); return dataToJson.dataToJsonFormat(car); } catch (Exception e) { response.status(500); return dataToJson.dataToJsonFormat(new Error(500, 5000, e.getMessage())); } }
From source file:com.ARA.DAO.DriverDAO.java
/** This method is used to create a driver. * @param request//from www.j av a2 s. c o m * @param response * @return The driver created. * @throws IOException */ public String createDriver(Request request, Response response) throws IOException { try { JsonObject jsonObject = (JsonObject) new JsonParser().parse(request.body()); String firstName = jsonObject.get("firstName").toString().replaceAll("\"", ""); String lastName = jsonObject.get("lastName").toString().replaceAll("\"", ""); String emailAddress = jsonObject.get("emailAddress").toString().replaceAll("\"", ""); String password = jsonObject.get("password").toString().replaceAll("\"", ""); String addressLine1 = jsonObject.get("addressLine1").toString().replaceAll("\"", ""); String addressLine2 = jsonObject.get("addressLine2").toString().replaceAll("\"", ""); String city = jsonObject.get("city").toString().replaceAll("\"", ""); String state = jsonObject.get("state").toString().replaceAll("\"", ""); String zip = jsonObject.get("zip").toString().replaceAll("\"", ""); String phoneNumber = jsonObject.get("phoneNumber").toString().replaceAll("\"", ""); String drivingLicense = jsonObject.get("drivingLicense").toString().replaceAll("\"", ""); String licensedState = jsonObject.get("licensedState").toString().replaceAll("\"", ""); if (password.length() > 20 || password.length() < 8) { response.status(400); return dataToJson.dataToJsonFormat(new Error(400, 2000, "Invalid data type")); } Driver newDriver = new Driver(firstName, lastName, emailAddress, password, addressLine1, addressLine2, city, state, zip, phoneNumber, drivingLicense, licensedState); // if (getDs().find(Driver.class).field("emailAddress").equal(emailAddress).get() != null // || getDs().find(Passenger.class).field("emailAddress").equal(emailAddress).get() != null) { // response.status(400); // return dataToJson.dataToJsonFormat(new Error(400, 3000, "email address already taken")); // } if (!newDriver.isValidDriver()) { response.status(400); return dataToJson.dataToJsonFormat(new Error(400, 2000, "Invalid data type")); } getDs().save(newDriver); response.status(200); return dataToJson.dataToJsonFormat(newDriver); } catch (Exception e) { response.status(500); return dataToJson.dataToJsonFormat(new Error(500, 5000, e.getMessage())); } }
From source file:com.ARA.DAO.DriverDAO.java
/** This method is used to update a specific driver with :id. * @param request/* ww w . j a v a2 s . c o m*/ * @param response * @return The driver specified with :id. * @throws IOException */ public String updateDriver(Request request, Response response) throws IOException { try { String id = request.params(":id"); JsonObject jsonObject = (JsonObject) new JsonParser().parse(request.body()); Driver driver = getDs().find(Driver.class).field("id").equal(id).get(); if (jsonObject.has("firstName")) { String firstName = jsonObject.get("firstName").toString().replaceAll("\"", ""); driver.setFirstName(firstName); } if (jsonObject.has("lastName")) { String lastName = jsonObject.get("lastName").toString().replaceAll("\"", ""); driver.setLastName(lastName); } if (jsonObject.has("emailAddress")) { String emailAddress = jsonObject.get("emailAddress").toString().replaceAll("\"", ""); if (getDs().find(Driver.class).field("emailAddress").equal(emailAddress).get() != null || getDs().find(Passenger.class).field("emailAddress").equal(emailAddress).get() != null) { response.status(400); return dataToJson.dataToJsonFormat(new Error(400, 3000, "email address already taken")); } driver.setEmailAddress(emailAddress); } if (jsonObject.has("password")) { String password = jsonObject.get("password").toString().replaceAll("\"", ""); if (password.length() > 20 || password.length() < 8) { response.status(400); return dataToJson.dataToJsonFormat(new Error(400, 2000, "Invalid data type")); } driver.setPassword(password); } if (jsonObject.has("addressLine1")) { String addressLine1 = jsonObject.get("addressLine1").toString().replaceAll("\"", ""); driver.setAddressLine1(addressLine1); } if (jsonObject.has("addressLine2")) { String addressLine2 = jsonObject.get("addressLine2").toString().replaceAll("\"", ""); driver.setAddressLine2(addressLine2); } if (jsonObject.has("city")) { String city = jsonObject.get("city").toString().replaceAll("\"", ""); driver.setCity(city); } if (jsonObject.has("state")) { String state = jsonObject.get("state").toString().replaceAll("\"", ""); driver.setState(state); } if (jsonObject.has("zip")) { String zip = jsonObject.get("zip").toString().replaceAll("\"", ""); driver.setZip(zip); } if (jsonObject.has("phoneNumber")) { String phoneNumber = jsonObject.get("phoneNumber").toString().replaceAll("\"", ""); driver.setPhoneNumber(phoneNumber); } if (jsonObject.has("drivingLicense")) { String drivingLicense = jsonObject.get("drivingLicense").toString().replaceAll("\"", ""); driver.setDrivingLicense(drivingLicense); } if (jsonObject.has("licensedState")) { String licensedState = jsonObject.get("licensedState").toString().replaceAll("\"", ""); driver.setLicensedState(licensedState); } if (!driver.isValidDriver()) { response.status(400); return dataToJson.dataToJsonFormat(new Error(400, 2000, "Invalid data type")); } getDs().save(driver); response.status(200); return dataToJson.dataToJsonFormat(driver); } catch (Exception e) { response.status(500); return dataToJson.dataToJsonFormat(new Error(500, 5000, e.getMessage())); } }
From source file:com.ARA.DAO.DriverDAO.java
/** This method is used to create cars of a specific driver with :id. * @param request/*from w w w .j a v a 2s.c o m*/ * @param response * @return The newe car created for a specific driver with :id. * @throws IOException */ public String createCar(Request request, Response response) throws IOException { try { String id = request.params(":id"); Driver driver = getDs().find(Driver.class).field("id").equal(id).get(); if (driver == null) { response.status(400); return dataToJson.dataToJsonFormat(new Error(400, 1003, "Given driver does not exist")); } // Create a new car JsonObject jsonObject = (JsonObject) new JsonParser().parse(request.body()); String make = jsonObject.get("make").toString().replaceAll("\"", ""); String model = jsonObject.get("model").toString().replaceAll("\"", ""); String license = jsonObject.get("license").toString().replaceAll("\"", ""); String carType = jsonObject.get("carType").toString().replaceAll("\"", ""); Integer maxPassengers = Integer.valueOf(jsonObject.get("maxPassengers").toString()); String color = jsonObject.get("color").toString().replaceAll("\"", ""); Type listType = new TypeToken<ArrayList<String>>() { }.getType(); List<String> validRideTypes = new Gson().fromJson(jsonObject.get("validRideTypes").getAsJsonArray(), listType); Car newCar = new Car(make, model, license, carType, maxPassengers, color, validRideTypes); newCar.setDrivers(id); if (!newCar.isValidCar()) { response.status(400); return dataToJson.dataToJsonFormat(new Error(400, 2000, "Invalid data type")); } // save to Cars getDs().save(newCar); // associate new car to current driver driver.addCar(newCar.getId()); getDs().save(driver); response.status(200); return dataToJson.dataToJsonFormat(newCar); } catch (Exception e) { response.status(500); return dataToJson.dataToJsonFormat(new Error(500, 5000, e.getMessage())); } }
From source file:com.ARA.DAO.DriverDAO.java
/** This method is used to create a ride and attach it to current driver. * @param request/*from w w w. j av a 2s .co m*/ * @param response * @return The ride created. * @throws IOException */ public String createRide(Request request, Response response) throws IOException { try { String id = request.params(":id"); Driver driver = getDs().find(Driver.class).field("id").equal(id).get(); if (driver == null) { response.status(400); return dataToJson.dataToJsonFormat(new Error(400, 1003, "Given driver does not exist")); } JsonObject jsonObject = (JsonObject) new JsonParser().parse(request.body()); String rideType = jsonObject.get("rideType").toString().replaceAll("\"", ""); Type listType = new TypeToken<ArrayList<Double>>() { }.getType(); List<Double> startPoint = new Gson().fromJson(jsonObject.get("startPoint").getAsJsonArray(), listType); List<Double> endPoint = new Gson().fromJson(jsonObject.get("endPoint").getAsJsonArray(), listType); LocalDateTime requestTime = LocalDateTime .parse(jsonObject.get("requestTime").toString().replaceAll("\"", ""), formatter); LocalDateTime pickupTime = LocalDateTime .parse(jsonObject.get("pickupTime").toString().replaceAll("\"", ""), formatter); LocalDateTime dropOffTime = LocalDateTime .parse(jsonObject.get("dropOffTime").toString().replaceAll("\"", ""), formatter); String status = jsonObject.get("status").toString().replaceAll("\"", ""); Double fare = Double.parseDouble(jsonObject.get("fare").toString().replaceAll("\"", "")); Ride newRide = new Ride(rideType, startPoint, endPoint, requestTime.format(formatter), pickupTime.format(formatter), dropOffTime.format(formatter), status, fare); String passengerId = jsonObject.get("passenger").toString().replaceAll("\"", ""); Passenger passenger = getDs().find(Passenger.class).field("id").equal(passengerId).get(); if (!newRide.isValidRide() || passenger == null) { response.status(400); return dataToJson.dataToJsonFormat(new Error(400, 2000, "Invalid data type")); } newRide.setDriver(id); newRide.setPassenger(passengerId); getDs().save(newRide); // associate new ride to current driver and passenger driver.addRide(newRide.getId()); getDs().save(driver); passenger.addRide(newRide.getId()); getDs().save(passenger); response.status(200); return dataToJson.dataToJsonFormat(newRide); } catch (Exception e) { response.status(500); return dataToJson.dataToJsonFormat(new Error(500, 5000, e.getMessage())); } }
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/*from w w w . j a v a 2 s .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//from w w w . java 2 s .c o m */ 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")); }//www.ja v a 2s . 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;/* w w w .j av a2s . com*/ 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/*from w w w .j av a 2 s . com*/ * @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; }