2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ============LICENSE_END=========================================================
24 package org.onap.appc.util;
26 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";
36 * start with ${ and after there is one or more characters that are not $ and not } and ended with }
38 private final static String paramRegex = "\\$\\{(?<paramName>[^}$]+)\\}";
40 public static String format(String messageTemplate, Map<String, Object> params) {
41 if (StringUtils.isEmpty(messageTemplate))
43 if (params == null || params.isEmpty())
44 return messageTemplate;
46 String formattedMessage = messageTemplate;
47 if (formattedMessage.contains("$")) {
48 for (Map.Entry<String, Object> entry : params.entrySet()) {
49 formattedMessage = formattedMessage.replaceAll("\\$\\{" + entry.getKey() + "\\}",
50 escapeDollarChar(String.valueOf(entry.getValue())));
54 return formattedMessage;
57 private static String escapeDollarChar(String msg) {
58 String formatedMsg = msg;
59 if (formatedMsg.contains("$")) {
60 formatedMsg = formatedMsg.replaceAll("\\$", "\\\\\\$");
66 public static List<String> getParamsNamesList(String messageTemplate) {
67 List<String> paramsNames = null;
68 if (!StringUtils.isEmpty(messageTemplate)) {
69 paramsNames = new ArrayList<>();
70 Matcher m = Pattern.compile(paramRegex).matcher(messageTemplate);
72 String paramName = m.group(paramNameRegexGroupName);
73 paramsNames.add(paramName);
79 public static Set<String> getParamsNamesSet(String messageTemplate) {
80 List<String> paramsNamesList = getParamsNamesList(messageTemplate);
81 Set<String> paramsNamesSet = null;
82 if (paramsNamesList != null && !paramsNamesList.isEmpty()) {
83 paramsNamesSet = new HashSet<String>();
84 for (String paramName : paramsNamesList) {
85 paramsNamesSet.add(paramName);
88 return paramsNamesSet;