1
|
/**
|
2
|
* Copyright (C) 2007 EDIT
|
3
|
* European Distributed Institute of Taxonomy
|
4
|
* http://www.e-taxonomy.eu
|
5
|
*
|
6
|
* The contents of this file are subject to the Mozilla Public License Version 1.1
|
7
|
* See LICENSE.TXT at the top of this package for the full license terms.
|
8
|
*/
|
9
|
package eu.etaxonomy.cdm.remote.dto.assembler.converter;
|
10
|
|
11
|
|
12
|
import java.time.ZonedDateTime;
|
13
|
import java.util.GregorianCalendar;
|
14
|
|
15
|
import javax.xml.datatype.DatatypeConfigurationException;
|
16
|
import javax.xml.datatype.DatatypeFactory;
|
17
|
import javax.xml.datatype.XMLGregorianCalendar;
|
18
|
|
19
|
import org.dozer.CustomConverter;
|
20
|
import org.dozer.MappingException;
|
21
|
|
22
|
|
23
|
public class DateTimeConverter implements CustomConverter {
|
24
|
|
25
|
@Override
|
26
|
public Object convert(Object destination, Object source, Class destClass, Class sourceClass) {
|
27
|
if (source == null) {
|
28
|
return null;
|
29
|
}
|
30
|
Object result = null;
|
31
|
if (source instanceof ZonedDateTime) {
|
32
|
if(destClass.equals(ZonedDateTime.class)){
|
33
|
result = source;
|
34
|
} else if(destClass.equals(XMLGregorianCalendar.class)){
|
35
|
result = dataTypeFactory().newXMLGregorianCalendar( GregorianCalendar.from((ZonedDateTime)source)); //naive approach, may mot result in correct representation of partial datetime
|
36
|
}
|
37
|
}
|
38
|
|
39
|
if(result == null){
|
40
|
throw new MappingException("Converter TestCustomConverter used incorrectly. Arguments passed in were:"
|
41
|
+ destination + " and " + source);
|
42
|
}
|
43
|
return result;
|
44
|
}
|
45
|
|
46
|
/**
|
47
|
* Cache the DatatypeFactory because newInstance is very expensive.
|
48
|
*/
|
49
|
private static DatatypeFactory dataTypeFactory;
|
50
|
|
51
|
/**
|
52
|
* Returns a new instance of DatatypeFactory, or the cached one if previously created.
|
53
|
*
|
54
|
* @return instance of DatatypeFactory
|
55
|
*/
|
56
|
private static DatatypeFactory dataTypeFactory() {
|
57
|
if (dataTypeFactory == null) {
|
58
|
try {
|
59
|
dataTypeFactory = DatatypeFactory.newInstance();
|
60
|
} catch (DatatypeConfigurationException e) {
|
61
|
throw new MappingException(e);
|
62
|
}
|
63
|
}
|
64
|
return dataTypeFactory;
|
65
|
}
|
66
|
|
67
|
}
|