List of usage examples for com.fasterxml.jackson.databind.node ObjectNode get
public JsonNode get(String paramString)
From source file:me.tfeng.play.avro.AvroHelper.java
private static JsonNode convertFromSimpleRecord(Schema schema, JsonNode json, JsonNodeFactory factory) throws IOException { if (json.isObject() && schema.getType() == Type.RECORD) { ObjectNode node = (ObjectNode) json; ObjectNode newNode = factory.objectNode(); for (Field field : schema.getFields()) { String fieldName = field.name(); if (node.has(fieldName)) { newNode.put(fieldName, convertFromSimpleRecord(field.schema(), node.get(fieldName), factory)); } else if (field.defaultValue() != null) { newNode.put(fieldName, Json.parse(field.defaultValue().toString())); } else { newNode.put(fieldName, factory.nullNode()); }/*from w w w .ja v a 2 s .c om*/ } return newNode; } else if (json.isObject() && schema.getType() == Type.MAP) { ObjectNode node = (ObjectNode) json; ObjectNode newNode = factory.objectNode(); Schema valueType = schema.getValueType(); Iterator<Entry<String, JsonNode>> entries = node.fields(); while (entries.hasNext()) { Entry<String, JsonNode> entry = entries.next(); newNode.put(entry.getKey(), convertFromSimpleRecord(valueType, entry.getValue(), factory)); } return newNode; } else if (schema.getType() == Type.UNION) { Schema type = AvroHelper.getSimpleUnionType(schema); if (type == null) { if (json.isNull()) { return json; } else { ObjectNode node = (ObjectNode) json; Entry<String, JsonNode> entry = node.fields().next(); for (Schema unionType : schema.getTypes()) { if (unionType.getFullName().equals(entry.getKey())) { ObjectNode newNode = factory.objectNode(); newNode.put(entry.getKey(), convertFromSimpleRecord(unionType, entry.getValue(), factory)); return newNode; } } throw new IOException("Unable to get schema for type " + entry.getKey() + " in union"); } } else if (json.isNull()) { return json; } else { ObjectNode newNode = factory.objectNode(); newNode.put(type.getFullName(), convertFromSimpleRecord(type, json, factory)); return newNode; } } else if (json.isArray() && schema.getType() == Type.ARRAY) { ArrayNode node = (ArrayNode) json; ArrayNode newNode = factory.arrayNode(); Iterator<JsonNode> iterator = node.elements(); while (iterator.hasNext()) { newNode.add(convertFromSimpleRecord(schema.getElementType(), iterator.next(), factory)); } return newNode; } else { return json; } }
From source file:me.tfeng.toolbox.avro.AvroHelper.java
private static JsonNode convertFromSimpleRecord(Schema schema, JsonNode json, JsonNodeFactory factory) throws IOException { if (json.isObject() && schema.getType() == Type.RECORD) { ObjectNode node = (ObjectNode) json; ObjectNode newNode = factory.objectNode(); for (Field field : schema.getFields()) { String fieldName = field.name(); if (node.has(fieldName)) { newNode.set(fieldName, convertFromSimpleRecord(field.schema(), node.get(fieldName), factory)); } else if (field.defaultValue() != null) { newNode.set(fieldName, MAPPER.readTree(field.defaultValue().toString())); } else { newNode.set(fieldName, factory.nullNode()); }//from w ww . j av a2 s . c o m } return newNode; } else if (json.isObject() && schema.getType() == Type.MAP) { ObjectNode node = (ObjectNode) json; ObjectNode newNode = factory.objectNode(); Schema valueType = schema.getValueType(); Iterator<Entry<String, JsonNode>> entries = node.fields(); while (entries.hasNext()) { Entry<String, JsonNode> entry = entries.next(); newNode.set(entry.getKey(), convertFromSimpleRecord(valueType, entry.getValue(), factory)); } return newNode; } else if (schema.getType() == Type.UNION) { Schema type = getSimpleUnionType(schema); if (type == null) { if (json.isNull()) { return json; } else { ObjectNode node = (ObjectNode) json; Entry<String, JsonNode> entry = node.fields().next(); for (Schema unionType : schema.getTypes()) { if (unionType.getFullName().equals(entry.getKey())) { ObjectNode newNode = factory.objectNode(); newNode.set(entry.getKey(), convertFromSimpleRecord(unionType, entry.getValue(), factory)); return newNode; } } throw new IOException("Unable to get schema for type " + entry.getKey() + " in union"); } } else if (json.isNull()) { return json; } else { ObjectNode newNode = factory.objectNode(); newNode.set(type.getFullName(), convertFromSimpleRecord(type, json, factory)); return newNode; } } else if (json.isArray() && schema.getType() == Type.ARRAY) { ArrayNode node = (ArrayNode) json; ArrayNode newNode = factory.arrayNode(); Iterator<JsonNode> iterator = node.elements(); while (iterator.hasNext()) { newNode.add(convertFromSimpleRecord(schema.getElementType(), iterator.next(), factory)); } return newNode; } else { return json; } }
From source file:com.redhat.lightblue.util.JsonDoc.java
private static JsonNode modifyObjectNode(JsonNode parentNode, JsonNode newValue, String last, Path p) { JsonNode oldValue;//from w w w . j a v a 2 s .c o m if (Util.isNumber(last)) { throw new IllegalArgumentException(UtilConstants.ERR_INVALID_INDEXED_ACCESS + p); } ObjectNode obj = (ObjectNode) parentNode; if (newValue == null) { oldValue = obj.get(last); obj.remove(last); } else { oldValue = obj.replace(last, newValue); } return oldValue; }
From source file:com.ikanow.aleph2.harvest.logstash.utils.LogstashConfigUtils.java
public static String validateLogstashInput(LogstashHarvesterConfigBean globals, String sourceKey, String config, StringBuffer errorMessage, boolean isAdmin) { _allowedInputs.addAll(Arrays.asList(globals.non_admin_inputs().toLowerCase().split("\\s*,\\s*"))); _allowedFilters.addAll(Arrays.asList(globals.non_admin_filters().toLowerCase().split("\\s*,\\s*"))); _allowedOutputs.addAll(Arrays.asList(globals.non_admin_outputs().toLowerCase().split("\\s*,\\s*"))); // Configuration validation, phase 1 errorMessage.append("Validation error:"); ObjectNode jsonifiedConfig = parseLogstashConfig(config, errorMessage); if (null == jsonifiedConfig) { return null; }/*from ww w .ja v a2s . c o m*/ errorMessage.setLength(0); // Configuration validation, phase 2 - very basic checks on the structure of the object Object input = jsonifiedConfig.get("input"); if ((null == input) || !(input instanceof ObjectNode)) { // Does input exist? errorMessage.append( "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (0)"); return null; } //TESTED (3_1d) else { // Check there's only one input type and (unless admin) it's one of the allowed types ObjectNode inputDbo = (ObjectNode) input; if (1 != inputDbo.size()) { errorMessage.append( "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (1)"); return null; } //TESTED if (!isAdmin) { for (String key : (Iterable<String>) () -> inputDbo.fieldNames()) { if (!_allowedInputs.contains(key.toLowerCase())) { errorMessage.append("Security error, non-admin not allowed input type " + key + ", allowed options: " + _allowedInputs.toString()); return null; } //TESTED } } //TESTED (3_1abc) } Object filter = jsonifiedConfig.get("filter"); if ((null == filter) || !(filter instanceof ObjectNode)) { // Does filter exist? errorMessage.append( "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (2)"); return null; } //TESTED (3_2d) else { // Check there's only one input type and (unless admin) it's one of the allowed types if (!isAdmin) { ObjectNode filterDbo = (ObjectNode) filter; for (String key : (Iterable<String>) () -> filterDbo.fieldNames()) { if (!_allowedFilters.contains(key.toLowerCase())) { errorMessage.append("Security error, non-admin not allowed filter type " + key + ", allowed options: " + _allowedFilters.toString()); return null; } //TESTED } } //TESTED (3_2abc) } //TODO: same for output // Configuration validation, phase 3 Matcher m = null; m = _validationRegexInputReplace.matcher(config); if (!m.find()) { errorMessage.append( "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (3)"); return null; } //TESTED (see above) else { // If admin check on allowed types String inputType = m.group(2).toLowerCase(); // If it's a file-based plugin then replace sincedb_path (check that it's not used during the JSON-ification): if (inputType.equalsIgnoreCase("file")) { config = _validationRegexInputReplace.matcher(config) .replaceFirst("$1\n sincedb_path => \"_XXX_DOTSINCEDB_XXX_\"\n"); } else if (inputType.equalsIgnoreCase("s3")) { config = _validationRegexInputReplace.matcher(config).replaceFirst( "$1\n sincedb_path => \"_XXX_DOTSINCEDB_XXX_\"\n temporary_directory => \"_XXX_LSTEMPDIR_XXX_\""); } } //TESTED m = _validationRegexNoSourceKey.matcher(config); // (this won't help malicious changes to source key, but will let people know they're not supposed to) if (m.find()) { errorMessage.append( "Not allowed to reference sourceKey - this is automatically appended by the logstash harvester"); return null; } //TESTED // OK now need to append the sourceKey at each stage of the pipeline to really really ensure that nobody sets sourceKey to be different m = _validationRegexAppendFields.matcher(config); StringBuffer newConfig = new StringBuffer(); if (m.find()) { m.appendReplacement(newConfig, "add_field => [ \"[@metadata][sourceKey]\", \"" + sourceKey + "\"] \n\n" + m.group() + " \n if [@metadata][sourceKey] == \"" + sourceKey + "\" { \n\n "); } else { errorMessage.append( "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (4)"); return null; } m.appendTail(newConfig); config = newConfig.toString(); config = config.replaceAll("}[^}]*$", ""); // (remove the last }) config += "\n\n mutate { update => [ \"[@metadata][sourceKey]\", \"" + sourceKey + "\"] } \n}\n}\n"; // double check the sourceKey hasn't been overwritten and close the if from above //TESTED (syntactically correct and does overwrite sourceKey everywhere - success_2_2) return config; }
From source file:org.dswarm.wikidataimporter.WikibaseAPIClient.java
public static String getToken(final Response loginResponse) { try {//from w ww. j a v a2 s .com final String responseBody = loginResponse.readEntity(String.class); if (responseBody == null) { LOG.error("cannot extract token - response body is not available"); return null; } final ObjectNode json = MAPPER.readValue(responseBody, ObjectNode.class); if (json == null) { LOG.error("cannot extract token - response JSON is not available"); return null; } final JsonNode loginNode = json.get(MEDIAWIKI_API_LOGIN); if (loginNode == null) { LOG.error("cannot extract token - '{}' node is not available in response JSON '{}'", MEDIAWIKI_API_LOGIN, responseBody); return null; } final JsonNode tokenNode = loginNode.get(MEDIAWIKI_API_TOKEN_IDENTIFIER); if (tokenNode == null) { LOG.error("cannot extract token - '{}' node is not available in response JSON '{}'", MEDIAWIKI_API_TOKEN_IDENTIFIER, responseBody); return null; } return tokenNode.asText(); } catch (final Exception e) { LOG.error( "cannot extract token - an error occurred while trying to extract the token from the response body", e); return null; } }
From source file:org.dswarm.wikidataimporter.WikibaseAPIClient.java
public static String getEditToken(final Response editTokenResponse) { try {//from ww w.java 2 s . c o m final String responseBody = editTokenResponse.readEntity(String.class); if (responseBody == null) { LOG.error("cannot extract edit token - response body is not available"); return null; } final ObjectNode json = MAPPER.readValue(responseBody, ObjectNode.class); if (json == null) { LOG.error("cannot extract edit token - response JSON is not available"); return null; } final JsonNode queryNode = json.get(MEDIAWIKI_API_QUERY); if (queryNode == null) { LOG.error("cannot extract edit token - '{}' node is not available in response JSON '{}'", MEDIAWIKI_API_QUERY, responseBody); return null; } final JsonNode tokensNode = queryNode.get(MEDIAWIKI_API_TOKENS_IDENTIFIER); if (tokensNode == null) { LOG.error("cannot extract edit token - '{}' node is not available in response JSON '{}'", MEDIAWIKI_API_TOKENS_IDENTIFIER, responseBody); return null; } final JsonNode csrfTokenNode = tokensNode.get(MEDIAWIKI_API_CSRFTOKEN_IDENTIFIER); if (csrfTokenNode == null) { LOG.error("cannot extract edit token - '{}' node is not available in response JSON '{}'", MEDIAWIKI_API_CSRFTOKEN_IDENTIFIER, responseBody); return null; } return csrfTokenNode.asText(); } catch (final Exception e) { LOG.error( "cannot extract edit token - an error occurred while trying to extract the edit token from the response body", e); return null; } }
From source file:mobile.service.RNSService.java
private static ServiceResult createOrUpdateRequire(ObjectNode data, ObjectNodeResult returnRawResult) { if (data.hasNonNull("id")) { Long id = data.get("id").asLong(); Require require = Require.queryRequireById(id); if (null == require) { return ServiceResult.error("1007", "?"); }/*from w w w .jav a 2 s . co m*/ } if ("-1".equals(data.path("budget").asText())) { data.put("budget", ""); } ObjectNodeResult objectNodeResult = RequireService.createOrUpdateService(MobileUtil.getCurrentUser(), data); if (null != returnRawResult) { returnRawResult.setAll(objectNodeResult.getObjectNode()); } // ? if (!objectNodeResult.isSuccess()) { if ("700002".equals(objectNodeResult.getErrorCode())) { return ServiceResult.error("1001", objectNodeResult.getError()); } else if ("-301".equals(objectNodeResult.getErrorCode())) { return ServiceResult.error("1003", "??"); } Logger.error(objectNodeResult.getObjectNode().toString()); return ServiceResult.error("100001", ""); } return ServiceResult.success(); }
From source file:mobile.service.RNSService.java
private static ServiceResult createOrUpdateService(ObjectNode data, ObjectNodeResult returnRawResult) { if (data.hasNonNull("id")) { Long id = data.get("id").asLong(); Service service = Service.queryServiceById(id); if (null == service) { return ServiceResult.error("1008", "??"); }//from w ww . j av a 2s .c o m } if ("-1".equals(data.path("price").asText())) { data.put("price", ""); } ObjectNodeResult objectNodeResult = ServicesService.createOrUpdateService(MobileUtil.getCurrentUser(), data); if (null != returnRawResult) { returnRawResult.setAll(objectNodeResult.getObjectNode()); } // ? if (!objectNodeResult.isSuccess()) { if ("800002".equals(objectNodeResult.getErrorCode())) { return ServiceResult.error("1001", objectNodeResult.getError()); } else if ("-301".equals(objectNodeResult.getErrorCode())) { return ServiceResult.error("1004", "???"); } Logger.error(objectNodeResult.getObjectNode().toString()); return ServiceResult.error("100001", ""); } return ServiceResult.success(); }
From source file:com.pros.jsontransform.expression.FunctionAbstract.java
static JsonNode transformArgument(final JsonNode argumentNode, final ObjectTransformer transformer) throws ObjectTransformerException { ObjectNode resultNode = transformer.mapper.createObjectNode(); if (argumentNode.isContainerNode()) { // transform argument node JsonNode sourceNode = transformer.getSourceNode(); JsonNode valueNode = transformer.transformExpression(sourceNode, argumentNode); resultNode.put("result", valueNode); } else if (argumentNode.isTextual()) { // transform $i modifier String textValue = argumentNode.textValue(); if (textValue.contains($I)) { int arrayIndex = transformer.getIndexOfSourceArray(); textValue = textValue.replace($I, String.valueOf(arrayIndex)); }/*from w ww . j a v a 2 s . c o m*/ resultNode.put("result", textValue); } else { resultNode.put("result", argumentNode); } return resultNode.get("result"); }
From source file:io.coala.enterprise.Fact.java
/** * override and deserialize bean properties as declared in factType * <p>//from w w w . ja v a 2s . co m * TODO detect properties from builder methods: {@code withKey(T value)} * * @param om * @param json * @param factType * @param properties * @return the properties again, to allow chaining * @throws IntrospectionException */ static <T extends Fact> Map<String, Object> fromJSON(final ObjectMapper om, final TreeNode json, final Class<T> factType, final Map<String, Object> properties) { try { final ObjectNode tree = (ObjectNode) json; final BeanInfo beanInfo = Introspector.getBeanInfo(factType); for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) if (tree.has(pd.getName())) properties.computeIfPresent(pd.getName(), (property, current) -> JsonUtil.valueOf(om, tree.get(property), pd.getPropertyType())); return properties; } catch (final Throwable e) { return Thrower.rethrowUnchecked(e); } }