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 static org.junit.jupiter.api.Assertions.assertArrayEquals;
20  import static org.junit.jupiter.api.Assertions.assertEquals;
21  import static org.junit.jupiter.api.Assertions.assertNull;
22  import static org.junit.jupiter.api.Assertions.assertThrows;
23  import static org.junit.jupiter.api.Assertions.assertTrue;
24  
25  import java.util.ArrayList;
26  import java.util.Arrays;
27  import java.util.Calendar;
28  import java.util.Collection;
29  import java.util.Date;
30  import java.util.Iterator;
31  import java.util.List;
32  
33  import org.apache.commons.configuration2.ex.ConversionException;
34  import org.apache.commons.configuration2.interpol.ConfigurationInterpolator;
35  import org.junit.jupiter.api.BeforeEach;
36  import org.junit.jupiter.api.Test;
37  
38  /**
39   * Test class for {@code DefaultConversionHandler}.
40   */
41  public class TestDefaultConversionHandler {
42      /** Constant for a variable. */
43      private static final String VAR = "${test}";
44  
45      /** Constant for the value to replace the variable. */
46      private static final String REPLACEMENT = "1";
47  
48      /**
49       * Creates a special test ConfigurationInterpolator. This object only replaces the test variable by its replacement.
50       * Other substitutions are not performed.
51       *
52       * @return the test {@code ConfigurationInterpolator}
53       */
54      private static ConfigurationInterpolator createInterpolator() {
55          return new ConfigurationInterpolator() {
56              @Override
57              public Object interpolate(final Object value) {
58                  if (VAR.equals(value)) {
59                      return REPLACEMENT;
60                  }
61                  return value;
62              }
63          };
64      }
65  
66      /** The conversion handler to be tested. */
67      private DefaultConversionHandler handler;
68  
69      /**
70       * Helper method for testing the result of the conversion of a single value.
71       *
72       * @param expResult the expected result
73       */
74      private void checkSingleValue(final Integer expResult) {
75          assertEquals(Integer.parseInt(REPLACEMENT), expResult.intValue());
76      }
77  
78      @BeforeEach
79      public void setUp() {
80          handler = new DefaultConversionHandler();
81      }
82  
83      /**
84       * Tests whether the default date format is used if no format has been set.
85       */
86      @Test
87      public void testGetDateFormatNotSet() {
88          assertEquals(DefaultConversionHandler.DEFAULT_DATE_FORMAT, handler.getDateFormat());
89      }
90  
91      @Test
92      public synchronized void testListDelimiterHandler() {
93          assertEquals(DefaultConversionHandler.LIST_DELIMITER_HANDLER, handler.getListDelimiterHandler());
94          handler.setListDelimiterHandler(null);
95          assertEquals(DefaultConversionHandler.LIST_DELIMITER_HANDLER, handler.getListDelimiterHandler());
96          final LegacyListDelimiterHandler legacyListDelimiterHandler = new LegacyListDelimiterHandler(',');
97          handler.setListDelimiterHandler(legacyListDelimiterHandler);
98          assertEquals(legacyListDelimiterHandler, handler.getListDelimiterHandler());
99          handler.setListDelimiterHandler(null);
100         assertEquals(DefaultConversionHandler.LIST_DELIMITER_HANDLER, handler.getListDelimiterHandler());
101     }
102 
103     /**
104      * Tests whether the date format can be changed.
105      */
106     @Test
107     public void testSetDateFormat() {
108         final String dateFormat = "dd.MM.yyyy";
109         handler.setDateFormat(dateFormat);
110         assertEquals(dateFormat, handler.getDateFormat());
111     }
112 
113     /**
114      * Tests a conversion to an array from an empty string. An empty string should be interpreted as an empty array.
115      */
116     @Test
117     public void testToArrayEmptyString() {
118         final int[] array = (int[]) handler.toArray("", Integer.TYPE, null);
119         assertEquals(0, array.length);
120     }
121 
122     /**
123      * Tests toArray() if the source object is null.
124      */
125     @Test
126     public void testToArrayNullInput() {
127         assertNull(handler.toArray(null, Integer.class, null));
128     }
129 
130     /**
131      * Tests a conversion to an array of Objects.
132      */
133     @Test
134     public void testToArrayObject() {
135         final List<String> src = Arrays.asList(VAR, "100");
136         final Integer[] array = (Integer[]) handler.toArray(src, Integer.class, createInterpolator());
137         assertArrayEquals(new Integer[] {Integer.valueOf(REPLACEMENT), Integer.valueOf(src.get(1))}, array);
138     }
139 
140     /**
141      * Tests a conversion to an array of primitive type if the source object is something else.
142      */
143     @Test
144     public void testToArrayPrimitiveOtherType() {
145         final List<String> src = Arrays.asList(VAR, "100");
146         final int[] array = (int[]) handler.toArray(src, Integer.TYPE, createInterpolator());
147         assertArrayEquals(new int[] {Integer.parseInt(REPLACEMENT), Integer.parseInt(src.get(1))}, array);
148     }
149 
150     /**
151      * Tests a conversion to an array of primitive type if the source array already has the correct type.
152      */
153     @Test
154     public void testToArrayPrimitiveSameType() {
155         final int[] src = {1, 2, 3, 4, 5, 6};
156         final int[] array = (int[]) handler.toArray(src, Integer.TYPE, createInterpolator());
157         assertArrayEquals(src, array);
158     }
159 
160     /**
161      * Tests a conversion to an array of primitive type if the source array is of the corresponding wrapper type.
162      */
163     @Test
164     public void testToArrayPrimitiveWrapperType() {
165         final Integer[] src = {0, 1, 2, 4, 8, 16, 32, 64, 128};
166         final int[] array = (int[]) handler.toArray(src, Integer.TYPE, createInterpolator());
167         assertArrayEquals(new int[] {0, 1, 2, 4, 8, 16, 32, 64, 128}, array);
168     }
169 
170     /**
171      * Tests a conversion to a Calendar object using the default format.
172      */
173     @Test
174     public void testToCalendarWithDefaultFormat() {
175         final Calendar cal = handler.to("2013-08-19 21:17:22", Calendar.class, null);
176         assertEquals(19, cal.get(Calendar.DATE));
177         assertEquals(Calendar.AUGUST, cal.get(Calendar.MONTH));
178         assertEquals(2013, cal.get(Calendar.YEAR));
179         assertEquals(21, cal.get(Calendar.HOUR_OF_DAY));
180         assertEquals(17, cal.get(Calendar.MINUTE));
181         assertEquals(22, cal.get(Calendar.SECOND));
182     }
183 
184     /**
185      * Tests a conversion to a collection if an empty string is passed in. An empty string should be interpreted as a list
186      * with no values.
187      */
188     @Test
189     public void testToCollectionEmptyString() {
190         final List<Integer> col = new ArrayList<>(1);
191         handler.toCollection("", Integer.class, null, col);
192         assertTrue(col.isEmpty());
193     }
194 
195     /**
196      * Tries to pass a null collection to toCollection().
197      */
198     @Test
199     public void testToCollectionNullCollection() {
200         final List<Integer> src = Arrays.asList(1, 2, 3);
201         assertThrows(IllegalArgumentException.class, () -> handler.toCollection(src, Integer.class, null, null));
202     }
203 
204     /**
205      * Tests a conversion to a collection if the source object is null.
206      */
207     @Test
208     public void testToCollectionNullInput() {
209         final ArrayList<Integer> col = new ArrayList<>();
210         handler.toCollection(null, Integer.class, null, col);
211         assertTrue(col.isEmpty());
212     }
213 
214     /**
215      * Tests a successful conversion to a collection.
216      */
217     @Test
218     public void testToCollectionSuccess() {
219         final Object[] src = {VAR, "100"};
220         final List<Integer> col = new ArrayList<>(src.length);
221         handler.toCollection(src, Integer.class, createInterpolator(), col);
222         assertEquals(Arrays.asList(Integer.valueOf(REPLACEMENT), Integer.valueOf(src[1].toString())), col);
223     }
224 
225     /**
226      * Tests whether a conversion to a date object is possible if a specific date format is used.
227      */
228     @Test
229     public void testToDateWithFormat() {
230         handler.setDateFormat("dd.MM.yyyy");
231         final Date dt = handler.to("19.08.2013", Date.class, null);
232         final Calendar cal = Calendar.getInstance();
233         cal.setTime(dt);
234         assertEquals(19, cal.get(Calendar.DATE));
235         assertEquals(Calendar.AUGUST, cal.get(Calendar.MONTH));
236         assertEquals(2013, cal.get(Calendar.YEAR));
237     }
238 
239     /**
240      * Tests a failed conversion.
241      */
242     @Test
243     public void testToFailedConversion() {
244         assertThrows(ConversionException.class, () -> handler.to(VAR, Integer.class, null));
245     }
246 
247     /**
248      * Tests whether a conversion from an array is possible.
249      */
250     @Test
251     public void testToFromArray() {
252         final Object[] src = {VAR, true, 20130808221759L};
253         checkSingleValue(handler.to(src, Integer.class, createInterpolator()));
254     }
255 
256     /**
257      * Tests whether a conversion from a collection is possible.
258      */
259     @Test
260     public void testToFromCollection() {
261         final Collection<String> src = Arrays.asList(VAR, "true", "1000");
262         checkSingleValue(handler.to(src, Integer.class, createInterpolator()));
263     }
264 
265     /**
266      * Tests whether empty complex objects are handled when converting to a single value.
267      */
268     @Test
269     public void testToFromEmptyCollection() {
270         assertNull(handler.to(new ArrayList<>(), Integer.class, createInterpolator()));
271     }
272 
273     /**
274      * Tests whether a conversion from an iterator is possible.
275      */
276     @Test
277     public void testToFromIterator() {
278         final Iterator<String> src = Arrays.asList(VAR, "true", "1000").iterator();
279         checkSingleValue(handler.to(src, Integer.class, createInterpolator()));
280     }
281 
282     /**
283      * Tests whether a ConfigurationInterpolator is optional.
284      */
285     @Test
286     public void testToNoInterpolator() {
287         final Integer result = handler.to(REPLACEMENT, Integer.class, null);
288         checkSingleValue(result);
289     }
290 
291     /**
292      * Tests whether null input is handled by to().
293      */
294     @Test
295     public void testToNull() {
296         assertNull(handler.to(null, Integer.class, null));
297     }
298 
299     /**
300      * Tests a conversion to a primitive type.
301      */
302     @Test
303     public void testToPrimitive() {
304         final Long value = 20130819214935L;
305         final Object result = handler.to(value.toString(), Long.TYPE, null);
306         assertEquals(value, result);
307     }
308 
309     /**
310      * Tests a conversion with a ConfigurationInterpolator.
311      */
312     @Test
313     public void testToWithInterpolator() {
314         final Integer result = handler.to(VAR, Integer.class, createInterpolator());
315         checkSingleValue(result);
316     }
317 }