2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright (C) 2017 Amdocs
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
20 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.openecomp.appc.util;
25 import org.apache.commons.lang3.StringUtils;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
32 public class MessageFormatter {
33 private final static String paramNameRegexGroupName = "paramName";
34 private final static String paramRegex = "\\$\\{(?<paramName>[^}$]+)\\}"; //start with ${ and after there is one or more characters that are not $ and not } and ended with }
37 public static String format(String messageTemplate, Map<String,Object> params) {
38 if (StringUtils.isEmpty(messageTemplate))
40 if (params == null || params.isEmpty())
41 return messageTemplate;
43 String formattedMessage = messageTemplate;
44 if (formattedMessage.contains("$")) {
45 for (Map.Entry<String, Object> entry : params.entrySet()) {
46 formattedMessage = formattedMessage.replaceAll("\\$\\{" + entry.getKey() + "\\}", String.valueOf(entry.getValue()));
50 return formattedMessage;
53 public static List<String> getParamsNamesList(String messageTemplate) {
54 List<String> paramsNames = null;
55 if(!StringUtils.isEmpty(messageTemplate)){
56 paramsNames = new ArrayList<String>();
57 Matcher m = Pattern.compile(paramRegex).matcher(messageTemplate);
59 String paramName = m.group(paramNameRegexGroupName);
60 paramsNames.add(paramName);
65 public static Set<String> getParamsNamesSet(String messageTemplate) {
66 List<String> paramsNamesList = getParamsNamesList(messageTemplate);
67 Set<String> paramsNamesSet = null;
68 if(paramsNamesList != null && !paramsNamesList.isEmpty()){
69 paramsNamesSet = new HashSet<String>();
70 for(String paramName : paramsNamesList){
71 paramsNamesSet.add(paramName);
74 return paramsNamesSet;