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.openecomp.mso.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;
39 private JsonPathUtil() {
40 conf = Configuration.defaultConfiguration().jsonProvider(new JacksonJsonNodeJsonProvider()).addOptions(Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS);
43 private static class Helper {
44 private static final JsonPathUtil INSTANCE = new JsonPathUtil();
47 public static JsonPathUtil getInstance() {
48 return Helper.INSTANCE;
50 public boolean pathExists(String json, String jsonPath) {
51 return JsonPath.using(conf).parse(json).<ArrayNode>read(jsonPath).size() != 0;
54 public Optional<String> locateResult(String json, String jsonPath) {
55 final ArrayNode result = JsonPath.using(conf).parse(json).read(jsonPath);
56 if (result.size() == 0) {
57 return Optional.empty();
59 if (result.get(0).isValueNode()) {
60 return Optional.of(result.get(0).asText());
62 return Optional.of(result.get(0).toString());
68 public List<String> locateResultList(String json, String jsonPath) {
69 final ArrayNode resultNodes = JsonPath.using(conf).parse(json).read(jsonPath);
70 final ArrayList<String> result = new ArrayList<>();
72 for (JsonNode node : resultNodes) {
73 if (node.isValueNode()) {
74 result.add(node.asText());
76 result.add(node.toString());