List of usage examples for com.fasterxml.jackson.databind JsonNode get
public JsonNode get(String paramString)
From source file:com.heliosapm.tsdblite.metric.MetricCache.java
/** * Returns the long hash code for the passed metric JSON node * @param metricNode a metric JSON node//from w w w . j av a2 s. co m * @return the long hash code */ public static long hashCode(final JsonNode metricNode) { if (metricNode == null) throw new IllegalArgumentException("The passed node was null"); try { final TreeMap<String, String> cleanedTags = new TreeMap<String, String>(ROOT_COLLATOR); final JsonNode tags = metricNode.get("tags"); for (final Iterator<String> keyIter = tags.fieldNames(); keyIter.hasNext();) { final String key = keyIter.next(); cleanedTags.put(key, tags.get(key).textValue()); } return hashCode(metricNode.get("metric").textValue(), cleanedTags); } catch (Exception ex) { throw new RuntimeException("Failed to calc hash for metric node [" + metricNode + "]", ex); } }
From source file:org.kiji.rest.representations.KijiRestEntityId.java
/** * Create KijiRestEntityId from json node. * * @param node of the RKF2-formatted, materialization unsuppressed row. * @param rowKeyFormat2 of the layout or null if the layout has RowKeyFormat1. * If null, then long components may not be recognized. * @return a properly constructed KijiRestEntityId. * @throws IOException if KijiRestEntityId can not be properly constructed. */// w w w . ja v a 2 s.c o m public static KijiRestEntityId create(final JsonNode node, final RowKeyFormat2 rowKeyFormat2) throws IOException { Preconditions.checkNotNull(node); if (node.isArray()) { final Object[] components = new Object[node.size()]; boolean wildCarded = false; for (int i = 0; i < node.size(); i++) { final Object component = getNodeValue(node.get(i)); if (component.equals(WildcardSingleton.INSTANCE)) { wildCarded = true; components[i] = null; } else if (null != rowKeyFormat2 && ComponentType.LONG == rowKeyFormat2.getComponents().get(i).getType()) { components[i] = ((Number) component).longValue(); } else { components[i] = component; } } return new KijiRestEntityId(components, wildCarded); } else { // Disallow non-arrays. throw new IllegalArgumentException( "Provide components wrapped as a JSON array or provide the row key."); } }
From source file:com.baasbox.controllers.Document.java
@With({ UserCredentialWrapFilter.class, ConnectToDBFilter.class, ExtractQueryParameters.class }) @BodyParser.Of(BodyParser.Json.class) public static Result updateDocument(String collectionName, String id, boolean isUUID) { if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method Start"); Http.RequestBody body = request().body(); JsonNode bodyJson = body.asJson(); if (bodyJson == null) return badRequest(JSON_BODY_NULL); if (bodyJson.get("@version") != null && !bodyJson.get("@version").isInt()) return badRequest("@version field must be an Integer"); ODocument document = null;// w ww . ja v a2s .com try { if (!bodyJson.isObject()) throw new InvalidJsonException("The body must be an JSON object"); if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("updateDocument collectionName: " + collectionName); if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("updateDocument id: " + id); String rid = DocumentService.getRidByString(id, isUUID); document = com.baasbox.service.storage.DocumentService.update(collectionName, rid, (ObjectNode) bodyJson); } catch (DocumentNotFoundException e) { return notFound("Document " + id + " not found"); } catch (AclNotValidException e) { return badRequest("ACL fields are not valid: " + ExceptionUtils.getMessage(e)); } catch (UpdateOldVersionException e) { return status(CustomHttpCode.DOCUMENT_VERSION.getBbCode(), "You are attempting to update an older version of the document. Your document version is " + e.getVersion1() + ", the stored document has version " + e.getVersion2()); } catch (RidNotFoundException e) { return notFound("id " + id + " not found"); } catch (InvalidCollectionException e) { return notFound(collectionName + " is not a valid collection name"); } catch (InvalidModelException e) { return notFound(id + " is not a valid belongs to " + collectionName); } catch (InvalidParameterException e) { return badRequest(id + " is not a document"); } catch (IllegalArgumentException e) { return badRequest(id + " is not a document"); } catch (ODatabaseException e) { return notFound(id + " unknown"); } catch (OSecurityException e) { return forbidden("You have not the right to modify " + id); } catch (InvalidJsonException e) { return badRequest( "JSON not valid. HINT: check if it is not just a JSON collection ([..]), a single element ({\"element\"}) or you are trying to pass a @version:null field"); } catch (Throwable e) { BaasBoxLogger.error(ExceptionUtils.getFullStackTrace(e)); return internalServerError(ExceptionUtils.getFullStackTrace(e)); } if (document == null) return notFound("Document " + id + " was not found in the collection " + collectionName); if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method End"); return ok(prepareResponseToJson(document)); }
From source file:org.createnet.raptor.indexer.impl.ElasticSearchIndexer.java
/** * * @param file/*from ww w . j a v a 2 s . c om*/ * @return */ public static Map<String, JsonNode> loadIndicesFromFile(String file) { // Load indices.json to configuration Map<String, JsonNode> indices = new HashMap(); ObjectMapper mapper = Indexer.getObjectMapper(); JsonNode json; try { json = mapper.readTree(Files.readAllBytes(Paths.get(file))); } catch (IOException ex) { throw new IndexerException(ex); } Iterator<String> it = json.fieldNames(); while (it.hasNext()) { String indexName = it.next(); indices.put(indexName, json.get(indexName)); } return indices; }
From source file:controllers.Rules.java
@Security.Authenticated(Secured.class) @BodyParser.Of(BodyParser.Json.class) public static Promise<Result> addString(String name, String groupID) { JsonNode json = request().body().asJson(); ObjectNode group = Json.newObject(); group.put("uuid", groupID); ObjectNode string = Json.newObject(); String uuid = UUIDGenerator.from(json.get("content").asText()); string.put("uuid", uuid); string.put("content", json.get("content").asText()); Promise<Boolean> connected = CombinationGroup.nodes.connect(group, string); ObjectNode result = Json.newObject(); result.put("id", uuid); return connected.map(new ResultFunction("String successfully added.", "String not added.", result)); }
From source file:controllers.user.UserSettingApp.java
/** * ?// w w w.j ava 2 s. c om * * @return */ @Transactional(readOnly = false) public static Result changePassword() { JsonNode json = getJson(); // ? boolean isValidParams = json.hasNonNull("old") && json.hasNonNull("new"); if (!isValidParams) { return illegalParameters(); } User user = User.getFromSession(session()); ObjectNodeResult result = User.changePassword(user, json.get("old").asText(), json.get("new").asText(), session()); return ok(result.getObjectNode()); }
From source file:edu.ucsd.sbrg.escher.EscherConverter.java
/** * Parses given JSON file into an {@link EscherMap} instance using Jackson. * //from w w w . j a v a 2s . c om * @param input The {@link File} to parse. * @return The {@link EscherMap} instance. * @throws IOException Thrown if there are problems in reading the {@code input} file. */ public static EscherMap parseEscherJson(File input) throws IOException { ObjectMapper objectMapper = edu.ucsd.sbrg.escher.utilities.Utils.getObjectMapper(); logger.info(format(bundle.getString("EscherConverter.readingFile"), input)); // An Escher array contains meta-info about the map as the first object and the actual map as // second map. JsonNode escherJson = objectMapper.readTree(input); // Meta-info. EscherMap meta = objectMapper.treeToValue(escherJson.get(0), EscherMap.class); // Layout map (nodes, reactions, text labels and canvas info). EscherMap map = objectMapper.treeToValue(escherJson.get(1), EscherMap.class); // Put meta-info from first to second. map.setId(meta.getId()); map.setName(meta.getName()); map.setDescription(meta.getDescription()); map.setSchema(meta.getSchema()); map.setURL(meta.getURL()); map.processMap(); logger.info(format(bundle.getString("EscherConverter.readingDone"), input)); return map; }
From source file:com.spotify.docker.client.messages.RegistryAuth.java
private static RegistryAuth.Builder parseDockerConfig(final Path configPath, String serverAddress) throws IOException { checkNotNull(configPath);//from w w w. j av a 2 s . c o m final RegistryAuth.Builder authBuilder = RegistryAuth.builder(); final JsonNode authJson = extractAuthJson(configPath); if (isNullOrEmpty(serverAddress)) { final Iterator<String> servers = authJson.fieldNames(); if (servers.hasNext()) { serverAddress = servers.next(); } } else { if (!authJson.has(serverAddress)) { LOG.error("Could not find auth config for {}. Returning empty builder", serverAddress); return RegistryAuth.builder().serverAddress(serverAddress); } } final JsonNode serverAuth = authJson.get(serverAddress); if (serverAuth != null && serverAuth.has("auth")) { authBuilder.serverAddress(serverAddress); final String authString = serverAuth.get("auth").asText(); final String[] authParams = Base64.decodeAsString(authString).split(":"); if (authParams.length == 2) { authBuilder.username(authParams[0].trim()); authBuilder.password(authParams[1].trim()); } else if (serverAuth.has("identityToken")) { authBuilder.identityToken(serverAuth.get("identityToken").asText()); return authBuilder; } else { LOG.warn("Failed to parse auth string for {}", serverAddress); return authBuilder; } } else { LOG.warn("Could not find auth field for {}", serverAddress); return authBuilder; } if (serverAuth.has("email")) { authBuilder.email(serverAuth.get("email").asText()); } return authBuilder; }
From source file:models.service.reminder.RemindService.java
/** * ???// www. j a va2s. c om * * @param session Http session * @param user ? * @param cfg Json * @param items ?items * * @return true - ??, false - ? */ public static boolean saveCfgJson(Http.Session session, User user, JsonNode cfg, Item[] cfgItems) { boolean isValidCfg = verifyCfg(cfg, cfgItems); if (!isValidCfg) { return false; } JsonNode oldUserCfg = null; if (StringUtils.isNotBlank(user.safetyReminderConfig)) { oldUserCfg = Json.parse(user.safetyReminderConfig); } ObjectNode newUserCfg = Json.newObject(); for (Item item : Item.values()) { String val = item.getVal(); if (ArrayUtils.contains(cfgItems, item)) { newUserCfg.set(val, cfg.get(val)); } else { if (null != oldUserCfg && oldUserCfg.hasNonNull(val)) { newUserCfg.set(val, oldUserCfg.get(val)); } } } JPA.em().createQuery("update User set safetyReminderConfig=:newCfg where id=:id") .setParameter("newCfg", newUserCfg.toString()).setParameter("id", user.id).executeUpdate(); LoginUserCache.refreshBySession(session); return true; }
From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java
/** * Registers a passed in User and returns that user with an assigned UserID * * @param registerMe// w w w . j a v a 2 s .co m * @param password * @return the passed-in user with an assigned ID by the server * @throws Exception */ public static User register(User registerMe, String password) throws Exception { // Server URL setup String _url = getBaseUri().build().toString(); // Establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.POST); addRequestHeader(conn, true); // 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); password = Utilities.computeHash(password); // Build JSON Object jgen.writeStartObject(); jgen.writeStringField(Keys.User.NAME, registerMe.getDisplayName()); jgen.writeStringField("password", password); jgen.writeStringField(Keys.User.EMAIL, registerMe.getEmail()); jgen.writeStringField(Keys.User.PHONE, registerMe.getPhone()); jgen.writeStringField(Keys.User.COMPANY, registerMe.getCompany()); jgen.writeStringField(Keys.User.TITLE, registerMe.getTitle()); jgen.writeStringField(Keys.User.LOCATION, registerMe.getLocation()); 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); User createUser = new User(registerMe); /* * result should get valid={"userID":"##"} */ String result = ""; if (!response.isEmpty()) { JsonNode tree = MAPPER.readTree(response); if (!tree.has(Keys.User.ID)) { result = "duplicate email or username"; } else { result = tree.get(Keys.User.ID).asText(); createUser.setID(result); } } conn.disconnect(); return createUser; }