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 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 Period to a String. 27 * Converts to a String in the ISO 8601 format, 28 * in the same way as {@link Period#toString()}. 29 * For example, "P6Y3M7D" represents 6 years, 3 months, 7 days. 30 * 31 * @author Ludovico Fischer 32 * @since 2.4.0 33 */ 34 public class FmtPeriod extends CellProcessorAdaptor { 35 36 /** 37 * Constructs a new <tt>FmtPeriod</tt> processor, which formats a 38 * Period as a String. 39 */ 40 public FmtPeriod() { 41 super(); 42 } 43 44 /** 45 * Constructs a new <tt>FmtPeriod</tt> processor, which formats a 46 * Period as a String, then calls the next processor in the chain. 47 * 48 * @param next the next processor in the chain 49 * @throws NullPointerException if formatter or next is null 50 */ 51 public FmtPeriod(final CellProcessor next) { 52 super(next); 53 } 54 55 /** 56 * {@inheritDoc} 57 * 58 * @throws SuperCsvCellProcessorException if value is null or not a Period 59 */ 60 public Object execute(final Object value, final CsvContext context) { 61 validateInputNotNull(value, context); 62 if( !(value instanceof Period) ) { 63 throw new SuperCsvCellProcessorException(Period.class, value, context, this); 64 } 65 final Period period = (Period) value; 66 final String result = period.toString(); 67 68 return next.execute(result, context); 69 } 70 71 }