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.joda;
17  
18  import org.joda.time.Duration;
19  import org.supercsv.cellprocessor.CellProcessorAdaptor;
20  import org.supercsv.cellprocessor.ift.CellProcessor;
21  import org.supercsv.exception.SuperCsvCellProcessorException;
22  import org.supercsv.util.CsvContext;
23  
24  /**
25   * Converts a String to a Joda Duration.
26   * 
27   * The String should be in the ISO8601 duration format including only seconds
28   * and milliseconds.
29   * <p>
30   * For example, "PT72.345S" represents 1 minute, 12 seconds and 345
31   * milliseconds.
32   * <p>
33   * 
34   * @since 2.3.0
35   * @author James Bassett
36   */
37  public class ParseDuration extends CellProcessorAdaptor {
38  
39  	/**
40  	 * Constructs a new <tt>ParseDuration</tt> processor, which parses a String
41  	 * as a Joda Duration.
42  	 */
43  	public ParseDuration() {
44  	}
45  
46  	/**
47  	 * Constructs a new <tt>ParseDuration</tt> processor, which parses a String
48  	 * as a Joda Duration, then calls the next processor in the chain.
49  	 * 
50  	 * @param next
51  	 *            the next processor in the chain
52  	 */
53  	public ParseDuration(final CellProcessor next) {
54  		super(next);
55  	}
56  
57  	/**
58  	 * {@inheritDoc}
59  	 * 
60  	 * @throws SuperCsvCellProcessorException
61  	 *             if value is null or is not a String
62  	 */
63  	public Object execute(final Object value, final CsvContext context) {
64  		validateInputNotNull(value, context);
65  		if (!(value instanceof String)) {
66  			throw new SuperCsvCellProcessorException(String.class, value,
67  					context, this);
68  		}
69  		final Duration result;
70  		try {
71  			result = Duration.parse((String) value);
72  		} catch (IllegalArgumentException e) {
73  			throw new SuperCsvCellProcessorException(
74  					"Failed to parse value as a Duration", context, this, e);
75  		}
76  		return next.execute(result, context);
77  	}
78  
79  }