2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021 Nordix Foundation
4 * Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.cps.spi.query;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25 import lombok.AccessLevel;
28 import org.onap.cps.spi.exceptions.CpsPathException;
31 @Setter(AccessLevel.PRIVATE)
32 public class CpsPathQuery {
34 private String xpathPrefix;
35 private String leafName;
36 private Object leafValue;
38 public static final Pattern QUERY_CPS_PATH_WITH_SINGLE_LEAF_PATTERN =
39 Pattern.compile("(.*)\\[\\s*@(.*?)\\s*=\\s*(.*?)\\s*]");
41 public static final Pattern LEAF_STRING_VALUE_PATTERN = Pattern.compile("['\"](.*)['\"]");
43 public static final Pattern LEAF_INTEGER_VALUE_PATTERN = Pattern.compile("[-+]?\\d+");
46 * Returns a xpath prefix, leaf name and leaf value for the given cps path.
48 * @param cpsPath cps path
49 * @return a CpsPath object containing the xpath prefix, leaf name and leaf value.
51 public static CpsPathQuery createFrom(final String cpsPath) {
52 final Matcher matcher = QUERY_CPS_PATH_WITH_SINGLE_LEAF_PATTERN.matcher(cpsPath);
53 if (matcher.matches()) {
54 final CpsPathQuery cpsPathQuery = new CpsPathQuery();
55 cpsPathQuery.setXpathPrefix(matcher.group(1));
56 cpsPathQuery.setLeafName(matcher.group(2));
57 cpsPathQuery.setLeafValue(convertLeafValueToCorrectType(matcher.group(3)));
60 throw new CpsPathException("Invalid cps path.",
61 String.format("Cannot interpret or parse cps path %s.", cpsPath));
64 private static Object convertLeafValueToCorrectType(final String leafValueString) {
65 final Matcher stringValueWithQuotesMatcher = LEAF_STRING_VALUE_PATTERN.matcher(leafValueString);
66 if (stringValueWithQuotesMatcher.matches()) {
67 return stringValueWithQuotesMatcher.group(1);
69 final Matcher integerValueMatcher = LEAF_INTEGER_VALUE_PATTERN.matcher(leafValueString);
70 if (integerValueMatcher.matches()) {
71 return Integer.valueOf(leafValueString);
73 throw new CpsPathException("Unsupported leaf value.",
74 String.format("Unsupported leaf value %s in cps path.", leafValueString));