View Javadoc
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  
19  import java.lang.reflect.Array;
20  import java.nio.file.Path;
21  import java.util.ArrayList;
22  import java.util.Collection;
23  import java.util.Iterator;
24  import java.util.LinkedList;
25  import java.util.Set;
26  
27  /**
28   * <p>
29   * An abstract base class for concrete {@code ListDelimiterHandler} implementations.
30   * </p>
31   * <p>
32   * This base class provides a fully functional implementation for parsing a value object which can deal with different
33   * cases like collections, arrays, iterators, etc. This logic is typically needed by every concrete subclass. Other
34   * methods are partly implemented handling special corner cases like <b>null</b> values; concrete subclasses do not have
35   * do implement the corresponding checks.
36   * </p>
37   *
38   * @since 2.0
39   */
40  public abstract class AbstractListDelimiterHandler implements ListDelimiterHandler {
41  
42      /**
43       * Flattens the given iterator. For each element in the iteration {@code flatten()} is called recursively.
44       *
45       * @param handler the working handler
46       * @param target the target collection
47       * @param iterator the iterator to process
48       * @param limit a limit for the number of elements to extract
49       * @param dejaVue Previously visited objects.
50       */
51      static void flattenIterator(final ListDelimiterHandler handler, final Collection<Object> target, final Iterator<?> iterator, final int limit,
52              Set<Object> dejaVue) {
53          int size = target.size();
54          while (size < limit && iterator.hasNext()) {
55              final Object next = iterator.next();
56              if (!dejaVue.contains(next)) {
57                  target.addAll(flatten(handler, next, limit - size, dejaVue));
58                  size = target.size();
59              }
60          }
61      }
62  
63      static Collection<?> flatten(final ListDelimiterHandler handler, final Object value, final int limit, final Set<Object> dejaVu) {
64          dejaVu.add(value);
65          if (value instanceof String) {
66              return handler.split((String) value, true);
67          }
68          final Collection<Object> result = new LinkedList<>();
69          if (value instanceof Path) {
70              // Don't handle as an Iterable.
71              result.add(value);
72          } else if (value instanceof Iterable) {
73              AbstractListDelimiterHandler.flattenIterator(handler, result, ((Iterable<?>) value).iterator(), limit, dejaVu);
74          } else if (value instanceof Iterator) {
75              AbstractListDelimiterHandler.flattenIterator(handler, result, (Iterator<?>) value, limit, dejaVu);
76          } else if (value != null) {
77              if (value.getClass().isArray()) {
78                  for (int len = Array.getLength(value), idx = 0, size = 0; idx < len && size < limit; idx++, size = result.size()) {
79                      result.addAll(handler.flatten(Array.get(value, idx), limit - size));
80                  }
81              } else {
82                  result.add(value);
83              }
84          }
85          return result;
86      }
87  
88      /**
89       * {@inheritDoc} This implementation checks whether the object to be escaped is a string. If yes, it delegates to
90       * {@link #escapeString(String)}, otherwise no escaping is performed. Eventually, the passed in transformer is invoked
91       * so that additional encoding can be performed.
92       */
93      @Override
94      public Object escape(final Object value, final ValueTransformer transformer) {
95          return transformer.transformValue(value instanceof String ? escapeString((String) value) : value);
96      }
97  
98      /**
99       * Escapes the specified string. This method is called by {@code escape()} if the passed in object is a string. Concrete
100      * subclasses have to implement their specific escaping logic here, so that the list delimiters they support are
101      * properly escaped.
102      *
103      * @param s the string to be escaped (not <b>null</b>)
104      * @return the escaped string
105      */
106     protected abstract String escapeString(String s);
107 
108     /**
109      * Performs the actual work as advertised by the {@code parse()} method. This method delegates to
110      * {@link #flatten(Object, int)} without specifying a limit.
111      *
112      * @param value the value to be processed
113      * @return a &quot;flat&quot; collection containing all primitive values of the passed in object
114      */
115     private Collection<?> flatten(final Object value) {
116         return flatten(value, Integer.MAX_VALUE);
117     }
118 
119     /**
120      * {@inheritDoc} Depending on the type of the passed in object the following things happen:
121      * <ul>
122      * <li>Strings are checked for delimiter characters and split if necessary. This is done by calling the {@code split()}
123      * method.</li>
124      * <li>For objects implementing the {@code Iterable} interface, the corresponding {@code Iterator} is obtained, and
125      * contained elements are added to the resulting iteration.</li>
126      * <li>Arrays are treated as {@code Iterable} objects.</li>
127      * <li>All other types are directly inserted.</li>
128      * <li>Recursive combinations are supported, e.g. a collection containing an array that contains strings: The resulting
129      * collection will only contain primitive objects.</li>
130      * </ul>
131      */
132     @Override
133     public Iterable<?> parse(final Object value) {
134         return flatten(value);
135     }
136 
137     /**
138      * {@inheritDoc} This implementation handles the case that the passed in string is <b>null</b>. In this case, an empty
139      * collection is returned. Otherwise, this method delegates to {@link #splitString(String, boolean)}.
140      */
141     @Override
142     public Collection<String> split(final String s, final boolean trim) {
143         return s == null ? new ArrayList<>(0) : splitString(s, trim);
144     }
145 
146     /**
147      * Actually splits the passed in string which is guaranteed to be not <b>null</b>. This method is called by the base
148      * implementation of the {@code split()} method. Here the actual splitting logic has to be implemented.
149      *
150      * @param s the string to be split (not <b>null</b>)
151      * @param trim a flag whether the single components have to be trimmed
152      * @return a collection with the extracted components of the passed in string
153      */
154     protected abstract Collection<String> splitString(String s, boolean trim);
155 }