LegacyListDelimiterHandler.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.configuration2.convert;

  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.Iterator;
  22. import java.util.List;

  23. import org.apache.commons.lang3.StringUtils;

  24. /**
  25.  * <p>
  26.  * A specialized implementation of {@code ListDelimiterHandler} which simulates the list delimiter handling as it was
  27.  * used by {@code PropertiesConfiguration} in Commons Configuration 1.x.
  28.  * </p>
  29.  * <p>
  30.  * This class mainly exists for compatibility reasons. It is intended to be used by applications which have to deal with
  31.  * properties files created by an older version of this library.
  32.  * </p>
  33.  * <p>
  34.  * In the 1.x series of Commons Configuration list handling was not fully consistent. The escaping of property values
  35.  * was done in a different way if they contained a list delimiter or not. From version 2.0 on, escaping is more
  36.  * stringent which might cause slightly different results when parsing properties files created by or for Configuration
  37.  * 1.x. If you encounter such problems, you can switch to this {@code ListDelimiterHandler} implementation rather than
  38.  * the default one. In other cases, this class should not be used!
  39.  * </p>
  40.  * <p>
  41.  * Implementation note: An instance of this class can safely be shared between multiple {@code Configuration} instances.
  42.  * </p>
  43.  *
  44.  * @since 2.0
  45.  */
  46. public class LegacyListDelimiterHandler extends AbstractListDelimiterHandler {
  47.     /** Constant for the escaping character. */
  48.     private static final String ESCAPE = "\\";

  49.     /** Constant for the escaped escaping character. */
  50.     private static final String DOUBLE_ESC = ESCAPE + ESCAPE;

  51.     /** Constant for a duplicated sequence of escaping characters. */
  52.     private static final String QUAD_ESC = DOUBLE_ESC + DOUBLE_ESC;

  53.     /**
  54.      * Returns the number of trailing backslashes. This is sometimes needed for the correct handling of escape characters.
  55.      *
  56.      * @param line the string to investigate
  57.      * @return the number of trailing backslashes
  58.      */
  59.     private static int countTrailingBS(final String line) {
  60.         int bsCount = 0;
  61.         for (int idx = line.length() - 1; idx >= 0 && line.charAt(idx) == '\\'; idx--) {
  62.             bsCount++;
  63.         }

  64.         return bsCount;
  65.     }

  66.     /** The list delimiter character. */
  67.     private final char delimiter;

  68.     /**
  69.      * Creates a new instance of {@code LegacyListDelimiterHandler} and sets the list delimiter character.
  70.      *
  71.      * @param listDelimiter the list delimiter character
  72.      */
  73.     public LegacyListDelimiterHandler(final char listDelimiter) {
  74.         delimiter = listDelimiter;
  75.     }

  76.     /**
  77.      * {@inheritDoc} This implementation performs delimiter escaping for a single value (which is not part of a list).
  78.      */
  79.     @Override
  80.     public Object escape(final Object value, final ValueTransformer transformer) {
  81.         return escapeValue(value, false, transformer);
  82.     }

  83.     /**
  84.      * Performs the escaping of backslashes in the specified properties value. Because a double backslash is used to escape
  85.      * the escape character of a list delimiter, double backslashes also have to be escaped if the property is part of a
  86.      * (single line) list. In addition, because the output is written into a properties file, each occurrence of a backslash
  87.      * again has to be doubled. This method is called by {@code escapeValue()}.
  88.      *
  89.      * @param value the value to be escaped
  90.      * @param inList a flag whether the value is part of a list
  91.      * @return the value with escaped backslashes as string
  92.      */
  93.     protected String escapeBackslashs(final Object value, final boolean inList) {
  94.         String strValue = String.valueOf(value);

  95.         if (inList && strValue.contains(DOUBLE_ESC)) {
  96.             strValue = StringUtils.replace(strValue, DOUBLE_ESC, QUAD_ESC);
  97.         }

  98.         return strValue;
  99.     }

  100.     /**
  101.      * {@inheritDoc} This implementation performs a special encoding of backslashes at the end of a string so that they are
  102.      * not interpreted as escape character for a following list delimiter.
  103.      */
  104.     @Override
  105.     public Object escapeList(final List<?> values, final ValueTransformer transformer) {
  106.         if (!values.isEmpty()) {
  107.             final Iterator<?> it = values.iterator();
  108.             String lastValue = escapeValue(it.next(), true, transformer);
  109.             final StringBuilder buf = new StringBuilder(lastValue);
  110.             while (it.hasNext()) {
  111.                 // if the last value ended with an escape character, it has
  112.                 // to be escaped itself; otherwise the list delimiter will
  113.                 // be escaped
  114.                 if (lastValue.endsWith(ESCAPE) && countTrailingBS(lastValue) / 2 % 2 != 0) {
  115.                     buf.append(ESCAPE).append(ESCAPE);
  116.                 }
  117.                 buf.append(getDelimiter());
  118.                 lastValue = escapeValue(it.next(), true, transformer);
  119.                 buf.append(lastValue);
  120.             }
  121.             return buf.toString();
  122.         }
  123.         return null;
  124.     }

  125.     /**
  126.      * {@inheritDoc} This is just a dummy implementation. It is never called.
  127.      */
  128.     @Override
  129.     protected String escapeString(final String s) {
  130.         return null;
  131.     }

  132.     /**
  133.      * Escapes the given property value. This method is called on saving the configuration for each property value. It
  134.      * ensures a correct handling of backslash characters and also takes care that list delimiter characters in the value
  135.      * are escaped.
  136.      *
  137.      * @param value the property value
  138.      * @param inList a flag whether the value is part of a list
  139.      * @param transformer the {@code ValueTransformer}
  140.      * @return the escaped property value
  141.      */
  142.     protected String escapeValue(final Object value, final boolean inList, final ValueTransformer transformer) {
  143.         String escapedValue = String.valueOf(transformer.transformValue(escapeBackslashs(value, inList)));
  144.         if (getDelimiter() != 0) {
  145.             escapedValue = StringUtils.replace(escapedValue, String.valueOf(getDelimiter()), ESCAPE + getDelimiter());
  146.         }
  147.         return escapedValue;
  148.     }

  149.     /**
  150.      * Gets the list delimiter character.
  151.      *
  152.      * @return the list delimiter character
  153.      */
  154.     public char getDelimiter() {
  155.         return delimiter;
  156.     }

  157.     /**
  158.      * {@inheritDoc} This implementation simulates the old splitting algorithm. The string is split at the delimiter
  159.      * character if it is not escaped. If the delimiter character is not found, the input is returned unchanged.
  160.      */
  161.     @Override
  162.     protected Collection<String> splitString(final String s, final boolean trim) {
  163.         if (s.indexOf(getDelimiter()) < 0) {
  164.             return Collections.singleton(s);
  165.         }

  166.         final List<String> list = new ArrayList<>();

  167.         StringBuilder token = new StringBuilder();
  168.         int begin = 0;
  169.         boolean inEscape = false;
  170.         final char esc = ESCAPE.charAt(0);

  171.         while (begin < s.length()) {
  172.             final char c = s.charAt(begin);
  173.             if (inEscape) {
  174.                 // last character was the escape marker
  175.                 // can current character be escaped?
  176.                 if (c != getDelimiter() && c != esc) {
  177.                     // no, also add escape character
  178.                     token.append(esc);
  179.                 }
  180.                 token.append(c);
  181.                 inEscape = false;
  182.             } else if (c == getDelimiter()) {
  183.                 // found a list delimiter -> add token and
  184.                 // resetDefaultFileSystem buffer
  185.                 String t = token.toString();
  186.                 if (trim) {
  187.                     t = t.trim();
  188.                 }
  189.                 list.add(t);
  190.                 token = new StringBuilder();
  191.             } else if (c == esc) {
  192.                 // eventually escape next character
  193.                 inEscape = true;
  194.             } else {
  195.                 token.append(c);
  196.             }

  197.             begin++;
  198.         }

  199.         // Trailing delimiter?
  200.         if (inEscape) {
  201.             token.append(esc);
  202.         }
  203.         // Add last token
  204.         String t = token.toString();
  205.         if (trim) {
  206.             t = t.trim();
  207.         }
  208.         list.add(t);

  209.         return list;
  210.     }
  211. }