org.openrewrite.json.JsonPathMatcher Maven / Gradle / Ivy
Show all versions of rewrite-json Show documentation
/*
* Copyright 2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.json;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.openrewrite.Cursor;
import org.openrewrite.Tree;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.json.internal.grammar.JsonPath;
import org.openrewrite.json.internal.grammar.JsonPathBaseVisitor;
import org.openrewrite.json.internal.grammar.JsonPathLexer;
import org.openrewrite.json.internal.grammar.JsonPathVisitor;
import org.openrewrite.json.tree.Json;
import org.openrewrite.json.tree.JsonValue;
import java.util.*;
import java.util.function.BiPredicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static java.util.Collections.disjoint;
/**
* Provides methods for matching the given cursor location to a specified JsonPath expression.
*
* This is not a full implementation of the JsonPath syntax as linked in the "see also."
*
* @see https://support.smartbear.com/alertsite/docs/monitors/api/endpoint/jsonpath.html
*/
public class JsonPathMatcher {
private final String jsonPath;
public JsonPathMatcher(String jsonPath) {
this.jsonPath = jsonPath;
}
public Optional find(Cursor cursor) {
LinkedList cursorPath = cursor.getPathAsStream()
.filter(o -> o instanceof Tree)
.map(Tree.class::cast)
.collect(Collectors.toCollection(LinkedList::new));
if (cursorPath.isEmpty()) {
return Optional.empty();
}
Collections.reverse(cursorPath);
Tree start;
if (jsonPath.startsWith(".") && !jsonPath.startsWith("..")) {
start = cursor.getValue();
} else {
start = cursorPath.peekFirst();
}
@SuppressWarnings("ConstantConditions") JsonPathVisitor