Java Code Examples for com.fasterxml.jackson.databind.JsonNode#at()

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#at() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonReader.java    From tablesaw with Apache License 2.0 6 votes vote down vote up
@Override
public Table read(JsonReadOptions options) throws IOException {
  JsonNode jsonObj = mapper.readTree(options.source().createReader(null));
  if (options.path() != null) {
    jsonObj = jsonObj.at(options.path());
  }
  if (!jsonObj.isArray()) {
    throw new IllegalStateException(
        "Only reading a JSON array is currently supported. The array must hold an array or object for each row.");
  }
  if (jsonObj.size() == 0) {
    return Table.create(options.tableName());
  }

  JsonNode firstNode = jsonObj.get(0);
  if (firstNode.isArray()) {
    return convertArrayOfArrays(jsonObj, options);
  }
  return convertArrayOfObjects(jsonObj, options);
}
 
Example 2
Source File: RemoveIfExistsOperation.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Override
JsonNode apply(final JsonNode node) {
    if (path.toString().isEmpty()) {
        return MissingNode.getInstance();
    }

    final JsonNode found = node.at(path);
    if (found.isMissingNode()) {
        return node;
    }

    final JsonNode parentNode = node.at(path.head());
    final String raw = path.last().getMatchingProperty();
    if (parentNode.isObject()) {
        ((ObjectNode) parentNode).remove(raw);
    } else if (parentNode.isArray()) {
        ((ArrayNode) parentNode).remove(Integer.parseInt(raw));
    }
    return node;
}
 
Example 3
Source File: AddOperation.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
static JsonNode addToArray(final JsonPointer path, final JsonNode node, final JsonNode value) {
    final ArrayNode target = (ArrayNode) node.at(path.head());
    final String rawToken = path.last().getMatchingProperty();

    if (rawToken.equals(LAST_ARRAY_ELEMENT)) {
        target.add(value);
        return node;
    }

    final int size = target.size();
    final int index;
    try {
        index = Integer.parseInt(rawToken);
    } catch (NumberFormatException ignored) {
        throw new JsonPatchException("not an index: " + rawToken + " (expected: a non-negative integer)");
    }

    if (index < 0 || index > size) {
        throw new JsonPatchException("index out of bounds: " + index +
                                     " (expected: >= 0 && <= " + size + ')');
    }

    target.insert(index, value);
    return node;
}
 
Example 4
Source File: DefaultWorkplaceDescription.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Creating workplace description from json tree.
 * @param root root node for workplace description
 * @return workplace description
 * @throws WorkflowException workflow exception
 */
public static DefaultWorkplaceDescription valueOf(JsonNode root) throws WorkflowException {

    JsonNode node = root.at(ptr(WP_NAME));
    if (!(node instanceof TextNode)) {
        throw new WorkflowException("invalid workplace name for " + root);
    }

    Builder builder = builder()
        .name(node.asText());

    node = root.at(ptr(WP_DATA));
    if (node != null && !(node instanceof MissingNode)) {
        if (!(node instanceof ObjectNode) && !(node instanceof ArrayNode)) {
            throw new WorkflowException("invalid workplace data for " + root);
        }
        builder.data(node);
    }

    return builder.build();
}
 
Example 5
Source File: JSONUtils.java    From SkaETL with Apache License 2.0 5 votes vote down vote up
public void put(JsonNode jsonNode, String path, JsonNode value) {
    JsonPointer valueNodePointer = JsonPointer.compile(asJsonPath(path));
    JsonPointer parentPointer = valueNodePointer.head();
    addMissingNodeIfNecessary(jsonNode, path);
    JsonNode parentNode = jsonNode.at(parentPointer);

    if (parentNode.getNodeType() == JsonNodeType.OBJECT) {
        ObjectNode parentNodeToUpdate = (ObjectNode) parentNode;
        parentNodeToUpdate.set(StringUtils.replace(valueNodePointer.last().toString(),"/", ""), value);
    }
}
 
Example 6
Source File: JSONUtils.java    From SkaETL with Apache License 2.0 5 votes vote down vote up
public void remove(JsonNode jsonNode, String path) {
    JsonPointer valueNodePointer = JsonPointer.compile(asJsonPath(path));
    JsonPointer parentPointer = valueNodePointer.head();
    JsonNode parentNode = jsonNode.at(parentPointer);
    if (parentNode.getNodeType() == JsonNodeType.OBJECT) {
        ObjectNode parentNodeToUpdate = (ObjectNode) parentNode;
        parentNodeToUpdate.remove(StringUtils.replace(valueNodePointer.last().toString(),"/",""));
    }

}
 
Example 7
Source File: JsonPointerBasedInboundEventKeyDetector.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public String detectEventDefinitionKey(JsonNode event) {
    JsonNode result = event.at(jsonPointerExpression);

    if (result == null || result.isMissingNode() || result.isNull()) {
        LOGGER.warn("JsonPointer expression {} did not detect event key", jsonPointerExpression);
        return null;
    }

    if (result.isTextual()) {
        return result.asText();
    }

    return null;
}
 
