View Javadoc
1   package net.avcompris.binding.dom.siteExamples;
2   
3   import static com.avcompris.util.junit.JUnitUtils.createTmpFileFromCommentsAroundThisMethod;
4   import static org.junit.Assert.assertEquals;
5   
6   import javax.xml.parsers.DocumentBuilderFactory;
7   
8   import net.avcompris.binding.annotation.XPath;
9   import net.avcompris.binding.dom.helper.DomBinderUtils;
10  
11  import org.junit.Test;
12  import org.w3c.dom.Document;
13  
14  /**
15   * tests that match the APT documentation.
16   * 
17   * @author David Andrianavalontsalama
18   */
19  public class GettingStartedExamplesTest {
20  
21  	@Test
22  	public void testGettingStarted_example001() throws Exception {
23  
24  		final Document document = DocumentBuilderFactory.newInstance()
25  				.newDocumentBuilder().parse(
26  						createTmpFileFromCommentsAroundThisMethod());
27  
28  		/*
29  		 * This is equivalent to:
30  		 * final DomBinder binder = new DefaultDomBinder();
31  		 * final Book book = binder.bind(document, Book.class); 
32  		 *
33  		 */		
34  		final Book book = DomBinderUtils.xmlContentToJava(document, Book.class);
35  
36  		assertEquals("Treasure Island", book.getTitle());
37  		assertEquals(1883, book.getPublishYear());
38  		assertEquals(2, book.getAuthorNames().length);
39  		assertEquals("Robert Louis Stevenson", book.getAuthorNames()[0]);
40  		assertEquals("R. L. Stevenson", book.getAuthorNames()[1]);
41  		assertEquals(2, book.getReferences().length);
42  		assertEquals("en", book.getReferences()[0].getLang());
43  		assertEquals("fr", book.getReferences()[1].getLang());
44  	}
45  
46  	// <book title="Treasure Island">
47  	//    <reference url="http://en.wikipedia.org/wiki/Treasure_Island" lang="en"/>
48  	//    <reference url="http://fr.wikipedia.org/wiki/L'Île_au_trésor" lang="fr"/>
49  	//    <publishedIn>1883</publishedIn>
50  	//    <author>
51  	//       <name>Robert Louis Stevenson</name>
52  	//       <name>R. L. Stevenson</name>
53  	//    </author>
54  	// </book>
55  
56  	@XPath("/book")
57  	public interface Book {
58  
59  		@XPath("@title")
60  		String getTitle();
61  
62  		@XPath("publishedIn")
63  		int getPublishYear();
64  
65  		@XPath("author/name")
66  		String[] getAuthorNames();
67  
68  		@XPath("reference")
69  		MyBookReference[] getReferences();
70  
71  		interface MyBookReference {
72  
73  			@XPath("@url")
74  			String getUrl();
75  
76  			@XPath("@lang")
77  			String getLang();
78  		}
79  	}
80  }