View Javadoc
1   package net.sf.logdistiller.util;
2   
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  import java.util.Map;
18  
19  /**
20   * A small utility to replace properties within strings (syntax: <code>${<i>name</i>}</code>).
21   */
22  public class PropertiesReplacer
23  {
24      private final String beginMark;
25  
26      private final String endMark;
27  
28      private final Map<String, String> properties;
29  
30      public PropertiesReplacer( Map<String, String> properties, String beginMark, String endMark )
31      {
32          this.properties = properties;
33          this.beginMark = beginMark;
34          this.endMark = endMark;
35      }
36  
37      public PropertiesReplacer( Map<String, String> properties )
38      {
39          this( properties, "${", "}" );
40      }
41  
42      /**
43       * Replace <code>${<i>name</i>}</code> by the value of the property.
44       *
45       * @param source String the string to interpret (or <code>null</code>)
46       * @return String the transformed string
47       * @throws IllegalArgumentException if the source string references an inexistent property
48       */
49      public String replaceProperties( String source )
50      {
51          if ( source == null )
52          {
53              return null;
54          }
55          int index = 0;
56          int nextBegin, nextEnd;
57          StringBuffer buff = new StringBuffer();
58          while ( ( ( nextBegin = source.indexOf( beginMark, index ) ) >= 0 )
59              && ( ( nextEnd = source.indexOf( endMark, nextBegin ) ) >= 0 ) )
60          {
61              String name = source.substring( nextBegin + 2, nextEnd );
62              String value = properties.get( name );
63              if ( value == null )
64              {
65                  throw new IllegalArgumentException( "unknown property '" + name + "'" );
66              }
67              buff.append( source.substring( index, nextBegin ) );
68              buff.append( value );
69              index = nextEnd + 1;
70          }
71          if ( index == 0 )
72          {
73              // little optimization...
74              return source;
75          }
76          buff.append( source.substring( index ) );
77          return buff.toString();
78      }
79  }