001package net.sf.logdistiller.util;
002
003/*
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017import java.util.Map;
018
019/**
020 * A small utility to replace properties within strings (syntax: <code>${<i>name</i>}</code>).
021 */
022public class PropertiesReplacer
023{
024    private final String beginMark;
025
026    private final String endMark;
027
028    private final Map<String, String> properties;
029
030    public PropertiesReplacer( Map<String, String> properties, String beginMark, String endMark )
031    {
032        this.properties = properties;
033        this.beginMark = beginMark;
034        this.endMark = endMark;
035    }
036
037    public PropertiesReplacer( Map<String, String> properties )
038    {
039        this( properties, "${", "}" );
040    }
041
042    /**
043     * Replace <code>${<i>name</i>}</code> by the value of the property.
044     *
045     * @param source String the string to interpret (or <code>null</code>)
046     * @return String the transformed string
047     * @throws IllegalArgumentException if the source string references an inexistent property
048     */
049    public String replaceProperties( String source )
050    {
051        if ( source == null )
052        {
053            return null;
054        }
055        int index = 0;
056        int nextBegin, nextEnd;
057        StringBuffer buff = new StringBuffer();
058        while ( ( ( nextBegin = source.indexOf( beginMark, index ) ) >= 0 )
059            && ( ( nextEnd = source.indexOf( endMark, nextBegin ) ) >= 0 ) )
060        {
061            String name = source.substring( nextBegin + 2, nextEnd );
062            String value = properties.get( name );
063            if ( value == null )
064            {
065                throw new IllegalArgumentException( "unknown property '" + name + "'" );
066            }
067            buff.append( source.substring( index, nextBegin ) );
068            buff.append( value );
069            index = nextEnd + 1;
070        }
071        if ( index == 0 )
072        {
073            // little optimization...
074            return source;
075        }
076        buff.append( source.substring( index ) );
077        return buff.toString();
078    }
079}