f63ab3149666b0960ecd618f69462f731dfaa2ff
[so.git] / bpmn / MSOCoreBPMN / src / main / java / org / onap / so / bpmn / core / internal / VariableNameExtractor.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.so.bpmn.core.internal;
22
23 import java.util.Optional;
24 import java.util.regex.Matcher;
25 import java.util.regex.Pattern;
26
27 /**
28  * Extracts variable name from expression if entire expression is just
29  * one variable, for example "${x}".
30  *
31  * Ignores all whitespaces, except inside variable name.
32  *
33  * Examples:
34  * "${x}", extracted variable name is "x"
35  * " ${\t weird_NAME    }", extracted variable name is "weird_NAME"
36  * "${incorrect name}", no extracted name
37  * "${two}+${two}", no extracted name
38  */
39 public class VariableNameExtractor {
40
41     private static final Pattern VARIABLE_NAME_PATTERN = Pattern
42             .compile("^\\s*\\$\\s*\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\s*$");
43
44     private final String expression;
45
46
47     /**
48      * Creates new VariableNameExtractor
49      * @param expression expression to be parsed
50      */
51     public VariableNameExtractor(String expression) {
52         this.expression = expression;
53     }
54
55     /**
56      * Extracts variable name from expression given in constructor
57      * @return Optional of variable name, empty if expression wasn't single variable
58      */
59     public Optional<String> extract() {
60         Matcher matcher = VARIABLE_NAME_PATTERN.matcher(expression);
61         if (!matcher.matches()) {
62             return Optional.empty();
63         }
64         return Optional.of(matcher.group(1));
65     }
66
67 }