List of usage examples for com.fasterxml.jackson.databind JsonNode get
public JsonNode get(String paramString)
From source file:models.service.reminder.RemindService.java
/** * ???/*www . j a v a 2 s .c o m*/ * * @param user ? * @param items ?items * * @return true - ???, false - ??? */ public static boolean isEmpty(User user, Item[] items) { String cfg = user.safetyReminderConfig; if (StringUtils.isBlank(cfg)) { return true; } boolean isEmpty = true; JsonNode options = Json.parse(cfg); for (Item item : items) { if (item.isEnable && options.hasNonNull(item.getVal()) && options.get(item.getVal()).size() > 0) { isEmpty = false; break; } } return isEmpty; }
From source file:com.baasbox.controllers.Root.java
/** * /root/configuration (POST)//from ww w .j a va 2s.c o m * * this method allows to set (or override) just two configuration parameter (at the moment) * the db size Threshold in bytes: * baasbox.db.size * A percentage needed by the console to show alerts on dashboard when DB size is near the defined Threshold * baasbox.db.alert * * @return a 200 OK with the new values */ @With({ RootCredentialWrapFilter.class }) public static Result overrideConfiguration() { Http.RequestBody body = request().body(); JsonNode bodyJson = body.asJson(); JsonNode newDBAlert = bodyJson.get(BBConfiguration.DB_ALERT_THRESHOLD); JsonNode newDBSize = bodyJson.get(BBConfiguration.DB_SIZE_THRESHOLD); try { if (newDBAlert != null && !newDBAlert.isInt() && newDBAlert.asInt() < 1) throw new IllegalArgumentException( BBConfiguration.DB_ALERT_THRESHOLD + " must be a positive integer value"); if (newDBSize != null && !newDBSize.isLong() && newDBSize.asInt() < 0) throw new IllegalArgumentException(BBConfiguration.DB_SIZE_THRESHOLD + " must be a positive integer value, or 0 to disable it"); } catch (Throwable e) { return badRequest(ExceptionUtils.getMessage(e)); } if (newDBAlert != null) BBConfiguration.setDBAlertThreshold(newDBAlert.asInt()); if (newDBSize != null) BBConfiguration.setDBSizeThreshold(BigInteger.valueOf(newDBSize.asLong())); HashMap returnMap = new HashMap(); returnMap.put(BBConfiguration.DB_ALERT_THRESHOLD, BBConfiguration.getDBAlertThreshold()); returnMap.put(BBConfiguration.DB_SIZE_THRESHOLD, BBConfiguration.getDBSizeThreshold()); try { return ok(new ObjectMapper().writeValueAsString(returnMap)); } catch (JsonProcessingException e) { return internalServerError(ExceptionUtils.getMessage(e)); } }
From source file:com.twosigma.beakerx.table.serializer.TableDisplayDeSerializer.java
@SuppressWarnings("unchecked") public static List<List<?>> getValues(BeakerObjectConverter parent, JsonNode n, ObjectMapper mapper) throws IOException { List<List<?>> values = null; List<String> classes = null; if (n.has("types")) classes = mapper.readValue(n.get("types").toString(), List.class); if (n.has("values")) { JsonNode nn = n.get("values"); values = new ArrayList<List<?>>(); if (nn.isArray()) { for (JsonNode nno : nn) { if (nno.isArray()) { ArrayList<Object> val = new ArrayList<Object>(); for (int i = 0; i < nno.size(); i++) { JsonNode nnoo = nno.get(i); Object obj = parent.deserialize(nnoo, mapper); val.add(TableDisplayDeSerializer.getValueForDeserializer(obj, classes != null && classes.size() > i ? classes.get(i) : null)); }//from ww w. j a va2 s . com values.add(val); } } } } return values; }
From source file:gate.corpora.twitter.TweetUtils.java
/** * Dig through a JSON object, key-by-key (recursively). * @param node// w ww.j a v a 2 s . co m * @param keySequence * @return the value held by the last key in the sequence; this will * be a FeatureMap if there is further nesting */ public static Object dig(JsonNode node, String[] keySequence, int index) { if ((index >= keySequence.length) || (node == null)) { return null; } if (node.has(keySequence[index])) { JsonNode value = node.get(keySequence[index]); if (keySequence.length == (index + 1)) { // Found last key in sequence; convert the JsonNode // value to a normal object (possibly FeatureMap) return process(value); } else if (value != null) { // Found current key; keep digging for the rest return dig(value, keySequence, index + 1); } } return null; }
From source file:com.spoiledmilk.cykelsuperstier.break_rote.LocalTrainData.java
public static ArrayList<ITransportationInfo> getNext3Arrivals(String fromStation, String toStation, String line, Context context) {// w w w . j a v a 2 s . c o m ArrayList<ITransportationInfo> ret = new ArrayList<ITransportationInfo>(); String lineNumber = line.split(" ")[0]; String jsonStr = Util.stringFromJsonAssets(context, "stations/local-trains-timetable.json"); JsonNode root = Util.stringToJsonNode(jsonStr); JsonNode lines = root.get("local-trains"); for (int i = 0; i < lines.size(); i++) { if (lines.get(i).get("line").asText().trim().equalsIgnoreCase(lineNumber.trim())) { JsonNode stationsArray = lines.get(i).get("stations"); int direction = -1, index1 = -1, index2 = -1; for (int j = 0; j < stationsArray.size(); j++) { if (stationsArray.get(j).asText().trim().equalsIgnoreCase(fromStation.trim()) && index1 < 0) { index1 = j; if (direction < 0) direction = DEPARTURE; else break; } if (stationsArray.get(j).asText().trim().equalsIgnoreCase(toStation.trim()) && index2 < 0) { index2 = j; if (direction < 0) direction = ARRIVAL; else break; } } if (direction < 0 || index1 < 0 || index2 < 0) break; JsonNode timetableNodeContainer = direction == DEPARTURE ? lines.get(i).get("departure") : lines.get(i).get("arrival"); Calendar calendar = Calendar.getInstance(); int day = calendar.get(Calendar.DAY_OF_WEEK); if (day == 1) day = 6; else day -= 2; int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); JsonNode timeTableNode; if (day >= 0 && day <= 4) { timeTableNode = timetableNodeContainer.get("weekdays"); if (timeTableNode != null) getTimesForWeekdays(hour, minute, ret, timeTableNode, index1, index2, stationsArray.size()); } else if (day == 5) { // Saturday timeTableNode = timetableNodeContainer.get("weekend").get("saturday"); if (timeTableNode != null) { JsonNode dataNodeArray = timetableNodeContainer.get("weekend").get("data-table"); getTimesForWeekend(hour, minute, ret, timeTableNode, index1, index2, stationsArray.size(), dataNodeArray); } } else { // Saturday timeTableNode = timetableNodeContainer.get("weekend").get("sunday"); if (timeTableNode != null) { JsonNode dataNodeArray = timetableNodeContainer.get("weekend").get("data-table"); getTimesForWeekend(hour, minute, ret, timeTableNode, index1, index2, stationsArray.size(), dataNodeArray); } } if (timeTableNode == null) break; break; } } return ret; }
From source file:com.meetingninja.csse.database.GroupDatabaseAdapter.java
public static Group createGroup(Group g) throws IOException, MalformedURLException { // Server URL setup String _url = getBaseUri().build().toString(); // establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); addRequestHeader(conn, true);//from w w w . j ava 2 s.co m // prepare POST payload ByteArrayOutputStream json = new ByteArrayOutputStream(); // this type of print stream allows us to get a string easily PrintStream ps = new PrintStream(json); // Create a generator to build the JSON string JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8); // Build JSON Object jgen.writeStartObject(); jgen.writeStringField(Keys.Group.TITLE, g.getGroupTitle()); jgen.writeArrayFieldStart(Keys.Group.MEMBERS); for (User member : g.getMembers()) { jgen.writeStartObject(); jgen.writeStringField(Keys.User.ID, member.getID()); jgen.writeEndObject(); } jgen.writeEndArray(); jgen.writeEndObject(); jgen.close(); // Get JSON Object payload from print stream String payload = json.toString("UTF8"); ps.close(); // send payload int responseCode = sendPostPayload(conn, payload); String response = getServerResponse(conn); // prepare to get the id of the created Meeting // Map<String, String> responseMap = new HashMap<String, String>(); /* * result should get valid={"meetingID":"##"} */ String result = new String(); if (!response.isEmpty()) { // responseMap = MAPPER.readValue(response, // new TypeReference<HashMap<String, String>>() { // }); JsonNode groupNode = MAPPER.readTree(response); if (!groupNode.has(Keys.Group.ID)) { result = "invalid"; } else result = groupNode.get(Keys.Group.ID).asText(); } if (!result.equalsIgnoreCase("invalid")) g.setID(result); conn.disconnect(); return g; }
From source file:com.spoiledmilk.ibikecph.search.HTTPAutocompleteHandler.java
public static JsonNode getOiorestGeocode(String urlString, String houseNumber) { JsonNode rootNode = performGET(urlString); JsonNode ret = null;//from ww w. j a v a 2s . c o m if (rootNode != null && rootNode.size() != 0) { ret = rootNode.get(0); for (int i = 0; i < rootNode.size(); i++) { if (rootNode.get(i).has("husnr") && rootNode.get(i).get("husnr").asText().toLowerCase(Locale.US).equals(houseNumber)) { ret = rootNode.get(i); break; } } } if (ret != null && ret.has("husnr")) { LOG.d("Geocode succesfull, searched number = " + houseNumber + " foundNumber = " + ret.get("husnr").asText()); } return ret; }
From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java
/** * Uploads the specified file to the community site. The return identifier * can be used later when composing other requests. * /*from w w w . ja v a2 s .c om*/ * @param httpclient * the http client * @param attachment * the file to attach * @param authCookie * the session cookie to use for authentication purpose * @return the identifier of the file uploaded, <code>null</code> otherwise * @throws CommunityAPIException */ public static String uploadFile(CloseableHttpClient httpclient, File attachment, Cookie authCookie) throws CommunityAPIException { FileInputStream fin = null; try { fin = new FileInputStream(attachment); byte fileContent[] = new byte[(int) attachment.length()]; fin.read(fileContent); byte[] encodedFileContent = Base64.encodeBase64(fileContent); FileUploadRequest uploadReq = new FileUploadRequest(attachment.getName(), encodedFileContent); HttpPost fileuploadPOST = new HttpPost(CommunityConstants.FILE_UPLOAD_URL); EntityBuilder fileUploadEntity = EntityBuilder.create(); fileUploadEntity.setText(uploadReq.getAsJSON()); fileUploadEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE)); fileUploadEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET); fileuploadPOST.setEntity(fileUploadEntity.build()); CloseableHttpResponse resp = httpclient.execute(fileuploadPOST); int httpRetCode = resp.getStatusLine().getStatusCode(); String responseBodyAsString = EntityUtils.toString(resp.getEntity()); if (HttpStatus.SC_OK == httpRetCode) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); JsonNode jsonRoot = mapper.readTree(responseBodyAsString); String fid = jsonRoot.get("fid").asText(); //$NON-NLS-1$ return fid; } else { CommunityAPIException ex = new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError); ex.setHttpStatusCode(httpRetCode); ex.setResponseBodyAsString(responseBodyAsString); throw ex; } } catch (FileNotFoundException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_FileNotFoundError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e); } catch (UnsupportedEncodingException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e); } catch (IOException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e); } finally { IOUtils.closeQuietly(fin); } }
From source file:com.meetingninja.csse.database.ProjectDatabaseAdapter.java
public static Project parseProject(JsonNode projectNode, Project p) throws IOException { String projectID = projectNode.get(Keys.Project.ID).asText(); List<Meeting> meetinglist = new ArrayList<Meeting>(); List<Note> notelist = new ArrayList<Note>(); List<User> userlist = new ArrayList<User>(); p.setMeetings(meetinglist);//from ww w. j a v a2s . c o m p.setMembers(userlist); p.setNotes(notelist); if (projectID != null) { p.setProjectID(projectID); p.setProjectTitle(projectNode.get(Keys.Project.TITLE).asText()); JsonNode meetings = projectNode.get(Keys.Project.MEETINGS); if (meetings != null && meetings.isArray()) { for (final JsonNode meetingNode : meetings) { Meeting meeting = new Meeting(); meeting.setID(meetingNode.get(Keys.Meeting.ID).asText()); meeting = MeetingDatabaseAdapter.getMeetingInfo(meeting.getID()); p.addMeeting(meeting); } } JsonNode notes = projectNode.get(Keys.Project.NOTES); if (notes != null && notes.isArray()) { for (final JsonNode noteNode : notes) { Note note = new Note(); note.setID(noteNode.get(Keys.Note.ID).asText()); // NotesDatabaseAdapter.get //TODO: lkjaslfdkjsad;lkfj p.addNote(note); } } JsonNode members = projectNode.get(Keys.Project.MEMBERS); if (members != null && members.isArray()) { for (final JsonNode memberNode : members) { User user = new User(); user.setID(memberNode.get(Keys.User.ID).asText()); user = UserDatabaseAdapter.getUserInfo(user.getID()); p.addMember(user); } } } return p; }
From source file:com.meetingninja.csse.database.MeetingDatabaseAdapter.java
public static Meeting parseMeeting(JsonNode node) { logPrint(node.toString());/*from w w w . j a va 2 s .c om*/ Meeting m = new Meeting(); // if (m.getID().isEmpty()) // m.setID(node.get(KEY_ID).asText()); m.setTitle(node.get(Keys.Meeting.TITLE).asText()); m.setLocation(node.get(Keys.Meeting.LOCATION).asText()); m.setStartTime(node.get(Keys.Meeting.DATETIME).asText()); m.setEndTime(node.get(Keys.Meeting.OTHEREND).asText()); m.setDescription(node.get(Keys.Meeting.DESC).asText()); JsonNode attendance = node.get(Keys.Meeting.ATTEND); if (attendance != null && attendance.isArray()) { for (final JsonNode attendeeNode : attendance) { String _id = attendeeNode.get("userID").asText(); m.addAttendee(_id); } } else Log.e(TAG, "Error: Unable to parse meeting attendance"); return m; }