001/* 
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.  
018 */
019package org.apache.wiki.util;
020
021import java.io.ByteArrayInputStream;
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.OutputStream;
025import java.io.Reader;
026import java.nio.charset.StandardCharsets;
027import java.util.Map;
028import java.util.Map.Entry;
029import java.util.Properties;
030import java.util.concurrent.locks.ReentrantLock;
031
032/**
033 * Extends {@link java.util.Properties} by providing support for comment
034 * preservation. When the properties are written to disk, previous
035 * comments present in the file are preserved.
036 * @since 2.4.22
037 */
038public class CommentedProperties extends Properties {
039
040    private static final long serialVersionUID = 8057284636436329669L;
041
042    private String m_propertyString;
043
044    /**
045     * A lock used to ensure thread safety when accessing shared resources.
046     * This lock provides more flexibility and capabilities than the intrinsic locking mechanism,
047     * such as the ability to attempt to acquire a lock with a timeout, or to interrupt a thread
048     * waiting to acquire a lock.
049     *
050     * @see java.util.concurrent.locks.ReentrantLock
051     */
052    private final ReentrantLock lock = new ReentrantLock();
053
054    /**
055     * @see java.util.Properties#Properties()
056     */
057    public CommentedProperties()
058    {
059        super();
060    }
061
062    /**
063     *  Creates new properties.
064     *
065     *  @param defaultValues A list of default values, which are used if in subsequent gets a key is not found.
066     */
067    public CommentedProperties( final Properties defaultValues )
068    {
069        super( defaultValues );
070    }
071
072    /**
073     *  {@inheritDoc}
074     */
075    @Override
076    public void load(final InputStream inStream ) throws IOException
077    {
078        Synchronizer.synchronize(lock, () -> {
079            // Load the file itself into a string
080            m_propertyString = FileUtil.readContents( inStream, StandardCharsets.ISO_8859_1.name() );
081
082            // Now load it into the properties object as normal
083            super.load( new ByteArrayInputStream( m_propertyString.getBytes(StandardCharsets.ISO_8859_1) ) );
084        });
085    }
086
087    /**
088     *  Loads properties from a file opened by a supplied Reader.
089     *  
090     *  @param in The reader to read properties from
091     *  @throws IOException in case something goes wrong.
092     */
093    @Override
094    public void load(final Reader in ) throws IOException
095    {
096        Synchronizer.synchronize(lock, () -> {
097            m_propertyString = FileUtil.readContents( in );
098
099            // Now load it into the properties object as normal
100            super.load( new ByteArrayInputStream( m_propertyString.getBytes(StandardCharsets.ISO_8859_1) ) );
101        });
102    }
103
104    /**
105     * {@inheritDoc}
106     */
107    @Override
108    public Object setProperty(final String key, final String value )
109    {
110        return Synchronizer.synchronize(lock, () -> put(key, value));
111    }
112
113    /**
114     * {@inheritDoc}
115     */
116    @Override
117    public void store(final OutputStream out, final String comments ) throws IOException
118    {
119        Synchronizer.synchronize(lock, () -> {
120            final byte[] bytes = m_propertyString.getBytes( StandardCharsets.ISO_8859_1 );
121            FileUtil.copyContents( new ByteArrayInputStream( bytes ), out );
122            out.flush();
123        });
124    }
125
126    /**
127     * {@inheritDoc}
128     */
129    @Override
130    public Object put(final Object arg0, final Object arg1 )
131    {
132       return Synchronizer.synchronize(lock, () -> {
133            // Write the property to the stored string
134            writeProperty( arg0, arg1 );
135
136            // Return the result of from the superclass properties object
137            return super.put(arg0, arg1);
138        });
139    }
140
141    /**
142     * {@inheritDoc}
143     */
144    @Override
145    public void putAll(final Map< ? , ? > arg0 )
146    {
147        Synchronizer.synchronize(lock, () -> {
148            // Shove all of the entries into the property string
149            for (final Entry<?, ?> value : arg0.entrySet()) {
150                @SuppressWarnings("unchecked") final Entry<Object, Object> entry = (Entry<Object, Object>) value;
151                writeProperty(entry.getKey(), entry.getValue());
152            }
153
154            // Call the superclass method
155            super.putAll(arg0);
156        });
157    }
158
159    /**
160     * {@inheritDoc}
161     */
162    @Override
163    public Object remove(final Object key )
164    {
165        return  Synchronizer.synchronize(lock, () -> {
166            // Remove from the property string
167            deleteProperty( key );
168
169            // Call the superclass method
170            return super.remove(key);
171        });
172    }
173
174    /**
175     * {@inheritDoc}
176     */
177    @Override
178    public String toString()
179    {
180       return Synchronizer.synchronize(lock, () -> m_propertyString);
181
182    }
183
184    private void deleteProperty(final Object arg0 )
185    {
186        // Get key and value
187        if ( arg0 == null )
188        {
189            throw new IllegalArgumentException( "Key cannot be null." );
190        }
191        final String key = arg0.toString();
192
193        // Iterate through each line and replace anything matching our key
194        int idx = 0;
195        while( ( idx < m_propertyString.length() ) && ( ( idx = m_propertyString.indexOf( key, idx ) ) != -1 ) )
196        {
197            final int prevret = m_propertyString.lastIndexOf( "\n", idx );
198            if ( prevret != -1 )
199            {
200                // Commented lines are skipped
201                if ( m_propertyString.charAt( prevret + 1 ) == '#' )
202                {
203                    idx += key.length();
204                    continue;
205                }
206            }
207
208            // If "=" present, delete the entire line
209            final int eqsign = m_propertyString.indexOf( "=", idx );
210            if ( eqsign != -1 )
211            {
212                final int ret = m_propertyString.indexOf( "\n", eqsign );
213                m_propertyString = TextUtil.replaceString( m_propertyString, prevret, ret, "" );
214                return;
215            }
216        }
217    }
218
219    private void writeProperty(final Object arg0, Object arg1 )
220    {
221        // Get key and value
222        if ( arg0 == null )
223        {
224            throw new IllegalArgumentException( "Key cannot be null." );
225        }
226        if ( arg1 == null )
227        {
228            arg1 = "";
229        }
230        final String key = arg0.toString();
231        final String value = TextUtil.native2Ascii( arg1.toString() );
232
233        // Iterate through each line and replace anything matching our key
234        int idx = 0;
235        while( ( idx < m_propertyString.length() ) && ( ( idx = m_propertyString.indexOf( key, idx ) ) != -1 ) )
236        {
237            final int prevret = m_propertyString.lastIndexOf( "\n", idx );
238            if ( prevret != -1 )
239            {
240                // Commented lines are skipped
241                if ( m_propertyString.charAt( prevret + 1 ) == '#' )
242                {
243                    idx += key.length();
244                    continue;
245                }
246            }
247
248            // If "=" present, replace everything in line after it
249            final int eqsign = m_propertyString.indexOf( "=", idx );
250            if ( eqsign != -1 )
251            {
252                int ret = m_propertyString.indexOf( "\n", eqsign );
253                if ( ret == -1 )
254                {
255                    ret = m_propertyString.length();
256                }
257                m_propertyString = TextUtil.replaceString( m_propertyString, eqsign + 1, ret, value );
258                return;
259            }
260        }
261
262        // If it was not found, we'll add it to the end.
263        m_propertyString += "\n" + key + " = " + value + "\n";
264    }
265
266}