    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.convert;
    018
    019import java.util.Collection;
    020import java.util.LinkedList;
    021import java.util.List;
    022
    023import org.apache.commons.lang3.StringUtils;
    024
    025/**
    026 * <p>
    027 * The default implementation of the {@code ListDelimiterHandler} interface.
    028 * </p>
    029 * <p>
    030 * This class supports list splitting and delimiter escaping using a delimiter character that can be specified when
    031 * constructing an instance. Splitting of strings works by scanning the input for the list delimiter character. The list
    032 * delimiter character can be escaped by a backslash. So, provided that a comma is configured as list delimiter, in the
    033 * example {@code val1,val2,val3} three values are recognized. In {@code 3\,1415} the list delimiter is escaped so that
    034 * only a single element is detected. (Note that when writing these examples in Java code, each backslash has to be
    035 * doubled. This is also true for all other examples in this documentation.)
    036 * </p>
    037 * <p>
    038 * Because the backslash has a special meaning as escaping character it is always treated in a special way. If it occurs
    039 * as a normal character in a property value, it has to be escaped using another backslash (similar to the rules of the
    040 * Java programming language). The following example shows the correct way to define windows network shares:
    041 * {@code \\\\Server\\path}. Note that each backslash is doubled. When combining the list delimiter with backslashes the
    042 * same escaping rules apply. For instance, in {@code C:\\Temp\\,D:\\data\\} the list delimiter is recognized; it is not
    043 * escaped by the preceding backslash because this backslash is itself escaped. In contrast,
    044 * {@code C:\\Temp\\\,D:\\data\\} defines a single element with a comma being part of the value; two backslashes after
    045 * {@code Temp} result in a single one, the third backslash escapes the list delimiter.
    046 * </p>
    047 * <p>
    048 * As can be seen, there are some constellations which are a bit tricky and cause a larger number of backslashes in
    049 * sequence. Nevertheless, the escaping rules are consistent and do not cause ambiguous results.
    050 * </p>
    051 * <p>
    052 * Implementation node: An instance of this class can safely be shared between multiple {@code Configuration} instances.
    053 * </p>
    054 *
    055 * @since 2.0
    056 */
    057public class DefaultListDelimiterHandler extends AbstractListDelimiterHandler {
    058    /** Constant for the escape character. */
    059    private static final char ESCAPE = '\\';
    060
    061    /**
    062     * Constant for a buffer size for escaping strings. When a character is escaped the string becomes longer. Therefore,
    063     * the output buffer is longer than the original string length. But we assume, that there are not too many characters
    064     * that need to be escaped.
    065     */
    066    private static final int BUF_SIZE = 16;
    067
    068    /** Stores the list delimiter character. */
    069    private final char delimiter;
    070
    071    /**
    072     * Creates a new instance of {@code DefaultListDelimiterHandler} and sets the list delimiter character.
    073     *
    074     * @param listDelimiter the list delimiter character
    075     */
    076    public DefaultListDelimiterHandler(final char listDelimiter) {
    077        delimiter = listDelimiter;
    078    }
    079
    080    @Override
    081    public Object escapeList(final List<?> values, final ValueTransformer transformer) {
    082        final Object[] escapedValues = new Object[values.size()];
    083        int idx = 0;
    084        for (final Object v : values) {
    085            escapedValues[idx++] = escape(v, transformer);
    086        }
    087        return StringUtils.join(escapedValues, getDelimiter());
    088    }
    089
    090    @Override
    091    protected String escapeString(final String s) {
    092        final StringBuilder buf = new StringBuilder(s.length() + BUF_SIZE);
    093        for (int i = 0; i < s.length(); i++) {
    094            final char c = s.charAt(i);
    095            if (c == getDelimiter() || c == ESCAPE) {
    096                buf.append(ESCAPE);
    097            }
    098            buf.append(c);
    099        }
    100        return buf.toString();
    101    }
    102
    103    /**
    104     * Gets the list delimiter character used by this instance.
    105     *
    106     * @return the list delimiter character
    107     */
    108    public char getDelimiter() {
    109        return delimiter;
    110    }
    111
    112    /**
    113     * {@inheritDoc} This implementation reverses the escaping done by the {@code escape()} methods of this class. However,
    114     * it tries to be tolerant with unexpected escaping sequences: If after the escape character "\" no allowed character
    115     * follows, both the backslash and the following character are output.
    116     */
    117    @Override
    118    protected Collection<String> splitString(final String s, final boolean trim) {
    119        final List<String> list = new LinkedList<>();
    120        StringBuilder token = new StringBuilder();
    121        boolean inEscape = false;
    122
    123        for (int i = 0; i < s.length(); i++) {
    124            final char c = s.charAt(i);
    125            if (inEscape) {
    126                // last character was the escape marker
    127                // can current character be escaped?
    128                if (c != getDelimiter() && c != ESCAPE) {
    129                    // no, also add escape character
    130                    token.append(ESCAPE);
    131                }
    132                token.append(c);
    133                inEscape = false;
    134            } else if (c == getDelimiter()) {
    135                // found a list delimiter -> add token and
    136                // reset buffer
    137                String t = token.toString();
    138                if (trim) {
    139                    t = t.trim();
    140                }
    141                list.add(t);
    142                token = new StringBuilder();
    143            } else if (c == ESCAPE) {
    144                // potentially escape next character
    145                inEscape = true;
    146            } else {
    147                token.append(c);
    148            }
    149        }
    150
    151        // Trailing delimiter?
    152        if (inEscape) {
    153            token.append(ESCAPE);
    154        }
    155        // Add last token
    156        String t = token.toString();
    157        if (trim) {
    158            t = t.trim();
    159        }
    160        list.add(t);
    161
    162        return list;
    163    }
    164}