View Javadoc
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.Duration;
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 Duration.
28   * The String should be in the ISO 8601 duration format as defined in
29   * {@link Duration#parse(CharSequence)}
30   * For example, "PT1M12.345S" represents 1 minute, 12 seconds and 345
31   * milliseconds.
32   *
33   * @author Ludovico Fischer
34   * @since 2.4.0
35   */
36  public class ParseDuration extends CellProcessorAdaptor {
37  
38  	/**
39  	 * Constructs a new <tt>ParseDuration</tt> processor, which parses a String
40  	 * as a Duration.
41  	 */
42  	public ParseDuration() {
43  	}
44  
45  	/**
46  	 * Constructs a new <tt>ParseDuration</tt> processor, which parses a String
47  	 * as a Duration, then calls the next processor in the chain.
48  	 *
49  	 * @param next the next processor in the chain
50  	 */
51  	public ParseDuration(final CellProcessor next) {
52  		super(next);
53  	}
54  
55  	/**
56  	 * {@inheritDoc}
57  	 *
58  	 * @throws SuperCsvCellProcessorException if value is null or is not a String
59  	 */
60  	public Object execute(final Object value, final CsvContext context) {
61  		validateInputNotNull(value, context);
62  		if( !(value instanceof String) ) {
63  			throw new SuperCsvCellProcessorException(String.class, value, context, this);
64  		}
65  		final Duration result;
66  		try {
67  			result = Duration.parse((String) value);
68  		}
69  		catch(DateTimeParseException e) {
70  			throw new SuperCsvCellProcessorException("Failed to parse value as a Duration", context, this, e);
71  		}
72  		return next.execute(result, context);
73  	}
74  
75  }