1 /*
2 * Copyright 2007 Kasper B. Graversen
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.supercsv.cellprocessor.time;
17
18 import java.time.Period;
19 import java.time.format.DateTimeParseException;
20
21 import org.supercsv.cellprocessor.CellProcessorAdaptor;
22 import org.supercsv.cellprocessor.ift.CellProcessor;
23 import org.supercsv.exception.SuperCsvCellProcessorException;
24 import org.supercsv.util.CsvContext;
25
26 /**
27 * Converts a String to a Period.
28 * The input String must conform to the ISO 8601 period format,
29 * recognised by {@link Period#parse(CharSequence)}.
30 * For example, "P6Y3M7D" represents 6 years, 3 months, 7 days.
31 *
32 * @author Ludovico Fischer
33 * @since 2.4.0
34 */
35 public class ParsePeriod extends CellProcessorAdaptor {
36
37 /**
38 * Constructs a new <tt>ParsePeriod</tt> processor, which parses a String as
39 * a Period.
40 */
41 public ParsePeriod() {
42 super();
43 }
44
45 /**
46 * Constructs a new <tt>ParsePeriod</tt> processor, which parses a String as
47 * a Period, then calls the next processor in the chain.
48 *
49 * @param next the next processor in the chain
50 * @throws NullPointerException if next is null
51 */
52 public ParsePeriod(final CellProcessor next) {
53 super(next);
54 }
55
56 /**
57 * {@inheritDoc}
58 *
59 * @throws SuperCsvCellProcessorException if value is null or is not a String
60 */
61 public Object execute(final Object value, final CsvContext context) {
62 validateInputNotNull(value, context);
63 if( !(value instanceof String) ) {
64 throw new SuperCsvCellProcessorException(String.class, value, context, this);
65 }
66
67 final String string = (String) value;
68 final Period result;
69
70 try {
71 result = Period.parse(string);
72 }
73 catch(DateTimeParseException e) {
74 throw new SuperCsvCellProcessorException("Failed to parse value as a Period", context, this, e);
75 }
76
77 return next.execute(result, context);
78 }
79
80 }