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 20 import org.supercsv.cellprocessor.CellProcessorAdaptor; 21 import org.supercsv.cellprocessor.ift.CellProcessor; 22 import org.supercsv.exception.SuperCsvCellProcessorException; 23 import org.supercsv.util.CsvContext; 24 25 /** 26 * Converts a Duration to a String. 27 * 28 * For example, "PT1M12.345S" represents 1 minute, 12 seconds and 345 29 * milliseconds. 30 * 31 * @author Ludovico Fischer 32 * @since 2.4.0 33 */ 34 public class FmtDuration extends CellProcessorAdaptor { 35 36 /** 37 * Constructs a new <tt>FmtDuration</tt> processor, which formats a 38 * Duration as a String in the ISO 8601 duration format, 39 * in the same way as {@link Duration#toString()} 40 * 41 * @see Duration#toString() 42 */ 43 public FmtDuration() { 44 } 45 46 /** 47 * Constructs a new <tt>FmtDuration</tt> processor, which formats a 48 * Duration as a String, then calls the next processor in the chain. 49 * 50 * @param next next processor in the chain 51 * @throws NullPointerException if next is null 52 */ 53 public FmtDuration(final CellProcessor next) { 54 super(next); 55 } 56 57 /** 58 * {@inheritDoc} 59 * 60 * @throws SuperCsvCellProcessorException if value is null or not a Duration 61 */ 62 public Object execute(final Object value, final CsvContext context) { 63 validateInputNotNull(value, context); 64 if( !(value instanceof Duration) ) { 65 throw new SuperCsvCellProcessorException(Duration.class, value, context, this); 66 } 67 final Duration duration = (Duration) value; 68 final String result = duration.toString(); 69 return next.execute(result, context); 70 } 71 }