View Javadoc

1   package com.atlassian.sal.api.user;
2   
3   import java.io.StringReader;
4   import java.io.StringWriter;
5   
6   import javax.xml.bind.JAXBContext;
7   import javax.xml.bind.Marshaller;
8   import javax.xml.bind.Unmarshaller;
9   import javax.xml.bind.annotation.XmlElement;
10  import javax.xml.bind.annotation.XmlRootElement;
11  import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
12  
13  import org.junit.Before;
14  import org.junit.Test;
15  
16  import static javax.xml.bind.Marshaller.JAXB_FRAGMENT;
17  import static org.hamcrest.Matchers.is;
18  import static org.junit.Assert.assertThat;
19  
20  public class TestUserKeyXmlAdapter
21  {
22      private Marshaller marshaller;
23      private Unmarshaller unmarshaller;
24  
25      @Before
26      public void setUp() throws Exception
27      {
28          JAXBContext jaxbContext = JAXBContext.newInstance(TestEntity.class);
29  
30          marshaller = jaxbContext.createMarshaller();
31          marshaller.setProperty(JAXB_FRAGMENT, true);
32  
33          unmarshaller = jaxbContext.createUnmarshaller();
34      }
35  
36      @Test
37      public void xmlAdapterMarshalsAndUnMarshalsCorrectly() throws Exception
38      {
39          final TestEntity testEntity = new TestEntity();
40          testEntity.userKey = new UserKey("abc");
41  
42          final StringWriter buffer = new StringWriter();
43          marshaller.marshal(testEntity, buffer);
44  
45          assertThat(buffer.toString(), is("<testEntity><userKey>abc</userKey></testEntity>"));
46  
47          final TestEntity unmarshalledEntity = (TestEntity) unmarshaller.unmarshal(new StringReader(buffer.toString()));
48  
49          assertThat(unmarshalledEntity.userKey, is(new UserKey("abc")));
50      }
51  
52      @XmlRootElement
53      public static class TestEntity
54      {
55          @XmlJavaTypeAdapter(UserKeyXmlAdapter.class)
56          @XmlElement
57          UserKey userKey;
58      }
59  }