Replaced all tabs with spaces in java and pom.xml
[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 one variable, for example "${x}".
29  *
30  * Ignores all whitespaces, except inside variable name.
31  *
32  * Examples: "${x}", extracted variable name is "x" " ${\t weird_NAME }", extracted variable name is "weird_NAME"
33  * "${incorrect name}", no extracted name "${two}+${two}", no extracted name
34  */
35 public class VariableNameExtractor {
36
37     private static final Pattern VARIABLE_NAME_PATTERN =
38             Pattern.compile("^\\s*\\$\\s*\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\s*$");
39
40     private final String expression;
41
42
43     /**
44      * Creates new VariableNameExtractor
45      * 
46      * @param expression expression to be parsed
47      */
48     public VariableNameExtractor(String expression) {
49         this.expression = expression;
50     }
51
52     /**
53      * Extracts variable name from expression given in constructor
54      * 
55      * @return Optional of variable name, empty if expression wasn't single variable
56      */
57     public Optional<String> extract() {
58         Matcher matcher = VARIABLE_NAME_PATTERN.matcher(expression);
59         if (!matcher.matches()) {
60             return Optional.empty();
61         }
62         return Optional.of(matcher.group(1));
63     }
64
65 }