|
| 1 | +package com.baeldung.dozer; |
| 2 | + |
| 3 | +import java.text.DateFormat; |
| 4 | +import java.text.ParseException; |
| 5 | +import java.text.SimpleDateFormat; |
| 6 | +import java.util.Date; |
| 7 | + |
| 8 | +import org.dozer.CustomConverter; |
| 9 | +import org.dozer.MappingException; |
| 10 | + |
| 11 | +public class MyCustomConvertor implements CustomConverter { |
| 12 | + |
| 13 | + @Override |
| 14 | + public Object convert(Object dest, Object source, Class<?> arg2, |
| 15 | + Class<?> arg3) { |
| 16 | + if (source == null) { |
| 17 | + return null; |
| 18 | + } |
| 19 | + if (source instanceof Personne3) { |
| 20 | + Personne3 person = (Personne3) source; |
| 21 | + Date date = new Date(person.getDtob()); |
| 22 | + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); |
| 23 | + String isoDate = format.format(date); |
| 24 | + return new Person3(person.getName(), isoDate); |
| 25 | + |
| 26 | + } else if (source instanceof Person3) { |
| 27 | + Person3 person = (Person3) source; |
| 28 | + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); |
| 29 | + Date date = null; |
| 30 | + try { |
| 31 | + date = format.parse(person.getDtob()); |
| 32 | + |
| 33 | + } catch (ParseException e) { |
| 34 | + throw new MappingException("Converter MyCustomConvertor " |
| 35 | + + "used incorrectly:" + e.getMessage()); |
| 36 | + } |
| 37 | + long timestamp = date.getTime(); |
| 38 | + return new Personne3(person.getName(), timestamp); |
| 39 | + |
| 40 | + } else { |
| 41 | + throw new MappingException("Converter MyCustomConvertor " |
| 42 | + + "used incorrectly. Arguments passed in were:" + dest |
| 43 | + + " and " + source); |
| 44 | + |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | +} |
0 commit comments