    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *     http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.configuration2;
    018
    019import java.io.IOException;
    020import java.io.Reader;
    021import java.io.Writer;
    022import java.net.URL;
    023import java.util.ArrayDeque;
    024import java.util.LinkedHashMap;
    025import java.util.List;
    026import java.util.Map;
    027import java.util.Objects;
    028import java.util.Set;
    029import java.util.concurrent.atomic.AtomicInteger;
    030
    031import org.apache.commons.configuration2.event.ConfigurationEvent;
    032import org.apache.commons.configuration2.event.EventListener;
    033import org.apache.commons.configuration2.ex.ConfigurationException;
    034import org.apache.commons.configuration2.ex.ConfigurationRuntimeException;
    035import org.apache.commons.lang3.StringUtils;
    036
    037/**
    038 * <p>
    039 * A helper class used by {@link PropertiesConfiguration} to keep the layout of a properties file.
    040 * </p>
    041 * <p>
    042 * Instances of this class are associated with a {@code PropertiesConfiguration} object. They are responsible for
    043 * analyzing properties files and for extracting as much information about the file layout (e.g. empty lines, comments)
    044 * as possible. When the properties file is written back again it should be close to the original.
    045 * </p>
    046 * <p>
    047 * The {@code PropertiesConfigurationLayout} object associated with a {@code PropertiesConfiguration} object can be
    048 * obtained using the {@code getLayout()} method of the configuration. Then the methods provided by this class can be
    049 * used to alter the properties file's layout.
    050 * </p>
    051 * <p>
    052 * Implementation note: This is a very simple implementation, which is far away from being perfect, i.e. the original
    053 * layout of a properties file won't be reproduced in all cases. One limitation is that comments for multi-valued
    054 * property keys are concatenated. Maybe this implementation can later be improved.
    055 * </p>
    056 * <p>
    057 * To get an impression how this class works consider the following properties file:
    058 * </p>
    059 *
    060 * <pre>
    061 * # A demo configuration file
    062 * # for Demo App 1.42
    063 *
    064 * # Application name
    065 * AppName=Demo App
    066 *
    067 * # Application vendor
    068 * AppVendor=DemoSoft
    069 *
    070 *
    071 * # GUI properties
    072 * # Window Color
    073 * windowColors=0xFFFFFF,0x000000
    074 *
    075 * # Include some setting
    076 * include=settings.properties
    077 * # Another vendor
    078 * AppVendor=TestSoft
    079 * </pre>
    080 *
    081 * <p>
    082 * For this example the following points are relevant:
    083 * </p>
    084 * <ul>
    085 * <li>The first two lines are set as header comment. The header comment is determined by the last blank line before the
    086 * first property definition.</li>
    087 * <li>For the property {@code AppName} one comment line and one leading blank line is stored.</li>
    088 * <li>For the property {@code windowColors} two comment lines and two leading blank lines are stored.</li>
    089 * <li>Include files is something this class cannot deal with well. When saving the properties configuration back, the
    090 * included properties are simply contained in the original file. The comment before the include property is
    091 * skipped.</li>
    092 * <li>For all properties except for {@code AppVendor} the &quot;single line&quot; flag is set. This is relevant only
    093 * for {@code windowColors}, which has multiple values defined in one line using the separator character.</li>
    094 * <li>The {@code AppVendor} property appears twice. The comment lines are concatenated, so that
    095 * {@code layout.getComment("AppVendor");} will result in {@code Application vendor&lt;CR&gt;Another vendor}, with
    096 * {@code &lt;CR&gt;} meaning the line separator. In addition the &quot;single line&quot; flag is set to <b>false</b>
    097 * for this property. When the file is saved, two property definitions will be written (in series).</li>
    098 * </ul>
    099 *
    100 * @since 1.3
    101 */
    102public class PropertiesConfigurationLayout implements EventListener<ConfigurationEvent> {
    103    /** Constant for the line break character. */
    104    private static final String CR = "\n";
    105
    106    /** Constant for the default comment prefix. */
    107    private static final String COMMENT_PREFIX = "# ";
    108
    109    /** Stores a map with the contained layout information. */
    110    private final Map<String, PropertyLayoutData> layoutData;
    111
    112    /** Stores the header comment. */
    113    private String headerComment;
    114
    115    /** Stores the footer comment. */
    116    private String footerComment;
    117
    118    /** The global separator that will be used for all properties. */
    119    private String globalSeparator;
    120
    121    /** The line separator. */
    122    private String lineSeparator;
    123
    124    /** A counter for determining nested load calls. */
    125    private final AtomicInteger loadCounter;
    126
    127    /** Stores the force single line flag. */
    128    private boolean forceSingleLine;
    129
    130    /** Seen includes. */
    131    private final ArrayDeque<URL> seenStack = new ArrayDeque<>();
    132
    133    /**
    134     * Creates a new, empty instance of {@code PropertiesConfigurationLayout}.
    135     */
    136    public PropertiesConfigurationLayout() {
    137        this(null);
    138    }
    139
    140    /**
    141     * Creates a new instance of {@code PropertiesConfigurationLayout} and copies the data of the specified layout object.
    142     *
    143     * @param c the layout object to be copied
    144     */
    145    public PropertiesConfigurationLayout(final PropertiesConfigurationLayout c) {
    146        loadCounter = new AtomicInteger();
    147        layoutData = new LinkedHashMap<>();
    148
    149        if (c != null) {
    150            copyFrom(c);
    151        }
    152    }
    153
    154    /**
    155     * Returns the comment for the specified property key in a canonical form. &quot;Canonical&quot; means that either all
    156     * lines start with a comment character or none. If the {@code commentChar} parameter is <b>false</b>, all comment
    157     * characters are removed, so that the result is only the plain text of the comment. Otherwise it is ensured that each
    158     * line of the comment starts with a comment character. Also, line breaks in the comment are normalized to the line
    159     * separator &quot;\n&quot;.
    160     *
    161     * @param key the key of the property
    162     * @param commentChar determines whether all lines should start with comment characters or not
    163     * @return the canonical comment for this key (can be <b>null</b>)
    164     */
    165    public String getCanonicalComment(final String key, final boolean commentChar) {
    166        return constructCanonicalComment(getComment(key), commentChar);
    167    }
    168
    169    /**
    170     * Returns the comment for the specified property key. The comment is returned as it was set (either manually by calling
    171     * {@code setComment()} or when it was loaded from a properties file). No modifications are performed.
    172     *
    173     * @param key the key of the property
    174     * @return the comment for this key (can be <b>null</b>)
    175     */
    176    public String getComment(final String key) {
    177        return fetchLayoutData(key).getComment();
    178    }
    179
    180    /**
    181     * Sets the comment for the specified property key. The comment (or its single lines if it is a multi-line comment) can
    182     * start with a comment character. If this is the case, it will be written without changes. Otherwise a default comment
    183     * character is added automatically.
    184     *
    185     * @param key the key of the property
    186     * @param comment the comment for this key (can be <b>null</b>, then the comment will be removed)
    187     */
    188    public void setComment(final String key, final String comment) {
    189        fetchLayoutData(key).setComment(comment);
    190    }
    191
    192    /**
    193     * Returns the number of blank lines before this property key. If this key does not exist, 0 will be returned.
    194     *
    195     * @param key the property key
    196     * @return the number of blank lines before the property definition for this key
    197     * @deprecated Use {@link #getBlankLinesBefore(String)}.
    198     */
    199    @Deprecated
    200    public int getBlancLinesBefore(final String key) {
    201        return getBlankLinesBefore(key);
    202    }
    203
    204    /**
    205     * Returns the number of blank lines before this property key. If this key does not exist, 0 will be returned.
    206     *
    207     * @param key the property key
    208     * @return the number of blank lines before the property definition for this key
    209     */
    210    public int getBlankLinesBefore(final String key) {
    211        return fetchLayoutData(key).getBlankLines();
    212    }
    213
    214    /**
    215     * Sets the number of blank lines before the given property key. This can be used for a logical grouping of properties.
    216     *
    217     * @param key the property key
    218     * @param number the number of blank lines to add before this property definition
    219     * @deprecated use {@link PropertiesConfigurationLayout#setBlankLinesBefore(String, int)}.
    220     */
    221    @Deprecated
    222    public void setBlancLinesBefore(final String key, final int number) {
    223        setBlankLinesBefore(key, number);
    224    }
    225
    226    /**
    227     * Sets the number of blank lines before the given property key. This can be used for a logical grouping of properties.
    228     *
    229     * @param key the property key
    230     * @param number the number of blank lines to add before this property definition
    231     * @since 2.8.0
    232     */
    233    public void setBlankLinesBefore(final String key, final int number) {
    234        fetchLayoutData(key).setBlankLines(number);
    235    }
    236
    237    /**
    238     * Returns the header comment of the represented properties file in a canonical form. With the {@code commentChar}
    239     * parameter it can be specified whether comment characters should be stripped or be always present.
    240     *
    241     * @param commentChar determines the presence of comment characters
    242     * @return the header comment (can be <b>null</b>)
    243     */
    244    public String getCanonicalHeaderComment(final boolean commentChar) {
    245        return constructCanonicalComment(getHeaderComment(), commentChar);
    246    }
    247
    248    /**
    249     * Returns the header comment of the represented properties file. This method returns the header comment exactly as it
    250     * was set using {@code setHeaderComment()} or extracted from the loaded properties file.
    251     *
    252     * @return the header comment (can be <b>null</b>)
    253     */
    254    public String getHeaderComment() {
    255        return headerComment;
    256    }
    257
    258    /**
    259     * Sets the header comment for the represented properties file. This comment will be output on top of the file.
    260     *
    261     * @param comment the comment
    262     */
    263    public void setHeaderComment(final String comment) {
    264        headerComment = comment;
    265    }
    266
    267    /**
    268     * Returns the footer comment of the represented properties file in a canonical form. This method works like
    269     * {@code getCanonicalHeaderComment()}, but reads the footer comment.
    270     *
    271     * @param commentChar determines the presence of comment characters
    272     * @return the footer comment (can be <b>null</b>)
    273     * @see #getCanonicalHeaderComment(boolean)
    274     * @since 2.0
    275     */
    276    public String getCanonicalFooterCooment(final boolean commentChar) {
    277        return constructCanonicalComment(getFooterComment(), commentChar);
    278    }
    279
    280    /**
    281     * Returns the footer comment of the represented properties file. This method returns the footer comment exactly as it
    282     * was set using {@code setFooterComment()} or extracted from the loaded properties file.
    283     *
    284     * @return the footer comment (can be <b>null</b>)
    285     * @since 2.0
    286     */
    287    public String getFooterComment() {
    288        return footerComment;
    289    }
    290
    291    /**
    292     * Sets the footer comment for the represented properties file. This comment will be output at the bottom of the file.
    293     *
    294     * @param footerComment the footer comment
    295     * @since 2.0
    296     */
    297    public void setFooterComment(final String footerComment) {
    298        this.footerComment = footerComment;
    299    }
    300
    301    /**
    302     * Returns a flag whether the specified property is defined on a single line. This is meaningful only if this property
    303     * has multiple values.
    304     *
    305     * @param key the property key
    306     * @return a flag if this property is defined on a single line
    307     */
    308    public boolean isSingleLine(final String key) {
    309        return fetchLayoutData(key).isSingleLine();
    310    }
    311
    312    /**
    313     * Sets the &quot;single line flag&quot; for the specified property key. This flag is evaluated if the property has
    314     * multiple values (i.e. if it is a list property). In this case, if the flag is set, all values will be written in a
    315     * single property definition using the list delimiter as separator. Otherwise multiple lines will be written for this
    316     * property, each line containing one property value.
    317     *
    318     * @param key the property key
    319     * @param f the single line flag
    320     */
    321    public void setSingleLine(final String key, final boolean f) {
    322        fetchLayoutData(key).setSingleLine(f);
    323    }
    324
    325    /**
    326     * Returns the &quot;force single line&quot; flag.
    327     *
    328     * @return the force single line flag
    329     * @see #setForceSingleLine(boolean)
    330     */
    331    public boolean isForceSingleLine() {
    332        return forceSingleLine;
    333    }
    334
    335    /**
    336     * Sets the &quot;force single line&quot; flag. If this flag is set, all properties with multiple values are written on
    337     * single lines. This mode provides more compatibility with {@code java.lang.Properties}, which cannot deal with
    338     * multiple definitions of a single property. This mode has no effect if the list delimiter parsing is disabled.
    339     *
    340     * @param f the force single line flag
    341     */
    342    public void setForceSingleLine(final boolean f) {
    343        forceSingleLine = f;
    344    }
    345
    346    /**
    347     * Returns the separator for the property with the given key.
    348     *
    349     * @param key the property key
    350     * @return the property separator for this property
    351     * @since 1.7
    352     */
    353    public String getSeparator(final String key) {
    354        return fetchLayoutData(key).getSeparator();
    355    }
    356
    357    /**
    358     * Sets the separator to be used for the property with the given key. The separator is the string between the property
    359     * key and its value. For new properties &quot; = &quot; is used. When a properties file is read, the layout tries to
    360     * determine the separator for each property. With this method the separator can be changed. To be compatible with the
    361     * properties format only the characters {@code =} and {@code :} (with or without whitespace) should be used, but this
    362     * method does not enforce this - it accepts arbitrary strings. If the key refers to a property with multiple values
    363     * that are written on multiple lines, this separator will be used on all lines.
    364     *
    365     * @param key the key for the property
    366     * @param sep the separator to be used for this property
    367     * @since 1.7
    368     */
    369    public void setSeparator(final String key, final String sep) {
    370        fetchLayoutData(key).setSeparator(sep);
    371    }
    372
    373    /**
    374     * Returns the global separator.
    375     *
    376     * @return the global properties separator
    377     * @since 1.7
    378     */
    379    public String getGlobalSeparator() {
    380        return globalSeparator;
    381    }
    382
    383    /**
    384     * Sets the global separator for properties. With this method a separator can be set that will be used for all
    385     * properties when writing the configuration. This is an easy way of determining the properties separator globally. To
    386     * be compatible with the properties format only the characters {@code =} and {@code :} (with or without whitespace)
    387     * should be used, but this method does not enforce this - it accepts arbitrary strings. If the global separator is set
    388     * to <b>null</b>, property separators are not changed. This is the default behavior as it produces results that are
    389     * closer to the original properties file.
    390     *
    391     * @param globalSeparator the separator to be used for all properties
    392     * @since 1.7
    393     */
    394    public void setGlobalSeparator(final String globalSeparator) {
    395        this.globalSeparator = globalSeparator;
    396    }
    397
    398    /**
    399     * Returns the line separator.
    400     *
    401     * @return the line separator
    402     * @since 1.7
    403     */
    404    public String getLineSeparator() {
    405        return lineSeparator;
    406    }
    407
    408    /**
    409     * Sets the line separator. When writing the properties configuration, all lines are terminated with this separator. If
    410     * no separator was set, the platform-specific default line separator is used.
    411     *
    412     * @param lineSeparator the line separator
    413     * @since 1.7
    414     */
    415    public void setLineSeparator(final String lineSeparator) {
    416        this.lineSeparator = lineSeparator;
    417    }
    418
    419    /**
    420     * Returns a set with all property keys managed by this object.
    421     *
    422     * @return a set with all contained property keys
    423     */
    424    public Set<String> getKeys() {
    425        return layoutData.keySet();
    426    }
    427
    428    /**
    429     * Reads a properties file and stores its internal structure. The found properties will be added to the specified
    430     * configuration object.
    431     *
    432     * @param config the associated configuration object
    433     * @param reader the reader to the properties file
    434     * @throws ConfigurationException if an error occurs
    435     */
    436    public void load(final PropertiesConfiguration config, final Reader reader) throws ConfigurationException {
    437        loadCounter.incrementAndGet();
    438        @SuppressWarnings("resource") // createPropertiesReader wraps the reader.
    439        final PropertiesConfiguration.PropertiesReader pReader = config.getIOFactory().createPropertiesReader(reader);
    440
    441        try {
    442            while (pReader.nextProperty()) {
    443                if (config.propertyLoaded(pReader.getPropertyName(), pReader.getPropertyValue(), seenStack)) {
    444                    final boolean contained = layoutData.containsKey(pReader.getPropertyName());
    445                    int blankLines = 0;
    446                    int idx = checkHeaderComment(pReader.getCommentLines());
    447                    while (idx < pReader.getCommentLines().size() && StringUtils.isEmpty(pReader.getCommentLines().get(idx))) {
    448                        idx++;
    449                        blankLines++;
    450                    }
    451                    final String comment = extractComment(pReader.getCommentLines(), idx, pReader.getCommentLines().size() - 1);
    452                    final PropertyLayoutData data = fetchLayoutData(pReader.getPropertyName());
    453                    if (contained) {
    454                        data.addComment(comment);
    455                        data.setSingleLine(false);
    456                    } else {
    457                        data.setComment(comment);
    458                        data.setBlankLines(blankLines);
    459                        data.setSeparator(pReader.getPropertySeparator());
    460                    }
    461                }
    462            }
    463
    464            setFooterComment(extractComment(pReader.getCommentLines(), 0, pReader.getCommentLines().size() - 1));
    465        } catch (final IOException ioex) {
    466            throw new ConfigurationException(ioex);
    467        } finally {
    468            loadCounter.decrementAndGet();
    469        }
    470    }
    471
    472    /**
    473     * Writes the properties file to the given writer, preserving as much of its structure as possible.
    474     *
    475     * @param config the associated configuration object
    476     * @param writer the writer
    477     * @throws ConfigurationException if an error occurs
    478     */
    479    public void save(final PropertiesConfiguration config, final Writer writer) throws ConfigurationException {
    480        try {
    481            @SuppressWarnings("resource") // createPropertiesReader wraps the writer.
    482            final PropertiesConfiguration.PropertiesWriter pWriter = config.getIOFactory().createPropertiesWriter(writer, config.getListDelimiterHandler());
    483            pWriter.setGlobalSeparator(getGlobalSeparator());
    484            if (getLineSeparator() != null) {
    485                pWriter.setLineSeparator(getLineSeparator());
    486            }
    487
    488            if (headerComment != null) {
    489                writeComment(pWriter, getCanonicalHeaderComment(true));
    490            }
    491
    492            boolean firstKey = true;
    493            for (final String key : getKeys()) {
    494                if (config.containsKeyInternal(key)) {
    495                    // preset header comment needs to be separated from key
    496                    if (firstKey && headerComment != null && getBlankLinesBefore(key) == 0) {
    497                        pWriter.writeln(null);
    498                    }
    499
    500                    // Output blank lines before property
    501                    for (int i = 0; i < getBlankLinesBefore(key); i++) {
    502                        pWriter.writeln(null);
    503                    }
    504
    505                    // Output the comment
    506                    writeComment(pWriter, getCanonicalComment(key, true));
    507
    508                    // Output the property and its value
    509                    final boolean singleLine = isForceSingleLine() || isSingleLine(key);
    510                    pWriter.setCurrentSeparator(getSeparator(key));
    511                    pWriter.writeProperty(key, config.getPropertyInternal(key), singleLine);
    512                }
    513                firstKey = false;
    514            }
    515
    516            writeComment(pWriter, getCanonicalFooterCooment(true));
    517            pWriter.flush();
    518        } catch (final IOException ioex) {
    519            throw new ConfigurationException(ioex);
    520        }
    521    }
    522
    523    /**
    524     * The event listener callback. Here event notifications of the configuration object are processed to update the layout
    525     * object properly.
    526     *
    527     * @param event the event object
    528     */
    529    @Override
    530    public void onEvent(final ConfigurationEvent event) {
    531        if (!event.isBeforeUpdate() && loadCounter.get() == 0) {
    532            if (ConfigurationEvent.ADD_PROPERTY.equals(event.getEventType())) {
    533                final boolean contained = layoutData.containsKey(event.getPropertyName());
    534                final PropertyLayoutData data = fetchLayoutData(event.getPropertyName());
    535                data.setSingleLine(!contained);
    536            } else if (ConfigurationEvent.CLEAR_PROPERTY.equals(event.getEventType())) {
    537                layoutData.remove(event.getPropertyName());
    538            } else if (ConfigurationEvent.CLEAR.equals(event.getEventType())) {
    539                clear();
    540            } else if (ConfigurationEvent.SET_PROPERTY.equals(event.getEventType())) {
    541                fetchLayoutData(event.getPropertyName());
    542            }
    543        }
    544    }
    545
    546    /**
    547     * Returns a layout data object for the specified key. If this is a new key, a new object is created and initialized
    548     * with default values.
    549     *
    550     * @param key the key
    551     * @return the corresponding layout data object
    552     */
    553    private PropertyLayoutData fetchLayoutData(final String key) {
    554        if (key == null) {
    555            throw new IllegalArgumentException("Property key must not be null!");
    556        }
    557
    558        PropertyLayoutData data = layoutData.get(key);
    559        if (data == null) {
    560            data = new PropertyLayoutData();
    561            data.setSingleLine(true);
    562            layoutData.put(key, data);
    563        }
    564
    565        return data;
    566    }
    567
    568    /**
    569     * Removes all content from this layout object.
    570     */
    571    private void clear() {
    572        seenStack.clear();
    573        layoutData.clear();
    574        setHeaderComment(null);
    575        setFooterComment(null);
    576    }
    577
    578    /**
    579     * Tests whether a line is a comment, i.e. whether it starts with a comment character.
    580     *
    581     * @param line the line
    582     * @return a flag if this is a comment line
    583     */
    584    static boolean isCommentLine(final String line) {
    585        return PropertiesConfiguration.isCommentLine(line);
    586    }
    587
    588    /**
    589     * Trims a comment. This method either removes all comment characters from the given string, leaving only the plain
    590     * comment text or ensures that every line starts with a valid comment character.
    591     *
    592     * @param s the string to be processed
    593     * @param comment if <b>true</b>, a comment character will always be enforced; if <b>false</b>, it will be removed
    594     * @return the trimmed comment
    595     */
    596    static String trimComment(final String s, final boolean comment) {
    597        final StringBuilder buf = new StringBuilder(s.length());
    598        int lastPos = 0;
    599        int pos;
    600
    601        do {
    602            pos = s.indexOf(CR, lastPos);
    603            if (pos >= 0) {
    604                final String line = s.substring(lastPos, pos);
    605                buf.append(stripCommentChar(line, comment)).append(CR);
    606                lastPos = pos + CR.length();
    607            }
    608        } while (pos >= 0);
    609
    610        if (lastPos < s.length()) {
    611            buf.append(stripCommentChar(s.substring(lastPos), comment));
    612        }
    613        return buf.toString();
    614    }
    615
    616    /**
    617     * Either removes the comment character from the given comment line or ensures that the line starts with a comment
    618     * character.
    619     *
    620     * @param s the comment line
    621     * @param comment if <b>true</b>, a comment character will always be enforced; if <b>false</b>, it will be removed
    622     * @return the line without comment character
    623     */
    624    static String stripCommentChar(final String s, final boolean comment) {
    625        if (StringUtils.isBlank(s) || (isCommentLine(s) == comment)) {
    626            return s;
    627        }
    628        if (!comment) {
    629            int pos = 0;
    630            // find first comment character
    631            while (PropertiesConfiguration.COMMENT_CHARS.indexOf(s.charAt(pos)) < 0) {
    632                pos++;
    633            }
    634
    635            // Remove leading spaces
    636            pos++;
    637            while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) {
    638                pos++;
    639            }
    640
    641            return pos < s.length() ? s.substring(pos) : StringUtils.EMPTY;
    642        }
    643        return COMMENT_PREFIX + s;
    644    }
    645
    646    /**
    647     * Extracts a comment string from the given range of the specified comment lines. The single lines are added using a
    648     * line feed as separator.
    649     *
    650     * @param commentLines a list with comment lines
    651     * @param from the start index
    652     * @param to the end index (inclusive)
    653     * @return the comment string (<b>null</b> if it is undefined)
    654     */
    655    private String extractComment(final List<String> commentLines, final int from, final int to) {
    656        if (to < from) {
    657            return null;
    658        }
    659        final StringBuilder buf = new StringBuilder(commentLines.get(from));
    660        for (int i = from + 1; i <= to; i++) {
    661            buf.append(CR);
    662            buf.append(commentLines.get(i));
    663        }
    664        return buf.toString();
    665    }
    666
    667    /**
    668     * Checks if parts of the passed in comment can be used as header comment. This method checks whether a header comment
    669     * can be defined (i.e. whether this is the first comment in the loaded file). If this is the case, it is searched for
    670     * the latest blank line. This line will mark the end of the header comment. The return value is the index of the first
    671     * line in the passed in list, which does not belong to the header comment.
    672     *
    673     * @param commentLines the comment lines
    674     * @return the index of the next line after the header comment
    675     */
    676    private int checkHeaderComment(final List<String> commentLines) {
    677        if (loadCounter.get() == 1 && layoutData.isEmpty()) {
    678            int index = commentLines.size() - 1;
    679            // strip comments that belong to first key
    680            while (index >= 0 && StringUtils.isNotEmpty(commentLines.get(index))) {
    681                index--;
    682            }
    683            // strip blank lines
    684            while (index >= 0 && StringUtils.isEmpty(commentLines.get(index))) {
    685                index--;
    686            }
    687            if (getHeaderComment() == null) {
    688                setHeaderComment(extractComment(commentLines, 0, index));
    689            }
    690            return index + 1;
    691        }
    692        return 0;
    693    }
    694
    695    /**
    696     * Copies the data from the given layout object.
    697     *
    698     * @param c the layout object to copy
    699     */
    700    private void copyFrom(final PropertiesConfigurationLayout c) {
    701        for (final String key : c.getKeys()) {
    702            final PropertyLayoutData data = c.layoutData.get(key);
    703            layoutData.put(key, data.clone());
    704        }
    705
    706        setHeaderComment(c.getHeaderComment());
    707        setFooterComment(c.getFooterComment());
    708    }
    709
    710    /**
    711     * Helper method for writing a comment line. This method ensures that the correct line separator is used if the comment
    712     * spans multiple lines.
    713     *
    714     * @param writer the writer
    715     * @param comment the comment to write
    716     * @throws IOException if an IO error occurs
    717     */
    718    private static void writeComment(final PropertiesConfiguration.PropertiesWriter writer, final String comment) throws IOException {
    719        if (comment != null) {
    720            writer.writeln(StringUtils.replace(comment, CR, writer.getLineSeparator()));
    721        }
    722    }
    723
    724    /**
    725     * Helper method for generating a comment string. Depending on the boolean argument the resulting string either has no
    726     * comment characters or a leading comment character at each line.
    727     *
    728     * @param comment the comment string to be processed
    729     * @param commentChar determines the presence of comment characters
    730     * @return the canonical comment string (can be <b>null</b>)
    731     */
    732    private static String constructCanonicalComment(final String comment, final boolean commentChar) {
    733        return comment == null ? null : trimComment(comment, commentChar);
    734    }
    735
    736    /**
    737     * A helper class for storing all layout related information for a configuration property.
    738     */
    739    static class PropertyLayoutData implements Cloneable {
    740        /** Stores the comment for the property. */
    741        private StringBuffer comment;
    742
    743        /** The separator to be used for this property. */
    744        private String separator;
    745
    746        /** Stores the number of blank lines before this property. */
    747        private int blankLines;
    748
    749        /** Stores the single line property. */
    750        private boolean singleLine;
    751
    752        /**
    753         * Creates a new instance of {@code PropertyLayoutData}.
    754         */
    755        public PropertyLayoutData() {
    756            singleLine = true;
    757            separator = PropertiesConfiguration.DEFAULT_SEPARATOR;
    758        }
    759
    760        /**
    761         * Returns the number of blank lines before this property.
    762         *
    763         * @return the number of blank lines before this property
    764         * @deprecated Use {#link {@link #getBlankLines()}}.
    765         */
    766        @Deprecated
    767        public int getBlancLines() {
    768            return getBlankLines();
    769        }
    770
    771        /**
    772         * Returns the number of blank lines before this property.
    773         *
    774         * @return the number of blank lines before this property
    775         * @since 2.8.0
    776         */
    777        public int getBlankLines() {
    778            return blankLines;
    779        }
    780
    781        /**
    782         * Sets the number of properties before this property.
    783         *
    784         * @param blankLines the number of properties before this property
    785         * @deprecated Use {@link #setBlankLines(int)}.
    786         */
    787        @Deprecated
    788        public void setBlancLines(final int blankLines) {
    789            setBlankLines(blankLines);
    790        }
    791
    792        /**
    793         * Sets the number of properties before this property.
    794         *
    795         * @param blankLines the number of properties before this property
    796         * @since 2.8.0
    797         */
    798        public void setBlankLines(final int blankLines) {
    799            this.blankLines = blankLines;
    800        }
    801
    802        /**
    803         * Returns the single line flag.
    804         *
    805         * @return the single line flag
    806         */
    807        public boolean isSingleLine() {
    808            return singleLine;
    809        }
    810
    811        /**
    812         * Sets the single line flag.
    813         *
    814         * @param singleLine the single line flag
    815         */
    816        public void setSingleLine(final boolean singleLine) {
    817            this.singleLine = singleLine;
    818        }
    819
    820        /**
    821         * Adds a comment for this property. If already a comment exists, the new comment is added (separated by a newline).
    822         *
    823         * @param s the comment to add
    824         */
    825        public void addComment(final String s) {
    826            if (s != null) {
    827                if (comment == null) {
    828                    comment = new StringBuffer(s);
    829                } else {
    830                    comment.append(CR).append(s);
    831                }
    832            }
    833        }
    834
    835        /**
    836         * Sets the comment for this property.
    837         *
    838         * @param s the new comment (can be <b>null</b>)
    839         */
    840        public void setComment(final String s) {
    841            if (s == null) {
    842                comment = null;
    843            } else {
    844                comment = new StringBuffer(s);
    845            }
    846        }
    847
    848        /**
    849         * Returns the comment for this property. The comment is returned as it is, without processing of comment characters.
    850         *
    851         * @return the comment (can be <b>null</b>)
    852         */
    853        public String getComment() {
    854            return Objects.toString(comment, null);
    855        }
    856
    857        /**
    858         * Returns the separator that was used for this property.
    859         *
    860         * @return the property separator
    861         */
    862        public String getSeparator() {
    863            return separator;
    864        }
    865
    866        /**
    867         * Sets the separator to be used for the represented property.
    868         *
    869         * @param separator the property separator
    870         */
    871        public void setSeparator(final String separator) {
    872            this.separator = separator;
    873        }
    874
    875        /**
    876         * Creates a copy of this object.
    877         *
    878         * @return the copy
    879         */
    880        @Override
    881        public PropertyLayoutData clone() {
    882            try {
    883                final PropertyLayoutData copy = (PropertyLayoutData) super.clone();
    884                if (comment != null) {
    885                    // must copy string buffer, too
    886                    copy.comment = new StringBuffer(getComment());
    887                }
    888                return copy;
    889            } catch (final CloneNotSupportedException cnex) {
    890                // This cannot happen!
    891                throw new ConfigurationRuntimeException(cnex);
    892            }
    893        }
    894    }
    895}