PageRenderTime 92ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/Prototipo/Servlet/lib/xstream-distribution-1.4.1-bin/xstream-1.4.1/docs/annotations-tutorial.html

http://prototipomemoria.googlecode.com/
HTML | 497 lines | 410 code | 67 blank | 20 comment | 0 complexity | 4e86e726f002cf88a4e37915b4307897 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <!--
  4. Copyright (C) 2005, 2006 Joe Walnes.
  5. Copyright (C) 2006, 2007, 2008 XStream committers.
  6. All rights reserved.
  7. The software in this package is published under the terms of the BSD
  8. style license a copy of which has been included with this distribution in
  9. the LICENSE.txt file.
  10. Created on 29. January 2005 by Joe Walnes
  11. -->
  12. <head>
  13. <title>XStream - Annotations Tutorial</title>
  14. <link rel="stylesheet" type="text/css" href="style.css"/>
  15. <!-- Google analytics -->
  16. <script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
  17. </script>
  18. <script type="text/javascript">
  19. _uacct = "UA-110973-2";
  20. urchinTracker();
  21. </script>
  22. </head>
  23. <body>
  24. <div id="banner">
  25. <a href="index.html"><img id="logo" src="logo.gif" alt="XStream"/></a>
  26. </div>
  27. <div id="center" class="Content2Column"> <!-- Content3Column for index -->
  28. <div id="content">
  29. <h1 class="FirstChild">Annotations Tutorial</h1>
  30. <!-- ...................................................... -->
  31. <h2 id="Motivation">Motivation</h2>
  32. <p>Sometimes it can get tedious to call all those XStream aliases/register converter methods or you might simply like
  33. the new trend on configuring POJOs: Java annotations.</p>
  34. <p>This tutorial will show you how to use some of the annotations provided by XStream in order to make configuration
  35. easier. Let's start with a custom Message class:</p>
  36. <div class="Source Java"><pre>package com.thoughtworks.xstream;
  37. package com.thoughtworks.xstream;
  38. public class RendezvousMessage {
  39. private int messageType;
  40. public RendezvousMessage(int messageType) {
  41. this.messageType = messageType;
  42. }
  43. }</pre></div>
  44. <p>Let's code the XStream calls which generate the XML file:</p>
  45. <div class="Source Java"><pre>
  46. package com.thoughtworks.xstream;
  47. public class Tutorial {
  48. public static void main(String[] args) {
  49. XStream stream = new XStream();
  50. RendezvousMessage msg = new RendezvousMessage(15);
  51. System.out.println(stream.toXML(msg));
  52. }
  53. }
  54. </pre></div>
  55. <p>Results in the following XML:</p>
  56. <div class="Source Java"><pre>
  57. &lt;com.thoughtworks.xstream.RendezvousMessage&gt;
  58. &lt;messageType&gt;15&lt;/messageType&gt;
  59. &lt;/com.thoughtworks.xstream.RendezvousMessage&gt;
  60. </pre></div>
  61. <!-- ...................................................... -->
  62. <h2 id="Aliasing">Aliasing Annotation</h2>
  63. <p>The most basic annotation is the one responsible for type and field aliasing: @XStreamAlias. Let's annotate both
  64. our type and field and run the tutorial method again:</p>
  65. <div class="Source Java"><pre>
  66. @XStreamAlias("message")
  67. class RendezvousMessage {
  68. @XStreamAlias("type")
  69. private int messageType;
  70. public RendezvousMessage(int messageType) {
  71. this.messageType = messageType;
  72. }
  73. }
  74. </pre></div>
  75. <p>In some strange way, the result is the same. What happened here? XStream does not read this annotation by default
  76. as it would be impossible to deserialize the XML code. Therefore we need to tell XStream to read the annotations from
  77. this type:</p>
  78. <div class="Source Java"><pre>
  79. public static void main(String[] args) {
  80. XStream stream = new XStream();
  81. xstream.processAnnotations(RendezvousMessage.class);
  82. RendezvousMessage msg = new RendezvousMessage(15);
  83. System.out.println(stream.toXML(msg));
  84. }
  85. </pre></div>
  86. <p>Note that we have called the processAnnotations method of XStream. This method registers all aliases annotations in
  87. the XStream instance passed as first argument. You may also use the overloaded version of this method taking an array
  88. of types. The resulting XML is now what we have expected:</p>
  89. <div class="Source Java"><pre>
  90. &lt;message&gt;
  91. &lt;type&gt;15&lt;/type&gt;
  92. &lt;/message&gt;
  93. </pre></div>
  94. <p>If you let XStream process the annotations of a type, it will also process all annotations of the related types i.e.
  95. all super types, implemented interfaces, the class types of the members and all their generic types.</p>
  96. <!-- ...................................................... -->
  97. <h2 id="ImplicitCollections">Implicit Collections</h2>
  98. <p>Let's add a List of content to our RendezvousMessage. We desire the same functionality obtained with implicit
  99. collections:</p>
  100. <div class="Source Java"><pre>
  101. @XStreamAlias("message")
  102. class RendezvousMessage {
  103. @XStreamAlias("type")
  104. private int messageType;
  105. private List&lt;String&gt; content;
  106. public RendezvousMessage(int messageType, String ... content) {
  107. this.messageType = messageType;
  108. this.content = Arrays.asList(content);
  109. }
  110. }
  111. </pre></div>
  112. <div class="Source Java"><pre>
  113. public static void main(String[] args) {
  114. XStream stream = new XStream();
  115. xstream.processAnnotations(RendezvousMessage.class);
  116. RendezvousMessage msg = new RendezvousMessage(15, "firstPart","secondPart");
  117. System.out.println(stream.toXML(msg));
  118. }
  119. </pre></div>
  120. <p>The resulting XML shows the collection name before its elements:</p>
  121. <div class="Source Java"><pre>
  122. &lt;message&gt;
  123. &lt;type&gt;15&lt;/type&gt;
  124. &lt;content class="java.util.Arrays$ArrayList"&gt;
  125. &lt;a class="string-array"&gt;
  126. &lt;string&gt;firstPart&lt;/string&gt;
  127. &lt;string&gt;secondPart&lt;/string&gt;
  128. &lt;/a&gt;
  129. &lt;/content&gt;
  130. &lt;/message&gt;
  131. </pre></div>
  132. <p>This is not what we desire therefore we will annotate the content list to be recognized as an implicit collection:</p>
  133. <div class="Source Java"><pre>
  134. @XStreamAlias("message")
  135. class RendezvousMessage {
  136. @XStreamAlias("type")
  137. private int messageType;
  138. @XStreamImplicit
  139. private List&lt;String&gt; content;
  140. public RendezvousMessage(int messageType, String... content) {
  141. this.messageType = messageType;
  142. this.content = Arrays.asList(content);
  143. }
  144. }
  145. </pre></div>
  146. <p>Resulting in an XML which ignores the field name (content) of the list:</p>
  147. <div class="Source Java"><pre>
  148. &lt;message&gt;
  149. &lt;type&gt;15&lt;/type&gt;
  150. &lt;a class="string-array"&gt;
  151. &lt;string&gt;firstPart&lt;/string&gt;
  152. &lt;string&gt;secondPart&lt;/string&gt;
  153. &lt;/a&gt;
  154. &lt;/message&gt;
  155. </pre></div>
  156. <p>We are almost there... we still want to remove the 'a' tag, and define each content part with the tag 'part'. In
  157. order to do so, let's add another attribute to our implicit collection annotation. The attribute field defines the
  158. name of the tag used for data contained inside this collection:</p>
  159. <div class="Source Java"><pre>
  160. @XStreamAlias("message")
  161. class RendezvousMessage {
  162. @XStreamAlias("type")
  163. private int messageType;
  164. @XStreamImplicit(itemFieldName="part")
  165. private List&lt;String&gt; content;
  166. public RendezvousMessage(int messageType, String... content) {
  167. this.messageType = messageType;
  168. this.content = Arrays.asList(content);
  169. }
  170. }
  171. </pre></div>
  172. <p>Resulting in a cleaner XML:</p>
  173. <div class="Source Java"><pre>
  174. &lt;message&gt;
  175. &lt;type&gt;15&lt;/type&gt;
  176. &lt;part&gt;firstPart&lt;/part&gt;
  177. &lt;part&gt;secondPart&lt;/part&gt;
  178. &lt;/message&gt;
  179. </pre></div>
  180. <p>The implicit annotation can also be used for arrays and maps. In the latter case you should provide the field name
  181. of the values that are used as key of the map.</p>
  182. <!-- ...................................................... -->
  183. <h2 id="LocalConverters">Local Converters</h2>
  184. <p>Let's create another attribute which defines the timestamp when the message was created:</p>
  185. <div class="Source Java"><pre>
  186. @XStreamAlias("message")
  187. class RendezvousMessage {
  188. @XStreamAlias("type")
  189. private int messageType;
  190. @XStreamImplicit(itemFieldName="part")
  191. private List&lt;String&gt; content;
  192. private Calendar created = new GregorianCalendar();
  193. public RendezvousMessage(int messageType, String... content) {
  194. this.messageType = messageType;
  195. this.content = Arrays.asList(content);
  196. }
  197. }
  198. </pre></div>
  199. <p>Resulting in the following xml:</p>
  200. <div class="Source Java"><pre>
  201. &lt;message&gt;
  202. &lt;type&gt;15&lt;/type&gt;
  203. &lt;part&gt;firstPart&lt;/part&gt;
  204. &lt;part&gt;secondPart&lt;/part&gt;
  205. &lt;created&gt;
  206. &lt;time&gt;1154097812245&lt;/time&gt;
  207. &lt;timezone&gt;America/Sao_Paulo&lt;/timezone&gt;
  208. &lt;/created&gt;
  209. &lt;/message&gt;
  210. </pre></div>
  211. <p>Now we face the following problem: We want to use a custom converter locally for this Calendar, but only for this
  212. Calendar, this exact field in this exact type. Easy... let's annotate it with the custom converter annotation:</p>
  213. <div class="Source Java"><pre>
  214. @XStreamAlias("message")
  215. class RendezvousMessage {
  216. @XStreamAlias("type")
  217. private int messageType;
  218. @XStreamImplicit(itemFieldName="part")
  219. private List&lt;String&gt; content;
  220. @XStreamConverter(SingleValueCalendarConverter.class)
  221. private Calendar created = new GregorianCalendar();
  222. public RendezvousMessage(int messageType, String... content) {
  223. this.messageType = messageType;
  224. this.content = Arrays.asList(content);
  225. }
  226. }
  227. </pre></div>
  228. <p>Let's create the custom converter:</p>
  229. <div class="Source Java"><pre>
  230. public class SingleValueCalendarConverter implements Converter {
  231. public void marshal(Object source, HierarchicalStreamWriter writer,
  232. MarshallingContext context) {
  233. Calendar calendar = (Calendar) source;
  234. writer.setValue(String.valueOf(calendar.getTime().getTime()));
  235. }
  236. public Object unmarshal(HierarchicalStreamReader reader,
  237. UnmarshallingContext context) {
  238. GregorianCalendar calendar = new GregorianCalendar();
  239. calendar.setTime(new Date(Long.parseLong(reader.getValue())));
  240. return calendar;
  241. }
  242. public boolean canConvert(Class type) {
  243. return type.equals(GregorianCalendar.class);
  244. }
  245. }
  246. </pre></div>
  247. <p>And we end up with the converter being used and generating the following XML:</p>
  248. <div class="Source Java"><pre>
  249. &lt;message&gt;
  250. &lt;type&gt;15&lt;/type&gt;
  251. &lt;part&gt;firstPart&lt;/part&gt;
  252. &lt;part&gt;secondPart&lt;/part&gt;
  253. &lt;created&gt;1154097812245&lt;/created&gt;
  254. &lt;/message&gt;
  255. </pre></div>
  256. <!-- ...................................................... -->
  257. <h2 id="Attributes">Attributes</h2>
  258. <p>The client may asks for the type tag to be an attribute inside the message tag, as follows:</p>
  259. <div class="Source Java"><pre>
  260. &lt;message type="15"&gt;
  261. &lt;part&gt;firstPart&lt;/part&gt;
  262. &lt;part&gt;secondPart&lt;/part&gt;
  263. &lt;created&gt;1154097812245&lt;/created&gt;
  264. &lt;/message&gt;
  265. </pre></div>
  266. <p>All you need to do is add the @XStreamAsAttribute annotation:</p>
  267. <div class="Source Java"><pre>
  268. @XStreamAlias("message")
  269. class RendezvousMessage {
  270. @XStreamAlias("type")
  271. @XStreamAsAttribute
  272. private int messageType;
  273. @XStreamImplicit(itemFieldName="part")
  274. private List&lt;String&gt; content;
  275. @XStreamConverter(SingleValueCalendarConverter.class)
  276. private Calendar created = new GregorianCalendar();
  277. public RendezvousMessage(int messageType, String... content) {
  278. this.messageType = messageType;
  279. this.content = Arrays.asList(content);
  280. }
  281. }
  282. </pre></div>
  283. <!-- ...................................................... -->
  284. <h2 id="OmitField">Omitting Fields</h2>
  285. <p>Sometimes a class may contain elements that should not be part of the resulting XML. In our case we may now drop
  286. the 'messageType', since we are only interested at the content. This is easy using the @XStreamOmitField annotation:</p>
  287. <div class="Source Java"><pre>
  288. @XStreamAlias("message")
  289. class RendezvousMessage {
  290. @XStreamOmitField
  291. private int messageType;
  292. @XStreamImplicit(itemFieldName="part")
  293. private List&lt;String&gt; content;
  294. @XStreamConverter(SingleValueCalendarConverter.class)
  295. private Calendar created = new GregorianCalendar();
  296. public RendezvousMessage(int messageType, String... content) {
  297. this.messageType = messageType;
  298. this.content = Arrays.asList(content);
  299. }
  300. }
  301. </pre></div>
  302. <p>The resulting XML does not contain the type of the message anymore:</p>
  303. <div class="Source Java"><pre>
  304. &lt;message&gt;
  305. &lt;part&gt;firstPart&lt;/part&gt;
  306. &lt;part&gt;secondPart&lt;/part&gt;
  307. &lt;created&gt;1154097812245&lt;/created&gt;
  308. &lt;/message&gt;
  309. </pre></div>
  310. <!-- ...................................................... -->
  311. <h2 id="AutoDetect">Auto-detect Annotations</h2>
  312. <p>Until now we have always told you, that you have to call processAnnotation to configure the XStream instance with
  313. the present annotations in the different classes. However, this is only half the truth. You can run XStream also in a
  314. lazy mode, where it auto-detects the annotations while processing the object graph and configure the XStream instance
  315. on-the-fly:</p>
  316. <div class="Source Java"><pre>
  317. package com.thoughtworks.xstream;
  318. public class Tutorial {
  319. public static void main(String[] args) {
  320. XStream stream = new XStream();
  321. xstream.autodetectAnnotations(true);
  322. RendezvousMessage msg = new RendezvousMessage(15);
  323. System.out.println(stream.toXML(msg));
  324. }
  325. }
  326. </pre></div>
  327. <p>The resulting XML will look as expected! Nevertheless you have to understand the implications, therefore some words
  328. of warning:</p>
  329. <ol>
  330. <li><strong>Chicken-and-egg problem</strong>
  331. <p>An XStream instance caches all class types processed for annotations. Every time XStream converts an object it will
  332. in auto-detection mode first process the object's type and all the types related (as explained
  333. <a href="#Aliasing">above</a>). Therefore it is no problem to serialize an object graph into XML, since XStream will
  334. know of all types in advance. This is no longer true at deserialization time. XStream has to know the alias to turn
  335. it into the proper type, but it can find the annotation for the alias only if it has processed the type in advance.
  336. Therefore deserialization will fail if the type has not already been processed either by having called XStream's
  337. processAnnotations method or by already having serialized this type. However, @XStreamAlias is the only annotation
  338. that may fail in this case.</p></li>
  339. <li><strong>Concurrency</strong>
  340. <p>XStream is not thread-safe while it is configured, thread-safety is only guaranteed during marshalling and
  341. unmarshalling. However an annotation is defining a change in configuration that is now applied while object
  342. marshalling is processed. Therefore will the auto-detection mode turn XStream's marshalling process in a thread-unsafe
  343. operation any you may run under certain circumstances into concurrency problems.</p></li>
  344. <li><strong>Exceptions</strong>
  345. <p>XStream uses a well-defined exception hierarchy. Normally an InitializationException is only thrown while XStream
  346. is configured. If annotations are processed on the fly they can be thrown obviously also in a marshalling process.</p></li>
  347. <li><strong>Performance</strong>
  348. <p>In auto-detection mode XStream will have to examine any unknown class type for annotations. This will slow down the
  349. marshalling process until all processed types have been examined once.</p></li>
  350. </ol>
  351. <p>Please note, that any call to XStream.processAnnotations will turn off the auto-detection mode.</p>
  352. <!-- ...................................................... -->
  353. <h2 id="Summary">Summing up</h2>
  354. <p>The XStream annotations support might help you configuring your class mappings in some ways, as the custom
  355. configuration will appear in your types, but might not be the solution for other problems, i.e. when you need to map
  356. the same type to two different XML 'standards'. Others might claim that the configuration should be clearly stated in
  357. a Java class and not mixed with your model, its up to you to pick the best approach in your case: Annotations or
  358. direct method calls to the XStream instance. Annotations do not provide more functionality, but may improve
  359. convenience.</p>
  360. <br/>
  361. </div>
  362. </div>
  363. <div class="SidePanel" id="left">
  364. <div class="MenuGroup">
  365. <h1>Software</h1>
  366. <ul>
  367. <li><a href="index.html">About XStream</a></li>
  368. <li><a href="news.html">News</a></li>
  369. <li><a href="changes.html">Change History</a></li>
  370. <li><a href="versioning.html">About Versioning</a></li>
  371. </ul>
  372. </div>
  373. <div class="MenuGroup">
  374. <h1>Evaluating XStream</h1>
  375. <ul>
  376. <li><a href="tutorial.html">Two Minute Tutorial</a></li>
  377. <li><a href="graphs.html">Object references</a></li>
  378. <li><a href="manual-tweaking-output.html">Tweaking the Output</a></li>
  379. <li><a href="license.html">License</a></li>
  380. <li><a href="download.html">Download</a></li>
  381. <li><a href="references.html">References</a></li>
  382. <li><a href="parser-benchmarks.html">Parser Benchmarks</a></li>
  383. <li><a href="http://www.ohloh.net/projects/3459">Code Statistics</a></li>
  384. </ul>
  385. </div>
  386. <div class="MenuGroup">
  387. <h1>Using XStream</h1>
  388. <ul>
  389. <li><a href="architecture.html">Architecture Overview</a></li>
  390. <li><a href="converters.html">Converters</a></li>
  391. <li><a href="faq.html">Frequently Asked Questions</a></li>
  392. <li><a href="list-user.html">Users' Mailing List</a></li>
  393. <li><a href="issues.html">Reporting Issues</a></li>
  394. </ul>
  395. </div>
  396. <div class="MenuGroup">
  397. <h1>Javadoc</h1>
  398. <ul>
  399. <li><a href="javadoc/index.html">XStream Core</a></li>
  400. <li><a href="hibernate-javadoc/index.html">Hibernate Extensions</a></li>
  401. <li><a href="benchmark-javadoc/index.html">Benchmark Module</a></li>
  402. </ul>
  403. </div>
  404. <div class="MenuGroup">
  405. <h1>Tutorials</h1>
  406. <ul>
  407. <li><a href="tutorial.html">Two Minute Tutorial</a></li>
  408. <li><a href="alias-tutorial.html">Alias Tutorial</a></li>
  409. <li class="currentLink">Annotations Tutorial</li>
  410. <li><a href="converter-tutorial.html">Converter Tutorial</a></li>
  411. <li><a href="objectstream.html">Object Streams Tutorial</a></li>
  412. <li><a href="persistence-tutorial.html">Persistence API Tutorial</a></li>
  413. <li><a href="json-tutorial.html">JSON Tutorial</a></li>
  414. </ul>
  415. </div>
  416. <div class="MenuGroup">
  417. <h1>Developing XStream</h1>
  418. <ul>
  419. <li><a href="how-to-contribute.html">How to Contribute</a></li>
  420. <li><a href="list-dev.html">Developers' Mailing List</a></li>
  421. <li><a href="team.html">Development Team</a></li>
  422. <li><a href="repository.html">Source Repository</a></li>
  423. <li><a href="http://bamboo.ci.codehaus.org/browse/XSTREAM">Continuous Integration</a></li>
  424. </ul>
  425. </div>
  426. </div>
  427. </body>
  428. </html>