View Javadoc
1   /*
2    * Copyright 2001-2010 The Apache Software Foundation.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *
16   */
17  package org.apache.juddi.v3.client.config;
18  
19  import java.util.Properties;
20  import java.util.regex.Matcher;
21  import java.util.regex.Pattern;
22  
23  import org.apache.commons.logging.Log;
24  import org.apache.commons.logging.LogFactory;
25  
26  public class TokenResolver {
27  	
28  	private static Log log = LogFactory.getLog(TokenResolver.class);
29  	
30  	public synchronized static String replaceTokens(String string, Properties properties) {
31      	
32      	if (properties==null || string==null) return string;
33      	string = string.replaceAll("\\n"," ").replaceAll("\\r", "").replaceAll(" ","");
34  		/* pattern that is multi-line (?m), and looks for a pattern of
35  		 * ${token}, in a 'reluctant' manner, by using the ? to 
36  		 * make sure we find ALL the tokens.
37  		 */
38  		Pattern pattern = Pattern.compile("(?m)\\$\\{.*?\\}");
39          Matcher matcher = pattern.matcher(string);
40          while (matcher.find()) {
41              String token = matcher.group();
42              token = token.substring(2,token.length()-1);
43              String replacement = properties.getProperty(token);
44              if (replacement!=null) {
45              	log.debug("Found token " + token + " and replacement value " + replacement);
46              	string = string.replaceAll("\\$\\{" + token + "\\}", replacement);
47              } else {
48              	log.error("Found token " + token + " but could not obtain its value. Data: " + string);
49              }
50          }
51          log.debug("Data after token replacement: " + string);
52          return string;
53  	}
54  }