List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree
public JsonNode readTree(URL source) throws IOException, JsonProcessingException
From source file:com.nextdoor.bender.config.BenderConfig.java
public static boolean validate(String data, ObjectMapper objectMapper, BenderSchema benderSchema) throws ConfigurationException { ProcessingReport report;//ww w . j a va 2 s . c o m try { /* * Create object */ JsonNode node = objectMapper.readTree(data); /* * Create JSON schema */ JsonNode jsonSchema = benderSchema.getSchema(); /* * Validate */ final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); final JsonSchema schema = factory.getJsonSchema(jsonSchema); report = schema.validate(node); } catch (IOException | ProcessingException ioe) { throw new ConfigurationException("unable to validate config", ioe); } if (report.isSuccess()) { return true; } else { throw new ConfigurationException("invalid config file", report.iterator().next().asException()); } }
From source file:com.infinities.skyport.util.JsonUtil.java
public static String toJson(boolean insertResponseCode, String msg, Object object, Class<? extends Views.Short> view) { ObjectMapper mapper = getObjectMapper(); ObjectWriter writer = mapper.writerWithView(view).withDefaultPrettyPrinter(); JsonNode rootNode = mapper.createObjectNode(); try {//from w w w.j av a2s .co m if (object == null || "".equals(object)) { object = mapper.createObjectNode(); } String temp = writer.writeValueAsString(object); rootNode = mapper.readTree(temp); } catch (Exception e) { logger.error("json parsing failed", e); } ObjectNode root = getObjectMapper().createObjectNode(); root.put(JsonConstants.STATUS, insertResponseCode ? 1 : 0).put(JsonConstants.MSG, msg) .put(JsonConstants._DATA, rootNode); try { return getObjectMapper().configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, false) .writeValueAsString(root); } catch (Exception e) { logger.error("json parsing failed", e); throw new RuntimeException(e); } }
From source file:com.ikanow.aleph2.data_model.utils.BeanTemplateUtils.java
/** Returns a template builder of the designated type from the JSON (note: not very high performance, should only be used for management-type operations) * @param json_str/*from ww w .j ava2s . c o m*/ * @param bean_clazz * @return * @throws JsonParseException * @throws JsonMappingException * @throws IOException */ static public <T> TemplateHelper<T> build(final String json_str, final Class<T> bean_clazz) throws JsonParseException, JsonMappingException, IOException { ObjectMapper object_mapper = BeanTemplateUtils.configureMapper(Optional.empty()); return build(object_mapper.treeToValue(object_mapper.readTree(json_str.getBytes()), bean_clazz)); }
From source file:org.apache.manifoldcf.elasticsearch.MCFAuthorizerUtils.java
public static SearchRequest parseSearchRequestMCF(RestRequest request) throws MCFAuthorizerException { SearchRequest searchRequest;//from ww w.j a va2 s. com String username = request.param("u"); //if(username==null) throw new MCFAuthorizerException("Username not passed."); if (username != null) { String[] indices = Strings.splitStringByCommaToArray(request.param("index")); searchRequest = new SearchRequest(indices); boolean isTemplateRequest = request.path().endsWith("/template"); if (request.hasContent() || request.hasParam("source")) { FilterBuilder authorizationFilter = buildAuthorizationFilter(username); FilteredQueryBuilder filteredQueryBuilder; ObjectMapper objectMapper = new ObjectMapper(); ObjectNode modifiedJSON, innerJSON; JsonNode requestJSON; try { requestJSON = objectMapper.readTree(RestActions.getRestContent(request).toBytes()); if (isTemplateRequest) { modifiedJSON = (ObjectNode) requestJSON; innerJSON = (ObjectNode) requestJSON.findValue("template"); filteredQueryBuilder = QueryBuilders.filteredQuery( QueryBuilders.wrapperQuery(innerJSON.findValue("query").toString()), authorizationFilter); modifiedJSON.replace("template", innerJSON.set("query", objectMapper.readTree(filteredQueryBuilder.buildAsBytes().toBytes()))); searchRequest.templateSource(modifiedJSON.toString()); } else { filteredQueryBuilder = QueryBuilders.filteredQuery( QueryBuilders.wrapperQuery(requestJSON.findValue("query").toString()), authorizationFilter); modifiedJSON = (ObjectNode) requestJSON; modifiedJSON.set("query", objectMapper.readTree(filteredQueryBuilder.buildAsBytes().toBytes())); searchRequest.source(modifiedJSON.toString()); } } catch (IOException e) { e.printStackTrace(); throw new MCFAuthorizerException("JSON parser error"); } } searchRequest.extraSource(parseSearchSourceMCF(request)); searchRequest.searchType(request.param("search_type")); searchRequest.queryCache(request.paramAsBoolean("query_cache", null)); String scroll = request.param("scroll"); if (scroll != null) { searchRequest.scroll(new Scroll(parseTimeValue(scroll, null))); } searchRequest.types(Strings.splitStringByCommaToArray(request.param("type"))); searchRequest.routing(request.param("routing")); searchRequest.preference(request.param("preference")); searchRequest.indicesOptions(IndicesOptions.fromRequest(request, searchRequest.indicesOptions())); } else { searchRequest = RestSearchAction.parseSearchRequest(request); } return searchRequest; }
From source file:io.coala.enterprise.Fact.java
static <F extends Fact> F fromJSON(final ObjectMapper om, final String json, final Class<F> factType) { try {/*w ww . j a v a2s .c o m*/ return json == null ? null : fromJSON(om, om.readTree(json), factType); } catch (final Exception e) { e.printStackTrace(); return Thrower.rethrowUnchecked(e); } }
From source file:ext.usercenter.UCClient.java
/** * ?queryUserById?json/* ww w. ja v a 2 s .co m*/ * @param json * @return */ public static User parseJsonForQueryUserById(String json) { ObjectMapper mapper = JackJsonUtil.getMapperInstance(false); User user = new User(); if (StringUtils.isNotEmpty(json)) { JsonNode node = null; try { node = mapper.readTree(json); } catch (JsonProcessingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } JsonNode jsonNode = node.path("data"); Long privateId = jsonNode.path("privateId").asLong(); String email = jsonNode.path("email").asText(); String realname = jsonNode.path("realname").asText(); String phoneNumber = jsonNode.path("phoneNumber").asText(); user.setId(privateId); user.setUserName(realname); user.setEmail(email); user.setPhoneNumber(phoneNumber); } return user; }
From source file:com.ikanow.aleph2.data_model.utils.JsonUtils.java
/** Takes a tuple expressed as LinkedHashMap<String, Object> (by convention the Objects are primitives, JsonNode, or POJO), and where one of the objects * is a JSON representation of the original object and creates an object by folding them all together * Note the other fields of the tuple take precedence over the JSON * @param in - the tuple/*from w ww . java2 s.c o m*/ * @param mapper - the Jackson object mapper * @param json_field - optional fieldname of the string representation of the JSON - if not present then the last field is used (set to eg "" if there is no base object) * @return */ public static JsonNode foldTuple(final LinkedHashMap<String, Object> in, final ObjectMapper mapper, final Optional<String> json_field) { try { // (do this imperatively to handle the "last element can be the base object case" final Iterator<Map.Entry<String, Object>> it = in.entrySet().iterator(); ObjectNode acc = mapper.createObjectNode(); while (it.hasNext()) { final Map.Entry<String, Object> kv = it.next(); if ((json_field.isPresent() && kv.getKey().equals(json_field.get())) || !json_field.isPresent() && !it.hasNext()) { acc = (ObjectNode) ((ObjectNode) mapper.readTree(kv.getValue().toString())).setAll(acc); } else { final ObjectNode acc_tmp = acc; Patterns.match(kv.getValue()).andAct().when(String.class, s -> acc_tmp.put(kv.getKey(), s)) .when(Long.class, l -> acc_tmp.put(kv.getKey(), l)) .when(Integer.class, l -> acc_tmp.put(kv.getKey(), l)) .when(Boolean.class, b -> acc_tmp.put(kv.getKey(), b)) .when(Double.class, d -> acc_tmp.put(kv.getKey(), d)) .when(JsonNode.class, j -> acc_tmp.set(kv.getKey(), j)) .when(Float.class, f -> acc_tmp.put(kv.getKey(), f)) .when(BigDecimal.class, f -> acc_tmp.put(kv.getKey(), f)) .otherwise(x -> acc_tmp.set(kv.getKey(), BeanTemplateUtils.toJson(x))); } } return acc; } catch (Exception e) { throw new RuntimeException(e); } // (convert to unchecked exception) }
From source file:com.ikanow.aleph2.distributed_services.utils.KafkaUtils.java
/** Generates a connection string by reading ZooKeeper * @param curator/*from www.j a va 2 s . c o m*/ * @param path_override * @return * @throws Exception */ public static String getBrokerListFromZookeeper(final CuratorFramework curator, Optional<String> path_override, final ObjectMapper mapper) throws Exception { final String path = path_override.orElse("/brokers/ids"); final List<String> brokers = curator.getChildren().forPath(path); return brokers.stream() .map(Lambdas.wrap_u(broker_node -> new String(curator.getData().forPath(path + "/" + broker_node)))) .flatMap(Lambdas.flatWrap_i(broker_str -> mapper.readTree(broker_str))) // (just discard any badly formatted nodes) .flatMap(Lambdas.flatWrap_i(json -> json.get("host").asText() + ":" + json.get("port").asText())) .collect(Collectors.joining(",")); }
From source file:ext.usercenter.UCClient.java
/** * ?queryUserById?json/*from w w w .j ava 2 s. c o m*/ * @param json * @return */ public static List<UCUserVO> parseJsonForQueryUserListByIds(String json) { ObjectMapper mapper = JackJsonUtil.getMapperInstance(false); List<UCUserVO> ucUserVOList = new ArrayList<UCUserVO>(); if (StringUtils.isNotEmpty(json)) { JsonNode node = null; try { node = mapper.readTree(json); } catch (JsonProcessingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (node != null && node.path("responsecode").asText().equals("_200")) { JsonNode jsonNode = node.path("data"); Iterator<Entry<String, JsonNode>> fieldIte = jsonNode.fields(); // 2053={"englishName":null,"realname":null} while (fieldIte.hasNext()) { Entry<String, JsonNode> entry = fieldIte.next(); Long userId = new Long(entry.getKey()); JsonNode valueNode = entry.getValue(); String englishName = valueNode.path("englishName").asText(); String realname = valueNode.path("realname").asText(); UCUserVO vo = new UCUserVO(userId, englishName, realname); ucUserVOList.add(vo); } } } return ucUserVOList; }
From source file:com.baasbox.service.storage.DocumentService.java
public static ODocument update(String collectionName, String rid, JsonNode bodyJson, PartsParser pp) throws MissingNodeException, InvalidCollectionException, InvalidModelException, ODatabaseException, IllegalArgumentException, DocumentNotFoundException { ODocument od = get(rid);/*from ww w. j ava 2s .c o m*/ if (od == null) throw new InvalidParameterException(rid + " is not a valid document"); ObjectMapper mapper = new ObjectMapper(); StringBuffer q = new StringBuffer(""); if (!pp.isMultiField() && !pp.isArray()) { q.append("update ").append(collectionName).append(" set ").append(pp.treeFields()).append(" = ") .append(bodyJson.get("data").toString()); } else { q.append("update ").append(collectionName).append(" merge "); String content = od.toJSON(); ObjectNode json = null; try { json = (ObjectNode) mapper.readTree(content.toString()); } catch (Exception e) { throw new RuntimeException("Unable to modify inline json"); } JsonTree.write(json, pp, bodyJson.get("data")); q.append(json.toString()); } q.append(" where @rid = ").append(rid); try { DocumentDao.getInstance(collectionName).updateByQuery(q.toString()); } catch (OSecurityException e) { throw e; } catch (InvalidCriteriaException e) { throw new RuntimeException(e); } od = get(collectionName, rid); return od; }