Example 8
Source File: LDJsonParseFilter.java    From storm-crawler with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(String URL, byte[] content, DocumentFragment doc,
        ParseResult parse) {
    if (doc == null) {
        return;
    }
    try {
        JsonNode json = filterJson(doc);
        if (json == null) {
            return;
        }

        ParseData parseData = parse.get(URL);
        Metadata metadata = parseData.getMetadata();

        // extract patterns and store as metadata
        for (LabelledJsonPointer expression : expressions) {
            JsonNode match = json.at(expression.pointer);
            if (match.isMissingNode()) {
                continue;
            }
            metadata.addValue(expression.label, match.asText());
        }

    } catch (Exception e) {
        LOG.error("Exception caught when extracting json", e);
    }

}
 
Example 9
Source File: JsonReference.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the node that is referenced by this reference.
 * 
 * If the resolution of the referenced node fails, this method returns null. If the pointer does not points to an
 * existing node, this method will return a missing node (see JsonNode.isMissingNode()).
 * 
 * @param document
 * @param baseURI
 * @return referenced node
 */
public JsonNode resolve(JsonDocument document, URI baseURI) {
    if (resolved == null) {
        JsonNode doc = getDocument(document, baseURI);
        if (doc != null) {
            try {
                resolved = doc.at(pointer);
            } catch (Exception e) {
                resolved = null;
            }
        }
    }

    return resolved;
}
 
Example 10
Source File: SshAccessInfo.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Builds SshAccessInfo from json.
 * @param root json root node for SshAccessinfo
 * @return SSH access information
 * @throws WorkflowException workflow exception
 */
public static SshAccessInfo valueOf(JsonNode root) throws WorkflowException {

    JsonNode node = root.at(ptr(REMOTE_IP));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid remoteIp for " + root);
    }
    IpAddress sshIp = IpAddress.valueOf(node.asText());

    node = root.at(ptr(PORT));
    if (node == null || !(node instanceof NumericNode)) {
        throw new WorkflowException("invalid port for " + root);
    }
    TpPort sshPort = TpPort.tpPort(node.asInt());

    node = root.at(ptr(USER));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid user for " + root);
    }
    String sshUser = node.asText();

    node = root.at(ptr(PASSWORD));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid password for " + root);
    }
    String sshPassword = node.asText();

    node = root.at(ptr(KEYFILE));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid keyfile for " + root);
    }
    String sshKeyfile = node.asText();

    return new SshAccessInfo(sshIp, sshPort, sshUser, sshPassword, sshKeyfile);
}
 
Example 11
Source File: LinkedInAuthFilter.java    From para with Apache License 2.0 5 votes vote down vote up
private String getFullName(JsonNode profileNode) {
	JsonNode fNameNode = profileNode.at("/firstName/localized");
	JsonNode lNameNode = profileNode.at("/lastName/localized");
	String fName = fNameNode.elements().hasNext() ? fNameNode.elements().next().textValue() : "";
	String lName = lNameNode.elements().hasNext() ? lNameNode.elements().next().textValue() : "";
	return (fName + " " + lName).trim();
}
 
Example 12
Source File: JsonPatchOperation.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
JsonNode ensureExistence(JsonNode node) {
    final JsonNode found = node.at(path);
    if (found.isMissingNode()) {
        throw new JsonPatchException("non-existent path: " + path);
    }
    return found;
}
 
Example 13
Source File: SampleWorkflow.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Allocates or gets data model.
 *
 * @param context workflow context
 * @return json object node
 * @throws WorkflowException workflow exception
 */
protected ObjectNode allocOrGetModel(WorkflowContext context) throws WorkflowException {

    JsonDataModelTree tree = (JsonDataModelTree) context.data();
    JsonNode params = tree.root();

    if (params.at(MODEL_SAMPLE_JOB).getNodeType() == JsonNodeType.MISSING) {
        tree.alloc(MODEL_SAMPLE_JOB, DataModelTree.Nodetype.MAP);
    }
    return (ObjectNode) params.at(MODEL_SAMPLE_JOB);
}
 
Example 14
Source File: DafPreStandardization.java    From daf-kylo with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This method is public to be testable
 * @param mapper
 * @param root
 * @return
 */
public static Stream<FlatSchema> getFlatSchema(ObjectMapper mapper, JsonNode root) {
    final JsonNode list = root.at("/dataschema/flatSchema");

    return StreamSupport.stream(list.spliterator(), false)
            .map(n -> {
                try {
                    return mapper.treeToValue(n, FlatSchema.class);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                    return null;
                }
            })
            .filter(Objects::nonNull);
}
 
