001package io.konik.csv.processor; 002 003import org.slf4j.Logger; 004import org.slf4j.LoggerFactory; 005import org.supercsv.cellprocessor.ift.CellProcessor; 006import org.supercsv.util.CsvContext; 007 008import java.text.DateFormat; 009import java.text.ParseException; 010import java.text.SimpleDateFormat; 011import java.util.Date; 012 013/** 014 * Custom {@link CellProcessor} for {@link Date} class. 015 * 016 * It uses proper {@link java.text.DateFormat} to convert object from and to a String value. 017 */ 018public final class DateProcessor implements CellProcessor { 019 020 private static final Logger log = LoggerFactory.getLogger(DateProcessor.class); 021 022 private static final ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() { 023 @Override 024 protected DateFormat initialValue() { 025 return new SimpleDateFormat("yyyyMMdd"); 026 } 027 }; 028 029 public DateFormat getDateFormat() { 030 return dateFormat.get(); 031 } 032 033 @Override 034 public Object execute(Object value, CsvContext context) { 035 036 if (value instanceof String) { 037 String dateStr = (String) value; 038 Date date = null; 039 040 try { 041 return dateFormat.get().parse(dateStr); 042 } catch (ParseException e) { 043 log.error("Parsing {} throws an exception: {}", value, e.getMessage()); 044 throw new RuntimeException(String.format("Value %s does not match valid date format (yyyyMMdd)", value)); 045 } 046 } 047 048 if (value instanceof Date) { 049 return dateFormat.get().format(value); 050 } 051 052 return null; 053 } 054}