List of usage examples for com.google.gson JsonElement getAsString
public String getAsString()
From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java
License:Open Source License
/** * Sets the json element at the specified jpath. * * @param source the source//from w w w. ja v a 2 s .c om * @param jpath the fully qualified json path to the field required. eg set({'a': {'b': {'c': [1, * 2, 3, 4]}}}, ["a", "b" "c", 1, 5]) is {'a': {'b': {'c': [1, 5, 3, 4]}}}. Array indexes need * to be specified as numerals. Strings are always presumed to be field names. * @param value the value * @return the json element */ public JsonElement set(JsonElement source, JsonArray jpath, JsonElement value) { JsonElement result = JsonNull.INSTANCE; if (isNotNull(jpath)) { result = source; JsonElement field = result; if (jpath.size() > 0) { JsonElement previousPath = null; JsonElement currentPath = null; Iterator<JsonElement> iterator = jpath.iterator(); if (iterator.hasNext()) { previousPath = iterator.next(); } while (iterator.hasNext()) { currentPath = iterator.next(); // get the field field = getRepleteField(field, previousPath, currentPath); result = updateResult(result, field); field = isNumber(previousPath) ? field.getAsJsonArray().get(previousPath.getAsInt()) : field.getAsJsonObject().get(previousPath.getAsString()); previousPath = currentPath; } field = setField(field, previousPath, value); } } return result; }
From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java
License:Open Source License
/** * Returns the source json as a string if possible. Else returns the default string * * @param source the source json element * @param defaultStr the default string//from w ww . j a v a 2 s. c o m * @return the source json as a string */ public String asString(JsonElement source, String defaultStr) { return isString(source) ? source.getAsString() : defaultStr; }
From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java
License:Open Source License
/** * Sets the field.//from w w w .j a v a 2 s . c o m * * @param field the field * @param path the path * @param value the value * @return the json element */ protected JsonElement setField(JsonElement field, JsonElement path, JsonElement value) { if (isNumber(path)) { JsonArray jArray = asJsonArray(field.getAsJsonArray(), new JsonArray()); int index = path.getAsInt(); repleteArray(jArray, index, JsonNull.class); jArray.set(index, value); field = jArray; } else { JsonObject jObject = asJsonObject(field, new JsonObject()); jObject.add(path.getAsString(), value); field = jObject; } return field; }
From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java
License:Open Source License
/** * Gets the replete field.//from ww w. ja va2s .co m * * @param field the field * @param path the path * @param nextPath the next path * @return the replete field */ protected JsonElement getRepleteField(JsonElement field, JsonElement path, JsonElement nextPath) { if (isNumber(path)) { Integer index = path.getAsInt(); if (!isArray(field)) { field = new JsonArray(); } JsonArray fArray = repleteArray(field.getAsJsonArray(), index, isNumber(nextPath) ? JsonArray.class : JsonObject.class); field = fArray; } else { String fieldName = path.getAsString(); if (!isObject(field)) { field = new JsonObject(); } JsonObject fJson = repleteJson(field.getAsJsonObject(), fieldName, isNumber(nextPath) ? JsonArray.class : JsonObject.class); field = fJson; } return field; }
From source file:com.bccriskadvisory.link.rest.gson.ZonedDateTimeAdapter.java
License:Apache License
@Override public ZonedDateTime deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException { String date = element.getAsString(); try {/* w ww. ja v a 2s. c o m*/ TemporalAccessor parse = JSON_PATTERN.parse(date); return ZonedDateTime.from(parse); } catch (DateTimeParseException e) { getLog().error("Unable to parse date due to:", e); return null; } }
From source file:com.bekwam.resignator.model.ConfigurationJSONAdapter.java
License:Apache License
@Override public Configuration deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { if (logger.isDebugEnabled()) { logger.debug("[DESERIALIZE]"); }// w w w. j a v a2 s.c om JsonObject obj = (JsonObject) jsonElement; JsonElement apElement = obj.get("activeProfile"); String ap = ""; if (apElement != null) { ap = apElement.getAsString(); } JsonElement jdkElem = obj.get("jdkHome"); String jdkHome = ""; if (jdkElem != null) { jdkHome = jdkElem.getAsString(); } JsonElement hpElem = obj.get("hashedPassword"); String hp = ""; if (hpElem != null) { hp = hpElem.getAsString(); } JsonElement ludElem = obj.get("lastUpdatedDate"); String lud = ""; LocalDateTime lastUpdatedDate = null; if (ludElem != null) { lud = ludElem.getAsString(); if (StringUtils.isNotEmpty(lud)) { lastUpdatedDate = LocalDateTime.parse(lud, DateTimeFormatter.ISO_LOCAL_DATE_TIME); } } JsonArray recentProfiles = obj.getAsJsonArray("recentProfiles"); JsonArray profiles = obj.getAsJsonArray("profiles"); if (logger.isDebugEnabled()) { logger.debug("[DESERIALIZE] rp={}, ap={}, jdkHome={}, keytool={}, profiles={}", recentProfiles.toString(), ap, jdkHome, profiles.toString()); } Configuration conf = new Configuration(); conf.setActiveProfile(Optional.of(ap)); conf.setJDKHome(Optional.of(jdkHome)); conf.getRecentProfiles().addAll(deserializeRecentProfiles(recentProfiles)); conf.getProfiles().addAll(deserializeProfiles(profiles)); conf.setHashedPassword(Optional.of(hp)); conf.setLastUpdatedDateTime(Optional.ofNullable(lastUpdatedDate)); return conf; }
From source file:com.bekwam.resignator.model.ConfigurationJSONAdapter.java
License:Apache License
private List<String> deserializeRecentProfiles(JsonArray recentProfiles) { List<String> rps = new ArrayList<>(); for (JsonElement e : recentProfiles) { rps.add(e.getAsString()); }/*from ww w . java2s . c o m*/ return rps; }
From source file:com.bekwam.resignator.model.ConfigurationJSONAdapter.java
License:Apache License
private List<Profile> deserializeProfiles(JsonArray profiles) { List<Profile> ps = new ArrayList<>(); for (JsonElement e : profiles) { JsonObject profileObj = (JsonObject) e; String profileName = profileObj.get("profileName").getAsString(); Boolean rs = Boolean.FALSE; if (profileObj.get("replaceSignatures") != null) { rs = profileObj.get("replaceSignatures").getAsBoolean(); }//from w w w .ja v a2s.c o m SigningArgumentsType argsType = SigningArgumentsType.JAR; if (profileObj.get("argsType") != null) { String at = profileObj.get("argsType").getAsString(); if (StringUtils.equalsIgnoreCase(at, String.valueOf(SigningArgumentsType.FOLDER))) { argsType = SigningArgumentsType.FOLDER; } } Profile p = new Profile(profileName, rs, argsType); // // SourceFile part // JsonObject sourceObj = profileObj.getAsJsonObject("sourceFile"); if (sourceObj != null) { JsonElement sfe = sourceObj.get("fileName"); if (sfe != null) { SourceFile sf = new SourceFile(sfe.getAsString()); p.setSourceFile(Optional.of(sf)); } } // // TargetFile part // JsonObject targetObj = profileObj.getAsJsonObject("targetFile"); if (sourceObj != null) { JsonElement tfe = targetObj.get("fileName"); if (tfe != null) { TargetFile tf = new TargetFile(tfe.getAsString()); p.setTargetFile(Optional.of(tf)); } } // // JarsignerConfig part // JsonObject jcObj = profileObj.getAsJsonObject("jarsignerConfig"); if (jcObj != null) { String alias = ""; String storepass = ""; String keypass = ""; String keystore = ""; Boolean verbose = false; JsonElement ae = jcObj.get("alias"); if (ae != null) { alias = ae.getAsString(); } JsonElement spe = jcObj.get("storepass"); if (spe != null) { storepass = spe.getAsString(); } JsonElement kpe = jcObj.get("keypass"); if (kpe != null) { keypass = kpe.getAsString(); } JsonElement kse = jcObj.get("keystore"); if (kse != null) { keystore = kse.getAsString(); } JsonElement ve = jcObj.get("verbose"); if (ve != null) { verbose = ve.getAsBoolean(); } JarsignerConfig jc = new JarsignerConfig(alias, "", "", keystore, verbose); jc.setEncryptedKeypass(keypass); jc.setEncryptedStorepass(storepass); p.setJarsignerConfig(Optional.of(jc)); } ps.add(p); } return ps; }
From source file:com.bing.maps.rest.services.impl.BaseBingMapsApiQuery.java
License:Apache License
/** * Gets the gson builder.// w w w .j a va 2s .c o m * * @return the gson builder */ protected GsonBuilder getGsonBuilder() { GsonBuilder builder = new GsonBuilder(); builder.setDateFormat(ApplicationConstants.RFC822DATEFORMAT); builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); builder.registerTypeAdapter(LocationType.class, new JsonDeserializer<LocationType>() { @Override public LocationType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return LocationType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(AddressComponentType.class, new JsonDeserializer<AddressComponentType>() { @Override public AddressComponentType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return AddressComponentType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(TravelMode.class, new JsonDeserializer<TravelMode>() { @Override public TravelMode deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return TravelMode.fromValue(arg0.getAsString()); } }); return builder; }
From source file:com.bios.controller.services.BidStatusService.java
/** * Handles the HTTP <code>GET</code> method to determine whether currently * placed bids will be successful at the end of the round. A json object * that contains the live bidding data relating to the bid will be created. * * @param request servlet request//ww w .java2 s .c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs * */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ConnectionManager manager = new ConnectionManager(); String requestObject = request.getParameter("r"); String token = request.getParameter("token"); ArrayList<String> errorList = new ArrayList<String>(); JsonObject responseObject = new JsonObject(); JsonArray allErrors = new JsonArray(); if (requestObject == null) { errorList.add("missing r"); } else if (requestObject.length() == 0) { errorList.add("blank r"); } if (token == null) { errorList.add("missing token"); } else if (token.length() == 0) { errorList.add("blank token"); } else { try { String result = JWTUtility.verify(token, "abcdefgh12345678"); if (!result.equals("admin")) { errorList.add("invalid token"); } } catch (JWTException e) { // do we need this? // This means not an admin, or token expired errorList.add("invalid username/token"); } } JsonElement jelementRequest = new JsonParser().parse(requestObject); JsonObject json = jelementRequest.getAsJsonObject(); JsonElement crse = json.get("course"); JsonElement sec = json.get("section"); if (crse == null) { errorList.add("missing course"); } else if (crse.getAsString().length() == 0) { errorList.add("blank course"); } if (sec == null) { errorList.add("missing section"); } else if (sec.getAsString().length() == 0) { errorList.add("blank section"); } if (errorList.size() > 0) { errorList.sort(new ErrorMsgComparator()); for (String s : errorList) { allErrors.add(new JsonPrimitive(s)); } responseObject.addProperty("status", "error"); responseObject.add("message", allErrors); response.setContentType("application/json"); response.getWriter().write(responseObject.toString()); return; } String courseID = crse.getAsString(); String sectionID = sec.getAsString(); int round = manager.getBiddingRound(); String status = manager.getBiddingRoundStatus(); // Section that user has selected Section section = SectionDAO.getInstance().findSection(courseID, sectionID); Course course = CourseDAO.getInstance().findCourse(courseID); if (course == null) { allErrors.add(new JsonPrimitive("invalid course")); } else if (course != null && section == null) { allErrors.add(new JsonPrimitive("invalid section")); } if (allErrors.size() > 0) { responseObject.addProperty("status", "error"); responseObject.add("message", allErrors); response.setContentType("application/json"); response.getWriter().write(responseObject.toString()); return; } // How many students have already been enrolled in the section successfully ArrayList<SectionStudent> sectionStudentList = SectionStudentDAO.getInstance() .getSectionStudentListWithID(courseID, sectionID); // Size of the class minus the already enrolled number, which essentially means vacancy int vacancy = section.getSize() - sectionStudentList.size(); // Minimum bid value that has to be shown to user, default is 10 double minBidValue = 10; // This lists the bids that are still pending approval in round 2, and contains the bids // that user has selected, and these bids are sorted from highest to lowest ArrayList<Bid> allBids = BidDAO.getInstance().getPendingBidsWithID(courseID, sectionID); // ArrayList<Bid> allBids= null; // if (round == 1 && status.equals("started")){ // allBids = BidDAO.getInstance().getBidList(); // } else if (status.equals("stopped") && round == 1){ // allBids = RoundOneBidDAO.getInstance().getBidList(); // } else if(round == 2 && status.equals("started")){ // allBids = BidDAO.getInstance().getPendingBids(); // } else{ // allBids = RoundTwoBidDAO.getInstance().getBidList(); // } allBids.sort(new BidComparator()); // This JsonObject is to be used as the reponse to the user JsonObject object = new JsonObject(); object.addProperty("status", "success"); DecimalFormat df = new DecimalFormat("0.00"); JsonArray arrayOfBids = new JsonArray(); if (round == 1 && status.equals("started")) { object.addProperty("vacancy", section.getSize()); if (section.getSize() > allBids.size() && allBids.size() > 0) { minBidValue = allBids.get(allBids.size() - 1).getAmount(); } else if (allBids.size() >= section.getSize()) { minBidValue = allBids.get(section.getSize() - 1).getAmount(); } object.addProperty("min-bid-amount", minBidValue); for (Bid bid : allBids) { JsonObject innerObject = new JsonObject(); Student stud = StudentDAO.getInstance().retrieve(bid.getUserID()); innerObject.add("userid", new JsonPrimitive(bid.getUserID())); innerObject.add("amount", new JsonPrimitive(bid.getAmount())); String result = df.format(stud.geteDollar()); double eDollar = Double.parseDouble(result); innerObject.add("balance", new JsonPrimitive(eDollar)); innerObject.add("status", new JsonPrimitive("pending")); arrayOfBids.add(innerObject); } } else if (round == 1 && status.equals("stopped")) { object.addProperty("vacancy", section.getSize() - BidDAO.getInstance().getSuccessfulBidsWithID(courseID, sectionID).size()); allBids = BidDAO.getInstance().getBids(courseID, sectionID); if (allBids.size() >= vacancy && vacancy != 0) { // should this be >=? wha if vacancy==0? minBidValue = allBids.get(vacancy - 1).getAmount(); } else if (allBids.size() < vacancy && allBids.size() > 0) { minBidValue = allBids.get(allBids.size() - 1).getAmount(); } object.addProperty("min-bid-amount", minBidValue); allBids = BidDAO.getInstance().getBids(courseID, sectionID); for (Bid bid : allBids) { JsonObject innerObject = new JsonObject(); Student stud = StudentDAO.getInstance().retrieve(bid.getUserID()); innerObject.add("userid", new JsonPrimitive(bid.getUserID())); innerObject.add("amount", new JsonPrimitive(bid.getAmount())); String result = df.format(stud.geteDollar()); double eDollar = Double.parseDouble(result); innerObject.add("balance", new JsonPrimitive(eDollar)); innerObject.add("status", new JsonPrimitive(bid.getStatus())); arrayOfBids.add(innerObject); } } else if (round == 2 && status.equals("started")) { object.addProperty("vacancy", vacancy); // This is to re-compute the minimum bid value // if (allBids.size() >= vacancy && vacancy != 0) { // should this be >=? wha if vacancy==0? // minBidValue = allBids.get(vacancy - 1).getAmount() + 1; // } // This allows us to store the minimum bids, and also to persist the bids such that it stores the min bid amount if (MinBidDAO.getInstance().updateMinBid(courseID + "-" + sectionID, minBidValue)) { // Bid was updated successfully object.addProperty("min-bid-amount", minBidValue); } else { object.addProperty("min-bid-amount", MinBidDAO.getInstance().getValue(courseID + "-" + sectionID)); } for (int i = 0; i < allBids.size(); i++) { Bid bid = allBids.get(i); JsonObject innerObject = new JsonObject(); Student stud = StudentDAO.getInstance().retrieve(bid.getUserID()); innerObject.add("userid", new JsonPrimitive(bid.getUserID())); innerObject.add("amount", new JsonPrimitive(bid.getAmount())); String result = df.format(stud.geteDollar()); double eDollar = Double.parseDouble(result); innerObject.add("balance", new JsonPrimitive(eDollar)); // If there are vacancies still if (vacancy >= allBids.size()) { innerObject.add("status", new JsonPrimitive("success")); } else if (allBids.size() > vacancy) { // If this bid is still within the vacancy requirements if (i <= vacancy) { Bid firstFailedBid = allBids.get(vacancy); if (bid.getAmount() == firstFailedBid.getAmount()) { innerObject.add("status", new JsonPrimitive("fail")); } else { innerObject.add("status", new JsonPrimitive("success")); } } else if (i > vacancy) { //what if vacancy+1's bid amout innerObject.add("status", new JsonPrimitive("fail")); } } arrayOfBids.add(innerObject); } } else { object.addProperty("vacancy", section.getSize() - BidDAO.getInstance().getSuccessfulBidsWithID(courseID, sectionID).size()); allBids = BidDAO.getInstance().getSuccessfulBidsWithID(courseID, sectionID); allBids.sort(new BidComparator()); minBidValue = allBids.get(allBids.size() - 1).getAmount(); object.addProperty("min-bid-amount", minBidValue); for (Bid bid : allBids) { JsonObject innerObject = new JsonObject(); Student stud = StudentDAO.getInstance().retrieve(bid.getUserID()); innerObject.add("userid", new JsonPrimitive(bid.getUserID())); innerObject.add("amount", new JsonPrimitive(bid.getAmount())); String result = df.format(stud.geteDollar()); double eDollar = Double.parseDouble(result); innerObject.add("balance", new JsonPrimitive(eDollar)); innerObject.add("status", new JsonPrimitive(bid.getStatus())); arrayOfBids.add(innerObject); } } object.add("students", arrayOfBids); response.setContentType("application/json"); response.getWriter().write(object.toString()); }