View Javadoc
1   /*
2    * Copyright 2011 the original author or authors.
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.openehealth.ipf.commons.ihe.xds.core.metadata;
17  
18  import org.junit.Assert;
19  import org.junit.Test;
20  import org.w3c.dom.Node;
21  
22  import javax.xml.bind.JAXBContext;
23  import javax.xml.bind.JAXBElement;
24  import javax.xml.bind.Marshaller;
25  import javax.xml.bind.Unmarshaller;
26  import javax.xml.namespace.QName;
27  import javax.xml.transform.dom.DOMResult;
28  
29  public class TimeRangeTest {
30      @Test
31      public void testXmlDateSerialization() throws Exception {
32          TimeRange timeRange = new TimeRange();
33  
34          timeRange.setFrom("2011030512");
35          timeRange.setTo("20120301080642.190");
36          checkSerialization("timeRange", timeRange);
37  
38          timeRange.setFrom("20110305");
39          timeRange.setTo("2012");
40          checkSerialization("timeRange", timeRange);
41      }
42  
43      @SuppressWarnings({"unchecked"})
44      private <T> void checkSerialization(String name, T object) throws Exception {
45          QName qname = new QName("http://www.openehealth.org/ipf/xds", name);
46          JAXBElement<T> jaxbElement = new JAXBElement<>(qname, (Class<T>) object.getClass(), object);
47          JAXBContext jaxbContext = JAXBContext.newInstance(TimeRange.class);
48          Marshaller marshaller = jaxbContext.createMarshaller();
49          marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
50          // marshaller.marshal(jaxbElement, System.out);
51  
52          DOMResult domResult = new DOMResult();
53          marshaller.marshal(jaxbElement, domResult);
54          Node marshalledNode = ((org.w3c.dom.Document) domResult.getNode()).getDocumentElement();
55  
56          Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
57          jaxbElement = (JAXBElement<T>) unmarshaller.unmarshal(marshalledNode, TimeRange.class);
58          T objectToo = jaxbElement.getValue();
59  
60          // .toString() is used because org.joda.DateTime.equals() compares not only
61          // the actual timestamps, but also chronologies, and even if they are almost
62          // identical, like ISO and Gregorian, equals() will return false
63          Assert.assertEquals(object.toString(), objectToo.toString());
64      }
65  }