2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.so.jsonpath;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Optional;
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.node.ArrayNode;
29 import com.jayway.jsonpath.Configuration;
30 import com.jayway.jsonpath.JsonPath;
31 import com.jayway.jsonpath.Option;
32 import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
34 public class JsonPathUtil {
37 private final Configuration conf;
38 private final Configuration pathListConf;
39 private JsonPathUtil() {
40 conf = Configuration.defaultConfiguration().jsonProvider(new JacksonJsonNodeJsonProvider()).addOptions(Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS);
41 pathListConf = Configuration.defaultConfiguration().addOptions(Option.AS_PATH_LIST, Option.SUPPRESS_EXCEPTIONS,Option.ALWAYS_RETURN_LIST);
44 private static class Helper {
45 private static final JsonPathUtil INSTANCE = new JsonPathUtil();
48 public static JsonPathUtil getInstance() {
49 return Helper.INSTANCE;
51 public boolean pathExists(String json, String jsonPath) {
52 return JsonPath.using(conf).parse(json).<ArrayNode>read(jsonPath).size() != 0;
55 public Optional<String> locateResult(String json, String jsonPath) {
56 final ArrayNode result = JsonPath.using(conf).parse(json).read(jsonPath);
57 if (result.size() == 0) {
58 return Optional.empty();
60 if (result.get(0).isValueNode()) {
61 return Optional.of(result.get(0).asText());
63 return Optional.of(result.get(0).toString());
69 public List<String> locateResultList(String json, String jsonPath) {
70 final ArrayNode resultNodes = JsonPath.using(conf).parse(json).read(jsonPath);
71 final ArrayList<String> result = new ArrayList<>();
73 for (JsonNode node : resultNodes) {
74 if (node.isValueNode()) {
75 result.add(node.asText());
77 result.add(node.toString());
84 public List<String> getPathList(String json, String jsonPath) {
85 return JsonPath.using(pathListConf).parse(json).read(jsonPath);