Project

General

Profile

Download (1.93 KB) Statistics
| Branch: | Tag: | Revision:
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
import javax.xml.datatype.DatatypeConfigurationException;
12
import javax.xml.datatype.DatatypeFactory;
13
import javax.xml.datatype.XMLGregorianCalendar;
14

    
15
import org.joda.time.DateTime;
16

    
17
import com.github.dozermapper.core.MappingException;
18

    
19
public class DateTimeConverter implements com.github.dozermapper.core.CustomConverter {
20

    
21
	@Override
22
    public Object convert(Object destination, Object source, Class<?> destClass, Class<?> sourceClass) {
23
		if (source == null) {
24
			return null;
25
		}
26
		Object result = null;
27
		if (source instanceof DateTime) {
28
			if(destClass.equals(DateTime.class)){
29
				result =  new DateTime((source));
30
			} else if(destClass.equals(XMLGregorianCalendar.class)){
31
				result = dataTypeFactory().newXMLGregorianCalendar(((DateTime)source).toGregorianCalendar()); //naive approach, may mot result in correct representation of partial datetime
32
			}
33
		}
34

    
35
		if(result == null){
36
			throw new MappingException("Converter TestCustomConverter used incorrectly. Arguments passed in were:"
37
					+ destination + " and " + source);
38
		}
39
		return result;
40
	}
41

    
42
	  /**
43
	   * Cache the DatatypeFactory because newInstance is very expensive.
44
	   */
45
	  private static DatatypeFactory dataTypeFactory;
46

    
47
	/**
48
	   * Returns a new instance of DatatypeFactory, or the cached one if previously created.
49
	   *
50
	   * @return instance of DatatypeFactory
51
	   */
52
	  private static DatatypeFactory dataTypeFactory() {
53
	    if (dataTypeFactory == null) {
54
	      try {
55
	        dataTypeFactory = DatatypeFactory.newInstance();
56
	      } catch (DatatypeConfigurationException e) {
57
	        throw new MappingException(e);
58
	      }
59
	    }
60
	    return dataTypeFactory;
61
	  }
62
}
(1-1/11)