Example 15
Source File: JSONUtils.java    From SkaETL with Apache License 2.0 4 votes vote down vote up
public JsonNode at(JsonNode jsonNode, String path) {
    String jsonPath = asJsonPath(path);
    return jsonNode.at(jsonPath);
}
 
Example 16
Source File: JSONUtils.java    From SkaETL with Apache License 2.0 4 votes vote down vote up
public boolean has(JsonNode jsonNode, String path) {
    String jsonPath = asJsonPath(path);
    JsonNode targetNode = jsonNode.at(jsonPath);
    return targetNode != null && targetNode.getNodeType() != JsonNodeType.NULL && targetNode.getNodeType() != JsonNodeType.MISSING;
}
 
Example 17
Source File: FFmpegParser.java    From airsonic with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Parses meta data for the given music file. No guessing or reformatting is done.
 *
 *
 * @param file The music file to parse.
 * @return Meta data for the file.
 */
@Override
public MetaData getRawMetaData(File file) {

    MetaData metaData = new MetaData();

    try {
        // Use `ffprobe` in the transcode directory if it exists, otherwise let the system sort it out.
        String ffprobe;
        File inTranscodeDirectory = new File(transcodingService.getTranscodeDirectory(), "ffprobe");
        if (inTranscodeDirectory.exists()) {
            ffprobe = inTranscodeDirectory.getAbsolutePath();
        } else {
            ffprobe = "ffprobe";
        }

        List<String> command = new ArrayList<>();
        command.add(ffprobe);
        command.addAll(Arrays.asList(FFPROBE_OPTIONS));
        command.add(file.getAbsolutePath());

        Process process = Runtime.getRuntime().exec(command.toArray(new String[0]));
        final JsonNode result = objectMapper.readTree(process.getInputStream());

        metaData.setDurationSeconds(result.at("/format/duration").asInt());
        // Bitrate is in Kb/s
        metaData.setBitRate(result.at("/format/bit_rate").asInt() / 1000);

        // Find the first (if any) stream that has dimensions and use those.
        // 'width' and 'height' are display dimensions; compare to 'coded_width', 'coded_height'.
        for (JsonNode stream : result.at("/streams")) {
            if (stream.has("width") && stream.has("height")) {
                metaData.setWidth(stream.get("width").asInt());
                metaData.setHeight(stream.get("height").asInt());
                break;
            }
        }
    } catch (Throwable x) {
        LOG.warn("Error when parsing metadata in " + file, x);
    }

    return metaData;
}
 
Example 18
Source File: FFmpegParser.java    From airsonic-advanced with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Parses meta data for the given music file. No guessing or reformatting is done.
 *
 *
 * @param file The music file to parse.
 * @return Meta data for the file.
 */
@Override
public MetaData getRawMetaData(Path file) {

    MetaData metaData = new MetaData();

    try {
        // Use `ffprobe` in the transcode directory if it exists, otherwise let the system sort it out.
        String ffprobe;
        Path inTranscodeDirectory = Util.isWindows() ?
            transcodingService.getTranscodeDirectory().resolve("ffprobe.exe") :
            transcodingService.getTranscodeDirectory().resolve("ffprobe");
        if (Files.exists(inTranscodeDirectory)) {
            ffprobe = inTranscodeDirectory.toAbsolutePath().toString();
        } else {
            ffprobe = "ffprobe";
        }

        List<String> command = new ArrayList<>();
        command.add(ffprobe);
        command.addAll(Arrays.asList(FFPROBE_OPTIONS));
        command.add(file.toAbsolutePath().toString());

        Process process = Runtime.getRuntime().exec(command.toArray(new String[0]));
        final JsonNode result = objectMapper.readTree(process.getInputStream());

        metaData.setDuration(result.at("/format/duration").asDouble());
        // Bitrate is in Kb/s
        metaData.setBitRate(result.at("/format/bit_rate").asInt() / 1000);

        // Find the first (if any) stream that has dimensions and use those.
        // 'width' and 'height' are display dimensions; compare to 'coded_width', 'coded_height'.
        for (JsonNode stream : result.at("/streams")) {
            if (stream.has("width") && stream.has("height")) {
                metaData.setWidth(stream.get("width").asInt());
                metaData.setHeight(stream.get("height").asInt());
                break;
            }
        }
    } catch (Throwable x) {
        LOG.warn("Error when parsing metadata in " + file, x);
    }

    return metaData;
}
 
Example 19
Source File: DafPreStandardization.java    From daf-kylo with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * This method is public to be testable
 * @param root
 * @return
 */
public static String getPhysicalUri(ObjectMapper mapper, JsonNode root) throws IOException {
    final JsonNode node = root.at("/operational/physical_uri");
    if (node.isMissingNode()) throw new NullPointerException("missing value for /operational/physical_uri");
    return node.textValue();
}
 
Example 20
Source File: JsonTemplateLayoutTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private static JsonNode point(final JsonNode node, final Object... fields) {
    final String pointer = createJsonPointer(fields);
    return node.at(pointer);
}