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