jenkins-xstream-1.4.4-jenkins-4/0000775000175000017500000000000012260544303017115 5ustar jamespagejamespagejenkins-xstream-1.4.4-jenkins-4/xstream-distribution/0000775000175000017500000000000012206661545023325 5ustar jamespagejamespagejenkins-xstream-1.4.4-jenkins-4/xstream-distribution/pom.xml0000664000175000017500000002074512206661545024652 0ustar jamespagejamespage 4.0.0 com.thoughtworks.xstream xstream-parent 1.4.4 xstream-distribution pom XStream Distribution ${project.groupId} xstream ${project.version} runtime ${project.groupId} xstream-hibernate ${project.version} runtime ${project.groupId} xstream-benchmark ${project.version} runtime jdk15-ge [1.5,) org.codehaus.xsite xsite-maven-plugin ${basedir}/src content/website.xml templates/skin.html xsite/xsite.xml resources ${project.build.directory}/xsite package run org.apache.maven.plugins maven-antrun-plugin package run ${project.groupId} xstream ${project.version} javadoc provided ${project.groupId} xstream-hibernate ${project.version} javadoc provided ${project.groupId} xstream-benchmark ${project.version} javadoc provided org.apache.maven.plugins maven-dependency-plugin collect-xstream-artifacts package copy-dependencies target/libs runtime true unpack-core package unpack-dependencies ${project.build.directory}/xsite/javadoc false true xstream javadoc provided unpack-hibernate package unpack-dependencies ${project.build.directory}/xsite/hibernate-javadoc false true xstream-hibernate javadoc provided unpack-benchmark package unpack-dependencies ${project.build.directory}/xsite/benchmark-javadoc false true xstream-benchmark javadoc provided org.apache.maven.plugins maven-assembly-plugin bin package attached ${basedir}/src/assembly/assembly-bin.xml xstream-${project.version} ${project.build.directory}/assembly/bin src package attached ${basedir}/src/assembly/assembly-src.xml xstream-${project.version} ${project.build.directory}/assembly/src jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/README.txt0000664000175000017500000000515012206661545025024 0ustar jamespagejamespage========================================== Copyright (C) 2005, 2006 Joe Walnes. Copyright (C) 2006, 2007 XStream committers. All rights reserved. The software in this package is published under the terms of the BSD style license a copy of which has been included with this distribution in the LICENSE.txt file. Created on 29. January 2005 by Joe Walnes ========================================== (The XStream website is build using XSite - http://xsite.codehaus.org) STRUCTURE The directories should be self explanatory: ./src/templates: contains the skin HTML and style sheet. Other templates might go here. ./src/content: contains the content in simple HTML. BUILDING SITE Run the XSite builder using the Maven 2 plugin associated to the install goal: mvn install The new site will be deployed in target/xsite Alternatively, download the standalone xsite distribution from http://xsite.codehaus.org/download $XSITE_HOME/bin/xsite src/content/website.xml src/template/skin.html target/xsite EDITING THE CONTENT OF THE SITE 1) Edit the files in ./src/content. These are plain HTML files and can be edited using any old HTML editor (including Mozilla Composer or Word). Supporting resources that are relevant to the content (such as images) can be placed in this directory. 2) If the structure of the navigation requires a change (necessary if adding a new page), update ./src/content/website.xml. EDITING THE LOOK AND FEEL OF THE SITE 1) Edit the file ./src/templates/skin.html. This is a FreeMarker template that is applied to each page using SiteMesh. Supporting resources that are relevant to the look and feel (such as images or CSS) can be placed in this directory. DESIGN PRINCIPLES The ideas behind site design are as follows: 1) It implements the design that resulted from the analysis of stereotypical users The menu is designed to put what our users most want right up front. Other, less important information can be linked from subpages. 2) It completely separates content, navigation and style This makes it easy to change the "skin" of the site or the style of that skin. 3) The navigation "skin" is designed to be convenient in browsers that do not process CSS. The banner appears first, then the main page content, followed by any side panels on the page. Thus, users of less capable browsers get the most important information first and less important information later. 4) All content is simple HTML. No styles required, although any styles and other media used by the content pages get merged into the final site by the templater. This makes it easy to create content in WYSIWYG editors. jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/0000775000175000017500000000000012206661545024114 5ustar jamespagejamespagejenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/templates/0000775000175000017500000000000012206661545026112 5ustar jamespagejamespagejenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/templates/skin.html0000664000175000017500000000365112206661545027751 0ustar jamespagejamespage XStream - ${title} ${head}

${title}

${body}
<#list sitemap.sections as section>
jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/assembly/0000775000175000017500000000000012206661545025733 5ustar jamespagejamespagejenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/assembly/assembly-bin.xml0000664000175000017500000000230112206661545031036 0ustar jamespagejamespage bin zip .. / LICENSE.txt README.txt target/docs docs target/libs lib ../xstream/target/dependencies lib/xstream ../xstream-hibernate/target/dependencies lib/xstream-hibernate jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/assembly/assembly-src.xml0000664000175000017500000000223712206661545031065 0ustar jamespagejamespage src zip .. / xstream-builder/** **/build/** **/target/** **/.*/** **/.* **/cobertura.ser **/release.properties **/surefire*.properties **/*~ **/*.bak **/*.classpath **/*.jps **/*.releaseBackup jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/resources/0000775000175000017500000000000012206661545026126 5ustar jamespagejamespagejenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/resources/style.css0000664000175000017500000001547612206661545030015 0ustar jamespagejamespage/* Copyright (C) 2005, 2006 Joe Walnes. Copyright (C) 2006, 2007 XStream committers. All rights reserved. The software in this package is published under the terms of the BSD style license a copy of which has been included with this distribution in the LICENSE.txt file. Created on 29. January 2005 by Joe Walnes */ /*--------------------------------------------------------------------------- * Two- and three-column layout */ #banner { top: 0px; left: 0px; right: 0px; height: 116px; } #left { position: absolute; z-index: 2; left: 8px; width: 184px; top: 125px; bottom: 8px; margin: 0px; padding: 0px; } #right { position: absolute; z-index: 1; right: 8px; width: 184px; top: 125px; bottom: 8px; margin: 0px; padding: 0px; } .Content3Column { position: absolute; top: 125px; bottom: 8px; left: 208px; right: 216px; } .Content2Column { position: absolute; top: 125px; bottom: 8px; left: 208px; right: 16px; } #center { z-index: 3; margin: 0px; border: none; padding-bottom: 8px; } /*--------------------------------------------------------------------------- * Default element styles */ body { padding: 0px; margin: 0px; border: 0px; font-family: helvetica, arial, sans-serif; font-size: 12px; background-color: white; color: black; } h1, h2, h3, h4, h5, h6 { margin: 0px; border: 0px; padding: 0px; font-weight: normal; } a:link { color: #0a0; } a:active { color: red; } a:hover { color: red; } a:visited { color: black; } iframe { width:100%; height: 800px; border: 0px; } img { border: 0px; padding: 0px; margin: 0px; } p { border: 0px; padding: 0px; margin: 0px; margin-bottom: 10px; } blockquote { margin-bottom: 10px; } td { font-size: 12px; padding: 2px; } th { font-size: 12px; font-weight: bold; white-space: nowrap; padding: 2px; } th.Row { text-align: left; vertical-align: top; } ul, ol { border: 0px; padding: 0px; margin-top: 0px; margin-bottom: 12px; margin-left: 20px; } /*--------------------------------------------------------------------------- * Page banner */ #banner { margin: 0px; border: 0px; border-bottom: 1px solid #afa; padding: 0px; background-color: #e0f0e0; color: #060; vertical-align: bottom; } #banner a { text-decoration: none; } #banner a:visited { color: #0a0; } #banner a:hover { color: red; } #banner a:active { color: red; } #logo { position: absolute; top: 5px; left: 8px; } #versions { position: absolute; width: auto; right: 0px; top: 0px; margin: 8px; font-weight: normal; } /*--------------------------------------------------------------------------- * Page content */ #content { margin: 0px; background-color: white; color: black; height: 100%; } #content h1 { width: 100%; font-size: 18px; background-color: #060; color: white; padding: 2px; padding-left: 6px; margin-top: 24px; margin-bottom: 12px; } #content .FirstChild { /* IE doesn't understand first-child pseudoelement */ margin-top: 0px; } #content a { text-decoration: underline; } #content a:link { color: #060; } #content a:visited { color: #060; } #content a:active { color: red; } #content a:hover { color: red; } #content h2 { margin-top: 24px; border-top: 1px solid #060; margin-bottom: 16px; font-size: 15px; font-weight: bold; background-color: #e0f0e0; padding: 2px; } #content li { margin-bottom: 6px; } #content th { background-color: #afa; } #content td { background-color: #dfd; } .Source pre { padding: 4px; font-family: courier new, monospace; font-size: 11px; border: 1px solid #080; background-color: #cfc; color: black; } .Source:before { margin: 0px; padding: 0px; border: 0px; font-size: inherit; line-spacing: 100%; } .highlight { background-color: #e0f0e0; border: 1px dotted #060; padding: 5px; } /* The following are for images, but can also apply to div's containing images. */ #content .Float { float: right; margin-left: 8px; margin-right: 0px; margin-top: 8px; margin-bottom: 8px; } #content .Diagram { display: block; margin-left: auto; margin-right: auto; margin-top: 8px; margin-bottom: 8px; } #content .Inline { display: inline; } .RuleOfThumb { font-weight: bold; } #content h1[id]:hover:after, #content h2[id]:hover:after { content: " #" attr(id) " "; font-size: 90%; color: #aaa; text-decoration: none; } /*--------------------------------------------------------------------------- * Side panels */ .SidePanel { background-color: white; padding: 0px; font-size: 11px; } .SidePanel h1 { margin: 0px; border: 0px; padding: 4px; color: #060; font-size: 12px; font-weight: bold; } .SidePanel a { text-decoration: none; } .SidePanel a:link { color: #060; } .SidePanel a:visited { color: #060; } .SidePanel a:active { color: red; } .SidePanel a:hover { color: red; } /*--------------------------------------------------------------------------- * Menus */ .MenuGroup { border-left: 1px solid #afa; border-top: 1px solid #afa; border-bottom: 1px solid white; /* IE work-around */ margin-bottom: 8px; background-color: white; color: #060; } .MenuGroup ul { margin: 0px; padding-left: 4px; list-style-type: none; } .MenuGroup li { padding: 2px; } .MenuGroup .currentLink { /* background-color: #060;*/ background-color: #e0f0e0; color: #000; } /*--------------------------------------------------------------------------- * News panel */ .NewsGroup { border-left: 1px solid #afa; border-top: 1px solid #afa; border-bottom: 1px solid white; /* IE workaround */ margin-bottom: 8px; color: #060; } .NewsItem { margin: 4px; } .NewsDate { font-weight: bold; margin: 0px; padding: 0px; } .NewsText { padding: 0px; margin: 0px; margin-bottom: 8px; } .NewsText a { text-decoration: underline; } .NewsText a:link { color: #060; } .NewsText a:visited { color: #060; } .NewsText a:active { color: red; } .NewsText a:hover { color: red; } .NewsMore { font-size: smaller; margin: 4px; margin-top: 8px; text-align: left; } .NewsGroup td { font-size: 12px; } /*--------------------------------------------------------------------------- * Document meta-information */ .Meta { margin-top: 64px; font-size: smaller; color: #C0C0C0; text-align: right; } .Meta a { text-decoration: underline; } .Meta a:link { color: #C0C0C0; } .Meta a:visited { color: #C0C0C0; } .Meta a:active { color: red; } .Meta a:hover { color: red; }jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/resources/logo.gif0000664000175000017500000001276412206661545027567 0ustar jamespagejamespageGIF89aIl                   "&"%(*,.,(**,.,. " " $" + . ( - 030467048::<>9 5 0  #!$$&#%#!)!$*$&)&$,$&.&*-*'0'(1(+4+-0-,4,/9/0402822<24845<58<8@BDFDAHKJLNPRUVXZ\^`bdfh6@68A89B9;@;:B::D:?C?>G>AGAAJABLBFKFFLFIOIGQGHRHKTKMRMLULOYOPVPPXPTZTT]TV^VZaZYdY\e\]g]^e^ajabibcjcemefofhphhrhjrjkukltllvlnwnpxpr{rr|ruuvvuuwwxxyyzzyy||~~µöķƹǺʼ!,Il H*\ȰÇ#JHŋ3jȱǏ CIɓ(S\ɲ˗0cʜI0`8sɳϟ9 ѣ?ɴS>`JիXjCAsUh:۷pʝK[/ 2a_ SKp~ ]8fAyiL.!63k.inD}G3HCVbm^͚ӰB\^I+;ֺ&MAn-SF Q,R~ -P_C@igB dޯKƶ=eJ}C#߀b)BAL`]+|CAȃyAa\$O|cp%bC4:% 0:ـHnuQJD ~#N!~t1U,EP>х  B 8S/ +|ЁdRy(1A yRKN 0jЖrHa tQJ*)iLCsRX _2㤨ҔO&P(\] M"L25RAF޼p$- F`5B-V6-LP\R|.Lp0Epae@ͻ2ug+!AՋD@1c CqJ܁p="4˱rI@`Zl8C@d%=ƠC@#e0PȢ:CGeLt`{4OKvŐ S\{a3ѕE: c”u5܀gIaBb~xF\iL BLܷ?DpIl`q22M/đpCͽ{ WF - L6H D2{.SJ;  ݒ!Aҁ,JԷ߾+d8[ ~?G@ꭁ+->cC a8V &c }=8WԂz{%H7>\4(!oK3*t>BC<<vx\aC AWiZ T( qX t Ũر|d©kA`>O݄ҏN5-j nIW! a@j ڽB!XCytwmJ?@!m5a N%_a.H|k7c FcA`6&}n{@0 ?ܩBy 5> .o>  (S9Th=J0ADRm?d#4R P2b LƠ'!ƪp:9X?7 *"` [޿bU8ւ@`ق{/+ S.,: "(@.&ȩ.,qaZy0AV>{ PYlA' 2 <΢ s\i Z-Ujq Հ 4 &ഊ&A<␣(B]=ی_  gCZHUx1}_SE9Rc F#&ʈ@?  vE{ `krw%/`( ReT$ "Ar꩘hZnXd=b8u#_8`LUPv(fm*n(+!>_U7#C9 ?jCB hm'xp C(0TxA؊^ 8 HJă=^aՆGtt0tyCfNW>8ȨBXt(G@( bU`xt rhcq `Q(H@3h y@Rtgu  f$>ȉ)('Q@ ղVG6P*I=hj:-^PŘPVI@8l4)/:hxt^n+~q 0 AUaHrAng0%Q4Q3Apz'C9SAX љA W@uaəɈ)I@95>0yw?EE 8PD5gԕIdy* yFR8>I$I: pR8=W&nB}YAyAYyAsI@~n0!A?0:}+$pDA>隭>Н4":9ɢ#sAzPDp}! BPxAƝiYEv۹zKڢhLGzAyř!B}"pq+IY@B> Q3rZ>p>hyI1:_BuPBu+D! aCy[+Mᩘ0iI )dMZ@Zt<zpB @ B1-Ї1ZZJ@؊AJFzLzAݚg%ʭxD]vqs! +@~B?@Ddw Ax:=۰Ė VB+[@ C"560"ir+t6{XBJ+<;= F[A'0A & 0*o1 $` Z;6>jc[;iq!ҳkK;iky x `1 Иq}q8P+XѱddBk4!vʱ [03S@ 1 +$G{xAQc[@M0m*TK@,`Pfn*En! JXn VjtATjB7P–M.D̀Q2 @4B$H~9k -)=3p~q $LK@&3>57>9< P z2~0p ;! : 20{`C3 ӣ吷TDb>;y1C ~@5U! :P\RwqŴs;>0wf,=C {iQ5ɪ|Al@Rh*pv` 񬇤k;L=={mէu<=91\$@Z\zHcԞfck t \@ύ7>C+PgiK' M@p pvHl*G Tt@ ZIGd!\ P:@yHE[;0(GnfN>>2-%͋ ``5bGҦvC\;`$O`k1EfM=$a q"^P^1  [; ܪBъ]@؂MrDW q#qG r; z ,0A}1;m3%$0 a C@4X yS kM;UE$k}[#--=h GͳȘaYL @0ZL@  F9   q`Oߢ" z!U> pq !4a 8N dJ P ` E> PXf^8zU>d^f~;jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/resources/logo-small.gif0000664000175000017500000000414512206661545030667 0ustar jamespagejamespageGIF87a1                   "&"%(*,.,(**,.,. " " $" + . ( - 030467048::<>9 5 0  #!$$&#%#!)!$*$&)&$,$&.&*-*'0'(1(+4+-0-,4,/9/0402822<24845<58<8@BDFDAHKJLNPRUVXZ\^`bdfh6@68A89B9;@;:B::D:?C?>G>AGAAJABLBFKFFLFIOIGQGHRHKTKMRMLULOYOPVPPXPTZTT]TV^VZaZYdY\e\]g]^e^ajabibcjcemefofhphhrhjrjkukltllvlnwnpxpr{rr|ruuvvuuwwxxyyzzyy||~~µöķƹǺʼ,1@ H*\ȰÇ#&@3j# hɋ@H\ɲK"f2&+G8^ JTb?33R3УSN;*ժ}KV+A}]R+ٮ3"Bࡤ;{M6v{i(7*TqI ]Cg825ao"&sմ!֋tZES^Z(N3uR{ָs+E3!N!G1NuoǁrYrH;Mfͦi49''F@cW8vU>T_D+y4X`A\|PtY @R UPUMuPY]bP-Q-SS%(D`< I>Cݑ-fEM$HF15\ \'M噫!`qRvtJeR)[U4c]@DaPNNUNUu'UW( UUsE:ӕ6tJkCw$< A1Te@n&P0ؓNWcG}NQ 'iy*VUUwɺ+UQn:TL^4F;T'T?o6y=An9+&aUs2b(kНUaP}ObT8笳? @^xt4nTer˜SzkWLҥxXb @&e9epEC^9ō B%"ב0oÈ(:*A<Җ^ ;jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/xsite/0000775000175000017500000000000012206661545025250 5ustar jamespagejamespagejenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/xsite/xsite.xml0000664000175000017500000000662012206661545027132 0ustar jamespagejamespage true JIRA:([A-Z]+)-([0-9]+) $1-$2]]> mailto: javascript: http:// https:// nntp:// hibernate-javadoc/ javadoc/ code-coverage/ jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/0000775000175000017500000000000012206661545025566 5ustar jamespagejamespagejenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/changes.html0000664000175000017500000017573412206661545030105 0ustar jamespagejamespage Change History

Changes are split into three categories:

  • Major changes: The major new features that all users should know about.
  • Minor changes: Any smaller changes, including bugfixes.
  • API changes: Any changes to the API that could impact existing users.

Full details can be found in Jira's Roadmap and Change Log.

1.4.4

Released 19. January 2013.

Minor changes

  • JIRA:XSTR-709: Locks up on Mac with Apple JVM due to unwanted initialization of AWT.
  • JIRA:XSTR-711: DateConverter cannot handle dates in different era.
  • JIRA:XSTR-712: HibernateMapper throws NPE if a collection contains null.
  • DateConverter supports now localized formats.
  • JIRA:XSTR-710: JsonWriter does not write BigInteger and BigDecimal as number values.
  • JIRA:XSTR-708: SqlTimestampConverter does not ignore timezone.
  • JIRA:XSTR-707: Creation of XmllPullParser with the XmlPullParserFactory may fail in OSGi environment.
  • JIRA:XSTR-705: Unnecessary synchronization accessing the field cache decreases performance.
  • JIRA:XSTR-714: Fields not found when XStream12FieldKeySorter used.

API changes

  • Deprecated method c.t.x.core.util.JVM.is14(), c.t.x.core.util.JVM.is15() and c.t.x.core.util.JVM.is16().

1.4.3

Released 17. July 2012.

Major changes

  • Support java.util.concurrent.ConcurrentHashMap with the MapConverter. This will also avoid a bug in JRockit JDK reported in JIRA:XSTR-608.
  • JIRA:XSTR-699: Support for Hibernate 4 with XStream's Hibernate module as default for Java 6 or higher.

Minor changes

  • JVM.loadClass will now also initialize the loaded class and ignore any occurring LinkageError.
  • JIRA:XSTR-596: SubjectConverter will be no longer registered if initialization of javax.security.auth.Subject fails.
  • JIRA:XSTR-683: Inheritance of implicit collections, arrays or maps is dependent on declaration sequence.
  • Inherited implicit collections, arrays or maps can be overwritten with own definition in subtype.
  • JIRA:XSTR-688: Cannot omit XML elements from derived fields.
  • JIRA:XSTR-696: Ill-formed JSON generated, because JSON writer is fed with type of declaring field instead of the real object's type.
  • JIRA:XSTR-685: Deserialization from file or URL keeps stream open.
  • JIRA:XSTR-684: XML 1.0 character validation fails for characters from 0x10 to 0x1f.
  • JavaBeanConverter supports now instantiation for a specific type and can therefore be used in @XStreamConverter annotation.
  • SerializableConverter is broken if the serialized type is the default implementation.
  • Method marshalUnserializableParent of SerializableConverter is protected now to skip the default mechanism in a derived converter that uses the default constructor to create the original type (as an alternative for JIRA:XSTR-695).
  • FieldDictionary may call sort of FieldKeySorter implementation with wrong type as key.
  • Sometimes DependencyInjectionFactory tries to instantiate objects with mismatching constructor arguments.
  • HSQLDB has to be a test dependency only for XStream's Hibernate module.

1.4.2

Released 3. November 2011.

Major changes

  • XStream libraries can be used now directly in Android, therefore support of Java 1.4.2 has been stopped with the delivery. Anyone who needs a version for Java 1.4.2 can build it easily from source, this build is still supported and part of CI.
  • JIRA:XSTR-675: New extended HierarchicalStreamReader interface with peekNextChild method. All XStream readers implement the new interface (by Nikita Levyankov).
  • JIRA:XSTR-673: Collections.EMPTY_LIST, Collections.EMPTY_SET and Collections.EMPTY_MAP supported with own alias and defined as immutable.
  • JIRA:XSTR-631: Collections.singletonList(), Collections.singletonSet() and Collections.singletonMap() supported with own alias and own converters.
  • JIRA:XSTR-406 + JIRA:XSTR-663: Support additional parameters for XStreamConverter annotation (e.g. to declare a ToAttributedValueConverter).

Minor changes

  • WstxDriver did not trigger Woodstox, but BEA StAX implementation.
  • JIRA:XSTR-260: PrettyPrintWriter does not handle tab and new line characters in attributes.
  • JIRA:XSTR-667: Cannot serialize empty list with JsonHierarchicalStreamDriver.
  • JIRA:XSTR-661: TreeMarshaller.CircularReference is not a ConversionException.
  • JIRA:XSTR-562: StAX: Namespace attribute is not written in non-repairing mode for second sibling.
  • JIRA:XSTR-664: ClassCastException in HibernatePersistentSortedSetConverter and HibernatePersistentSortedMapConverter.
  • JIRA:XSTR-674: Recreate binary compatibility with 1.3.x series for method CustomObjectInputStream.getInstance(...).
  • JIRA:XSTR-671: CannotResolveClassException should accept cause.
  • JIRA:XSTR-672: Collections.EMPTY_LIST, Collections.EMPTY_SET and Collections.EMPTY_MAP used for in implicit collection should not throw ReferencedImplicitElementException.
  • JIRA:XSTR-676: Introduce MissingFieldException thrown at deserialization time indicating a missing field or property (by Nikita Levyankov).
  • Add length limit for cached strings in StringConverter, 38 characters by default.
  • The JsonHierarchicalStreamDriver and the JsonWriter did not support the inherited NameCoder instance.
  • Add BinaryStreamDriver.
  • NPE in XppDomComparator.
  • Dom4JXmlWriter fails to flush the underlying writer.
  • Known control characters are not encoded with JsonWriter as proposed at json.org.
  • Detect duplicate property processing in JavaBeanConverter and throw DuplicatePropertyException instead of clobbering silently.
  • Allow access to Mapper and JavaBeanProvider in derived instances of JavaBeanConverter.
  • DependencyInjectionFactory failed to create instance when a matching constructor was found, but a default constructor was also present.

API changes

  • Added interface c.t.x.io.ExtendedHierarchicalStreamReader extending c.t.x.io.HierarchicalStreamReader. All implementations of c.t.x.io.HierarchicalStreamReader will implement also the extended interface.
  • Added c.t.x.converters.reflection.MissingFieldException derived from c.t.x.converters.reflection.ObjectAccessException and used instead when the unmarshalling process should write a field or property that is missing and does not exist.
  • Added methods c.t.x.io.path.PathTracker.peekElement(), c.t.x.io.path.PathTracker.peekElement(int), and c.t.x.io.path.PathTracker.depth().
  • Deprecated method c.t.x.core.ReferencingMarshallingContext.currentPath(). Wrong approach.

1.4.1

Released 11. August 2011.

Major changes

  • JIRA:XSTR-659: Use again Xpp3 as default parser, now with additional XmlPullParser API as regular dependency for the XPP factory. Only standard kXML2 package contains the XPP factory, but not the minimal kXML2 version.

Minor changes

  • Add utility class c.t.x.io.xml.xppdom.XppFactory and a path tracking comparator for XppDom.

1.4

Released 6. August 2011.

Major changes

  • Java 7 is detected and supported.
  • JIRA:XSTR-542: The XppDriver uses now the official XmlPullParser API to locate an available parser using the XmlPullParserFactory. This allows the usage of XPP technology with XStream in Android.
  • Additional explicit XPP drivers for the Xpp3 and kXML2 implementations.
  • Additional explicit XPP DOM drivers for the Xpp3 and kXML2 implementations.
  • kXML2 is now the preferred parser implementation, Xpp3 is optional.
  • Additional explicit StAX drivers for Woodstox, BEA StAX and SJSXP of the JDK 6 implementations.
  • JDK 1.3 is no longer officially supported.
  • JIRA:XSTR-377+JIRA:XSTR-226: New artifact xstream-hibernate with converters and mapper to process Hibernate object graphs (by Costin Leau, Konstantin Pribluda and in special Jaime Metcher).
  • New NameCoder interface and implementations to support a generic name translation between names from the object graph and a target format. The new XmlFriendlyNameCoder replaces the XmlFriendlyReplacer used for XML only.
  • JIRA:XSTR-553: Support annotations in Android.
  • JIRA:XSTR-556: DateConverter uses format with 3-letter time zones that are ambiguous. Therefore it will now always use UTC to write dates. Unmarshalled dates are not affected as long as they contain a time zone.
  • The type java.lang.reflect.Field is now handled by an own converter, that can still read the old format.
  • JIRA:XSTR-490: Provide path in Converter for contexts that track the path.
  • JIRA:XSTR-592+JIRA:XSTR-579: OmitField respected at deserialization time even for existing fields.
  • JIRA:XSTR-593: Direct support for java.net.URI instances (by Carlos Roman).
  • JIRA:XSTR-615+JIRA:XSTR-580: Dynamic proxies cannot be referenced recursively.
  • JIRA:XSTR-547: Wrong class loader used for Serializable types deserialized with an ObjectInputStream.
  • JIRA:XSTR-341: Support of implicit arrays.
  • JIRA:XSTR-306+JIRA:XSTR-406: Support of implicit maps.
  • JIRA:XSTR-344: New ToAttributedValueConverter to allow conversion of an element with string body and attributes.
  • JIRA:XSTR-573: SortedSet added with TreeSet as the default implementation.
  • JIRA:XSTR-576: TreeMap and TreeSet no longer add an element without comparator (by Jason Greanya), solves also invalid format with JSON for such objects (JIRA:XSTR-640).

Minor changes

  • JIRA:XSTR-612: Improve extensibility of c.t.x.javabean.* package by reintroducing a PropertyDictionary with the additional interface PropertySorter.
  • JIRA:XSTR-591: EnumSingleValueConverter did use toString() instead of name() to create the String representation of an enum value.
  • JIRA:XSTR-618: Add Oracle as vendor used for recent JRockit versions and former Sun JDK.
  • JIRA:XSTR-656: DomReader and Dom4JReader do not escape attribute names retrieving their values.
  • JIRA:XSTR-604: StringConverter's cache may cause an OutOfMemoryException.
  • JIRA:XSTR-577: Skip UTF-8 BOM in XmlHeaderAwareReader.
  • The XppReader no longer uses a BufferedReader.
  • JIRA:XSTR-543: Better deserialization support of the defined-in system attribute in combination with field aliases.
  • JIRA:XSTR-551: Deprecated XStream.InitializationException still thrown instead of InitializationException.
  • JIRA:XSTR-655: JsonWriter generates invalid JSON for Externalizable types.
  • JIRA:XSTR-540: Support Jettison-based configuration of JettisonMappedXmlDriver (by Doug Daniels).
  • JIRA:XSTR-633: JettisonMappedXmlDriver escaped property names according escape rules for XML tag names.
  • JIRA:XSTR-625: Optionally ignore XStream's hints for Jettison to generate JSON arrays (by Dejan Bosanac).
  • JIRA:XSTR-605: Upgrade to Jettison 1.2 (for Java 5 or higher).
  • New JsonWriter.EXPLICIT_MODE generating JSON that enforces property sequence.
  • JIRA:XSTR-552: Improve performance of ReflectionProvider (by Keith Kowalczykowski).
  • JIRA:XSTR-559: Improve performance of Sun14ReflectionProvider (by Keith Kowalczykowski).
  • JIRA:XSTR-564: Improve performance of AnnotationMapper (by Keith Kowalczykowski).
  • JIRA:XSTR-563: Use ReferenceQueue for cleaning-up WeakReferences in ObjectIdDictionary (by Keith Kowalczykowski).
  • JIRA:XSTR-646: Cache of Sun14ReflectionProvider consumes more PermGen space than necessary.
  • JIRA:XSTR-636: Ineffective cache in FieldDictionary using WeakHashMap with WeakReference values.
  • Ineffective cache for SerializationMethodInvoker (related to JIRA:XSTR-636).
  • Introduction of Caching interface implemented by all types in XStream that create local caches that may have to be flushed manually.
  • Avoid excessive creation of AbstractPullReader.Event objects by using a pool.
  • Possibility to generate XPath expressions that select always a single node instead of a node list.
  • Cannot reference replaced object using ID references.
  • Implicit collection functionality will no longer use custom collection converters that may write tags that are not recognized at deserialization time again.
  • JIRA:XSTR-654: Unmarshal fails when an implicit collection is defined and an element is named equal to the field.
  • JIRA:XSTR-574: AbstractReferenceUnmarshaller cannot handle null values for references.
  • Improve exception output in case of a missing field.
  • JIRA:XSTR-555: StAX driver tests do not honor repairing mode.
  • JIRA:XSTR-570: The @XStreamConverter provides now also the current type as possible constructor argument.
  • JIRA:XSTR-629: Deserialization of Externalizable with non-accessible default constructor fails.
  • JIRA:XSTR-571: Cannot serialize synchronized RandomAccessList types.
  • JIRA:XSTR-583: BinaryDriver fails to handle Strings with more than 64K bytes.
  • JIRA:XSTR-639: Cannot omit field at deserialization if the field has a class attribute.
  • JIRA:XSTR-599: EncodedByteArrayConverter should implement SingleValueConverter.
  • JIRA:XSTR-584: Race condition in XmlFriendlyReplacer.
  • JIRA:XSTR-623: XmlFriendlyReplacer may write illegal name characters (by Michael Schnell).
  • The ConversionException hides information if its ErrorWriter contains the added key already.
  • JIRA:XSTR-598: Attribute "defined-in" was wrongly evaluated for other attributes.
  • JIRA:XSTR-650: Possible NullPointerException at initialization on platforms like Android that do not support all types of the JDK.
  • JIRA:XSTR-652: Initialization of XStream fails if DurationConverter constructor throws a javax.xml.datatype.DatatypeConfigurationException. Converter will no longer handle Duration types if no instance of the internal DatatypeFactory can be created.
  • Constructor DocumentWriter(Element) forgets the provided element.
  • JIRA:XSTR-597: Optimize AbstractReflectionConverter.
  • Introduce Caching interface to flush the internal cache of specific components.
  • Support JIRA:XSTR-407 also for IBM JRE 1.6 and greater.
  • java.nio.charset.Charset's converter was added as immutable type instead of the type itself.
  • java.util.Currency added as immutable type.
  • Fix selection of same parameter types in DependencyInjectionFactory.
  • Deprecation of c.t.x.javabean.PropertyDictionary has been countermanded.

API changes

  • Any deprecated stuff of the 1.2.x releases has been removed.
  • Deprecated constructors of c.t.x.converters.reflection.SerializableConverter, c.t.x.converters.reflection.ExternalizableConverter and c.t.x.converters.reflection.CGLIBEnhancedConverter; new versions take an additional argument for class loader (as a result for JIRA:XSTR-547).
  • Deprecated constructors of c.t.x.io.xml.XppReader, new versions take an additional argument for the XmlPullParser.
  • Deprecated c.t.x.io.xml.XppReader.createParser(), the XPP parser is now created by the driver.
  • Package c.t.x.io.xml.xppdom is now part of the official API.
  • c.t.x.io.xml.xppdom.Xpp3Dom and c.t.x.io.xmlxpp.dom.Xpp3DomBuilder have been deprecated. Functionality is merged in c.t.x.io.xml.xppdom.XppDom.
  • Deprecated c.t.x.mapper.XStream11XmlFriendlyMapper and c.t.x.mapper.AbstractXmlFriendlyMapper.
  • Added interface c.t.x.core.ReferencingMarshallingContext which is implemented by all referencing marshallers.
  • Added interface c.t.x.io.naming.NameCoder and implementations.
  • Deprecated c.t.x.io.xml.XmlFriendlyReplacer, c.t.x.io.xml.XmlFriendlyReader and c.t.x.io.xml.XmlFriendlyWriter.
  • Deprecated c.t.x.io.xml.AbstractXmlDriver, c.t.x.io.xml.AbstractXmlReader and c.t.x.io.xml.AbstractXmlWriter, added c.t.x.io.AbstractDriver, c.t.x.io.AbstractReader and c.t.x.io.AbstractWriter instead.
  • Deprecated all constructors of Driver, Reader and Writer implementations that take a XmlFriendlyReplacer as argument, added constructors taking a NameCoder instead.
  • Added interface com.thoughtworks.xstream.converters.ErrorReporter to allow other types to report also errors (apart from a HierarchicalStreamReader). Any converter and the parent object of the currently deserialized element may provide additional error information now.

1.3.1

Released 6 December 2008.

CGLIB support must be explicitly activated now. The decision has been made due to possible problems using an own classloader and because of ongoing complaints about occurring exceptions in the CGLIBEnhancedConverter at XStream initialization although they are caused by incompatible ASM versions on the user's classpath (JIRA:XSTR-469, JIRA:XSTR-513 and JIRA:XSTR-518).

XStream uses some attributes on its own. Until now it was possible to use XStream.aliasAttribute to define a different name. This does still work but is deprecated for system attributes. Use the new call XStream.aliasSystemAttribute for such an alias.

Major changes

  • JIRA:XSTR-515: CGLIB support is no longer activated automatically and has to be explicitly turned on.
  • JIRA:XSTR-448: Separated system attributes and user defined attributes for aliases.
  • JIRA:XSTR-55: Ability to alias a package name.
  • JIRA:XSTR-434: New JsonWriter instead of JsonHierarchicalStreamWriter with mode to strip root node of generated JSON (by Paul Hammant).
  • Support for Diablo JDK on FreeBSD (by Reto Bachmann-Gmür).
  • JIRA:XSTR-495: New PersistenceStrategy instead of StreamStrategy (based on the code and comments by Alexander Radzin).

Minor changes

  • Support special Jettison functionality for JSON to detect collections or arrays with one element introduced with Jettison 1.0.
  • JIRA:XSTR-493: Using attributes for fields with XML-unfriendly names results in NPE at deserialization.
  • JIRA:XSTR-497: Unsafe operation with WeakHashMap can raise a NPE in Sun14ReflectionProvider.
  • JIRA:XSTR-423: Support of CGLIB enhanced proxies with multiple callbacks if the proxy uses a factory (CGLIB default).
  • JIRA:XSTR-536: XStream silently ignores unknown elements.
  • JIRA:XSTR-503: Omitted properties in JavaBeans are requested at serialization (by Kevin Conaway).
  • Fix possible memory leak in ObjectIdMap for JVMs that provide real distinct identity hash codes (happened on amd64 system).
  • JIRA:XSTR-480: Aliasing of array types.
  • JIRA:XSTR-515: The SubjectConverter and DurationConverter are only registered if the converted class is part of the JDK, otherwise they must be registered now explicitly.
  • JIRA:XSTR-504: XmlHeaderAwareReader fails with improper sized PushbackInputStream.
  • JIRA:XSTR-489: @XStreamConverter supports now also SingleValueConverter implementations.
  • JIRA:XSTR-481: @XStreamConverter and @XStreamAsAttribute can be used together (as a result of JIRA:XSTR-489).
  • JIRA:XSTR-519: New annotation @XStreamInclude to force annotation detection of included types (by Seven Sparling).
  • JIRA:XSTR-469: Support custom converters for enum types.
  • JIRA:XSTR-502: ClassNotFoundException even if writeReplace returns proper object.
  • JIRA:XSTR-529: NullPointerException for null elements in implicit lists.
  • JIRA:XSTR-517: Miscellaneous performance improvements (by Tatu Saloranta).
  • JIRA:XSTR-525: JsonHierarchicalStreamDriver writes invalid JSON in case of system attribute.
  • JIRA:XSTR-535: Mode to allow plain values as result for JSON without root node.
  • JIRA:XSTR-531: Possibility to omit system attributes.
  • JIRA:XSTR-508: Fix marshalling error for nested serializable objects with own writeReplace/readResolve methods.
  • JIRA:XSTR-507: Advanced ReferenceByIdMarshaller uses id of the current object if available.
  • JIRA:XSTR-485: Check reference for valid object when deserializing.
  • Fix classloader problem, Xpp3 parser cannot be loaded within a web application.
  • Dependencies have been updated to latest versions of JDOM, Jettison, Joda Time, and Woodstox. Note for Maven builds that the groupId of JDOM has changed.
  • Fix possible IndexOutOfBoundsException creating returning the message for a ConversionException.
  • JIRA:XSTR-495: StreamStrategy cannot handle key with value null.

API changes

  • Deprecated c.t.x.io.json.JsonHierarchicalStreamWriter in favour of c.t.x.io.json.JsonWriter.
  • c.t.x.mapper.EnumMapper no longer derives from the c.t.x.mapper.AttributeMapper as it has been before version 1.3. Therefore the new constructor has been deprecated in favour of the old one.
  • c.t.x.mapper.Mapper.getConverterFromAttribute(Class, String) has been deprecated in favour of c.t.x.mapper.Mapper.getConverterFromAttribute(Class, String, Class) taking the type as third argument that should be handled by the converter.
  • c.t.x.core.ReferenceByIdMarshaller.IdGenerator.next() has now the current object as argument.
  • New c.t.x.persistence.PersistenceStrategy and c.t.x.persistence.FilePersistenceStrategy.
  • Deprecated c.t.x.persistence.StreamStrategy and c.t.x.persistence.FileStreamStrategy.

1.3

Released 27 February 2008.

Major changes

  • ReflectionConverter writes now the fields of the parent classes first.
  • Support for Converter definition at field level.
  • Refactoring of Annotation support, invent auto-detection mode.
  • Annotated converters are no longer detected automatically, all annotations are now handled in the same way.
  • JIRA:XSTR-334: XStream will deserialize directly from a file or URL. Some parser take advantage of these objects to define a SystemId used to resolve further references in XML, schema or DTD. Appropriate createReader methods have been added to c.t.x.io.HierarchicalStreamDriver.
  • JIRA:XSTR-261: All c.t.x.io.HierarchicalStreamDriver implementations respect now the encoding of an XML header if read from an InputStream.
  • DomDriver does no longer use explicitly UTF-8 by default, DomReader will therefore respect the encoding defined in the XML header or use native encoding
  • JIRA:XSTR-415: JavaBeanConverter uses now BeanIntrospection (by Hinse ter Schuur).
  • JIRA:XSTR-424: DateConverter uses now by default SimpleDateFormat instances in non-lenient mode.
  • JIRA:XSTR-386: SingleValueConverter that utilizes PropertyEditor implementations (by Jukka Lindström).
  • JIRA:XSTR-427: Converter for javax.xml.datatype.Duration (by John Kristian).
  • JIRA:XSTR-305: Field alias inheritance (by David Blevins).
  • XStream failed to initialize in environments without AWT or SQL classes.
  • JIRA:XSTR-420: XPath of references are not XmlFriendly encoded.
  • JIRA:XSTR-473: String "\0" serialized as invalid XML, support compliant behaviour according XML version.
  • JIRA:XSTR-431: Direct support of enhanced mode for SAP JVM (thanks to Norbert Kuck by SAP).
  • JIRA:XSTR-437: Static cache in annotation processing causes failing OSGi bundles.
  • JIRA:XSTR-279+JIRA:XSTR-335: Annotations are not inherited from parent class.
  • Fix StringConverter using a WeakHashMap with strong references in its value.
  • JIRA:XSTR-403: Attributes are no longer written with JSONHierarchicalStreamDriver if current object is a collection.
  • JIRA:XSTR-456: New LookAndFeelConverter handling LookAndFeel implementations with reflection.
  • JIRA:XSTR-462: CachingMapper keeps direct class references.
  • JIRA:XSTR-411: JsonHierarchicalStreamDriver does not escape characters according RFC 4627.
  • JsonHierarchicalStreamDriver writes wrong brackets around complex Java types with a single value.
  • JsonHierarchicalStreamDriver writes attribute names with a leading '@'.
  • JsonHierarchicalStreamDriver supports Map implementations.

Minor changes

  • Added converter for java.lang.StringBuilder instances.
  • Added converter for java.util.UUID instances.
  • JIRA:XSTR-430: Fields written as attributes could not be omitted.
  • JIRA:XSTR-407: Comparator might access uninitialized elements for TreeSet and TreeMap. A deserialized Comparator is no longer called, the converters expect the elements now in a sorted order.
  • JIRA:XSTR-404, @XStreamImplicit() for ArrayList<ArrayList<Type>> throws ClassCastException.
  • @XStreamContainedType() for ArrayList<ArrayList<Type>> throws ClassCastException.
  • XStreamer did not persist a FieldKeySorter instance.
  • JIRA:XSTR-241: JavaBeanConverter now supports customized BeanProvider.
  • JIRA:XSTR-280: JavaBeanConverter now supports aliasField and omitField (by Hinse ter Schuur).
  • JIRA:XSTR-280: SerializationConverter now supports aliasField and omitField.
  • JIRA:XSTR-429: XmlFriendlyReplacer support for SaxWriter and TraxSource (by Adrian Wilkens).
  • JIRA:XSTR-421: Characters cannot be written as attribute.
  • JIRA:XSTR-426: java.swt.KeyStroke not properly serialized because of a character undefined in unicode.
  • JIRA:XSTR-352: Strings with arbitrary ISO control characters are not properly serialized.
  • JIRA:XSTR-428: An attribute named like a transient field did abort deserialization of following fields.
  • JIRA:XSTR-443: XStream.createObjectOutputStream does not use the given driver to create the HierarchicalStreamWriter.
  • JIRA:XSTR-440: Implicit collections can be declared for fields that are not of Collection type.
  • JIRA:XSTR-446: Handle all primitives and their boxed counterpart for JsonHierarchicalStreamDriver.
  • JIRA:XSTR-447: Fix deserialization of Array class types in JDK 6 (see JDK bug 6500212).
  • JIRA:XSTR-450: @XStreamAlias is ignored if attributes should be used for the field type.
  • JIRA:XSTR-418: Inherited @XStreamAlias is ignored if field should be rendered as attribute.
  • JIRA:XSTR-393: Annotation processing is not consistent.
  • JIRA:XSTR-412: @XStreamImplicit throws NPE for untyped collections.
  • JIRA:XSTR-463: Cannot provide own default Mapper chain.
  • JIRA:XSTR-464: Cannot provide a ClassLoader that is used in all cases.
  • JIRA:XSTR-394: Allow enums as attributes.
  • JIRA:XSTR-413: Support @XStreamAsAttribute for enums.
  • JIRA:XSTR-478: Cannot specify default implementation for polymorphic enum.
  • JIRA:XSTR-419: Treat enums as immutable types.
  • Update annotation tutorial, explain limitations of auto-detection mode.
  • Added copyright notices to all files.
  • StaxWriter.flush did close Stax' XMLStreamWriter instead of flushing it.
  • JIRA:XSTR-471: XStream POMs do no longer declare a repository at all.
  • Calendar object could not be rendered with JSONHierarchicalStreamDriver.
  • JIRA:XSTR-476: Properties can be sorted by key.
  • XStream.createObjectInputStream and XStream.createObjectOutputStream overloaded to support a binary InputStream or OutputStream.
  • JIRA:XSTR-470: Allow transient fields to be optionally deserialized.

API changes

  • c.t.x.annotation.Annotations, c.t.x.annotation.AnnotationReflectionConverter and c.t.x.annotation.AnnotationProvider deprecated. Functionality is integrated in new c.t.x.mapper.AnnotationMapper and accessible with new methods c.t.x.XStream.processAnnotations().
  • New auto-detection mode for annotations, that can be turned on with c.t.x.XStream.autodetectAnnotations()
  • c.t.x.annotation.@XStreamContainedType deprecated, the behaviour is now always active and the annotation therefore superfluous.
  • Due to JIRA:XSTR-421 null characters are no longer written as tag with an attribute (<char null="true"/>), but as empty tag. The old representation is still supported at deserialization.
  • Characters that are not defined in unicode or ISO control characters (expect TAB and LF) are written as numerical entity now.
  • XPath references are now also XML-friendly encoded to match the path exactly. Unencoded references will normally work anyway, but in special cases the exact behaviour of XStream 1.2.x might be necessary. See acceptance tests for XStream 1.2.x compatibility.
  • c.t.x.core.BaseException deprecated in favour of c.t.x.XStreamException as base exception for all exceptions XStream throws.
  • c.t.x.XStream.InitializerException deprecated in favour of c.t.x.InitializerException.
  • New methods get() and keys() in interface c.t.x.converter.ErrorWriter.
  • c.t.x.mapper.XmlFriendlyMapper deprecated, technology is replaced since version 1.2 by c.t.x.io.xml.XmlFriendlyReplacer as part of the different XmlWriter implementations.
  • c.t.x.mapper.Mapper.aliasForAttribute() and c.t.x.mapper.Mapper.attributeForAlias() deprecated, since it provided in reality the combined functionality of c.t.x.mapper.Mapper.serializedMember()/realMember() and c.t.x.mapper.Mapper.getConverterFromItemType().
  • c.t.x.XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver) deprecated, in favour of c.t.x.XStream(ReflectionProvider, HierarchicalStreamDriver, Mapper, ClassLoader).
  • New interface c.t.x.converter.ConverterRegistry to express explicit functionality managing the converters.
  • c.t.x.core.DefaultConverterLookup no longer uses a c.t.x.mapper.Mapper. Therefore the old constructor has been deprecated in favour of a default constructor.
  • Overloaded methods of c.t.x.mapper.Mapper.getConverterFromItemType and c.t.x.mapper.Mapper.getConverterFromAttribute have been deprecated. Only one version has been kept, the implementation can handle all cases now at once and therefore multiple calls to the mapper chain are avoided.
  • c.t.x.mapper.EnumMapper derives now from the c.t.x.mapper.AttributeMapper to support enums as attributes. Therefore the old constructor has been deprecated in favour of one taking an additional c.t.x.converters.ConverterLookup that has to be passed to the new parent.

Note, to support a representation of null values in some way, it is absolutely necessary that each converter can handle a null value in its marshalling methods. If you have implemented your own custom converters, try to handle such a case also to prevent incompatibilities in case XStream will provide such values with its next major version.

Version 1.2.2

Released 24 May 2007.

Note, that next version of XStream will behave slightly different by default. XStream emits all fields in declaration order like Java serialization. But in contrast to Java it will omit the fields of parent classes last while Java serialization emits them first. This makes it difficult to match a given XML schema that defined inherited types or leads sometimes to obscure initialization problems. However, XStream itself will not be affected by the changed order of elements in the XML, any deserialization of current XML representations will work fine. Anyway we will provide with XStream 1.3 a FieldKeySorter implementation that mimics the old behaviour. In the meanwhile you can enforce the new field sorting by installing the NaturalFieldKeySorter.

Major changes

  • JIRA:XSTR-391, Support for writing (and reading) JSON by the new JettisonMappedXmlDriver (by Dejan Bosanac).
  • New FieldKeySorter interface allows a custom sort order of the XML elements.
  • JIRA:XSTR-68 and JIRA:XSTR-210, OmitField is now respected at deserialization to ignore removed fields.

Minor changes

  • JIRA:XSTR-387, Fix aliasing of inherited fields.
  • JIRA:XSTR-395, Fix StringConverter allocating PermGen space.
  • JIRA:XSTR-368, @XStreamConverter converters should be cached inside the AnnotationReflectionConverter.
  • JIRA:XSTR-392, @XStreamOmitField can be used to omit fields from the resulting XML (contributed by Chung-Onn Cheong).
  • JIRA:XSTR-371, Fix JSONWriter that omits a closing bracket for for fields with null value.
  • JIRA:XSTR-398, DomDriver ignores given XmlFriendlyReplacer.
  • JIRA:XSTR-370, Buildable with JDK 6, fix FontConverter for JDK 6.
  • JIRA:XSTR-382, Support hex and octal number values.
  • DateConverter did not respect change in TimeZone after first usage.
  • JIRA:XSTR-375, Support for aliasing native types.
  • JIRA:XSTR-243 again, XML elements for transient fields are now ignored completely at deserialization.
  • Release unused object references to keep memory print low.
  • Support for AWT and SQL is now optional: XStream now works on embedded virtual machines lacking such APIs (by Nicolas Gros d'Aillon).
  • Support raw bytes read from the ObjectInputStream.
  • JIRA:XSTR-373, Support for Hitachi JVM (tested by Yuji Yamano).
  • JIRA:XSTR-378 and JIRA:XSTR-379, Fix TextAttributeConverter and EnumSetConverter failing on Apache Harmony.
  • JIRA:XSTR-363, Support of native field order i.e. fields are processed in declaration order base classes first.
  • JIRA:XSTR-320, Static field in child may hide non-static field in parent.

API changes

  • JIRA:XSTR-365, Multiple implicit collections with annotations. Deprecated @XStreamImclicitCollection in favour of @XStreamImplicit declared at field level.

Version 1.2.1

Released 11 November 2006.

Major changes

  • Introduced DocumentWriter interface and generalized functionality for all writer implementations creating a DOM structure (DOM4J, DOM, JDom, Xom, Xpp3Dom).
  • Refactored build system to use Maven 2. Ant still supported on XStream Core.
  • Created separate XStream Benchmark module

Minor changes

  • JIRA:XSTR-346, XStream.getClassMapper() does not return a ClassMapper for the current Mapper.
  • Fix problem with fields containing a double underscore.
  • JIRA:XSTR-345, Dom4JWriter adds up attributes.
  • JIRA:XSTR-336, XStream fails to reference an implicit element.
  • JIRA:XSTR-337, Annotation cycle bug.
  • Fix packaging error for the resulting jar building with Maven2.
  • JIRA:XSTR-339, NPE for attribute null values.
  • JIRA:XSTR-338, NPE in JSON writer for converters using non-extended HierarchicalStreamWriter.
  • JIRA:XSTR-357, Fix escaping of values in JSON writer.
  • JIRA:XSTR-356, Fix unmarshaling error for fields containing proxies.
  • JIRA:XSTR-349, Fix backward compatibility of Dom4jWriter.
  • JIRA:XSTR-309, More versatile boolean conversion options (contributed by David Blevins).
  • Add XStream.getReflectionProvider() to retrieve ReflectionProvider in use.
  • JIRA:XSTR-358, @XStreamConverter annotation does not call converter constructor.
  • Website generated using XSite

API changes

  • Deprecate JDomWriter.getResult() in favour of DocumentWriter.getTopLevelNodes().
  • Deprecate ThreadSafeSimpleDateFormat, since this is an internal helper and not part of XStream API.

Version 1.2

Released 18 August 2006.

Major changes

  • JIRA:XSTR-269, Using attributes for fields (contributed by Paul Hammant and Ian Cartwright).
  • Aliasing of arbitrary attributes.
  • JIRA:XSTR-50, XStream can now serialize another XStream instance.
  • JIRA:XSTR-227, XStream has now the XStreamer, that serializes an object together with its XStream instance.
  • JIRA:XSTR-278, AnnotationConverter for fields (contributed by Guilherme Silveira).
  • JIRA:XSTR-256, PureJavaReflectionProvider supports now final fields starting with JDK 1.5
  • JIRA:XSTR-258, Any Collection type can now be declared implicit, the default implementation will be respected for unmarshaling.
  • JIRA:XSTR-88, XStream can now write all references as absolute XPath expression.
  • JIRA:XSTR-62 and JIRA:XSTR-211, New SingeValueConverter allows light weight converters if the value can be represented by a unique string.
  • Aliasing of classes of a specific type.
  • JIRA:XSTR-239, Support for certain types of proxies generated with the CGLIB Enhancer.
  • JIRA:XSTR-90 and JIRA:XSTR-311, Support for BEA JRockit starting with R25.1.0 (contributed by Henrik Ståhl of BEA).

Technology preview

  • Experimental binary reader and writer.
  • Experimental HierarichicalStreamCopier allows streams to be copied from one format to another without the overhead of serialization.
  • Experimental JSON support allows streams to be copied from one format to another without the overhead of serialization (contributed by Paul Hammant).

Minor changes

  • JIRA:XSTR-266, XStream fails to serialize elements of a unserializable class, that is a base class of a derived class
  • JIRA:XSTR-236, Priority constants for converter registration are now public
  • JIRA:XSTR-215, XStream writes now fields in declaration order even for JVMs reporting them in reverse order like IBM JDK.
  • JIRA:XSTR-276 and JIRA:XSTR-283, XStream does no longer attempt to create references to implicit element.
  • JIRA:XSTR-244, Closing a Writer can now be done twice, but any write attempt will later on fail.
  • JIRA:XSTR-243, Transient fields were unmarshalled from XML.
  • JIRA:XSTR-250, Providing a mapper to the XStream constructor will no longer result in a NPE.
  • JIRA:XSTR-281, After registering a new converter, the internal converter cache is now cleared.
  • JIRA:XSTR-284, XStream checks the object returned by a converter for compatibility.
  • XStream no longer fails serializing a Throwable without cause when no references shall be written.
  • Converter for java.awt.font.TextAttribute.
  • Converter for java.nio.charset.Charset.
  • JIRA:XSTR-286, XStream detects impossible self serialization and throws now an appropriate ConversionException.
  • JIRA:XSTR-291, XomDriver implementation added.
  • JIRA:XSTR-299, Fix for implicit collections with items using the same name as the field name of the underlying collection.
  • JIRA:XSTR-245, Broken XML with custom serialization in certain cases (patch contributed by Cyrille Le Clerc).
  • JIRA:XSTR-304, Bad handling of repairing namespace flag for StaxDriver (patch contributed by John Kristian).

API changes

  • JIRA:XSTR-252, Refactored support for XML friendly character mapping.
  • JIRA:XSTR-69, Refactored ReflectionConverter allows simpler subclassing.
  • Unmarshalling context has now an overloaded version of the method convertAnother to provide the Converter directly.
  • Deprecate ClassMapper for Mapper. All methods with a ClassMapper parameter have now a duplicate taking only a Mapper. The variant with the ClassMapper is deprecated.
  • Deprecate c.t.x.alias.CannotResolveClassException for c.t.x.mapper.CannotResolveClassException.
  • Deprecate NameMapper (was not used within XStream anymore anyway).
  • Deprecate constructor of DefaultMapper taking an alternative name for the class attribute. Use the aliasAttribute method.
  • Deprecate attributeForImplementationClass, attributeForClassDefiningField, attributeForReadResolveField, and attributeForEnumType in favour of the generalized aliasForAttribute in the Mapper interface.
  • Removed all deprecated stuff from 1.1.x and 1.0.x
  • JIRA:XSTR-211, A lot of existing (basic) Converters have been refactored to use the new SingleValueConverter interface.
  • Dom4JWriter uses now a DocumentFactory and a XMLWriter as constructor arguments.

Version 1.1.3

Released 13 January 2006.

Major changes

  • Added XStream.toXML(OutputStream) and XStream.fromXML(InputStream).
  • Ability to prevent fields from being serialized by calling XStream.omitField() or by implementing Mapper.shouldSerializeMember().
  • Added Converter for Enum, EnumMap and EnumSet
  • JIRA:XSTR-186, Added BeanConverter (contributed by Andrea Aime)
  • JIRA:XSTR-246, Added ISO8601SqlTimestampConverter (contributed by Cheong, Chung-Onn)
  • Added ISO8601GregorianCaledarConverter
  • JIRA:XSTR-215, Fixed support for IBM JVM (contributed by Gabor Liptak)
  • Enhanced mode support for Blackdown JDK
  • JIRA:XSTR-265, support for javax.security.auth.Subject
  • JIRA:XSTR-233, support for Integer[] arrays

Minor changes

  • Remove unnecessary PrintWriter wrapper in default writers (pointed out by Mathieu Champlon)
  • Bugfix: EnumSet converter can now deal with empty sets (contributed by Baba Buehler)
  • Update ISO8601DateConverter to use Joda 1.0
  • JIRA:XSTR-242, GregorianCalenderConverter saves now the timezone
  • JIRA:XSTR-247, ISO8601DateConverter now independent on timezone
  • JIRA:XSTR-263, Circular references with Externalizable objects fail

API changes

  • None.

Version 1.1.2

Released Apr 30, 2005. Most popular feature requests implemented. Java 5 Enum support. Serialization of JavaBeans using accessors. Aliasing of fields. StAX integration, with namespaces. Improved support on JDK 1.3 and IBM JDK.

Major changes

  • JIRA:XSTR-186, Option to serialize JavaBeans using public accessors, rather than private fields (contributed by Andrea Aime).
  • Ability to alias fields as well as classes, using XStream.addFieldAlias().
  • JIRA:XSTR-70, JIRA:XSTR-204 Support for JDK 5 enums (contributed by Eric Snell and Bryan Coleman).
  • JIRA:XSTR-206 Clean representation of JDK 5 EnumMap and EnumSet.
  • XStream can now be built using JDK 1.3 (previously it required JDK 1.4 to compile, but 1.3 to run).
  • JIRA:XSTR-215, Enhanced mode is now supported on the IBM 1.4 JDK.
  • The default HierarchicalStreamWriter implementation is supplied by the HierarichicalStreamDriver (as well as the reader).

Minor changes

  • JIRA:XSTR-104 HierarchicalStreamReader now exposes all available attributes to the Converter implementations (contributed by Trygve Laugstol).
  • Bugfix: Externalizable deserialization supported for objects not at the root of tree.
  • JavaMethodConverter handles non public methods/constructors (contributed by Kevin Ring).
  • PropertiesConverter also serializes default properties, if present (contributed by Kevin Ring).
  • Bugfix: In some cases, XppReader and StaxReader would get confused when calling hasMoreChildren() and getValue() on the same node.
  • JIRA:XSTR-217, ISO8601DateConverter now requires joda-time-1.2.1
  • PrettyPrintWriter and CompactWriter may have their text/attribute escaping rules customized by overriding writeText() and writeAttributeValue().

API changes

  • HierarchicalStreamDriver implementations now require a createWriter() method. The simplest implementation is to return a new PrettyPrintWriter.
  • Introduced ReaderWrapper/WriterWrapper classes to make it easier to wrap (decorate) HierarchicalStreamReader/Writer instances.

Version 1.1.1

Released Mar 7, 2005. Mostly bugfixes and minor feature enhancements.

Major changes

  • Converters can be registered with a priority, allowing more generic filters to handle classes that don't have more specific converters.
  • Converters can now access underlying HierarchicalStreamReader/Writer implementations to make implementation specific calls.
  • Improved support for classes using ObjectInputFields to follow the serialization specification.
  • JIRA:XSTR-179 Support for ObjectInputStream.registerValidation(ObjectInputValidation).
  • JIRA:XSTR-178 Serialized inner class now maintains reference to outer class.
  • JIRA:XSTR-199 Default ClassLoader may be changed using XStream.setClassLoader().

Minor changes

  • Bugfix: Thread context classloader is loaded by the correct thread. (Thanks to Padraic Renaghan for pointing this out).
  • Bugfix: Default implementations of aliased classes were not being deserialized by SerializableConverter.
  • Bugfix: JIRA:XSTR-180 Serializable objects support defaultReadObject() even when no default fields available.
  • Bugfix: For serialized objects class hierarchy is serialized starting with superclass (as per Java Object Serialization).
  • Bugfix: readObject() is now called for classes containing only transient fields.
  • Bugfix: Order of fields are maintained when calling ObjectOutputStream.putFields().
  • Bugfix: FontConverter extended to support FontUIResource which does some awkward native calls.
  • Bugfix: Deserialization of very complicated graphs (such as Swing components) sometimes resulted in broken object references. Now fixed.
  • Bugfix: JIRA:XSTR-188 Classes that use readResolve()/writeReplace() can now return different types.
  • Bugfix: JIRA:XSTR-185, JIRA:XSTR-195 Support for loading of array classes for classes that have not yet been loaded. (Thanks to Henri Tremblay and Simon Daniel)
  • Bugfix: JIRA:XSTR-190 PrettyPrintWriter and CompactWriter escape characters in XML attributes.
  • Bugfix: JIRA:XSTR-176, JIRA:XSTR-196 The XStream ObjectInputStream and ObjectOutputStream implementations now propegate the flush() and close() events to the underlying streams.
  • Bugfix: JIRA:XSTR-192 Implicit collection mappings are now supported in inheritance hierarchies.

API changes

  • ClassMapper is now deprecated. Replaced with MapperWrapper.
  • HierarchicalStreamWriter implementations must now implement close(), flush() and underlyingWriter().
  • HierarchicalStreamReader implementations must now implement close() and underlyingReader().

Version 1.1

Released Jan 15, 2005. Focus on support for objects defining custom serialization using the standard Java serialization mechanism.

Major changes

  • Provides drop in replacement for ObjectInputStream and ObjectOutputStream, using XStream.createObjectInputStream() and XStream.createObjectOutputStream() and XStream.createObjectInputStream(). This provides support for streaming objects.
  • Support for objects that specify their own serialization schemes by implementing readObject() and writeObject() (as in Java serialization spec). This includes support for ObjectInputStream.getFields() and ObjectOuputStream.putFields().
  • Support for objects to serialize other objects to the stream by implementing writeReplace() (as in Java serialization spec).
  • Support for any object that performs custom serialization by implementing java.io.Externalizable (as in Java serialization spec).
  • Implicit collections can be specified for classes, allowing the element wrapping the collection to be skipped.
  • New writer implementations to allow XStream to serialize directly to a SAX stream or TrAX pipeline.
  • The MarshallingContext and UnmarshallingContext interfaces now extend DataHolder, allowing arbitrary data to be stored by the user whilst walking the object graph and passed around to Converters. DataHolders can also be passed into XStream from the outside.
  • Includes new DomWriter implementation to serialize directly to a W3C DOM tree (to complement the existing DomReader).
  • Better support for instantiating objects on non Sun 1.4+ JVMs, including non-public constructors, private static inner classes and ANY class that implements java.io.Serializable.
  • DOM, DOM4J, JDOM, XOM, Electric-XML, SAX, STAX
  • Specific ClassLoaders can be passed into XStream, to allow for greater compatibility in J2EE containers.
  • Ability to change the default converter
  • Added optional ISO8601DateConverter for full ISO8601 date format support. The converter is not registered by default as it requires the joda-time dependency (http://joda-time.sf.net). To use, ensure joda-time is in classpath and register explicitly.
  • Enhanced mode is now supported on the Apple 1.4 JDK.

Minor changes

  • PrettyPrintWriter only flushes stream when necessary - large performance improvement for serialization.
  • Added XStream.fromXml(xml, root) convenience methods for deserializing into an existing root object.
  • JDK 1.3 compatibility: Added mechanism for accessing nested exception.
  • JDK 1.3 compatibility: GregorianCalendarConverter only calls Calendar.getTimeInMillis() the JDK supports it.
  • Bugfix: All caches are now synchronized - there were some thread safety issues.
  • Bugfix: Only immutable basic types will have references ignored in XML (for clarity).
  • Bugfix: Class names can contain underscores.
  • Bugfix: Support for '\0' char.
  • Bugfix: PropertyConverter no longer attempts to serialize subclasses of Properties.
  • Bugfix: JVM detection uses system properties, which is more accurate than searching the classpath.

API changes

  • XStream.addDefaultCollection() has been deprecated. Use XStream.addImplicitCollection() instead.

Version 1.0.2

Released Aug 7, 2004. Focus on improving the converters bundled with XStream to support a wider range of types.

Major changes

  • XML elements are written in order they are defined in class, rather than alphabetical.
  • Converters for java.io.File, java.sql.Timestamp, java.awt.Color, and dynamic proxies are now registered by default.
  • EncodedByteArrayConverter is now registered by default and uses a single Base64 string to store the contents of a byte[]. This now works on all JVMs as it no longer relies on Sun specific classes. This converter will also unmarshal byte[] that have been serialized without it, for backwards compatability.
  • New converters for java.sql.Time, java.sql.Date, java.util.Locale, java.util.Currency, java.util.Calendar and java.awt.Font.
  • All caching is done in XStream instance instead of statics, allowing applications that use hot redeployment of classes to use XStream in a parent classloader.
  • XStream will fail fast if a field value is defined more than once in XML when deserializing.

Minor changes

  • The <entry> element used in Maps can now be specified by creating an alias for java.util.Map.Entry.
  • Bugfix: Fields with characters that generate invalid XML (such as $ signs) are now escaped.
  • Bugfix: Pre-instantiated objects can be unmarshalled through multiple levels.

API changes

  • None.

Version 1.0.1

Released May 30, 2004. Misc features and bugfixes.

Major changes

  • Support for multidimensional arrays.
  • Object with readResolve() method will be treated the same way native serialization treats them.

Minor changes

  • New converters for Throwable and StackTraceElement that retain stack trace (JDK 1.4 only)
  • Bugfix: System.identityHashCode() is not guaranteed to be unique. Ensure reference checking is used as well.
  • Bugfix: Allows user classes to be defined in WEB-INF/classes in Servlet environments. Tries to use context classloader if available.
  • Support for java.util.Currency (through readResolve()).
  • Instances of Jakarta Commons Lang Enum are now reused (through readResolve()).
  • Bugfix: JavaClassConverter handles primitive type classes (contributed by Matthew Sandoz).

API changes

  • Additional method: ConverterLookup.defaultConverter(). Custom implementations of this class should implement this new method.

Version 1.0

Released May 14, 2004. Focusses on finalizing the API for 1.0 release.

Major changes

  • Supports fields of same name, hidden by inheritance.

Minor changes

  • JavaDoc for most important parts of API.

API changes

  • The ReflectionConverter and ReflectionProviders have had an overhaul to support hidden fields. Most methods now take an extra argument to specify which class a field is declared in.

Version 1.0 (release candidate 1)

Released May 9, 2004. Focusses on finalizing the API for 1.0 release.

Major changes

  • JDK 1.3 compatibility.
  • Informative error messages.
  • Defaults to using faster XPP based parser.
  • Serializes final field under JDK 1.4.
  • Fail fast when trying to serialize final field if not Sun 1.4 JRE.

Minor changes

  • Misc performance improvements.
  • Converters for TreeMap and TreeSet that store the Comparator.

API changes

  • Default constructor for XStream class uses XppDriver instead of DomDriver. To use DomDriver, explicitly pass it in to the constructor.
  • Exception is thrown if trying to serialize an object that contains a final field if not Sun 1.4 JRE.

About XStream version numbers...

Version 0.6

Released May 7, 2004. Focusses on providing full object graph support.

Major changes

  • None.

Minor changes

  • Bugfix: Objects that had no children could not be derefenced properly (thanks to Brian Slesinsky and Nick Pomfret).
  • Bugfix: DateConverter is now thread safe.
  • Optimization: String instances are reused as much as possible.
  • Converters for BigInteger and BigDecimal.
  • IntConverter now recognises hexadecimal and octal notations (thanks to Konstantin Pribluda).

API changes

  • None.

Version 0.6 (release candidate 1)

Released April 19, 2004. Focusses on providing full object graph support.

Major changes

  • Full support for object graphs, including duplicate references of same object and circular references.
  • References can be identified using XPath (default), unique-IDs or disabled.

Minor changes

  • Release includes Ant build file.
  • Converters for non standard collections such as Collections.EMPTY_LIST, syncronizedList(), unmodifiableMap(), etc.
  • Converter for nulls.
  • Converter for dynamic proxies.
  • Converter for java.net.URL.
  • Converters for java.util.LinkedHashMap and java.util.LinkedHashSet.
  • Converters for java.lang.reflect.Method and java.lang.reflect.Constructor.
  • If duplicate reference support is disabled and a circular reference is encountered, an exception will be thrown.

API changes

  • None.

Version 0.5

Released March 8, 2004. Focussed on performance.

Major changes

  • Massive performance improvements. Up to 3 times faster for serialization and 22 times faster for deserialization!
  • Non-DOM building pull parser based reader. Results in much smaller memory footprint, particularly when deserializing large object models.

Minor changes

  • Misc performance improvements.
  • Misc bugfixes.
  • Alternate encodings can be used with DomDriver.

API changes

  • Renamed XMLReader/Writer to HierarchicalStreamReader/Writer as XStream is not actually coupled to serializing just to XML.
  • Cleaned up the public API.
  • Moved internal XStream implementation classes to core package.
  • Misc package/class renames to make more sense. Dumped lots of dead code.

Version 0.4

This version was never publicly released. All changes were made available in 0.5. Focussed on making it easier to create custom converters.

Major changes

  • Overhaul of interface for Converters. Makes Converters much cleaner to write.

Minor changes

  • Added custom converters for java.io.File, java.util.Properties, java.util.Vector, java.util.Hashtable, java.util.BitSet byte[] (Base64 encoded), char[].
  • Misc bugfixes.

API changes

  • New interface to be implemented by custom converters.

Version 0.3

Released January 1, 2004.

Major changes

  • Added ElementMapper interface and default implementations to allow fine grained control over element name to class mapper operations.
  • Added an XPP based reader and writer that uses a pull-parser to create a lightweight DOM tree.

Minor changes

  • Added XStream.fromXML(XMLReader xmlReader,Object root) method to allow the population of an object graph starting with a live object root.
  • Added XMLReader.peek() method to allow access to the underlying hierarchical object being unmarshalled.

API changes

  • Aligned the the methods in XStream to use the specified ObjectFactory in the constructor instead of creating a SunReflectionObjectFactory.

Older versions

Changes in XStream prior to version 0.3 were not logged.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/annotations-tutorial.html0000664000175000017500000004734212206661545032664 0ustar jamespagejamespage Annotations Tutorial

Motivation

Sometimes it can get tedious to call all those XStream aliases/register converter methods or you might simply like the new trend on configuring POJOs: Java annotations.

This tutorial will show you how to use some of the annotations provided by XStream in order to make configuration easier. Let's start with a custom Message class:

package com.thoughtworks.xstream;
package com.thoughtworks.xstream;
public class RendezvousMessage {

	private int messageType;
	
	public RendezvousMessage(int messageType) {
		this.messageType = messageType;
	}
	
}

Let's code the XStream calls which generate the XML file:

package com.thoughtworks.xstream;
public class Tutorial {

	public static void main(String[] args) {
		XStream stream = new XStream();
		RendezvousMessage msg = new RendezvousMessage(15);
		System.out.println(stream.toXML(msg));
	}

}

Results in the following XML:

<com.thoughtworks.xstream.RendezvousMessage>
  <messageType>15</messageType>
</com.thoughtworks.xstream.RendezvousMessage>

Aliasing Annotation

The most basic annotation is the one responsible for type and field aliasing: @XStreamAlias. Let's annotate both our type and field and run the tutorial method again:

@XStreamAlias("message")
class RendezvousMessage {

	@XStreamAlias("type")
	private int messageType;
	
	public RendezvousMessage(int messageType) {
		this.messageType = messageType;
	}
	
}

In some strange way, the result is the same. What happened here? XStream does not read this annotation by default as it would be impossible to deserialize the XML code. Therefore we need to tell XStream to read the annotations from this type:

	public static void main(String[] args) {
		XStream stream = new XStream();
		xstream.processAnnotations(RendezvousMessage.class);
		RendezvousMessage msg = new RendezvousMessage(15);
		System.out.println(stream.toXML(msg));
	}

Note that we have called the processAnnotations method of XStream. This method registers all aliases annotations in the XStream instance passed as first argument. You may also use the overloaded version of this method taking an array of types. The resulting XML is now what we have expected:

<message>
  <type>15</type>
</message>

If you let XStream process the annotations of a type, it will also process all annotations of the related types i.e. all super types, implemented interfaces, the class types of the members and all their generic types.

Implicit Collections

Let's add a List of content to our RendezvousMessage. We desire the same functionality obtained with implicit collections:

@XStreamAlias("message")
class RendezvousMessage {

	@XStreamAlias("type")
	private int messageType;        
	
	private List<String> content;
	
	public RendezvousMessage(int messageType, String ... content) {
		this.messageType = messageType;
		this.content = Arrays.asList(content);
	}
	
}
	public static void main(String[] args) {
		XStream stream = new XStream();
		xstream.processAnnotations(RendezvousMessage.class);
		RendezvousMessage msg = new RendezvousMessage(15, "firstPart","secondPart");
		System.out.println(stream.toXML(msg));
	}

The resulting XML shows the collection name before its elements:

<message>
  <type>15</type>
  <content class="java.util.Arrays$ArrayList">
    <a class="string-array">
      <string>firstPart</string>
      <string>secondPart</string>
    </a>
  </content>
</message>

This is not what we desire therefore we will annotate the content list to be recognized as an implicit collection:

@XStreamAlias("message")
class RendezvousMessage {

	@XStreamAlias("type")
	private int messageType;

	@XStreamImplicit
	private List<String> content;

	public RendezvousMessage(int messageType, String... content) {
		this.messageType = messageType;
		this.content = Arrays.asList(content);
	}

}

Resulting in an XML which ignores the field name (content) of the list:

<message>
  <type>15</type>
  <a class="string-array">
    <string>firstPart</string>
    <string>secondPart</string>
  </a>
</message>

We are almost there... we still want to remove the 'a' tag, and define each content part with the tag 'part'. In order to do so, let's add another attribute to our implicit collection annotation. The attribute field defines the name of the tag used for data contained inside this collection:

@XStreamAlias("message")
class RendezvousMessage {

	@XStreamAlias("type")
	private int messageType;

	@XStreamImplicit(itemFieldName="part")
	private List<String> content;

	public RendezvousMessage(int messageType, String... content) {
		this.messageType = messageType;
		this.content = Arrays.asList(content);
	}

}

Resulting in a cleaner XML:

<message>
  <type>15</type>
  <part>firstPart</part>
  <part>secondPart</part>
</message>

The implicit annotation can also be used for arrays and maps. In the latter case you should provide the field name of the values that are used as key of the map.

Local Converters

Let's create another attribute which defines the timestamp when the message was created and one to flag special importance of the message:

@XStreamAlias("message")
class RendezvousMessage {

	@XStreamAlias("type")
	private int messageType;

	@XStreamImplicit(itemFieldName="part")
	private List<String> content;
	
	private boolean important;
	
	private Calendar created = new GregorianCalendar();

	public RendezvousMessage(int messageType, boolean important, String... content) {
		this.messageType = messageType;
		this.important = important;
		this.content = Arrays.asList(content);
	}

}

Resulting in the following xml:

<message>
  <type>15</type>
  <part>firstPart</part>
  <part>secondPart</part>
  <important>false</important>
  <created>
    <time>1154097812245</time>
    <timezone>America/Sao_Paulo</timezone>
  </created>
</message>

Now we face the following problem: We want to use a custom converter locally for this Calendar, but only for this Calendar, this exact field in this exact type. Easy... let's annotate it with the custom converter annotation:

@XStreamAlias("message")
class RendezvousMessage {

	@XStreamAlias("type")
	private int messageType;

	@XStreamImplicit(itemFieldName="part")
	private List<String> content;
	
	private boolean important;

	@XStreamConverter(SingleValueCalendarConverter.class)
	private Calendar created = new GregorianCalendar();

	public RendezvousMessage(int messageType, String... content) {
		this.messageType = messageType;
		this.content = Arrays.asList(content);
	}

}

Let's create the custom converter:

public class SingleValueCalendarConverter implements Converter {

    public void marshal(Object source, HierarchicalStreamWriter writer,
            MarshallingContext context) {
        Calendar calendar = (Calendar) source;
        writer.setValue(String.valueOf(calendar.getTime().getTime()));
    }

    public Object unmarshal(HierarchicalStreamReader reader,
            UnmarshallingContext context) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(new Date(Long.parseLong(reader.getValue())));
        return calendar;
    }

    public boolean canConvert(Class type) {
        return type.equals(GregorianCalendar.class);
    }
}

And we end up with the converter being used and generating the following XML:

<message>
  <type>15</type>
  <part>firstPart</part>
  <part>secondPart</part>
  <important>false</important>
  <created>1154097812245</created>
</message>

Additionally we want to format the importance flag not with a technical true or false, but with a natural yes or no. Fortunately the BooleanConverter supports alternate format styles, but how can we use an annotation to register a new instance locally? The XStreamConverter annotation uses some lightweight dependency injection mechanism to match given arguments with the parameters of available constructors. That way we can write now:

@XStreamAlias("message")
class RendezvousMessage {

	@XStreamAlias("type")
	private int messageType;

	@XStreamImplicit(itemFieldName="part")
	private List<String> content;
	
	@XStreamConverter(value=BooleanConverter.class, booleans={false}, strings={"yes", "no"})
	private boolean important;
	
	@XStreamConverter(SingleValueCalendarConverter.class)
	private Calendar created = new GregorianCalendar();

	public RendezvousMessage(int messageType, boolean important, String... content) {
		this.messageType = messageType;
		this.important = important;
		this.content = Arrays.asList(content);
	}

}

The BooleanConverter has an additional constructor with two string values expressing true and false and a third argument to ignore case of these values. Therefore we have added all 3 arguments to the annotation. The sequence of the arguments is only important for same types. As result we have now:

<message>
  <type>15</type>
  <part>firstPart</part>
  <part>secondPart</part>
  <important>no</important>
  <created>1154097812245</created>
</message>

See the Javadoc of the XStreamConverter annotation what more arguments are provided implicitly.

Attributes

The client may asks for the type tag and the importance flag to be an attribute inside the message tag, as follows:

<message type="15" important="no">
  <part>firstPart</part>
  <part>secondPart</part>
  <created>1154097812245</created>
</message>

All you need to do is add the @XStreamAsAttribute annotation:

@XStreamAlias("message")
class RendezvousMessage {

	@XStreamAlias("type")
   	@XStreamAsAttribute
	private int messageType;

	@XStreamImplicit(itemFieldName="part")
	private List<String> content;
	
   	@XStreamAsAttribute
	@XStreamConverter(value=BooleanConverter.class, booleans={false}, strings={"yes", "no"})
	private boolean important;

	@XStreamConverter(SingleValueCalendarConverter.class)
	private Calendar created = new GregorianCalendar();

	public RendezvousMessage(int messageType, boolean important, String... content) {
		this.messageType = messageType;
		this.important = important;
		this.content = Arrays.asList(content);
	}
}

Field as Text Value

Sometimes it is desirable to use a single field as text value for a XML element and all other fields should be written as attributes. XStream delivers the ToAttributedValueConverter, that will write a type with this form:

@XStreamAlias("message")
@XStreamConverter(value=ToAttributedValueConverter.class, strings={"content"})
class RendezvousMessage {

	@XStreamAlias("type")
	private int messageType;

	private List<String> content;
	
	@XStreamConverter(value=BooleanConverter.class, booleans={false}, strings={"yes", "no"})
	private boolean important;

	@XStreamConverter(SingleValueCalendarConverter.class)
	private Calendar created = new GregorianCalendar();

	public RendezvousMessage(int messageType, boolean important, String... content) {
		this.messageType = messageType;
		this.important = important;
		this.content = Arrays.asList(content);
	}
}

Unfortunately our little example does not work! Although we register the converter with the XStreamConverter annotation and provide with its arguments the field name, the conversion will fail later on. To use this converter you have to respect the implicit requirement: Any field (derived or not) has to be expressed as a single string i.e. technically XStream has to use a SingleValueConverter. In our case we have a list of strings that prevent the conversion. Therefore we have to use either a custom converter that transforms this list into a single string or we use for simplicity a simple string here:

@XStreamAlias("message")
@XStreamConverter(value=ToAttributedValueConverter.class, strings={"content"})
class RendezvousMessage {

	@XStreamAlias("type")
	private int messageType;

	private String content;
	
	@XStreamConverter(value=BooleanConverter.class, booleans={false}, strings={"yes", "no"})
	private boolean important;

	@XStreamConverter(SingleValueCalendarConverter.class)
	private Calendar created = new GregorianCalendar();

	public RendezvousMessage(int messageType, boolean important, String content) {
		this.messageType = messageType;
		this.important = important;
		this.content = content;
	}
}

Now it is possible to generate this XML:

<message type="15" important="no" created="1154097812245">This is the message content.</message>

Note, that no XStreamAsAttribute annotations were necessary. The converter assumes it implicitly.

Omitting Fields

Sometimes a class may contain elements that should not be part of the resulting XML. In our case we may now drop the 'messageType', since we are only interested at the content. This is easy using the @XStreamOmitField annotation:

@XStreamAlias("message")
class RendezvousMessage {

   	@XStreamOmitField
	private int messageType;

	@XStreamImplicit(itemFieldName="part")
	private List<String> content;

	@XStreamConverter(value=BooleanConverter.class, booleans={false}, strings={"yes", "no"})
	private boolean important;

	@XStreamConverter(SingleValueCalendarConverter.class)
	private Calendar created = new GregorianCalendar();

	public RendezvousMessage(int messageType, boolean important, String... content) {
		this.messageType = messageType;
		this.important = important;
		this.content = Arrays.asList(content);
	}
}

The resulting XML does not contain the type of the message anymore:

<message>
  <part>firstPart</part>
  <part>secondPart</part>
  <important>no</important>
  <created>1154097812245</created>
</message>

Auto-detect Annotations

Until now we have always told you, that you have to call processAnnotation to configure the XStream instance with the present annotations in the different classes. However, this is only half the truth. You can run XStream also in a lazy mode, where it auto-detects the annotations while processing the object graph and configure the XStream instance on-the-fly:

package com.thoughtworks.xstream;
public class Tutorial {

	public static void main(String[] args) {
		XStream stream = new XStream();
		xstream.autodetectAnnotations(true);
		RendezvousMessage msg = new RendezvousMessage(15);
		System.out.println(stream.toXML(msg));
	}

}

The resulting XML will look as expected! Nevertheless you have to understand the implications, therefore some words of warning:

  1. Chicken-and-egg problem

    An XStream instance caches all class types processed for annotations. Every time XStream converts an object it will in auto-detection mode first process the object's type and all the types related (as explained above). Therefore it is no problem to serialize an object graph into XML, since XStream will know of all types in advance. This is no longer true at deserialization time. XStream has to know the alias to turn it into the proper type, but it can find the annotation for the alias only if it has processed the type in advance. Therefore deserialization will fail if the type has not already been processed either by having called XStream's processAnnotations method or by already having serialized this type. However, @XStreamAlias is the only annotation that may fail in this case.

  2. Concurrency

    XStream is not thread-safe while it is configured, thread-safety is only guaranteed during marshalling and unmarshalling. Unfortunately an annotation is defining a change in configuration that is now applied while object marshalling is processed. Therefore will the auto-detection mode turn XStream's marshalling process in a thread-unsafe operation. While XStream synchronizes the configuration modification, it cannot guard concurrent reads and you may run under certain circumstances into concurrency problems.

  3. Exceptions

    XStream uses a well-defined exception hierarchy. Normally an InitializationException is only thrown while XStream is configured. If annotations are processed on the fly they can be thrown obviously also in a marshalling process.

  4. Performance

    In auto-detection mode XStream will have to examine any unknown class type for annotations. This will slow down the marshalling process until all processed types have been examined once.

Please note, that any call to XStream.processAnnotations will turn off the auto-detection mode.

Summing up

The XStream annotations support might help you configuring your class mappings in some ways, as the custom configuration will appear in your types, but might not be the solution for other problems, i.e. when you need to map the same type to two different XML 'standards'. Others might claim that the configuration should be clearly stated in a Java class and not mixed with your model, its up to you to pick the best approach in your case: Annotations or direct method calls to the XStream instance. Annotations do not provide more functionality, but may improve convenience.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/faq.html0000664000175000017500000012743112206661545027233 0ustar jamespagejamespage Frequently Asked Questions
  1. Compatibility
  2. Serialization
  3. XML specifics
  4. JSON specifics
  5. Comparison to other products
  6. Scalability
  7. Uses of XStream

Compatibility

Which JDK is required to use XStream?

1.4 or later.

Which dependencies are required to run XStream?

All dependencies are optional, XStream uses since version 1.4.1 by default xpp3:xpp3_min and xmlpull:xmlpull. However it depends on the use case. XStream will run without dependencies using the DOM driver on all Java runtimes or the StAX driver in combination with Java 6 or greater. See the list of optional dependencies.

Does XStream behave differently across different JVMs?

XStream has two modes of operation: Pure Java and Enhanced. In pure Java mode, XStream behaves in the same way across different JVMs, however its features are limited to what reflection allows, meaning it cannot serialize certain classes or fields. In enhanced mode, XStream does not have these limitations, however this mode of operation is not available to all JVMs.

Which JVMs allow XStream to operate in enhanced mode?

Currently on the Sun, Apple, HP, IBM and Blackdown 1.4 JVMs and onwards. Also for Hitachi, SAP and Diablo from 1.5 and onwards. Support for BEA JRockit starting with R25.1.0. OpenJDK 6 is also supported. For all other JVMs, XStream should be used in pure Java mode.

What are the advantages of using enhanced mode over pure Java mode?

FeaturePure JavaEnhanced Mode
Public classesYesYes
Non public classesNoYes
Static inner classesYesYes
Non-static inner classesNoYes
Anonymous inner classesNoYes
With default constructorYesYes
Without default constructorNoYes
Private fieldsYesYes
Final fieldsYes >= JDK 1.5Yes

Why is my application not able to create a XmlPullParser with the XppDriver since XStream 1.4?

The XML Pull Parser API defines an own mechanism to load the factory for the available XPP implementation. XStream's XppDriver never used this lookup mechanism automatically before version 1.4, now it will. Therefore you will have to add a dependency to xmlpull if the XPP implementation does not deliver the classes on its own. This dependency is necessary for Xpp3 in contrast to kXML2 that contains the classes. Use the Xpp3Driver or the KXml2Driver if you want to select one of the directly supported XPP implementation on your own without using the XPP factory. Note, that the minimal version of kXML2 does not support the XPP factory, but can be used by the KXml2Driver.

Can I use XStream in an Android application?

XStream does work in Android 1.0, but is reported to have limited capabilities. Since XStream 1.4 Android is treated at least as JD 5 platform, but it e.g. does not include the java.beans package. Therefore you cannot use the JavaBeanConverter. Note, that Android provides an XML Pull Parser, therefore XStream can work without additional dependencies.

Why does XStream fail on Apache Harmony?

Since JDK 5 it is possible according the Java specification to write into final fields using reflection. This is not yet supported by Harmony and therefore the PureJavaReflectionProvider fails. We have also already investigated into enhanced mode in Harmony, but the Harmony JVM crashed running the unit tests. However, Harmony has been retired, we will no longer make any efforts in this direction.

Are there plans to provide enhanced mode support to other JVMs?

Yes. Let us know which JVM you would like supported.

When should I use XStream not in enhanced mode?

Running XStream in a secured environment can prevent XStream from running in enhanced mode. This is especially true when running XStream in an applet. You may also try to use the JavaBeanConverter as alternative to the ReflectionConverter running in enhanced or pure Java mode.

Which permissions does XStream need when running with an active SecurityManager?

This depends on the mode XStream is running in. Refer to the SecurityManagerTest for details.

Why does XStream 1.2 no longer read XML generated with XStream 1.1.x?

The architecture in XStream has slightly changed. Starting with XStream 1.2 the HierarchicalStreamDriver implementation is responsible to ensure that XML tags and attributes are valid names in XML, in XStream 1.1.x this responsibility was part of the ClassMapper implementations. Under some rare circumstances this will result in an unreadable XML due to the different processing order in the workflow of such problematic tag names.

You can run XStream in 1.1 compatibility mode though:

XStream xstream = new XStream(new XppDriver(new XStream11XmlFriendlyReplacer())) {
    protected boolean useXStream11XmlFriendlyMapper() {
        return true;
    }
};

XStream 1.3 ignores suddenly annotated converters (@XStreamConverter and @XStreamConverters)?

XStream treats now all annotations the same and therefore it no longer auto-detects any annotation by default. You can configure XStream to run in auto-detection mode, but be aware if the implications. As alternative you might register the deprecated AnnotationReflectionConverter, that was used for XStream pre 1.3.x, but as drawback the functionality to register a local converter with XStream.registerLocalConverter will no longer work.

XStream 1.3 suddenly has a different field order?

Yes. This was announced with the last 1.2.x release and was done to support the type inheritance of XML schemas. However, XStream is delivered with the XStream12FieldKeySorter that can be used to sort the fields according XStream 1.2.2.

Serialization

Which class types can be serialized by XStream?

In contrast to the JDK XStream is not tied to a marker interface to serialize a class. XStream ships with some specialized converters, but will use reflection by default for "unknown" classes to examine, read and write the class' data. Therefore XStream can handle quite any class, especially the ones referred as POJO (Plain Old Java Object).

However, some types of classes exist with typical characteristics, that cannot be handled - at least not out of the box:

  1. Objects that are based on threads or thread local data: Thread, Timer, ThreadLocal and so on. These classes keep different data for different threads and there's no possibility to recreate a thread in a generic way nor recreating thread specific data. There might be special use cases, but this will always involve a custom converter where threads can be recreated in a specific way tied to that use case.
  2. Class types that are based on generated classes. Such types have often names that are unique to the current process and will have no meaning in a different process. A custom converter might help to write the appropriate data into the serializing stream to be able to recreate a equivalent class at deserialization time.
  3. Types that keep and use system resources like file handles, sockets, pipes and so on. ClassLoader, FileInputStream, FileOutputStream, Socket and so on. To deserialize such a class the converter must be able to claim the appropriate resource from the system again. With the help of a custom converter this might be possible, but with the reflection converter the deserialized class might refer a system resource that is no longer valid or belongs to somebody else. Behavior is undefined then.
  4. A very special case of such allocated system resources are those classes that keep handles to system memory directly, because they are partly implemented native. It is known to be true for the Linux version of Sun's JDK that the BufferedImage references some system specific types of the JDK that themselves have member fields with such memory handles. While it is possible at first sight to serialize and deserialize a BufferedImage, the reflection converter will also duplicate the memory handle. As a result the JVM might crash easily because of freeing unallocated memory or freeing the same memory twice. It might be possible to create a custom converter, but the data structure is really complex in this area and nobody has been investigating so far to such an extent. However, do not use the reflection converter for these types! You have been warned!
  5. Inner class types of the JDK can often vary in implementation details between JDK versions and vendors and are therefore only compatible for the same JDK. This includes collection types returned by the methods of the Collections class that wrap another one (like unmodifiableList) or the collections that are returned by the different Map implementations for the keySet(), entrySet() and values() methods.

How do I specify that a field should not be serialized?

Make it transient, specify it with XStream.omitField() or annotate it with @XStreamOmitField

How do I initialize a transient field at deserialization?

XStream uses the same mechanism as the JDK serialization. Example:

class ThreadAwareComponent {
  private transient ThreadLocal component;
  // ...
  private Object readResolve() {
    component = new ThreadLocal();
    return this;
  }
}

or

class ThreadAwareComponent {
  private transient ThreadLocal component;
  // ...
  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    component = new ThreadLocal();
  }
}

Use the latter in class hierarchies, readResolve is not called for base classes.

XStream is not calling the default constructor during deserialization.

This is, in fact, the same case as above. XStream uses the same mechanism as the JDK serialization. When using the enhanced mode with the optimized reflection API, it does not invoke the default constructor. The solution is to implement the readResolve or readObject as demonstrated with the last question.

What do serialized collections look like?

See example for the CollectionConverter.

Note, that it is possible to configure XStream to omit the container element toys using implicit collections.

My implicit collection is suddenly null after deserialization instead of empty!

By declaring a collection as implicit, the result will have no direct representation of the collection container itself anymore. Therefore, if the collection was empty at serialization time, the serialized result does not contain a trace of the collection anymore. At deserialization time it will therefore not know anything about the collection and will not initialize it. XStream cannot decide anyway at deserialization time, if the collection was empty or null.

The type of my implicit collection is different after deserialization.

By declaring a collection as implicit, the result will have no direct representation of the collection container itself anymore. Therefore XStream cannot track the original type of the collection. At deserialization time it will therefore look at the declaration type of the field that holds the collection and use this type's default implementation, e.g. for a List this is by default an ArrayList.

Beware, that this also means that collections with additional information (e.g. a TreeSet with a Comparator) cannot be restored, since the comparator was already omitted at serialization time.

Do my classes have to implement Serializable if XStream is to serialize them?

No, but XStream respects the Java serialization methods even for types not declared as Serializable.

Can dynamic proxies be serialized?

Yes.

Can CGLIB proxies be serialized?

Only limitedly. A proxy generated with the CGLIB Enhancer is supported, if the proxy uses either a factory or only one callback. Then it is possible to recreate the proxy instance at unmarshalling time. Starting with XStream 1.3.1 CGLIB support is no longer automatically installed because of possible classloader problems and side-effects, because of incompatible ASM versions. You can enable CGLIB support with:

XStream xstream = new XStream() {
    protected MapperWrapper wrapMapper(MapperWrapper next) {
        return new CGLIBMapper(next);
    }
};
xstream.registerConverter(new CGLIBEnhancedConverter(xstream.getMapper(), xstream.getReflectionProvider()));

CGLIBEnhancedConverter fails at initialization with ExceptionInInitializerError

This is not a problem of XStream. You have incompatible ASM versions in your classpath. CGLIB 2.1.x and below is based on ASM 1.5.x which is incompatible to newer versions that are used by common packages like Hibernate, Groovy or Guice. Check your dependencies and ensure that you are using either using cglib-nodep-2.x.jar instead of cglib-2.x.jar or update to cglib-2.2.x that depends on ASM 3.1. However, the nodep version contains a copy of the ASM classes with private packages and will therefore not raise class incompatibilities at all.

Serialization fails with NoSuchMethodError: net.sf.cglib.proxy.Enhancer.isEnhanced(Ljava/lang/Class;)Z

XStream uses this method to detect a CGLIB-enhanced proxy. Unfortunately the method is not available in the cglib-2.0 version. Since this version is many years old and the method is available starting with cglib-2.0.1, please consider an upgrade of the dependency, it works usually smoothly.

How do I use XStream's Hibernate package to serialize my objects?

Support of Hibernate enhanced collections and proxied types. To drop the internals of Hibernate when marshalling such objects to XStream, all converters and the mapper has to be registered for the XStream instance:

final XStream xstream = new XStream() {
  protected MapperWrapper wrapMapper(final MapperWrapper next) {
    return new HibernateMapper(next);
  }
};
xstream.registerConverter(new HibernateProxyConverter());
xstream.registerConverter(new HibernatePersistentCollectionConverter(xstream.getMapper()));
xstream.registerConverter(new HibernatePersistentMapConverter(xstream.getMapper()));
xstream.registerConverter(new HibernatePersistentSortedMapConverter(xstream.getMapper()));
xstream.registerConverter(new HibernatePersistentSortedSetConverter(xstream.getMapper()));

My attributes are interpreted by XStream itself and cause unexpected behavior

XStream's generic converters and the marshalling strategies use a number of attributes on their own. Especially the attributes named id, class and reference are likely to cause such collisions. Main reason is XStream's history, because originally user defined attributes were not supported and all attribute were system generated. Starting with XStream 1.3.1 you can redefine those attributes to allow the names to be used for your own ones. The following snippet defines XStream to use different system attributes for id and class while the field id of YourClass is written into the attribute class:

XStream xstream = new XStream() {
xstream.useAttributeFor(YourClass.class, "id");
xstream.aliasAttribute("class", "id");
xstream.aliasSystemAttribute("type", "class");
xstream.aliasSystemAttribute("refid", "id");

Can I select the field order in which XStream serializes objects?

Yes. XStream's ReflectionConverter uses the defined field order by default. You can override it by using an specific FieldKeySorter:

SortableFieldKeySorter sorter = new SortableFieldKeySorter();
sorter.registerFieldOrder(MyType.class, new String[] { "firstToSerialize", "secondToSerialize", "thirdToSerialize" });
xstream = new XStream(new Sun14ReflectionProvider(new FieldDictionary(sorter)));

How does XStream deal with newer versions of classes?

  • If a new field is added to the class, deserializing an old version will leave the field uninitialized.
  • If a field is removed from the class, deserializing an old version that contains the field will cause an exception. Leaving the field in place but declaring it as transient will avoid the exception, but XStream will not try to deserialize it.
  • If a class is renamed, aliases can be used to create an abstraction between the name used in XML and the real class name.
  • If a field is renamed, this should be treated as adding a field and removing a field.

For more advanced class migrations, you may

  • have to do custom pre-processing of the XML before sending it to XStream (for example, with XSLT or DOM manipulations)
  • declare new fields as transient
  • implement your own converter, that can handle the situation
  • add a readResolve() method to your class, that initializes the object accordingly
  • implement a custom mapper to ignore unknown fields automatically (see acceptance test CustomMapperTest.testCanBeUsedToOmitUnexpectedElements())

Future versions of XStream will include features to make these type of migrations easier.

How does XStream cope with isolated class loaders?

Serializing an object graph is never a problem, even if the classes of those objects have been loaded by a different class loader. The situation changes completely at deserialization time. In this case you must set the class loader to use with:

xstream.setClassLoader(yourClassLoader);

Although XStream caches a lot of type related information to gain speed, it keeps those information in tables with weak references that should be cleaned by the garbage collector when the class loader is freed.

Note, that this call should be made quite immediately after creating the XStream and before any other configuration is done. Otherwise configuration based on special types might refer classes loaded with the wrong classloader.

XML specifics

Why does XStream not respect the encoding in the XML declaration?

XStream architecture is based on IO Readers and Writers, while the XML declaration is the responsibility of XML parsers. All HierarchicalStreamDriver implementations respect the encoding since version 1.3, but only if you provide an InputStream. If XStream consumes a Reader you have to initialize the reader with the appropriate encoding yourself, since it is now the reader's task to perform the encoding and no XML parser can change the encoding of a Reader and any encoding definition in the XML header will be ignored.

Why does XStream not write an XML declaration?

XStream is designed to write XML snippets, so you can embed its output into an existing stream or string. You can write the XML declaration yourself into the Writer before using it to call XStream.toXML(writer).

Why does XStream not write XML in UTF-8?

XStream does no character encoding by itself, it relies on the configuration of the underlying XML writer. By default it uses its own PrettyPrintWriter which writes into the default encoding of the current locale. To write UTF-8 you have to provide a Writer with the appropriate encoding yourself.

Why do field names suddenly have double underscores in the generated XML?

XStream maps Java class names and field names to XML tags or attributes. Unfortunately this mapping cannot be 1:1, since some characters used for identifiers in Java are invalid in XML names. Therefore XStream uses an XmlFriendlyNameCoder to replace these characters with a replacement. By default this NameCoder uses an underscore as escape character and has therefore to escape the underscore itself also. You may provide a different configured instance of the XmlFriendlyNameCoder or a complete different implementation like the NoNameCoder to prevent name coding at all. However it is your responsibility then to ensure, that the resulting names are valid for XML.

XStream fails to unmarshal my given XML and I do not know why?

By default XStream is written for persistence i.e. it will read the XML it can write. If you have to transform a given XML into an object graph, you should go the other way round. Use XStream to transfer your objects into XML. If the written XML matches your schema, XStream is also able to read it. This way is much easier, since you can spot the differences in the XML much more easy than to interpret the exceptions XStream will throw if it cannot match the XML into your objects.

My parser claims the &#x0; character to be invalid, but it was written with XStream!

Your parser is basically right! A character of value 0 is not valid as part of XML according the XML specification (see version 1.0 or 1.1), neither directly nor as character entity nor within CDATA. But not every parser respects this part of the specification (e.g. Xpp3 will ignore it and read character entities). If you expect such characters in your strings and you do not use the Xpp3 parser, you should consider to use a converter that writes the string as byte array in Base64 code. As alternative you may force the PrettyPrintWriter or derived writers to be XML 1.0 or 1.1. compliant, i.e. in this mode a StreamException is thrown.

My parser claims a control character to be invalid, but it was written with XStream!

Your parser is probably right! Control characters are only valid as part of XML 1.1. You should add an XML header declaring this version or use a parser that does not care about this part of the specification (e.g. Xpp3 parser).

Why is my element not written as XML attribute although I have configured it?

You can only write types as attributes that are represented as a single String value and are handled therefore by SingleValueConverter implementations. If your type is handled by a Converter implementation, the configuration of XStream to write an attribute (using XStream.useAttributeFor() or @XStreamAsAttribute) is simply ignored.

Why are whitespace characters wrong in my attribute values after deserialization?

This is part of the XML specification and a required functionality for any XML parser called attribute value normalization. It cannot be influenced by XStream. A compliant XML parser will replace by default real tab, carriage return and line feed characters with normal spaces. If you want to keep these characters you will have to encode them with entities.

Why does XStream not have any namespace support?

Not every XML parser supports namespaces and not every XML parser that supports namespaces can be configured within XStream to use those. Basically namespaces must be supported individually for the different XML parsers and the only support for namespaces that has currently been implemented in XStream is for the StAX paser. Therefore use and configure the StaxDriver of XStream to use namespaces.

My XML contains XPath expressions in the references, but they seem not to work?

XStream generates only XPath compliant expressions. These have a very limited syntax and they are the only ones that can be interpreted at deserialization again, since XStream does not use an XPath interpreter. Therefore there is no support for attribute selectors, qualified element access with axis names or functions. For real XPath support you will have to implement your own MarshallingStrategy.

The XPath expressions in the references do select a list, but not a single node!

Yes, this is right. However, the result type of an XPath expression evaluation can be defined. A node result from a node list is the lists first node, therefore the XPath of XStream is compliant. Since XStream does not use a real XPath engine, you do not have to worry about memory consumption or wasted evaluation time, XStream will always operate on a single node anyway. Since XStream 1.4 you can force XStream to write XPath expressions that select explicit the single node by using the new modes XStream.SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES or SINGLE_NODE_XPATH_RELATIVE_REFERENCES. Instead of generating a path like "/doc/list/elem/field" XStream will then generate "/doc[1]/list[1]/elem[1]/field[1]". The two notations are transparent at deserialization time.

JSON specifics

Why are there two JSON driver implementations?

As always, first for historical reasons! Main difference is that the JettisonMappedXmlDriver is a thin wrapper around Jettison in combination with the StaxDriver, while the JsonHierarchicalStreamDriver uses an own more flexible implementation, but can only be used to generate JSON, deserialization is not implemented.

Which versions of Jettison are supported?

Users of Java 5 or higher can use Jettison 1.2 or higher, users of Java 1.4.2 have to use Jettison 1.0.1. Java 1.3 and Jettison 1.1 is not supported.

Why is it not possible to deserialize a JSON string starting with an array?

XStream's implementation to deserialize JSON is based on Jettison and StAX. Jettison implements a XMLStreamReader of StaX and transforms the processed JSON virtually into XML first. However, if the JSON string starts with an array it is not possible for Jettison to create a valid root element, since it has no name.

XStream fails to unmarshal my JSON string and I do not know why?

Deserialization of JSON is currently done by Jettison, that transforms the JSON string into a StAX stream. XStream itself does nothing know about the JSON format here. If your JSON string reaches some kind of complexity and you do not know how to design your Java objects and configure XStream to match those, you should have a look at the intermediate XML that is processed by XStream in the end. This might help to identify the problematic spots. Also consider then marshalling your Java objects into XML first. You can use following code to generate the XML:

String json = "{\"string\": \"foo\"}";
HierarchicalStreamDriver driver = new JettisonMappedXmlDriver();
StringReader reader = new StringReader(json);
HierarchicalStreamReader hsr = driver.createReader(reader);
StringWriter writer = new StringWriter();
new HierarchicalStreamCopier().copy(hsr, new PrettyPrintWriter(writer));
writer.close();
System.out.println(writer.toString());

What limitations has XStream's JSON support?

JSON represents a very simple data model for easy data transfer. Especially it has no equivalent for XML attributes. Those are written with a leading "@" character, but this is not always possible without violating the syntax (e.g. for array types). Those may silently dropped (and makes it therefore difficult to implement deserialization). References are another issue in the serialized object graph, since JSON has no possibility to express such a construct. You should therefore always set the NO_REFERENCES mode of XStream. Additionally you cannot use implicit collections, since the properties in a JSON object must have unique names.

Why are there invalid characters in my JSON representation?

The JSON spec requires any JSON string to be in UTF-8 encoding. However, XStream ensures this only if you provide an InputStream or an OutputStream. If you provide a Reader or Writer you have to ensure this requirement on your own.

The generated JSON is invalid, it contains a dash in the label!

Well, no, the JSON is valid! Please check yourself with the JSON syntax checker. However, some JavaScript libraries silently assume that the JSON labels are valid JavaScript identifiers, because JavaScript supports a convenient way to address an element, if the label is a valid JavaScript identifier:

var json = {"label": "foo", "label-with-dash": "bar"};
var fooVar = json.label; // works for labels that are JavaScript identifiers
var barVar = json["label-with-dash"]; // using an array index works always

As alternative you may wrap the JsonWriter and replace any dash with an underscore:

HierarchicalStreamDriver driver = new JsonHierarchicalStreamDriver() {
    public HierarchicalStreamWriter createWriter(Writer out) {
        return new WriterWrapper(super.createWriter(out)) {
            public void startNode(String name) {
                startNode(name, null);
            }
            public void startNode(String name, Class clazz) {
                wrapped.startNode(name.replace('-', '_'), clazz);
            }
        }
    }
};
XStream xstream = new XStream(driver);

Comparison to other products

How does XStream compare to java.beans.XMLEncoder?

XStream is designed for serializing objects using internal fields, whereas XMLEncoder is designed for serializing JavaBeans using public API methods (typically in the form of getXXX(), setXXX(), addXXX() and removeXXX() methods.

How does XStream compare to JAXB (Java API for XML Binding)?

JAXB is a Java binding tool. It generates Java code from a schema and you are able to transform from those classes into XML matching the processed schema and back. Note, that you cannot use your own objects, you have to use what is generated.

Scalability

Is XStream thread safe?

Yes. Once the XStream instance has been created and configured, it may be shared across multiple threads allowing objects to be serialized/deserialized concurrently (unless you enable the auto-detection to process annotations on-the-fly). Actually the creation and initialization of XStream is quite expensive, therefore it is recommended to keep the XStream instance itself.

How much memory does XStream consume?

This cannot be answered in general, but following topics have impact on the memory:

  1. XML parser technology in use: You should use a streaming parser like Xpp3 or StAX. DOM-based parsers process the complete XML and create their document model in memory before the first converter of XStream is called.
  2. Your object model: Is it necessary to keep the complete object graph in memory at once. As alternative you might use object streams or write custom converters that can load and save objects of your object model on the fly without adding them to the object graph physically. As example see the implementation of the XmlArrayList in combination with the FileStreamStrategy to keep parts of the object graph separate.
  3. References: By default XStream supports references to the same object in an object graph. This implies that XStream keeps track of all serialized and deserialized objects internally. These references are kept with WeakReferences, so that the memory can be freed as soon as nobody references these objects anymore.
  4. XML values: Any tag and attribute value that is converted into a Java String in the object graph will use by default the same String instance unless it exceeds 38 characters (length of a UUID string representation).
  5. XStream caches: To increase performance XStream caches quite a lot like classes, converters to use, aliasing, tag names. All those caches make usage of WeakReferences or will exist only while marshalling one object graph resp. unmarshalling one input stream.

Can the performance of XStream be increased?

XStream is a generalizing library, it inspects and handles your types on the fly. Therefore it will normally be slower than a piece of optimized Java code generated out of a schema. However, it is possible to increase the performance anyway:

  • Write custom converters for those of your types that occur very often in your XML.
  • Keep a configured XStream instance for multiple usage. Creation and initialization is quite expensive compared to the overhead of XStream when calling marshall or unmarshal.
  • Use Xpp3 or StAX parsers.

Note, you should never try to optimize code for performance simply because you believe that you have detected a bottle neck. Always use proper tools like a profiler to verify where your hotspots are and whether your optimization was really successful or not.

Uses of XStream

Is XStream a data binding tool?

No. It is a serialization tool.

Can XStream generate classes from XSD?

No. For this kind of work a data binding tool such as XMLBeans is appropriate.

Why is there no SaxReader?

XStream works on a stream-based parser model, while SAX is event-based. The stream based model implies, that the caller consumes the individual tokens from the XML parser on demand, while in an event-based model the parser controls the application flow on its own and will use callbacks to support client processing. The different architecture makes it therefore impossible for XStream to use an event-driven XML parser.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/architecture.html0000664000175000017500000001467412206661545031152 0ustar jamespagejamespage Architecture Overview

The architecture of XStream consists of the four main components:

  • Converters
  • Drivers (Writer and Reader)
  • Context
  • Facade

Converters

Whenever XStream encounters an object that needs to be converted to/from XML, it delegates to a suitable Converter implementation associated with the class of that Object.

XStream comes bundled with many converters for common types, including primitives, String, Collections, arrays, null, Date, etc.

XStream also has a default Converter, that is used when no other Converters match a type. This uses reflection to automatically generate the XML for all the fields in an object.

If an object is composed of other objects, the Converter may delegate to other Converters.

To customize the XML for particular object type a new Converter should be implemented.

Drivers (Writer and Reader)

XStream is abstracted from the underlying XML data using the HierarchicalStreamWriter and HierarchicalStreamReader interfaces for serializing and deserializing respectively.

This abstraction allows XStream to read XML from direct streams using an XML parser or directly manipulate existing structures (such as DOM). This prevents the overhead of having to reparse if XStream is working from XML that has been partially processed by other libraries (for instance a SOAP library). It also avoids tying XStream to a particular library.

XStream comes bundled with reader and writer implementations for most major XML libraries.

Writer and Readers can be implemented allowing XStream to serialize to most XML APIs. Writers and Readers can also be created around tree based non XML structures.

Context

When XStream serializes or deserializes some objects, it creates a MarshallingContext or UnmarshallingContext, which handle the traversing of the data and delegation to the necessary Converters.

The MarshallingContext/UnmarshallingContext is made available to converters allowing them to tell XStream to process objects contained within other objects.

XStream provides three pairs of context implementations that traverse the object graph with slightly different behaviors. The default can be changed using XStream.setMode(), passing in one of the following parameters:

  • XStream.XPATH_RELATIVE_REFERENCES
    (Default) Uses relative XPath references to signify duplicate references. This produces XML with the least clutter.
  • XStream.XPATH_ABSOLUTE_REFERENCES
    Uses absolute XPath references to signify duplicate references. This might produce for some situations better readable XML. Note, that XStream will read XML with relative paths as well as with absolute paths independent of the XPATH mode.
  • XStream.ID_REFERENCES
    Uses ID references to signify duplicate references. In some scenarios, such as when using hand-written XML, this is easier to work with.
  • XStream.NO_REFERENCES
    This disables object graph support and treats the object structure like a tree. Duplicate references are treated as two separate objects and circular references cause an exception. This is slightly faster and uses less memory than the other two modes.

A new context is created for each object graph that is serialized. Both the MarshallingContext and UnmarshallingContext implement DataHolder, a hash table passed around whilst processing the object graph that can be used as the user sees fit (in a similar way that the HttpServletRequest attributes are used in a web-application).

XStream facade

The main XStream class is typically used as the entry point. This assembles the necessary components of XStream (as described above; Context, Converter, Writer/Reader and ClassMapper) and provides a simple to use API for common operations.

Remember, the XStream class is just a facade - it can always be bypassed for more advanced operations.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/objectstream.html0000664000175000017500000001021312206661545031133 0ustar jamespagejamespage Object Streams Tutorial

XStream provides alternative implementations of java.io.ObjectInputStream and java.io.ObjectOutputStream, allowing streams of objects to be serialized or deserialized from XML.

This is useful when processing large sets of objects, as only one needs to be in memory at a time.

Obviously you should use also a stream-based XML parser reading the XML. A DOM-based XML parser will process the complete XML and build the object model before XStream is able to to handle the first element.

Using the Object Streams

The interface to the object streaming capabilities of XStream is through the standard java.io.ObjectOutputStream and java.io.ObjectInputStream objects.

Example

To serialize a stream of objects to XML:

ObjectOutputStream out = xstream.createObjectOutputStream(someWriter);

out.writeObject(new Person("Joe", "Walnes"));
out.writeObject(new Person("Someone", "Else"));
out.writeObject("hello");
out.writeInt(12345);

out.close();

The resulting XML:

<object-stream>
  <com.blah.Person>
    <firstname>Joe</firstname>
    <lastname>Walnes</lastname>
  </com.blah.Person>
  <com.blah.Person>
    <firstname>Someone</firstname>
    <lastname>Else</lastname>
  </com.blah.Person>
  <string>hello</string>
  <int>123</int>
</object-stream>

To deserialze the stream of objects from the XML:

ObjectInputStream in = xstream.createObjectInputStream(someReader);

Person a = (Person)in.readObject();
Person b = (Person)in.readObject();
String c = (String)in.readObject();
int    d = in.readInt();

Considerations

Root node

Because an XML document can only have a single root node, all the serialized elements must be wrapped in an additional root node. This root node defaults to <object-stream>, as shown in the example above.

This can be changed by using the overloaded method: xstream.createObjectOutputStream(Writer writer, String rootNodeName);

Close the ObjectOutputStream

Remember to call ObjectOutputStream.close(), otherwise the stream will contain incomplete XML.

Detecting the end of the ObjectInputStream

When there are no more objects left to read in the stream, ObjectInputStream.readObject() (or primitive equivalent) will throw java.io.EOFException.

References

Normally XStream will not know about references between the different objects that are written individually in the ObjectStream. Nevertheless there is an example in the acceptance tests (MultipleObjectsInOneStreamTest) where such a functionality is realized with the help of a custom MarshallingStrategy. Note, that this implementation is not for general use, since it will ignore some parameters at second invocation, but they do not matter in the demonstrated use case. Additionally those references prevent the objects from being garbage collected, which is a bit counter-productive for the use case of ObjectStreams as described above. So you have to know what you do!

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/website.xml0000664000175000017500000000415012206661545027752 0ustar jamespagejamespage
Software index.html news.html changes.html versioning.html
Evaluating XStream tutorial.html graphs.html manual-tweaking-output.html license.html download.html references.html parser-benchmarks.html http://www.ohloh.net/projects/3459
Using XStream architecture.html converters.html faq.html list-user.html issues.html
Javadoc javadoc/index.html hibernate-javadoc/index.html benchmark-javadoc/index.html
Tutorials tutorial.html alias-tutorial.html annotations-tutorial.html converter-tutorial.html objectstream.html persistence-tutorial.html json-tutorial.html
Developing XStream how-to-contribute.html list-dev.html team.html repository.html http://bamboo.ci.codehaus.org/browse/XSTREAM
jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/tutorial.html0000664000175000017500000001173312206661545030324 0ustar jamespagejamespage Two Minute Tutorial

This is a very quick introduction to XStream. Skim read it to get an idea of how simple it is to convert objects to XML and back again. I'm sure you'll have questions afterwards.

Create classes to be serialized

Here's a couple of simple classes. XStream can convert instances of these to XML and back again.

public class Person {
  private String firstname;
  private String lastname;
  private PhoneNumber phone;
  private PhoneNumber fax;
  // ... constructors and methods
}

public class PhoneNumber {
  private int code;
  private String number;
  // ... constructors and methods
}

Note: Notice that the fields are private. XStream doesn't care about the visibility of the fields. No getters or setters are needed. Also, XStream does not limit you to having a default constructor.

Initializing XStream

To use XStream, simply instantiate the XStream class:

XStream xstream = new XStream();

You require xstream-[version].jar, xpp3-[version].jar and xmlpull-[version].jar in the classpath. Xpp3 is a very fast XML pull-parser implementation. If you do not want to include these dependencies, you can use a standard JAXP DOM parser or since Java 6 the integrated StAX parser instead:

XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library
XStream xstream = new XStream(new StaxDriver()); // does not require XPP3 library starting with Java 6

Note: This class is a simple facade designed for common operations. For more flexibility you may choose to create your own facade that behaves differently.

Now, to make the XML outputted by XStream more concise, you can create aliases for your custom class names to XML element names. This is the only type of mapping required to use XStream and even this is optional.

xstream.alias("person", Person.class);
xstream.alias("phonenumber", PhoneNumber.class);

Note: This is an optional step. Without it XStream would work fine, but the XML element names would contain the fully qualified name of each class (including package) which would bulk up the XML a bit. See the Alias Tutorial a more complete introduction.

Serializing an object to XML

Let's create an instance of Person and populate its fields:

Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));

Now, to convert it to XML, all you have to do is make a simple call to XStream:

String xml = xstream.toXML(joe);

The resulting XML looks like this:

<person>
  <firstname>Joe</firstname>
  <lastname>Walnes</lastname>
  <phone>
    <code>123</code>
    <number>1234-456</number>
  </phone>
  <fax>
    <code>123</code>
    <number>9999-999</number>
  </fax>
</person>

It's that simple. Look at how clean the XML is.

Deserializing an object back from XML

To reconstruct an object, purely from the XML:

Person newJoe = (Person)xstream.fromXML(xml);

And that's how simple XStream is!

Summary

To recap:

  • Create element name to class name aliases for any custom classes using xstream.alias(String elementName, Class cls);
  • Convert an object to XML using xstream.toXML(Object obj);
  • Convert XML back to an object using xstream.fromXML(String xml);

maybe you like to read the alias tutorial to see more possibilities how you can rename things using XStream. Or look into the condensed overview how to configure XStream to tweak the output.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/manual-tweaking-output.html0000664000175000017500000003425312206661545033105 0ustar jamespagejamespage Tweaking the Output

Out of the box, XStream is able to serialize most objects without the need for custom mappings to be setup. The XML produced is clean, however sometimes it's desirable to make tweaks to it. The most common use for this is when using XStream to read configuration files and some more human-friendly XML is needed.

Modification by configuration

A big part of the standard output of XStream can be configured. It is possible to set aliases for class types and field names that are mapped to XML tag or attribute names. Objects that can be represented as simple string value can be written as attributes. It is possible to omit fields or to flatten the structure for collections.

Aliases

Aliases offer a simple way to use different tag or attribute names in the XML. The simplest and most commonly used tweak in XStream is to alias a fully qualified class to a shorter name. Another use case is a different field name for a class member. Aliases can be set for following elements:

  • Class types mapped to XML tags
  • Package names mapped to XML tags
  • Field names mapped to XML tags
  • Internal attributes names of XStream

The bold elements in the following example are affected:

<cat>
  <age>4</age>
  <name>Garfield</name>
  <owner type="StandardPerson">
    <name>Jon Arbuckle</name>
  </owner>
</cat>

Have a look at the Alias Tutorial for examples.

Attributes

XML is quite clumsy to read for fields in separate tags that can represent their content in a short single string value. In such a case attributes can help to shorten the XML and increase readability:

<cat age="4" name="Garfield">
  <owner class="StandardPerson" name="Jon Arbuckle"/>
</cat>

Attributes are also presented in the Alias Tutorial.

Omitted Fields

For a proper deserialization XStream has to write the complete object graph into XML that is referenced by a single object. Therefore XStream has to find a representation that contains all aspects to recreate the objects.

However, some parts might be superfluous e.g. if a member field is lazy initialized and its content can be easily recreated. In such a case a field can be omitted using XStream.omitField(Class, String).

Implicit Collections, Arrays and Maps

Another use case are collections, arrays and maps. If a class has a field that is a one of those types, by default all of its elements are embedded in an element that represents the container object itself. By configuring the XStream with the XStream.addImplicitCollection(), XStream.addImplicitArray(), and XStream.addImplicitMap() methods it is possible to keep the elements directly as child of the class and the surrounding tag for the container object is omitted. It is even possible to declare more than one implicit collection, array or map for a class, but the elements must then be distinguishable to populate the different containers correctly at deserialization.

In the following example the Java type representing the farm may have two containers, one for cats and one for dogs:

<farm>
  <cat>Garfield</cat>
  <cat>Arlene</cat>
  <cat>Nermal</cat>
  <dog>Odie</dog>
</farm>

The container might be a Collection, Array, or even a Map. In the latter case a member field of the value must have been defined, that is used as key in the deserialized map.

Field order

XStream is delivered with a lot of converters for standard types. Nevertheless most objects are processed by converters based on reflection. They will write the fields of a class in the sequence they are defined. It is possible to implement an algorithm for a different sequence or use an implementation that allows to define the sequence for each type separately using a FieldKeySorter. Similar functionality exists for Java Beans with the PropertySorter.

Output Format

XStream writes and reads XML by default. However, the I/O layer is separated from the model and you can use implementations for other formats as well. A reader/writer pair is typically managed by a HierarchicalStreamDriver. XStream is delivering additional drivers for JSON and a compact binary format (see BinaryStreamDriver). There are also drivers to write an object graph into a DOM structure instead of a text based stream (available for W3C DOM, DOM4J, JDOM, XOM, and XPP DOM).

Enhancing XStream

Sometimes customization is simply not enough to tweak the output. Depending on the use case it is fortunate to use specialized converters for own types, mapper implementations that control naming of things more globally or use specialized writers to influence the complete output.

Specialized Converters

Not all converters that are part of the XStream package are automatically registered. Some will only make sense for special types, others have parameters to tweak the behaviour. Most useful in the table of converters are the JavaBeanConverter, ToStringConverter, and ToAttributedValueConverter. Not to mention the separate Hibernate package of XStream.

As example can the ToAttributedValueConverter be used to define the owner's name directly as text value:

<cat age="4" name="Garfield">
  <owner class="StandardPerson">Jon Arbuckle</>
</cat>

Attributes are also presented in the Alias Tutorial.

Custom Converters

Sometimes the object to serialize contains fields or elements, that have no friendly representation for human beings e.g. if a long value represents in reality a time stamp. In such cases XStream supports custom converters for arbitrary types. Have a look at the Converter Tutorial for advanced possibilities. Note, that a custom converter is not different to one that is delivered by XStream. It's simply your code.

Custom Mappers

In case of global adjustments it can be helpful to implement an own mapper. A mapper is used to name things and map between the name in the Java world to the name used in the XML representation. The alias mechanism described above is implemented as such a mapper that can be configured. A typical use case is dropping all prefixes for field names like underscores in the resulting XML or omitting the package part of class names.

However, keep in mind that the algorithm must work in both directions to support deserialization.

Custom Name Coders

Names used e.g. in XML for attributes and element tags might contain characters or character sequences that violate the syntax of the output format. Instead of using different aliases for such names that depend on the output format, you may use a NameCoder implementation that transforms an internally used name to an external form. For XML we use e.g. a NameCoder that encodes '$' characters, while the one used in JSON performs no operation at all.

Again, keep in mind that the algorithm of the name coder must support encoding and decoding of the names.

Custom Writer

A custom writer can be used to affect the output completely. XStream itself delivers solutions for different use cases like the CompactWriter that does not insert any white spaces between the XML tags.

Another use case for such a writer is a wrapper to drop unwanted XML elements that XStream omits on its own. Especially if the written XML is not used for deserialization it can be useful to ignore internal attributes by a custom writer

Tweaking the own implementation

As shown, XStream can be configured and enhanced in multiple way, but sometimes it is easier to tweak the implementation of the serialized classes:

  • Declaring a field transparent will omit it automatically from the processing
  • Implementing a readResolve method that can be used to initialize additional fields
  • Usage of annotations

Preprocessing or postprocessing

XML Transformations

Never forget, you're dealing with XML! It is easy to transform XML with an XSLT. XStream is delivered with a SAXSource implementation, that allows an XStream instance to be the source of a XML transformer.

Example

Look at the following stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" omit-xml-declaration="yes" indent="no"/>
  <xsl:template match="/cat">
    <xsl:copy>
      <xsl:apply-templates select="mName"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

It is used here to remove the age of the cat on the fly (assuming XSLT is a string with the stylesheet above):

XStream xstream = new XStream();
xstream.alias("cat", Cat.class);

TraxSource traxSource = new TraxSource(new Cat(4, "Garfield"), xstream);
Writer buffer = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer(
    new StreamSource(new StringReader(XSLT)));
transformer.transform(traxSource, new StreamResult(buffer));

The result in the buffer:

<cat>
  <mName>Garfield</mName>
</cat>

Format Conversion

XStream is designed to transform Java objects into a specific format and recreate these objects again. However, XStream's readers and writers are based on an event model that can be used easily to convert the pure data between formats. XStream contains the HierarchicalStreamCopier tool that utilizes a reader and a writer of XStream to perform the conversion:

HierarchicalStreamCopier copier = new HierarchicalStreramCopier();
HierarchicalStreamDriver binaryDriver = new BinaryDriver();
HierarchicalStreamDriver jsonDriver = new JettisonMappedXmlDriver();

// transform a org.dom4j.Document into a binary stream of XStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copier.copy(new Dom4JDriver.createReader(dom4JDocument), binaryDriver.createWriter(baos));
byte[] data = baos.getBytes();

// transform binary XStream data into JSON
StringWriter strWriter = new StringWriter();
copier.copy(binaryDriver.createReader(data), jsonDriver.createWriter(strWriter));
String json = strWriter.toString();

// transform JSON into XML:
strWriter = new StringWriter();
copier.copy(jsonDriver.createReader(new StringReader(json)), new PrettyPrintWriter(strWriter));
String xml = strWriter.toString();
jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/repository.html0000664000175000017500000000425012206661545030674 0ustar jamespagejamespage Source Repository

Modules

XStream project consists of several modules:
  1. xstream - the core module
  2. xstream-benchmark - the benchmark tool
  3. xstream-distribution - the module contains the documentation and assembles the src and bin distributions
When you checkout the trunk you'll get all the modules, but you can just add the module you are interested in to the URL, e.g.
svn co http://svn.codehaus.org/xstream/trunk/[module]
to checkout out the single module separately.

Browser

You can use the browser to navigate within the sources online with the help of the FishEye installation on Codehaus.

Subversion

XStream uses Subversion as the SCM. See Subversion website for details and documentation on IDE integration.

WebDav Access

WebDav is an access protocol supported by SVN and being http-based is often allowed by corporate firewalls.

Anonymous Access

svn co http://svn.codehaus.org/xstream/trunk

You might also use this URL to browse the repository in a simple manner.

Committer Access

svn co https://svn.codehaus.org/xstream/trunk

This access protocol is available to all, but only developers can commit changes.

Developers require a LDAP password for Codehaus username (contact Bob at the Haus to get assigned a password if you don't have one).

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/manual.html0000664000175000017500000000303512206661545027732 0ustar jamespagejamespage Documentation

Essentials

  • Uses of XStream
  • Architecture Overview
jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/converters.html0000664000175000017500000013000412206661545030644 0ustar jamespagejamespage Converters

The core of XStream consists of a registry of Converters. The responsibility of a Converter is to provide a strategy for converting particular types of objects found in the object graph, to and from XML.

XStream is provided with Converters for common types such as primitives, String, File, Collections, arrays, and Dates.

java.lang (and core special types)

Converter Supported types Example Notes
NullConverter null values <null/> Usually, null fields are left out of the XML, however when used in arrays or the root object they have to be explicitly marked.
ArrayConverter Any kind of array <string-array>
  <string>apple</string>
  <string>banana</string>
  <string>cabbage</string>
</string-array>
This supports arrays of primitives as well as objects. It also supports multi-dimensional arrays, even if they are non-rectangular.
BooleanConverter boolean
java.lang.Boolean
<boolean>true</boolean>  
ByteConverter byte
java.lang.Byte
<byte>22</byte> The byte is represented as an integer.
EncodedByteArrayConverter byte[] <byte-array>AHiEFiEABQ==</byte-array> Uses Base64 encoding to store binary data in XML. Converter is not automatically registered.
CharConverter char
java.lang.Character
<char>X</char>  
CharArrayConverter char[] <char-array>hello<char-array> Joins all characters into a single String.
DoubleConverter double
java.lang.Double
<double>456774543443.4553435</double>  
FloatConverter float
java.lang.Float
<float>4563443.435</float>  
IntConverter int
java.lang.Integer
<int>12345678</int>  
LongConverter long
java.lang.Long
<long>2344556678888786</long>  
ShortConverter short
java.lang.Short
<short>1445</short>  
StringConverter java.lang.String <string>hello world</string>  
StringBufferConverter java.lang.StringBuffer <string-buffer>hello world</string-buffer>  
StringBuilderConverter java.lang.StringBuilder <string-builder>hello world</string-builder> Available under Java 1.5 or greater.
ThrowableConverter java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.Error
...and all subclasses of these.
<java.io.IOException>
  <detailMessage>No file</detailMessage>
  <stack-trace>
    <trace>com.x.Foo.stuff(Foo.java:22)</trace>
    <trace>com.x.Foo.blah(Foo.java:31)</trace>
    <trace>com.x.Foo.main(Foo.java:43)</trace>
  </stack-trace>
</java.io.IOException>
This is only available under Java 1.4 or greater. It retains the full stack trace, including that of any nested exceptions. The stack trace elements are handled by the StackTraceElementConverter.
EnumConverter java.lang.Enum <java.lang.annotation.RetentionPolicy>
CLASS
</java.lang.annotation.RetentionPolicy>
Available under Java 1.5 or greater.

java.util

Converter Supported types Example Notes
CollectionConverter java.util.ArrayList
java.util.LinkedList
java.util.HashSet
java.util.Vector
java.util.LinkedHashSet
<linked-list>
  <string>apple</string>
  <string>banana</string>
  <big-decimal>12345.4555</big-decimal>
</linked-list>
The objects inside the collection can be any type of objects, including nested collections.
MapConverter java.util.HashMap
java.util.Hashtable
java.util.LinkedHashMap
<map>
  <entry>
    <string>apple</string>
    <float>123.553</float>
  </entry>
  <entry>
    <string>orange</string>
    <float>55.4</float>
  </entry>
</map>
Both key and values can be any type of objects.
PropertiesConverter java.util.Properties <properties>
  <property name="host" value="localhost"/>
  <property name="port" value="888"/>
</properties>
Because the Properties class only accepts Strings for keys and values, the XML can be more concise. If the Properties instance includes a set of default Properties, these are serialized in a nested <defaults> element.
SingletonCollectionConverter java.util.Collections.singletonList().getClass()
java.util.Collections.singleton().getClass()
<singleton-set>
  <string>apple</string>
</singleton-set>
The objects inside the singleton collection can be any type of objects, including nested collections.
SingletonMapConverter java.util.Collections.singletonMap().getClass() <singleton-map>
  <entry>
    <string>apple</string>
    <float>123.553</float>
  </entry>
</singleton-map>
The objects inside the singleton collection can be any type of objects, including nested collections.
TreeMapConverter java.util.TreeMap <tree-map>
  <comparator class="com.blah.MyComparator"/>
  <entry>
    <string>apple</string>
    <float>123.553</float>
  </entry>
  <entry>
    <string>orange</string>
    <float>55.4</float>
  </entry>
</tree-map>
This is similar to MapConverter with an additional field for storing the java.util.Comparator associated with the TreeMap.
TreeSetConverter java.util.TreeSet <tree-set>
  <comparator class="com.blah.MyComparator"/>
  <string>apple</string>
  <string>banana</string>
  <string>cabbage</string>
</tree-set>
This is similar to CollectionConverter with an additional field for storing the java.util.Comparator associated with the TreeSet.
BitSetConverter java.util.BitSet <bit-set>0,1,3,5,6,8,10</bit-set> Stores a comma separated list of which bits are set. Designed to be readable without taking up too much space.
DateConverter java.util.Date <date>2004-02-22 15:16:04.0 EST</date>
GregorianCalendarConverter java.util.Calendar
java.util.GregorianCalendar
<gregorian-calendar>
  <time>555454646</time>
</gregorian-calendar>
 
ISO8601DateConverter java.util.Date <date>2006-07-28T12:06:17.654-03:00</date> Not automatically registered, needs joda-time
ISO8601GregorianCalendarConverter java.util.GregorianCalendar <gregorian-calendar>
2006-07-28T12:07:02.788-03:00
</gregorian-calendar>
Not automatically registered, needs joda-time
LocaleConverter java.util.Locale <locale>en_GB</locale>  
CurrencyConverter java.util.Currency <currency>USD</currency> Available under Java 1.4 or greater.
UUIDConverter java.util.UUID <uuid>ca05f023-e07f-4956-a6ef-14ddd23df47b</uuid> Available under Java 1.5 or greater.
EnumMapConverter java.util.EnumMap <enum-map enum-type="simple">
  <entry>
    <simple>GREEN</simple>
    <string>grass</string>
  </entry>
  <entry>
    <simple>BLUE</simple>
    <string>sky</string>
  </entry>
</enum-map>
Available under Java 1.5 or greater.
EnumSetConverter java.util.EnumSet <enum-set enum-type="simple">
  GREEN,BLUE
</enum-set>
Available under Java 1.5 or greater.
RegexPatternConverter java.util.regex.Pattern <java.util.regex.Pattern>
  <pattern>.*</pattern>
  <flags>0</flags>
</java.util.regex.Pattern>
Available under Java 1.4 or greater.

java.sql

Converter Supported types Example Notes
SqlDateConverter java.sql.Date <sql-date>1978-08-25</sql-date>  
SqlTimeConverter java.sql.Time <sql-time>14:07:33</sql-time>  
SqlTimestampConverter java.sql.Timestamp <sql-timestamp>1970-01-01 00:00:01.234</sql-timestamp>  
ISO8601SqlTimestampConverter java.sql.Timestamp <sql-timestamp>2006-07-28T12:06:17.654000000-03:00</sql-timestamp> Not automatically registered, needs joda-time

java.math

Converter Supported types Example Notes
BigDecimalConverter java.math.BigDecimal <big-decimal>342346.445332</big-decimal>  
BigIntegerConverter java.math.BigInteger <big-int>23434224556</big-int>  

java.net

Converter Supported types Example Notes
URLConverter java.net.Url <url>http://codehaus.org/blah</url>  

java.io

Converter Supported types Example Notes
FileConverter java.io.File <file>/stuff/hello.txt</file>  
SerializableConverter java.io.Serializable   See description at Generalized Converters
ExternalizableConverter java.io.Externalizable   See description at Generalized Converters

java.lang.reflect

Converter Supported types Example Notes
JavaClassConverter java.lang.Class <class>com.foo.MyThing</class> This converter will look for the class in the ClassLoader of the current XStream instance. It is possible to use another ClassLoader by re-registering a new instance of this converter that is wrapped around another ClassLoader.
JavaFieldConverter java.lang.reflect.Field <field>
  <name>myField</name>
  <class>com.foo.MyThing</class>
</field>
As with the JavaClassConverter, the converter will use the ClassLoader of the XStream instance to resolve classes by default. This can be changed by specifying another ClassLoader when constructing this Converter.
JavaMethodConverter java.lang.reflect.Method
java.lang.reflect.Constructor
<method>
  <class>com.foo.MyThing</class>
  <name>doStuff</name>
  <parameter-types>
    <class>java.lang.String</class>
    <class>java.util.Iterator</class>
  </parameter-types>
</method>
The enclosing element for this tag will either by <method> or <constructor>. As with the JavaClassConverter, the converter will use the ClassLoader of the XStream instance to resolve classes by default. This can be changed by specifying another ClassLoader when constructing this Converter.
DynamicProxyConverter Any dynamic proxy generated by java.lang.reflect.Proxy <dynamic-proxy>
  <interface>com.foo.Blah</interface>
  <interface>com.foo.Woo</interface>
  <handler class="com.foo.MyHandler">
    <something>blah</something>
  </handler>
</dynamic-proxy>
The dynamic proxy itself is not serialized, however the interfaces it implements and the actual InvocationHandler instance are serialized. This allows the proxy to be reconstructed after deserialization.

java.awt

Converter Supported types Example Notes
ColorConverter java.awt.Color <awt-color>
  <red>255</red>
  <green>255</green>
  <blue>255</blue>
  <alpha>255</alpha>
</awt-color>
Warning: The AWT toolkit is initialized when a Color is deserialized due to the internals of the Color class. This should only be an issue if deserializing a Color on a headless server process.
FontConverter java.awt.Font   Warning: The AWT toolkit is initialized when a Font is deserialized due to the internals of the Font class. This should only be an issue if deserializing a Font on a headless server process.

java.awt.font

Converter Supported types Example Notes
TextAttributeConverter java.awt.font.TextAttribute <awt-text-attribute>family</awt-text-attribute> Warning: The AWT toolkit is initialized when a TextAttribute is deserialized due to the internals of the TextAttribute class. This should only be an issue if deserializing a TextAttribute on a headless server process.

javax.swing

Converter Supported types Example Notes
LookAndFeelConverter javax.swing.LookAndFeel implementations   Explicit mapping to the ReflectionConverter. Although the implementations of the LookAndFeel classes are serializable, they will throw an exception executing writeObject(), therefore the SerializableConverter is not used.

javax.security.auth

Converter Supported types Example Notes
SubjectConverter javax.security.auth.Subject <auth-subject>
  <principals>
    <com.thoughtworks.xstream.Admin/>
  </principals>
  <readOnly>false</readOnly>
</auth-subject>
Available under Java 1.4 or greater. This converter does not serialize any credentials but only the principals.

java.nio

Converter Supported types Example Notes
CharsetConverter java.nio.charset.Charset <charset>US-ASCII</charset> Available under Java 1.4 or greater.

javax.xml.datatype

Converter Supported types Example Notes
DurationConverter javax.xml.datatype.Duration <duration>PT1H2M</duration> Available under Java 1.5 or greater.

Generalized Converters

Converter Supported types Explanation Notes
ReflectionConverter Any type The Converter is used as fallback. It uses reflection to examine the class and will serialize its fields.  
AnnotationReflectionConverter Any type The Converter is used as fallback. It uses reflection to examine the class and will serialize its fields and supports annotations for local converters. Needs JDK 1.5, default for JDK 1.5. Deprecated since XStream 1.3 and must be registered now explicitly.
SerializableConverter java.io.Serializable or types with one of the serializable methods readObject or writeObject The Converter is used for any JDK-serializable types, if not handled by a specialized Converter.  
ExternalizableConverter java.io.Externalizable The Converter is used for any JDK-externalizable types, if not handled by a specialized Converter.  
ToAttributedValueConverter Any type with all but one fields to be represented by a single string The Converter is used to write all but one fields of the type as attributes. The left over field is then used as current value. Must be registered explicitly for the appropriate type
ToStringConverter Any type with natural String representation The Converter must be initialized with a type, that provides a complete String representation with its toString() method and is able to be recreated by a constructor taking a single String argument. Must be registered explicitly for the appropriate type
JavaBeanConverter Java beans The Converter handles any type as Java bean. It expects the type to convert to have a public default constructor and appropriate getter and setters. Must be registered explicitly. Should be used as fallback.
PropertyEditorCapableConverter Any type with a PropertyEditor implementation The Converter can handles any type that provides a PropertyEditor implementation. The PropertyEditor's methods getAsText() and setAsText() are used to convert between object and string representation. Must be registered explicitly for the appropriate type.

Converters for 3rd party classes

Converter Supported types Explanation Notes
CGLIBEnhancedConverter Proxies generated by the CGLIB Enhancer The Converter handles proxies generated by the CGLIB Enhancer, if there were not multiple callbacks registered. A proxy with multiple callbacks can currently not be handled at all. Must be registered explicitly in combination with the CGLIBMapper. See FAQ.
HibernatePersistentCollectionConverter org.hibernate.collection.PersistentBag org.hibernate.collection.PersistentList org.hibernate.collection.PersistentSet The Converter handles Hibernate collections that are not handled by the other Hibernate converters. It will handle any element of the collection. Must be registered explicitly in combination with the HibernateMapper and all the other Hibernate converters. See package description.
HibernatePersistentMapConverter org.hibernate.collection.PersistentMap The Converter handles unsorted Hibernate maps. It will handle any key and value of the map. Must be registered explicitly in combination with the HibernateMapper and all the other Hibernate converters. See package description.
HibernatePersistentSortedMapConverter org.hibernate.collection.PersistentSortedMap The Converter handles sorted Hibernate maps. It will handle any key and value of the map. Must be registered explicitly in combination with the HibernateMapper and all the other Hibernate converters. See package description.
HibernatePersistentSortedSetConverter org.hibernate.collection.PersistentSortedSet The Converter handles sorted Hibernate sets. It will handle any element of the set. Must be registered explicitly in combination with the HibernateMapper and all the other Hibernate converters. See package description.
HibernateProxyConverter org.hibernate.proxy.HibernateProxy The Converter handle any element that is wrapped by a Hibernate proxy. Must be registered explicitly in combination with the HibernateMapper and all the other Hibernate converters. See package description.
jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/persistence-tutorial.html0000664000175000017500000001662712206661545032655 0ustar jamespagejamespage Persistence API Tutorial

Challenge

Suppose that you need a easy way to persist some objects in the file system. Not just one, but a whole collection. The real problem arrives when you start using java.io API in order to create one output stream for each object, showing itself to be really painful - although simple.

Imagine that you have the following Java class, a basic Author class (stolen from some other tutorial):

package com.thoughtworks.xstream;

public class Author {
        private String name;
        public Author(String name) {
                this.name = name;
        }
        public String getName() {
                return name;
        }
}

By using the XmlArrayList implementation of java.util.List you get an easy way to write all authors to disk

The XmlArrayList (and related collections) receives a PersistenceStrategy during its construction. This Strategy decides what to do with each of its elements. The basic implementation - our need - is the FilePersistenceStrategy, capable of writing different files to a base directory.

// prepares the file strategy to directory /tmp
PersistenceStrategy strategy = new FilePersistenceStrategy(new File("/tmp"));

We can easily create an XmlArrayList from that strategy:

// prepares the file strategy to directory /tmp
PersistenceStrategy strategy = new FilePersistenceStrategy(new File("/tmp"));
// creates the list:
List list = new XmlArrayList(strategy);

Adding elements

Now that we have an XmlArrayList object in our hands, we are able to add, remove and search for objects as usual. Let's add five authors and play around with our list:

package org.codehaus.xstream.examples;

public class AddAuthors {

	public static void main(String[] args) {
	
		// prepares the file strategy to directory /tmp
		PersistenceStrategy strategy = new FilePersistenceStrategy(new File("/tmp"));
		// creates the list:
		List list = new XmlArrayList(strategy);
		
		// adds four authors
		list.add(new Author("joe walnes"));
		list.add(new Author("joerg schaible"));
		list.add(new Author("mauro talevi"));
		list.add(new Author("guilherme silveira"));
		
		// adding an extra author
		Author mistake = new Author("mama");
		list.add(mistake);
	
	}
}

If we check the /tmp directory, there are five files: int@1.xml, int@2.xml, int@3.xml, int@4.xml, int@5.xml, each one containing the XML serialized form of our authors.

Playing around

Let's remove mama from the list and iterate over all authors:

package org.codehaus.xstream.examples;

public class RemoveMama {

	public static void main(String[] args) {
	
		// prepares the file strategy to directory /tmp
		PersistenceStrategy strategy = new FilePersistenceStrategy(new File("/tmp"));
		// looks up the list:
		List list = new XmlArrayList(strategy);
		
		// remember the list is still there! the files int@[1-5].xml are still in /tmp!
		// the list was persisted!
		
		for(Iterator it = list.iterator(); it.hasNext(); ) {
			Author author = (Author) it.next();
			if(author.getName().equals("mama")) {
				System.out.println("Removing mama...");
				it.remove();
			} else {
				System.out.println("Keeping " + author.getName());
			}
		}
	
	}
}

The result?

Keeping joe walnes
Keeping joerg schaible
Keeping mauro talevi
Keeping guilherme silveira
Removing mama...

Local Converter

Another use case is to split the XML into master/detail documents by declaring a local converter for a collection (or map) based on the collection types in XStream's persistence package. Think about a volume grouping different type of documents:

public abstract class AbstractDocument {
	String title;
} 
public class TextDocument extends AbstractDocument {
	List chapters = new ArrayList();
} 
public class ScannedDocument {
	List images = new ArrayList();
} 
public Volume {
	List documents = new ArrayList();
}

The documents might be big (especially the ones with the scanned pages), therefore it might be nice to separate each document into an own file. With the help of a local converter utilizing an XmlArrayList this is straight forward:

public final class PersistenceArrayListConverter implements Converter {
	private XStream xstream;
	
	public PersistenceArrayListConverter(XStream xstream) {
		this.xstream = xstream;
	}

	public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
		File dir = new File(System.getProperty("user.home"), "documents");
		XmlArrayList list = new XmlArrayList(new FilePersistenceStrategy(dir, xstream));
		context.convertAnother(dir);
		list.addAll((Collection)source); // generate the external files
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		File directory = (File)context.convertAnother(null, File.class);
		XmlArrayList persistentList = new XmlArrayList(new FilePersistenceStrategy(directory, xstream));
		ArrayList list = new ArrayList(persistentList); // read all files
		persistentList.clear(); // remove files
		return list;
	}

	public boolean canConvert(Class type) {
		return type == ArrayList.class;
	}
}

This converter will use a given XStream to store each element of an ArrayList into an own file located in the user's home directory in the folder documents. The master XML will now contain the name of the target folder instead of the marshalled documents. In our case those documents are destroyed if the volume is unmarshalled again. See the initialization of the XStream:

XStream = new XStream();
xstream.alias("volume", Volume.class);
xstream.registerLocalConverter(Volume.class, "documents", new PersistenceArrayListConverter(xstream));

Volume volume = new Volume();
volume.documents.addAll(...); // add a lot of documents
String xml = xstream.toXML(volume);

The resulting XML will be very simple:

<volume>~/documents</volume>

The documents can be found in individual files in the target folder with names like int@<index>.xml.

Going further

From this point on, you can implement different PersistentStrategy algorithms in order to generate other behaviour (e.g. persisting the objects in a database) using your XmlArrayList collection, or try the other implementations: XmlSet and XmlMap and you may create your own local converters. As an alternative to a converter you might use the persistent collection type directly as member instance, the effect is similar - give it a try!

See also XBird that makes usage of this XStream API to support object persistence.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/parser-benchmarks.html0000664000175000017500000001127712206661545032073 0ustar jamespagejamespage Parser Benchmarks

Benchmark results are always dependent on a very individual setup. Normally it is not useful to generalize such results for every use case, but it can give you a hint. However, if you're really in the need of maximum performance, you should probably create an own benchmark with your objects or even use a profiler to detect the real hot spots in your application.

Benchmark Values

Parser Single Value Converters Standard Converters Reflection Converter Serializable Converter
W3C DOM 1823.0 1495.0 1437.0 1758.0
JDOM 2620.0 1796.0 1776.0 2030.0
DOM4J 1824.0 1811.0 2636.0 2177.0
XOM 571.0 716.0 995.0 958.0
StAX (BEA) 430.0 359.0 531.0 737.0
StAX (Woodstox) 357.0 344.0 535.0 725.0
StAX (SJSXP) 332.0 445.0 491.0 667.0
XPP (Xpp3) 351.0 395.0 544.0 743.0
XPP (kXML2) 299.0 353.0 517.0 761.0
XppDom (Xpp3) 351.0 395.0 544.0 743.0
XppDom (kXML2) 299.0 353.0 517.0 761.0

Setup

The values have been generated running the ParserBenchmark harness of the XStream benchmark module's test code.

Single Value Converters
A list with a set of 10 objects of different types (like String, int, File, Locale, Double, ...) that will be all handled by a SingleValueConverter.
Standard Converters
A list with a set of 6 objects of different types (like Properties, Color, Class, Method, ...) that will be all handled by a specialized converter processing nested XML elements.
Reflection Converter
A list with a set of 6 objects of different types (One, Five of the XStream benchmark package) that will be all handled by the ReflectionConverter.
Serializable Converter
A list with a set of 6 objects of different types (SerializableOne, SerializableFive of the XStream benchmark package) that will be all handled by the SerializableConverter.
JavaBean Converter
A list with a set of 6 objects of different types (OneBean, FiveBean of the XStream benchmark package) that will be all handled by the JavaBeanConverter. This converter has been registered especially for this two types.

Environment

The values above's unit is ms measured after 1000 unmarshalling operations with the object graphs described in the setup using XStream 1.4. The benchmark was run on an AMD Athlon with 2.1GHz running a JVM of Sun JDK 1.6.0_13 (32-bit) in Gentoo Linux. Note again, that these values are no replacement for real profiler results and they may vary from run to run for ~100ms due to this machine's background processes on a single CPU. However, it can give you some idea of what you can expect using different parser technologies.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/graphs.html0000664000175000017500000001621312206661545027743 0ustar jamespagejamespage Object references

How does XStream deals with duplicate and circular references?

It depends on XStream's mode, the default is uses XPath to allow serialized objects to be treated as graphs instead of simple trees (typical XML usage).

Sometimes it's not desirable to work this way, let's take a look in a simple example in order to switch between XStream's modes and see what its capable of.

We start with a simple compact-disc class, with id and a bonus cd fields:

package com.thoughtworks.xstream;
public class Cd {
	private String id;

	private Cd bonusCd;

	Cd(String id, Cd bonusCd) {
		this.id = id;
		this.bonusCd = bonusCd;
	}

	Cd(String id) {
		this.id = id;
	}

	public String getId() {
		return id;
	}

	public Cd getBonusCd() {
		return bonusCd;
	}
}

And let's create an order with the same cd twice and the order itself, so we can simulate two references to the same object and a back-reference.

Cd bj = new Cd("basement_jaxx_singles");
		
List order = new ArrayList();
// adds the same cd twice (two references to the same object)
order.add(bj);
order.add(bj);

// adds itself (cycle)
order.add(order);

XStream xstream = new XStream();
xstream.alias("cd", Cd.class);
System.out.println(xstream.toXML(order));

If we execute the above code, XStream's uses its default mode called XPATH_RELATIVE_REFERENCES based on the W3C XPath specification. Cross and back references are treated in a way that it's (almost) human readable:

<list>
  <cd>
    <id>maria rita</id>
  </cd>
  <cd>
    <id>basement_jaxx_singles</id>
  </cd>
  <cd reference="../cd[2]"/>
  <list reference=".."/>
</list>

The second reference to the Basement Jaxx cd was serialized as "../cd[2]" while the order inside itself used the ".." path. The XPath Relative mode allows any type of graphs to be used as both cross and back-references are supported.

In order to make use of the XPath Relative mode one can implicitly call:

xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES);

Relative x Absolute

There is an absolute mode which is easy to use and understand. It works using the same XPath specification and also supports all types of graphs.

xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);

The changes in the resulting xml is a little more 'clutter':

<list>
  <cd>
    <id>maria rita</id>
  </cd>
  <cd>
    <id>basement_jaxx_singles</id>
  </cd>
  <cd reference="/list/cd[2]"/>
  <list reference="/list"/>
</list>

Single Node Selectors

In some cases where the XML is used later on or is generated by someone else, the XPath selectors can be forced to select always a single node instead of a node list where the first element is taken. Therefore two more modes exist:

xstream.setMode(XStream.SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES);
xstream.setMode(XStream.SINGLE_NODE_XPATH_RELATIVE_REFERENCES);

The changes in the resulting xml is even more 'clutter':

<list>
  <cd>
    <id>maria rita</id>
  </cd>
  <cd>
    <id>basement_jaxx_singles</id>
  </cd>
  <cd reference="/list[1]/cd[2]"/>
  <list reference="/list[1]"/>
</list>

For XStream is the notation with the single node selectors absolutely equivalent to the one without. These two notations are completely transparent at deserialization time.

Id mode

Both modes displayed until now are not so easy to write by hand. XStream has another mode which makes it is easier to read/write by a human being:

xstream.setMode(XStream.ID_REFERENCES);

The result is a XML which generates an "id" attribute for each new object marshaled, and whenever it finds back or cross-references, it uses a "reference" attribute to so it doesn't copy the entire object.

In our example, the list has id 1, the Maria Rita cd 2, and the Basement Jaxx 3. Therefore the cross-reference to our cd should contain a reference attribute to object number 2 and the back-reference to our order a reference to object 1. The result is:

<list id="1">
  <cd id="2">
    <id>maria rita</id>
  </cd>
  <cd id="3">
    <id>basement_jaxx_singles</id>
  </cd>
  <cd reference="3"/>
  <list reference="1"/>
</list>

No references

For some uses of XStream we do not desire any kind of back or cross references like a graph, but a simple tree. The most famous example is when using XStream to generate XML for B2B services.

In such scenarios it's impossible to represent a graph cycle (remember: no tree contains such structure), therefore we have to remove the last add call from our example:

Cd bj = new Cd("basement_jaxx_singles");
		
List order = new ArrayList();
// adds the same cd twice (two references to the same object)
order.add(bj);
order.add(bj);

XStream xstream = new XStream();
xstream.alias("cd", Cd.class);
System.out.println(xstream.toXML(order));

Now if we add the NO_REFERENCES option, every reference shall be completed serialized.

xstream.setMode(XStream.NO_REFERENCES);

The result are three references:

<list>
  <cd>
    <id>maria rita</id>
  </cd>
  <cd>
    <id>basement_jaxx_singles</id>
  </cd>
  <cd>
    <id>basement_jaxx_singles</id>
  </cd>
</list>

After reading from the above XML, you will get three different Cd instances.

Remember: it's impossible to support back-references (cycles) with NO_REFERENCES mode activated therefore a CircularReferenceException is thrown if you ever try to do so.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/list-user.html0000664000175000017500000000270212206661545030404 0ustar jamespagejamespage Users' Mailing List

General discussion and support for anyone using or evaluating XStream.

Post (Un-)Subscribe
user@xstream.codehaus.org Manage Email

Due to massive abuse by spammers the subscriptions is centralized for email lists of all projects hosted on Codehaus. After following the link above just register with your email address and you can manage all subscriptions at once.

Archives

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/license.html0000664000175000017500000000402612206661545030100 0ustar jamespagejamespage License

XStream is open source software, made available under a BSD license.

Copyright (c) 2003-2006, Joe Walnes
Copyright (c) 2006-2009, 2011 XStream Committers
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution.

3. Neither the name of XStream nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written
permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/team.html0000664000175000017500000000623412206661545027407 0ustar jamespagejamespage Development Team

Project Founder

  • Joe Walnes

Project Lead

  • Jörg Schaible

Active Committers

  • Joe Walnes
  • Mauro Talevi
  • Jörg Schaible
  • Guilherme Silveira

Hibernating Committers

  • Jason van Zyl
  • Nat Pryce
  • Dan North

Contributors

List in sequence of first contribution to XStream.

  • Tim Mackinnon
  • James Strachan
  • Jon Tirsén
  • Marcos Tarruella
  • Khurram Chaudhary
  • Brock Bulger
  • Paul Hammant
  • Nicky Sandhu
  • J. Matthew Pryor
  • Aslak Hellesøy
  • Nick Pomfret
  • Brian Slesinsky
  • Konstantin Pribluda
  • Ben Smith
  • Brian Oxley
  • Chris Kelly
  • Matthew Sandoz
  • Veaceslav Chicu
  • Jose A. Illescas
  • Laurent Bihanic
  • Martin Weindel
  • Michael Kopp
  • Brian Selinsky
  • Daniel Sheppard
  • Chris Nokleberg
  • Henri Tremblay
  • Simon Daniel
  • Eric Snell
  • Andrea Aime
  • Bryan Coleman
  • Kevin Ring
  • Trygve Laugstøl
  • Hannes Havel
  • Gábor Lipták
  • Baba Buehler
  • Emil Kirschner
  • Chung-Onn Cheong
  • Ian Cartwright
  • Costin Leau
  • Stefano Girotti
  • David Blevins
  • Henrik Ståhl of BEA
  • Cyrille Le Clerc
  • John Kristian
  • Chris Winters
  • Lucio Benfante
  • Nicolas Gros d'Aillon
  • Dejan Bosanac
  • Rene Schwietzke
  • Hinse ter Schuur
  • Adrian Wilkens
  • Jukka Lindström
  • Kevin Conaway
  • Kevin Bowman
  • Tatu Saloranta
  • Jerome Lacoste
  • Reto Bachmann-Gmür
  • Steven Sparling
  • Alexander Radzin
  • Doug Daniels
  • Jason Greanya
  • Carlos Roman
  • Jaime Metcher
  • Michael Schnell
  • Nikita Levyankov

Please direct all correspondence about XStream to the users' mailing lists rather than directly to one of the team.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/download.html0000664000175000017500000001412112206661545030262 0ustar jamespagejamespage Download

About XStream version numbers...

Stable Version: 1.4.4

  • Binary distribution: Contains the XStream jar files, the Hibernate and Benchmark modules and all the dependencies.
  • Source distribution: Contains the complete XStream project as if checked out from the Subversion version tag.
  • XStream Core only: The xstream.jar only as it is downloaded automatically when it is referenced as Maven dependency.
  • XStream Hibernate module: The xstream-hibernate.jar as it is downloaded automatically when it is referenced as Maven dependency.
  • XStream Benchmark module: The xstream-benchmark.jar as it is downloaded automatically when it is referenced as Maven dependency.

Latest Snapshot

Below are builds of the latest version of XStream from the repository.

Previous Releases

Previous releases of XStream are also available. However, use of the latest stable version is recommended.

Optional Dependencies

  • Supported XML parsers and packages:
  • Other optional 3rd party dependencies:
    • Joda Time for optional ISO8601 date/time formats.
    • CGLIB for optional support of some proxies generated with the CGLIB Enhancer.
    • Jettison for serialization and deserialization support with JSON. Note, that newer versions 1.3.x are no longer compatible with XStream.
    • Jettison 1.0.1 for serialization and deserialization support with JSON in JDK 1.4. Note, that newer version 1.1 is not compatible with XStream.

Dependencies Hibernate Module

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/references.html0000664000175000017500000003006612206661545030602 0ustar jamespagejamespage References

XStream is used in a lot of commercial and open source projects and is used in production since years.

XStream used for Core Technology

Atlassian Bamboo

Bamboo is build server for continuous integration and release management. Note, XStream itself uses Bamboo at Codehaus for continuous integration.

Atlassian Confluence

Confluence is an enterprise wiki that makes it easy for your team to collaborate and share knowledge.

Oracle Hudson CI

Hudson CI is also a build server for continuous integration and release management.

Apache Muse

The Apache Muse Project is a Java-based implementation of the WS-ResourceFramework (WSRF), WS-BaseNotification (WSN), and WS-DistributedManagement (WSDM) specifications. It is a framework upon which users can build web service interfaces for manageable resources without having to implement all of the "plumbing" described by the aforementioned standards. Applications built with Muse can be deployed in both Apache Axis2 and OSGi environments, and the project includes a set of command line tools that can generate the proper artifacts for your deployment scenario.

NanoContainer

The scope of the NanoContainer project is to complement the PicoContainer project, providing it with additional functionality. The project comprises of several components which can either be adoptions in various guises of PicoContainer (e.g. composition by-class-name rather than by-class), or adaptations to external components bringing them closer to the Dependency Injection ideal - particularly Constructor Injection.

Murq

Murq is a persistence framework with an emphasis on simplicity. It is also capable of storing binary data and meta data, supports search functionality and makes internationalization seamless.

XBird

XBird is a light-weight XQuery processor and database system written in Java. The light-weight means reasonably fast and embeddable. It uses the XStream persistence API for object persistence

EJOE

EJOE is a lightweight Java remoting framework built to send and receive objects through pluggable (de)serialization mechanisms. XStream provides the default (de)serialization mechanism.

OpenCraft

OpenCraft is an alternative/custom Minecraft server, written in Java, compatible with the original protocol. XStream provides the persistence layer.

XStream Support

jBoss ESB

jBossESB is the next generation of EAI - better and without the vendor-lockin characteristics of old. It uses a flexible architecture based on SOA principles such as loose-coupling and asynchronous message passing, emphasizing an incremental approach to adopting and deploying an SOI. XStream can be used as one possibility for the messaging part.

Restlet

Restlet is a lightweight REST framework for Java that lets you embrace the architecture of the Web and benefit from its simplicity and scalability. By leveraging our innovative REST engine, you can start blending your Web Sites and Web Services into uniform Web Applications!

The framework uses XStream as extension for a representation of objects in XML or JSON and a ConverterService based on this functionality.

ActiveSOAP

ActiveSOAP is a lightweight & easily embeddable REST and SOAP stack based on StAX with support for WS-Addressing and WSIF. ActiveSOAP uses StAX (the Standard API for pull parsing) to implement the SOAP protocols and then it delegates to plugin Handler objects for the heavy duty processing of the XML payloads. This means that you only need to pay for what you need; use fast pull based event parsing or full data binding mechanisms like JAXB or XStream or DOMish APIs like XMLBeans when they make sense.

Mule

Mule is the leading open source ESB (Enterprise Service Bus) and integration platform. It is a scalable, highly distributable object broker that can seamlessly handle interactions with services and applications using disparate transport and messaging technologies. Transformers are used to convert inbound data to an object type required by the UMO Component or outbound to an object type required by the transport such as a JmsMessage. Mule uses Transformers to convert event data between the different endpoints. They can be configured on endpoints that receive data to ensure that the expected object type is always received by a Mule Component. XStream is used for standard XML to Java object transformation.

Blojsom

Blojsom is Java-based, full-featured, multi-blog, multi-user software package that was inspired by blosxom. blojsom aims to retain a simplicity in design while adding flexibility in areas such as the flavors, templating, plugins, and the ability to run multiple blogs with a single blojsom installation. XStream is used for export.

FlatTree

FlatTree is a Java library for reading and writing of flat files: CSV, FLR (fixed length record) or mixed structures. It features a tree-style processing API, adapters for SAX, Stax and XStream for transformation, data binding or serialization.

Blogs and Articles

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/how-to-contribute.html0000664000175000017500000000663312206661545032055 0ustar jamespagejamespage How to Contribute

XStream is nothing without contributions from the user community. There are many ways to contribute. We are constantly working on the software and documentation, so it's a good idea to contact the team on the user or development mailing lists to avoid duplicating effort.

Documentation

One of the traditional weak points of open source software is the documentation. Any help with this aspect of the project will be welcomed with open arms, or at the very least with open email clients!

Examples

We are working on one or two examples of using XStream, but we can always do with more.

Feature Requests

We eat our own dogfood, but we're also happy to feed other people's dogs (if you'll excuse a stretched dachshund metaphor!). If you want to request a new feature you can either make a request through the issue tracker or by sending a message to the development mailing list. The benefit of any new features will be discussed on the mailing list, so its a good idea to sign up so that you can stick your oar in.

Bug Reports

You can report bugs through the issue tracker interface or the development mailing list. Additional brownie points are awarded for bug reports that include a failing unit test.

Bug Fixes

If you want lots of brownie points, send a fix along with your bug report and failing unit test. Bug fixes are best sent as patches that we can apply to the codebase. Remember to tell us which version the patch should be applied against, or we'll get very confused. To be accepted into the codebase, patches must be released under the same license as XStream itself.

New Code

If you have a new feature request, then we'll listen extra hard if you show us how it works. A new feature might be best implemented as a patch to an existing class or as a new class. The XStream API contains many extension points that allow new functionality to be integrated into the framework. We are rather anal about testing, so if you send us some code without any tests we will probably ask you to write the tests tests as well before we add it to the codebase.

Write Your Own XStream Extension

If you have a project that builds upon XStream we will be happy to announce your project on the XStream site.

Become a Committer

We follow the Codehaus manifesto when it comes to expanding the core team.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/list-dev.html0000664000175000017500000000312112206661545030200 0ustar jamespagejamespage Developers' Mailing List

General discussion and support for anyone who wants to get involved in the development of XStream.

Note, if you just have questions about using XStream, you should use the user's mailing list.

Post (Un-)Subscribe
dev@xstream.codehaus.org Manage Email

Due to massive abuse by spammers the subscriptions is centralized for email lists of all projects hosted on Codehaus. After following the link above just register with your email address and you can manage all subscriptions at once.

Archives

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/converter-tutorial.html0000664000175000017500000006022012206661545032324 0ustar jamespagejamespage Converter Tutorial

Simple Converter

Setting up a simple example

This is the most basic converter... let's start with a simple Person:

package com.thoughtworks.xstream.examples;

public class Person {

        private String name;

        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

}

So let's create a person and convert it to XML...

package com.thoughtworks.xstream.examples;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class PersonTest {

        public static void main(String[] args) {
                Person person = new Person();
                person.setName("Guilherme");

                XStream xStream = new XStream(new DomDriver());
                System.out.println(xStream.toXML(person));
        }

}

This results in a really ugly XML code which contains the full class name (including package)...

<com.thoughtworks.xstream.examples.Person>
  <name>Guilherme</name>
</com.thoughtworks.xstream.examples.Person>

So we make use of an 'alias' to change this full class name to something more 'human', for example 'person'.

XStream xStream = new XStream(new DomDriver());
xStream.alias("person", Person.class);
System.out.println(xStream.toXML(person));

And the outcome is much easier to read (and smaller):

<person>
  <name>Guilherme</name>
</person>

Now that we have configured a simple class to play with, let's see what XStream converters can do for us...

Creating a PersonConverter

Let's create a simple converter capable of:

  1. telling its capable of converting Person's
  2. translating a Person instance in XML
  3. translate XML into a new Person

We begin creating the PersonConverter class and implementing the Converter interface:

package com.thoughtworks.xstream.examples;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class PersonConverter implements Converter {

        public boolean canConvert(Class clazz) {
                return false;
        }

        public void marshal(Object value, HierarchicalStreamWriter writer,
                        MarshallingContext context) {
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                        UnmarshallingContext context) {
                return null;
        }

}

Now we tell whoever calls us that we can handle only Person's (and nothing else, including those classes which extends Person).

public boolean canConvert(Class clazz) {
        return clazz.equals(Person.class);
}

The second step is usually quite clean, unless you are dealing with generic converters.

The marshal method is responsible for translating an object to XML. It receives three arguments:

  1. the object we are trying to convert
  2. the writer were we should output the data
  3. the current marshalling context

We start casting the object to person:

Person person = (Person) value;

Now we can output the data... let's start creating a node called fullname and adding the person's name to it:

writer.startNode("fullname");
writer.setValue(person.getName());
writer.endNode();

Quite simple huh?

public void marshal(Object value, HierarchicalStreamWriter writer,
                MarshallingContext context) {
        Person person = (Person) value;
        writer.startNode("fullname");
        writer.setValue(person.getName());
        writer.endNode();
}

We could have called start/end node as many times as we would like (but remember to close everything you open)... and conversion usually takes place when calling the setValue method.

And now let's go to the unmarshal. We use the moveDown and moveUp methods to move in the tree hierarchy, so we can simply moveDown, read the value and moveUp.

                Person person = new Person();
                reader.moveDown();
                person.setName(reader.getValue());
                reader.moveUp();

Which gives us the following converter:

package com.thoughtworks.xstream.examples;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class PersonConverter implements Converter {

        public boolean canConvert(Class clazz) {
                return clazz.equals(Person.class);
        }

        public void marshal(Object value, HierarchicalStreamWriter writer,
                        MarshallingContext context) {
                Person person = (Person) value;
                writer.startNode("fullname");
                writer.setValue(person.getName());
                writer.endNode();
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                        UnmarshallingContext context) {
                Person person = new Person();
                reader.moveDown();
                person.setName(reader.getValue());
                reader.moveUp();
                return person;
        }

}

Now let's register our converter and see how our application main method looks like:

package com.thoughtworks.xstream.examples;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class PersonTest {

        public static void main(String[] args) {
                Person person = new Person();
                person.setName("Guilherme");

                XStream xStream = new XStream(new DomDriver());
                xStream.registerConverter(new PersonConverter());
                xStream.alias("person", Person.class);
                System.out.println(xStream.toXML(person));
        }

}

Did you notice how we registered our converter? It's a simple call to registerConverter:

xStream.registerConverter(new PersonConverter());

The final result is:

<person>
  <fullname>Guilherme</fullname>
</person>

So you might say... that only changed my tree, I want to convert data!

Try using an attribute called fullname in the person tag instead of creating a new child node.

An alternative for types with String representation

Let's enhance the Person with a String representation, that contains all necessary text to recreate the instance:

package com.thoughtworks.xstream.examples;

public class Person {

        private String name;

        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

        public String toString() {
                return getName();
        }
}

In this case we can simplify our Converter to

package com.thoughtworks.xstream.examples;

import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;

public class PersonConverter extends AbstractSingleValueConverter {

        public boolean canConvert(Class clazz) {
                return clazz.equals(Person.class);
        }

        public Object fromString(String str) {
                Person person = new Person();
                person.setName(string);
                return person;
        }

}

But even nicer, our XML is also simplified (using the alias for the Person class). Since the String representation is complete, a nested element is not necessary anymore:

<person>Guilherme</person>

Date Converter

Now that we know how the Converter interface works, let's create a simple calendar converter which uses the locale to convert the information.

Our converter will receive the Locale in its constructor and we will keep a reference to it in a member variable:

package com.thoughtworks.xstream.examples;

import java.util.Locale;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class DateConverter implements Converter {

        private Locale locale;

        public DateConverter(Locale locale) {
                super();
                this.locale = locale;
        }

        public boolean canConvert(Class clazz) {
                return false;
        }

        public void marshal(Object value, HierarchicalStreamWriter writer,
                        MarshallingContext context) {
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                        UnmarshallingContext context) {
                return null;
        }

}

Now let's convert anything which extends Calendar: means if instances of class clazz can be assigned to the Calendar class, they extends the abstract class Calendar:

public boolean canConvert(Class clazz) {
        return Calendar.class.isAssignableFrom(clazz);
}

Let's go for converting a Calendar in a localized string... we first cast the object to Calendar, extract its Date and then use a DateFormat factory method to get a date converter to our localized string.

public void marshal(Object value, HierarchicalStreamWriter writer,
                MarshallingContext context) {

        Calendar calendar = (Calendar) value;

        // grabs the date
        Date date = calendar.getTime();

        // grabs the formatter
        DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL,
                        this.locale);

        // formats and sets the value
        writer.setValue(formatter.format(date));

}

And the other way around... in order to unmarshall, we create a GregorianCalendar, retrieves the localized DateFormat instance, parses the string into a Date and puts this date in the original GregorianCalendar:

public Object unmarshal(HierarchicalStreamReader reader,
                UnmarshallingContext context) {

        // creates the calendar
        GregorianCalendar calendar = new GregorianCalendar();

        // grabs the converter
        DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL,
                        this.locale);

        // parses the string and sets the time
        try {
                calendar.setTime(formatter.parse(reader.getValue()));
        } catch (ParseException e) {
                throw new ConversionException(e.getMessage(), e);
        }

        // returns the new object
        return calendar;

}

Note 1: remember that some DateFormat implementations are not thread-safe, therefore don't put your formatter as a member of your converter.

Note 2: this implementation will convert other types of Calendar's to GregorianCalendar after save/load. If this is not what you want, change your canConvert method to return true only if class equals GregorianCalendar.

So we get the following converter:

package com.thoughtworks.xstream.examples;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class DateConverter implements Converter {

        private Locale locale;

        public DateConverter(Locale locale) {
                super();
                this.locale = locale;
        }

        public boolean canConvert(Class clazz) {
                return Calendar.class.isAssignableFrom(clazz);
        }

        public void marshal(Object value, HierarchicalStreamWriter writer,
                        MarshallingContext context) {
                Calendar calendar = (Calendar) value;
                Date date = calendar.getTime();
                DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL,
                                this.locale);
                writer.setValue(formatter.format(date));
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                        UnmarshallingContext context) {
                GregorianCalendar calendar = new GregorianCalendar();
                DateFormat formatter = DateFormat.getDateInstance(DateFormat.FULL,
                                this.locale);
                try {
                        calendar.setTime(formatter.parse(reader.getValue()));
                } catch (ParseException e) {
                        throw new ConversionException(e.getMessage(), e);
                }
                return calendar;
        }

}

And let's try it out. We create a DateTest class with a main method:

  1. creates a calendar (current date)
  2. creates the XStream object
  3. registers the converter with a Brazilian Portuguese locale
  4. translates the object in XML

Well, we already know how to do all those steps... so let's go:

package com.thoughtworks.xstream.examples;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class DateTest {

        public static void main(String[] args) {

                // grabs the current date from the virtual machine
                Calendar calendar = new GregorianCalendar();

                // creates the xstream
                XStream xStream = new XStream(new DomDriver());

                // brazilian portuguese locale
                xStream.registerConverter(new DateConverter(new Locale("pt", "br")));

                // prints the result
                System.out.println(xStream.toXML(calendar));

        }

}

The result? Well... it depends, but it will be something like:

<gregorian-calendar>Sexta-feira, 10 de Fevereiro de 2006</gregorian-calendar>

Note: we did not put any alias as gregorian-calendar is the default alias for GregorianCalendar.

And now let's try to unmarshal the result shown above:

// loads the calendar from the string
Calendar loaded = (Calendar) xStream
                .fromXML("<gregorian-calendar>Sexta-feira, 10 de Fevereiro de 2006</gregorian-calendar>");

And print it using the system locale, short date format:

// prints using the system defined locale
System.out.println(DateFormat.getDateInstance(DateFormat.SHORT).format(
                loaded.getTime()));

The result might be something like (if your system locale is American English):

2/10/06

Complex Converter

Setting up another example

We already defined some classes, so let them glue together:

package com.thoughtworks.xstream.examples;

public class Birthday {

        private Person person;
        private Calendar date;
        private char gender;

        public Person getPerson() {
                return person;
        }

        public void setPerson(Person person) {
                this.person = person;
        }

        public Calendar getDate() {
                return date;
        }

        public void setDate(Calendar date) {
                this.date = date;
        }
        
        public char getGender() {
                return gender;
        }

        public void setGenderMale() {
                this.gender = 'm';
        }

        public void setGenderFemale() {
                this.gender = 'f';
        }

}

While XStream is capable of converting this class without any problem, we write our own custom converter just for demonstration. This time we want to reuse our already written converters for the Person and the Calendar and add an own attribute for the gender. The canConvert method is plain simple. We convert no derived classes this time, since they might have additional fields. But we reuse the converters registered in XStream for our member fields and handle null values:

package com.thoughtworks.xstream.examples;

import java.util.Calendar;

import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class BirthdayConverter implements Converter {

        public boolean canConvert(Class clazz) {
                return Birthday.class == clazz;
        }

        public void marshal(Object value, HierarchicalStreamWriter writer,
                        MarshallingContext context) {
                Birthday birthday = (Birthday)value;
                if (birthday.getGender() != '\0') {
                        writer.addAttribute("gender", Character.toString(birthday.getGender()));
                }
                if (birthday.getPerson() != null) {
                        writer.startNode("person");
                        context.convertAnother(birthday.getPerson());
                        writer.endNode();
                }
                if (birthday.getDate() != null) {
                        writer.startNode("birth");
                        context.convertAnother(birthday.getDate());
                        writer.endNode();
                }
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                        UnmarshallingContext context) {
                Birthday birthday = new Birthday();
                String gender = reader.getAttribute("gender");
                if (gender != null) {
                        if (gender.length() > 0) {              
                                if (gender.char(0) == 'f') {
                                        birthday.setGenderFemale();
                                } else if (gender.char(0) == 'm') {
                                        birthday.setFemale();
                                } else {
                                        throw new ConversionException("Invalid gender value: " + gender);
                                }
                        } else {
                                throw new ConversionException("Empty string is invalid gender value");
                        }
                }
                while (reader.hasMoreChildren()) {
                        reader.moveDown();
                        if ("person".equals(reader.getNodeName())) {
                                Person person = (Person)context.convertAnother(birthday, Person.class);
                                birthday.setPerson(person);
                        } else if ("birth".equals(reader.getNodeName())) {
                                Calendar date = (Calendar)context.convertAnother(birthday, Calendar.class);
                                birthday.setDate(date);
                        }
                        reader.moveUp();
                }
                return birthday;
        }

}

The unmarshal method ensures the valid value for the gender by throwing a ConversionException for invalid entries.

Note, that attributes will always have to be written and read first. You work on a stream and accessing the value of a tag or its members will close the surrounding tag (that is still active when the method is called).

If the implementation of Birthday ensures, that none of its fields could hold a null value and gender contains a valid value, then we could drop the null condition in the marshal method and in unmarshal we could omit the loop as well as the comparison of the tag names:

package com.thoughtworks.xstream.examples;

import java.util.Calendar;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class BirthdayConverter implements Converter {

        public boolean canConvert(Class clazz) {
                return Birthday.class == clazz;
        }

        public void marshal(Object value, HierarchicalStreamWriter writer,
                        MarshallingContext context) {
                writer.addAttribute("gender", Character.toString(birthday.getGender()));
                Birthday birthday = (Birthday)value;
                writer.startNode("person");
                context.convertAnother(birthday.getPerson());
                writer.endNode();
                writer.startNode("birth");
                context.convertAnother(birthday.getDate());
                writer.endNode();
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                        UnmarshallingContext context) {
                Birthday birthday = new Birthday();
                if (reader.getAttribute("gender").charAt(0) == 'm') {
                        birthday.setGenderMale();
                } else {
                        birthday.setGenderFemale();
                }
                reader.moveDown();
                Person person = (Person)context.convertAnother(birthday, Person.class);
                birthday.setPerson(person);
                reader.moveUp();
                reader.moveDown();
                Calendar date = (Calendar)context.convertAnother(birthday, Calendar.class);
                birthday.setDate(date);
                reader.moveUp();
                return birthday;
        }

}
jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/json-tutorial.html0000664000175000017500000001532012206661545031267 0ustar jamespagejamespage JSON Tutorial

Due to XStream's flexible architecture, handling of JSON mappings is as easy as handling of XML documents. All you have to do is to initialize XStream object with an appropriate driver and you are ready to serialize your objects to (and from) JSON.

XStream currently delivers two drivers for JSON: The JsonHierarchicalStreamDriver and the JettisonMappedXmlDriver. The first one does not have an additional dependency, but can only be used to write XML, while the second one is based on Jettison and can also deserialize JSON to Java objects again. However, since the JettisonMappedXmlDriver transforms plain XML into JSON, you might get better JSON strings with the JsonHierarchicalStreamDriver, because this driver knows often about the type of the written data and can act properly.

One word of warning. JSON is made for an easy data transfer between systems and languages. It's syntax offers much less possibilities to express certain data structures. It supports name/value pairs of primitive data types, arrays and lists and allows to nest them - but that's it! No references, no possibility for meta data (attributes), no properties with same names (as generated for implicit collections), etc. Therefore do not expect wonders. XStream (and Jettison) try their best, but the procedure to convert any kind of object into JSON is a lossy transformation and especially deserialization will not be possible for any construct. See also FAQ.

Since JSON has no possibility to express references, you should always set the NO_REFERENCES mode writing JSON.

Jettison driver

Jettison driver uses Jettison StAX parser to read and write data in JSON format. It is available in XStream since version 1.2.2 and is implemented in com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver class. To successfully use this driver you need to have the Jettison project and StAX API in your classpath (see reference for optional dependencies).

Alternatively you can download JARs manually.

Here are a few simple examples:

Write to JSON with the Jettison-based implementation

The following example:

package com.thoughtworks.xstream.json.test;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

public class WriteTest {

	public static void main(String[] args) {

        Product product = new Product("Banana", "123", 23.00);
        XStream xstream = new XStream(new JettisonMappedXmlDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.alias("product", Product.class);

        System.out.println(xstream.toXML(product));		
		
	}

}

produces the following JSON document:

{"product":{"name":"Banana","id":123,"price":23.0}}

As you can see, all standard XStream features (such as aliases) can be used with this driver.

Note that Jettison will try to detect numerical values and omit the quotes. Since Jettison cannot know about the original data type, it has to guess. Hence it will therefore also write the value of the id field as numeric value in future.

Write to JSON with the self-contained JSON driver

The only difference to the example above is the line with the initialization:

XStream xstream = new XStream(new JsonHierarchicalStreamDriver());

The output is as follows:

{"product": {
  "name": "Banana",
  "id": "123",
  "price": 23.0
}}

While the difference because of line feeds is immediately obvious, you have to note also the value of the id element. This time the driver knew about the string value and therefore quotes were generated.

Write to JSON with the self-contained JSON driver dropping the root

Sometimes the root node in the generated JSON is superfluous, since its name is caused by the Java type of the written object that has no meaning in JSON and increases only the nesting level of the structure. Therefore it is possible to drop this root by initializing the internally used JsonWriter in a different mode. Again, the only difference to the example above is the line with the initialization:

XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
    public HierarchicalStreamWriter createWriter(Writer writer) {
        return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
    }
});

The output is as follows:

{
  "name": "Banana",
  "id": "123",
  "price": 23.0
}

Note, that it is now possible to create invalid JSON if XStream should marshal a single object with a single value to JSON (like String, int, URL, ...). JSON requires that the root is actually an object, but by dropping the root all that is generated is a single value. You can force the JsonWriter to throw a ConversionException in this case, see Javadoc of the JsonWriter.

Read from JSON

The following code:

package com.thoughtworks.xstream.json.test;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

public class ReadTest {

	public static void main(String[] args) {
		String json = "{\"product\":{\"name\":\"Banana\",\"id\":123"
		    + ",\"price\":23.0}}";
		    
		XStream xstream = new XStream(new JettisonMappedXmlDriver());
		xstream.alias("product", Product.class);
		Product product = (Product)xstream.fromXML(json);
		System.out.println(product.getName());
	}

}

serializes JSON document created with preceding example back to Java object. It prints:

Banana

as a result.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/versioning.html0000664000175000017500000001172312206661545030643 0ustar jamespagejamespage About Versioning

The XStream project follows strict rules that govern its use of version numbers. The version number of a release indicates how that release is compatible with previous and future releases.

Version numbers have the form major.minor.patch. A major version identifies the product stage of the project. Two libraries with different major version are designed to work together in the same application. This implies a major change in the API - either by not sharing the same types or using a different package name.

The minor version number identifies the API version. A release that changes the API in a way that breaks backwards compatibility will increment the minor version number and reset the patch version to zero. The patch version number identifies the backwards compatible revision of the API. A change in the minor version will still be mostly backward compatible, but may need some compatibility settings or slight migration adjustments. The patch version number identifies revisions that do not change the API although new API elements may occur or existing API may be deprecated to prepare users for the next release with a change in the minor version. A release that fixes bugs or refactors implementation details without changing the API will have the same minor and major versions as the previous release and increment the patch number.

A hypothetical example:

1.0.0First release
1.0.1Improves Javadoc comments, fixes bug
1.1.0Adds new API elements, may cause some migration
1.1.1Adds new API elements, deprecates some API elements
1.1.2Fixes bugs
1.2.0Adds new API, needs some migration effort and removes deprecated elements
2.0.0Complete API redesign, can be used simultanly with 1.x series.
2.0.1Deprecates API, fixes bugs
2.1.0Adds new API elements
etc.etc.

Release Candidates

Before a new major or minor release, XStream will make release candidate (RC) packages available so that users can test them against their own code. There will be one or more release candidates given the version major.minor.0 RCn, where the major and minor version numbers identify the upcoming release and RC1 identifies the first candidate release, RC2 the second, and so on.

A release candidate does not guarantee backward compatibility with new API features introduced by any previous RC of the same upcoming version. A major version RC can change/remove API features introduced in a previous RC for the same major version; a minor version RC can change API features introduced by any previous RC of the same upcoming minor version but guarantees backward compatibility with the previous minor version.

Development Snapshots

During development, the the developers may publish snapshot packages from time to time. These are not guaranteed to be complete: Although the unit tests will all pass the snapshot will probably contain failing acceptance tests that describe planned or requested features that have not yet been implemented. Snapshots are identified by the UTC time at which the package was built. The timestamp has the form VERSION-YYYYMMDD.hhmmss-n, where VERSION is the upcoming version, YYYY is the (four-digit) year, MM the month, DD the day, hh the hour, mm the minute, ss the second and n a sequential number.

Internal Classes

Many classes are for internal use only and not designed to be used by end users. These are exempt from the versioning rules above.

Such classes are clearly marked as internal in the source code headers and are excluded from the published JavaDoc.

Versioning and Deprecation

A patch release might deprecate some API features. Deprecated features will not actually be removed until the next minor release. A release will never remove API features that have not been deprecated in a previous release.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/alias-tutorial.html0000664000175000017500000003421712206661545031415 0ustar jamespagejamespage Alias Tutorial

The problem

Suppose that our client has defined a base XML file that we should make XStream read/write:

<blog author="Guilherme Silveira">
  <entry>
    <title>first</title>
    <description>My first blog entry.</description>
  </entry>
  <entry>
    <title>tutorial</title>
    <description>
        Today we have developed a nice alias tutorial. Tell your friends! NOW!
    </description>
  </entry>
</blog>

Based on the XML file above we shall create some model classes and configure XStream to write/read from this format.

The model

First things first, the classes which shall represent our xml files are shown next, beginning with a simple Blog:

package com.thoughtworks.xstream;

public class Blog {
        private Author writer;
        private List entries = new ArrayList();

        public Blog(Author writer) {
                this.writer = writer;
        }

        public void add(Entry entry) {
                entries.add(entry);
        }

        public List getContent() {
                return entries;
        }
}

A basic author with name:

package com.thoughtworks.xstream;

public class Author {
        private String name;
        public Author(String name) {
                this.name = name;
        }
        public String getName() {
                return name;
        }
}

A blog entry contains a title and description:

package com.thoughtworks.xstream;

public class Entry {
        private String title, description;
        public Entry(String title, String description) {
                this.title = title;
                this.description = description;
        }
}

Although we did not create many getters/setters its up to you to create those you wish or those which make sense.

A simple test

We can easily instantiate a new blog and use it with xstream:

public static void main(String[] args) {

        Blog teamBlog = new Blog(new Author("Guilherme Silveira"));
        teamBlog.add(new Entry("first","My first blog entry."));
        teamBlog.add(new Entry("tutorial",
                "Today we have developed a nice alias tutorial. Tell your friends! NOW!"));

        XStream xstream = new XStream();
        System.out.println(xstream.toXML(teamBlog));

}

And the resulting XML is not so nice as we would want it to be:

<com.thoughtworks.xstream.Blog>
  <writer>
    <name>Guilherme Silveira</name>
  </writer>
  <entries>
    <com.thoughtworks.xstream.Entry>
      <title>first</title>
      <description>My first blog entry.</description>
    </com.thoughtworks.xstream.Entry>
    <com.thoughtworks.xstream.Entry>
      <title>tutorial</title>
      <description>
        Today we have developed a nice alias tutorial. Tell your friends! NOW!
      </description>
    </com.thoughtworks.xstream.Entry>
  </entries>
</com.thoughtworks.xstream.Blog>

Class aliasing

The first thing we shall change is how XStream refers to the com.thoughtworks.xstream.Blog class. We shall name it simply blog: let's create an alias called blog to the desired class:

xstream.alias("blog", Blog.class);

Using the same idea, we can alias the 'Entry' class to 'entry':

xstream.alias("entry", Entry.class);

The result now becomes:

<blog>
  <writer>
    <name>Guilherme Silveira</name>
  </writer>
  <entries>
    <entry>
      <title>first</title>
      <description>My first blog entry.</description>
    </entry>
    <entry>
      <title>tutorial</title>
      <description>
        Today we have developed a nice alias tutorial. Tell your friends! NOW!
      </description>
    </entry>
  </entries>
</blog>

Field aliasing

Next we will change the name of the writer tag, but this time we have to use a field alias:

xstream.aliasField("author", Blog.class, "writer");

The result now becomes:

<blog>
  <author>
    <name>Guilherme Silveira</name>
  </author>
  <entries>
    <entry>
      <title>first</title>
      <description>My first blog entry.</description>
    </entry>
    <entry>
      <title>tutorial</title>
      <description>
        Today we have developed a nice alias tutorial. Tell your friends! NOW!
      </description>
    </entry>
  </entries>
</blog>

Implicit Collections

Now let's implement what was called an implicit collection: whenever you have a collection which doesn't need to display it's root tag, you can map it as an implicit collection.

In our example, we do not want to display the entries tag, but simply show the entry tags one after another.

A simple call to the addImplicitCollection method shall configure XStream and let it know that we do not want to write the entries tag as described above:

package com.thoughtworks.xstream;

import java.util.ArrayList;
import java.util.List;

public class Test {

        public static void main(String[] args) {

                Blog teamBlog = new Blog(new Author("Guilherme Silveira"));
                teamBlog.add(new Entry("first","My first blog entry."));
                teamBlog.add(new Entry("tutorial",
                        "Today we have developed a nice alias tutorial. Tell your friends! NOW!"));

                XStream xstream = new XStream();
                xstream.alias("blog", Blog.class);
                xstream.alias("entry", Entry.class);

                xstream.addImplicitCollection(Blog.class, "entries");

                System.out.println(xstream.toXML(teamBlog));

        }
}

Pay attention to the addImplicitCollection method call: it describes which class and which member variable shall assume the behaviour we described.

The result is almost what we wanted:

<blog>
  <author>
    <name>Guilherme Silveira</name>
  </author>
  <entry>
    <title>first</title>
    <description>My first blog entry.</description>
  </entry>
  <entry>
    <title>tutorial</title>
    <description>
        Today we have developed a nice alias tutorial. Tell your friends! NOW!
    </description>
  </entry>
</blog>

Just as a side note: An array or a map can also be declared as implicit.

Attribute aliasing

The next step is to set the writer member variable as an XML attribute. In order to do this, we shall tell XStream to alias the writer field of the Blog class as an "author" attribute:

                xstream.useAttributeFor(Blog.class, "writer");
                xstream.aliasField("author", Blog.class, "writer");

And now it leaves us with one problem: how does XStream converts an Author in a String so it can be written as a XML tag attribute?

Attributes cannot be written for types that are handled by Converter implementations, we have to use a SingleValueConverter and implement our own converter for the Author:

class AuthorConverter implements SingleValueConverter {
}

The first method to implement tells XStream which types it can deal with:

        public boolean canConvert(Class type) {
                return type.equals(Author.class);
        }

The second one is used to extract a String from an Author:

        public String toString(Object obj) {
                return ((Author) obj).getName();
        }

And the third one does the opposite job: takes a String and returns an Author:

        public Object fromString(String name) {
                return new Author(name);
        }

Finally, the entire single value converter, responsible for converting Strings to Objects (Authors in this case) is:

class AuthorConverter implements SingleValueConverter {

        public String toString(Object obj) {
                return ((Author) obj).getName();
        }

        public Object fromString(String name) {
                return new Author(name);
        }

        public boolean canConvert(Class type) {
                return type.equals(Author.class);
        }

}

And let's register this converter:

public class Test {

        public static void main(String[] args) {

                Blog teamBlog = new Blog(new Author("Guilherme Silveira"));
                teamBlog.add(new Entry("first","My first blog entry."));
                teamBlog.add(new Entry("tutorial",
                        "Today we have developed a nice alias tutorial. Tell your friends! NOW!"));

                XStream xstream = new XStream();
                xstream.alias("blog", Blog.class);
                xstream.alias("entry", Entry.class);

                xstream.addImplicitCollection(Blog.class, "entries");

                xstream.useAttributeFor(Blog.class, "author");
                xstream.registerConverter(new AuthorConverter());

                System.out.println(xstream.toXML(teamBlog));

        }
}

The result?

<blog author="Guilherme Silveira">
  <entry>
    <title>first</title>
    <description>My first blog entry.</description>
  </entry>
  <entry>
    <title>tutorial</title>
    <description>
        Today we have developed a nice alias tutorial. Tell your friends! NOW!
    </description>
  </entry>
</blog>

You have to be aware, that attribute values normally have to be normalized by the XML parser as required by the W3C spec. Leading and trailing whitespaces are normally removed as well as sequential ones! Therefore a deserialized string might differ from the value visible in the XML representation.

Package aliasing

In the example above we have so far always used class aliases for the Blog and Entry type. Sometimes it is necessary to map existing class types to others simply by changing the package name. Let us go back to the first attempt of our tutorial, but this time we alias the package name instead of the individual classes:

public static void main(String[] args) {

        Blog teamBlog = new Blog(new Author("Guilherme Silveira"));
        teamBlog.add(new Entry("first","My first blog entry."));
        teamBlog.add(new Entry("tutorial",
                "Today we have developed a nice alias tutorial. Tell your friends! NOW!"));

        XStream xstream = new XStream();
        xstream.aliasPackage("my.company", "org.thoughtworks");
        System.out.println(xstream.toXML(teamBlog));

}

And the resulting XML contains now the classes with the aliased package names:

<my.company.xstream.Blog>
  <author>
    <name>Guilherme Silveira</name>
  </author>
  <entries>
    <my.company.xstream.Entry>
      <title>first</title>
      <description>My first blog entry.</description>
    </my.company.xstream.Entry>
    <my.company.xstream.Entry>
      <title>tutorial</title>
      <description>
        Today we have developed a nice alias tutorial. Tell your friends! NOW!
      </description>
    </my.company.xstream.Entry>
  </entries>
</my.company.xstream.Blog>

Please recognize that the package name alias works also for sub packages in this example.

Summing up

To recap:

  • You can use class aliases to change tag names
  • You can use field aliases to change tag names
  • You can use package aliases to change tag names
  • Fields can be written as attributes if the field type is handled by a SingleValueConverter

Don't forget to read the converter tutorial to see other type of converters that you can create using XStream. Or look into the condensed overview how to configure XStream to tweak the output.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/news.html0000664000175000017500000004175012206661545027437 0ustar jamespagejamespage News

Jan 19, 2013 XStream 1.4.4 released

Maintenance release 1.4.4 of XStream with bug fixes and small improvements.

  • DateConverter supports now localized formats.

View the complete change log and download.

Note, the next major release 1.5 will require Java 6.

Jul 17, 2012 XStream 1.4.3 released

Maintenance release 1.4.3 of XStream with bug fixes and small improvements. Main changes:

  • Support java.util.concurrent.ConcurrentHashMap with the MapConverter.
  • Support for Hibernate 4 with XStream's Hibernate module as default for Java 6 or higher.

View the complete change log and download.

Nov 3, 2011 XStream 1.4.2 released

Maintenance release 1.4.2 of XStream with bug fixes and small improvements. Main changes:

  • XStream libraries can be used now directly in Android, therefore support of Java 1.4.2 has been stopped with the delivery. Anyone who needs a version for Java 1.4.2 can build it easily from source, this build is still supported and part of CI.
  • New extended HierarchicalStreamReader interface with peekNextChild method. All XStream readers implement the new interface (by Nikita Levyankov).
  • Special support for Collections.EMPTY_LIST, Collections.EMPTY_SET and Collections.EMPTY_MAP and collections created with Collections.singletonList(), Collections.singletonSet() and Collections.singletonMap().
  • Support additional parameters for XStreamConverter annotation (e.g. to declare a ToAttributedValueConverter).

View the complete change log and download.

Aug 11, 2011 XStream 1.4.1 released

Maintenance release 1.4.1 of XStream after turning out that it did not work in 1.4 with the new default dependencies. Therefore XStream is back with Xpp3 as default parser and refers additionally the XmlPullParser API to enable the XppDriver that is used by default.

View the complete change log and download.

Aug 6, 2011 XStream 1.4 released

Finally - XStream 1.4 is ready for delivery. A lot of things have changed and improved, new features added. Nevertheless we have maintain compatibility to the old versions:

  • Detection of Java 7 and Android i.e. enabled enhanced mode and annotations for both environments out of the box
  • Direct support of XmlPullParser factory and alternate kXML2 implementation
  • Explicit drivers to select the StAX implementation
  • New separate Hibernate module to support those managed instances (special thanks to Jaime Metcher)
  • Support of implicit arrays and maps additionally to already existing implicit collection support
  • Performance improvements (special thanks to Keith Kowalczykowski)
  • Some new converters (for URI and one to write all fields but one as attributes)
  • A lot of other enhancements and bug fixes

View the complete change log and download.

Thanks to this impressive list of contributors.

Note, that with version 1.4 the default parser has been changed from Xpp3 to kXML2.

Note, that JDK 1.3 support has been officially dropped. Nothing special has been done to enforce this, but there is no longer any support.

Note, to support a representation of null values in some way, it is absolutely necessary that each converter can handle a null value in its marshalling methods. If you have implemented your own custom converters, try to handle such a case also to prevent incompatibilities in case XStream will provide such values with its next major version.

Dec 6, 2008 XStream 1.3.1 released

A new XStream maintenance version has been released. The release contains some bug fixes, some minor enhancements and support of new JDKs:

  • Ability to alias package names
  • Converters are only registered by default for types delivered with the JDK in use preventing unexpected incompatibilities
  • Separation between user defined attributes and XStream attributes
  • New mode for JSONWriter to drop JSON root node
  • Support for FreeBSD's Diablo JDK.
  • Enhanced persistence package and extended tutorial.

View the complete change log and download.

Note, that XStream really supports by default now only types of the JDK in use. Especially for CGLIB this means that support of those proxies will have to be explicitly activated first. However, support for CGLIB proxies has been enhanced.

Note, to support a representation of null values in some way, it is absolutely necessary that each converter can handle a null value in its marshalling methods. If you have implemented your own custom converters, try to handle such a case also to prevent incompatibilities in case XStream will provide such values with its next major version.

Feb 27, 2008 XStream 1.3 released

The XStream committers proudly present XStream 1.3. This release contains some major refactorings concerning Java annotations, improved XML support regarding encoding and character sets, some minor new features, deprecations and a lot of bug fixes:

  • Annotation support is now implemented as Mapper and Annotations can either be processed in advance or on-the-fly (see Annotations tutorial for limitations).
  • Improved encoding support for JSON and XML (including automated support for XML headers). Enforceable check for valid XML characters in the written stream.
  • Dedicated converters can now be configured for individual fields also using the XStream facade.
  • New converters for java.lang.StringBuilder, java.util.UUID, javax.xml.datatype.Duration, and javax.swing.LookAndFeel. New generic converter for types using a java.beans.PropertyEditor. Auto-instantiated SingleValueConverter for Java enums to support enum values as attributes.
  • XML elements are now sorted by default according their declaration with the fields defined in parent classes first to improve support for type hierarchies in XML schemata.
  • A lot of bug fixes to improve JSON support for arbitrary types. Added section in FAQ for limitations and operation modes.
  • Native support for SAP VM.
  • All text-based files are now shipped with an appropriate license header to clean-up legal issues.

View the complete change log and download.

Note, to support a representation of null values in some way, it is absolutely necessary that each converter can handle a null value in its marshalling methods. If you have implemented your own custom converters, try to handle such a case also to prevent incompatibilities in case XStream will provide such values with its next major version.

May 24, 2007 XStream 1.2.2 released

A maintenance release of XStream that contains a lot of bug fixes and has some minor highlights:

  • JSON serialization and deserialization support with the help of the new JettisonMappedXmlDriver
  • Supports customized field sorting
  • Omitting fields at deserialization time

View the complete change log and download.

Note, that next version of XStream will behave slightly different by default. XStream emits all fields in declaration order like Java serialization. But in contrast to Java it will omit the fields of parent classes last while Java serialization emits them first. This makes it difficult to match a given XML schema that defined inherited types or leads sometimes to obscure initialization problems. However, XStream itself will not be affected by the changed order of elements in the XML, any deserialization of current XML representations will work fine. Anyway we will provide with XStream 1.3 a FieldKeySorter implementation that mimics the old behaviour. In the meanwhile you can enforce the new field sorting by installing the NaturalFieldKeySorter.

Nov 11, 2006 XStream 1.2.1 released

  • Introduced DocumentWriter interface and generalized functionality for all writer implementations creating a DOM structure (DOM4J, DOM, JDom, Xom, Xpp3Dom).
  • Refactor of build system to use Maven 2. Ant still supported on XStream Core.
  • Created separate XStream Benchmark module

View the complete change log and download.

Oct 10, 2006Joe Walness announcing new XStream Project Lead

I have been the XStream project lead, since it was open sourced 3 years ago. In that time, it has attracted some excellent developers who have formed the foundations of the user community, made all kinds of significant improvements and pushed out new releases. It's now approaching its 1000th commit.

The development community that has formed around XStream has been outstanding - more than I could ever have imagined. In particular, the following people have invested a lot of time into XStream, both from a technical and social point of view:

  • Jörg Schaible
  • Mauro Talevi
  • Guilherme Silveira
  • Jason van Zyl
  • Me (well I have!)

Recently I have been turning my attention to other things and XStream has been very much a self sustaining project. I've decided that the project would benefit from have a project lead who can invest a lot more time than I can currently offer.

So, the new XStream project lead will be Jörg Schaible, who along with Mauro Talevi and Guilherme Silveira will carry XStream forward. This has been happening for a long while anyway, it's just none of us ever realised or acknowledged it.

Of course, I'll still be lurking around, helping the transition, having loud mouth opinions and generally annoying people in any way I can... you haven't got rid of me that easily. ;)

I know Jörg, Mauro and Guilherme will be able carry XStream into the next generation (we have a lot of ambitious plans for XStream 2).

I'd also like to thank the 45(!) other contributers to the XStream project, who have all helped make it what it is today. Finally, thanks to Graham Glass, who's Electric XML library formed a lot of the inspiration for XStream.

Aug 18, 2006 XStream 1.2 released

  • Using attributes for fields (contributed by Paul Hammant and Ian Cartwright).
  • Aliasing of arbitrary attributes.
  • XStream can now serialize another XStream instance.
  • XStream has now the XStreamer, that serializes an object together with its XStream instance.
  • AnnotationConverter for fields (contributed by Guilherme Silveira).
  • PureJavaReflectionProvider supports now final fields starting with JDK 1.5
  • Any Collection type can now be declared implicit, the default implementation will be respected for unmarshalling.
  • XStream can now write all references as absolute XPath expression.
  • New SingeValueConverter allows light weight converters if the value can be represented by a unique string.
  • Aliasing of classes of a specific type.
  • Support for certain types of proxies generated with the CGLIB Enhancer.
  • Support for BEA JRockit starting with R25.1.0 (contributed by Henrik Ståhl of BEA).
  • Experimental binary reader and writer.
  • Experimental HierarichicalStreamCopier allows streams to be copied from one format to another without the overhead of serialization.
  • Experimental JSON support allows streams to be copied from one format to another without the overhead of serialization (contributed by Paul Hammant).

View the complete change log and download.

Jan 13, 2006 XStream 1.1.3 released

  • Added XStream.toXML(OutputStream) and XStream.fromXML(InputStream).
  • Ability to prevent fields from being serialized by calling XStream.omitField() or by implementing Mapper.shouldSerializeMember().
  • Added Converter for Enum, EnumMap and EnumSet
  • Added BeanConverter and ISO8601SqlTimestampConverter
  • Fixed support for IBM JVM (contributed by Gabor Liptak)
  • Enhanced mode support for Blackdown JDK.

View the complete change log and download.

Apr 30, 2005 XStream 1.1.2 released

Most popular feature requests implemented.

  • Java 5 Enum support.
  • JavaBeanConverter for serialization using getters and setters.
  • Aliasing of fields.
  • StAX integration, with namespaces.
  • Improved support on JDK 1.3 and IBM JDK.

View the complete change log and download.

Mar 7, 2005 XStream 1.1.1 released

  • Converters can be registered with a priority, allowing more generic filters to handle classes that don't have more specific converters.
  • Converters can now access underlying HierarchicalStreamReader/Writer implementations to make implementation specific calls.
  • Improved support for classes using ObjectInputFields and ObjectInputValidation to follow the serialization specification.
  • Default ClassLoader may be changed using XStream.setClassLoader().
  • Many bugfixes and performance enhancements.

View the complete change log and download.

Jan 15, 2005 XStream 1.1 released

  • Improved support for serializing objects as per the Java Serialization Specification:
    • Calls custom serialization methods, readObject(), writeObject(), readResolve() and writeReplace() in class, if defined.
    • Supports ObjectInputStream.getFields() and ObjectOutputStream.putFields() in custom serialization.
  • Provides implementations of ObjectInputStream and ObjectOutputStream, allowing drop in replacements for standard serialization, including support for streams of objects. [More...]
  • Reads and writes directly to most XML Java APIs: DOM, DOM4J, JDOM, XOM, Electric XML, StAX, Trax (write only), SAX (write only). [More...]

View the complete change log and download.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/issues.html0000664000175000017500000000423312206661545027771 0ustar jamespagejamespage Reporting Issues

XStream tracks and manages its issues in JIRA of Atlassian, that is supported by the Codehaus infrastructure and is free for open source development.

JIRA Account

Before you can report, comment or vote for an issue you need an account in JIRA. You will find in the upper right corner of the JIRA mask a Login link. Follow it and either login if you already have an account otherwise simply sign up. This is necessary to reduce spam in the system and as benefit you can be notified if work is done on your reported issues.

Policy

Please, before opening a new issue look through the open or resolved ones, you may already find your problem. Also do not use the system to ask questions, for that purpose we have a user list. We read the list continuously. If you are unsure whether the problem is caused by a bug or your usage of XStream, use the user's list first. If we can confirm a bug, you may still open an issue. Also do not report on the list that you have created a new issue, we are already notified by the system.

If you like to contribute code, we prefer a patch/diff in contrast to the complete modified file - unless the file itself is new. Please provide also unit tests, XStream has a high test coverage and we like to keep this. Additionally, if you provide new files, please also add a header with the copyright. It must be a BSD license, simply take the header of any other file in the distribution as template. Otherwise we might not be able to add any code of you.

Browse XStream in JIRA now.

jenkins-xstream-1.4.4-jenkins-4/xstream-distribution/src/content/index.html0000664000175000017500000000744212206661545027572 0ustar jamespagejamespage Java to XML serialization, and back again

XStream is a simple library to serialize objects to XML and back again.

Features

  • Ease of use. A high level facade is supplied that simplifies common use cases.
  • No mappings required. Most objects can be serialized without need for specifying mappings.
  • Performance. Speed and low memory footprint are a crucial part of the design, making it suitable for large object graphs or systems with high message throughput.
  • Clean XML. No information is duplicated that can be obtained via reflection. This results in XML that is easier to read for humans and more compact than native Java serialization.
  • Requires no modifications to objects. Serializes internal fields, including private and final. Supports non-public and inner classes. Classes are not required to have default constructor.
  • Full object graph support. Duplicate references encountered in the object-model will be maintained. Supports circular references.
  • Integrates with other XML APIs. By implementing an interface, XStream can serialize directly to/from any tree structure (not just XML).
  • Customizable conversion strategies. Strategies can be registered allowing customization of how particular types are represented as XML.
  • Error messages. When an exception occurs due to malformed XML, detailed diagnostics are provided to help isolate and fix the problem.
  • Alternative output format. The modular design allows other output formats. XStream ships currently with JSON support and morphing.

Typical Uses

  • Transport
  • Persistence
  • Configuration
  • Unit Tests

Known Limitations

If using the enhanced mode, XStream can re-instantiate classes that do not have a default constructor. However, if using a different JVM like an old JRockit version, a JDK 1.4 or you have restrictions because of a SecurityManager, a default constructor is required.

The enhanced mode is also necessary to restore final fields for any JDK < 1.5. This implies deserialization of instances of an inner class.

Auto-detection of annotations may cause race conditions. Preprocessing annotations is safe though.

Getting Started

Latest News

Jan 19, 2013 XStream 1.4.4 released

Maintenance release 1.4.4 of XStream with bug fixes and small improvements.

  • DateConverter supports now localized formats.

View the complete change log and download.

Note, the next major release 1.5 will require Java 6.

Thanks to this impressive list of contributors.

jenkins-xstream-1.4.4-jenkins-4/svn-autoprops.config0000664000175000017500000001157012206661545023160 0ustar jamespagejamespage[auto-props] *.apt = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.c = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.c++ = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.cpp = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.cs = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.css = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.dtd = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.ent = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.fml = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.groovy = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.h = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.h++ = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.hpp = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.html = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.idl = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.include = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.java = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.js = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.jsp = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.ldf = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.ldif = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.mak = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.mdo = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.php = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.rb = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.rtf = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.sql = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.svg = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.t2t = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.vm = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.xhtml = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.xml = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.xsd = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.xsl = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.xslt = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision Makefile = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.launch = svn:eol-style=native *.MF = svn:eol-style=native *.properties = svn:eol-style=native *.script = svn:eol-style=native *.txt = svn:eol-style=native *.dsp = svn:eol-style=CRLF *.dsw = svn:eol-style=CRLF *.iml = svn:eol-style=LF *.bat = svn:eol-style=CRLF;svn:executable;svn:keywords=Author Date Id HeadURL Revision *.cmd = svn:eol-style=CRLF;svn:executable;svn:keywords=Author Date Id HeadURL Revision *.ksh = svn:eol-style=LF;svn:executable;svn:keywords=Author Date Id HeadURL Revision *.sh = svn:eol-style=LF;svn:executable;svn:keywords=Author Date Id HeadURL Revision *.pl = svn:eol-style=native;svn:executable;svn:keywords=Author Date Id HeadURL Revision *.py = svn:eol-style=native;svn:executable;svn:keywords=Author Date Id HeadURL Revision *.bmp = svn:mime-type=image/bmp;svn:needs-lock=* *.gif = svn:mime-type=image/gif;svn:needs-lock=* *.ico = svn:mime-type=image/x-icon;svn:needs-lock=* *.jpeg = svn:mime-type=image/jpeg;svn:needs-lock=* *.jpg = svn:mime-type=image/jpeg;svn:needs-lock=* *.png = svn:mime-type=image/png;svn:needs-lock=* *.tif = svn:mime-type=image/tiff;svn:needs-lock=* *.tiff = svn:mime-type=image/tiff;svn:needs-lock=* *.doc = svn:mime-type=application/msword;svn:needs-lock=* *.jar = svn:mime-type=application/octet-stream;svn:needs-lock=* *.odc = svn:mime-type=application/vnd.oasis.opendocument.chart;svn:needs-lock=* *.odf = svn:mime-type=application/vnd.oasis.opendocument.formula;svn:needs-lock=* *.odg = svn:mime-type=application/vnd.oasis.opendocument.graphics;svn:needs-lock=* *.odi = svn:mime-type=application/vnd.oasis.opendocument.image;svn:needs-lock=* *.odp = svn:mime-type=application/vnd.oasis.opendocument.presentation;svn:needs-lock=* *.ods = svn:mime-type=application/vnd.oasis.opendocument.spreadsheet;svn:needs-lock=* *.odt = svn:mime-type=application/vnd.oasis.opendocument.text;svn:needs-lock=* *.pdf = svn:mime-type=application/pdf;svn:needs-lock=* *.ppt = svn:mime-type=application/vnd.ms-powerpoint;svn:needs-lock=* *.ser = svn:mime-type=application/octet-stream;svn:needs-lock=* *.swf = svn:mime-type=application/x-shockwave-flash;svn:needs-lock=* *.vsd = svn:mime-type=application/x-visio;svn:needs-lock=* *.xls = svn:mime-type=application/vnd.ms-excel;svn:needs-lock=* *.zip = svn:mime-type=application/zip;svn:needs-lock=* jenkins-xstream-1.4.4-jenkins-4/xstream-builder/0000775000175000017500000000000012206661545022234 5ustar jamespagejamespagejenkins-xstream-1.4.4-jenkins-4/xstream-builder/pom.xml0000664000175000017500000000222712206661545023554 0ustar jamespagejamespage 4.0.0 com.thoughtworks.xstream xstream-parent 1.4.2-SNAPSHOT xstream-builder jar XStream Builder ${project.groupId} xstream ${project.version} junit junit jenkins-xstream-1.4.4-jenkins-4/xstream-builder/src/0000775000175000017500000000000012206661545023023 5ustar jamespagejamespagejenkins-xstream-1.4.4-jenkins-4/xstream-builder/src/java/0000775000175000017500000000000012206661545023744 5ustar jamespagejamespagejenkins-xstream-1.4.4-jenkins-4/xstream-builder/src/java/com/0000775000175000017500000000000012206661545024522 5ustar jamespagejamespagejenkins-xstream-1.4.4-jenkins-4/xstream-builder/src/java/com/thoughtworks/0000775000175000017500000000000012206661545027272 5ustar jamespagejamespagejenkins-xstream-1.4.4-jenkins-4/xstream-builder/src/java/com/thoughtworks/xstream/0000775000175000017500000000000012206661545030755 5ustar jamespagejamespagejenkins-xstream-1.4.4-jenkins-4/xstream-builder/src/java/com/thoughtworks/xstream/builder/0000775000175000017500000000000012206661545032403 5ustar jamespagejamespage././@LongLink0000644000000000000000000000015312260544303011640 Lustar rootrootjenkins-xstream-1.4.4-jenkins-4/xstream-builder/src/java/com/thoughtworks/xstream/builder/FieldConfig.javajenkins-xstream-1.4.4-jenkins-4/xstream-builder/src/java/com/thoughtworks/xstream/builder/FieldConfi0000664000175000017500000000310112206661545034323 0ustar jamespagejamespage/* * Copyright (C) 2007 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 13. July 2007 by Guilherme Silveira */ package com.thoughtworks.xstream.builder; import java.util.ArrayList; import java.util.List; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.builder.processor.FieldConfigProcessor; import com.thoughtworks.xstream.builder.processor.TypeConfigProcessor; /** * A field configuration. * * @author Guilherme Silveira * @TODO gs: extract public interface, keep implementation hidden from the end user? */ public class FieldConfig implements TypeConfigProcessor { private final String fieldName; private final List processors; public FieldConfig(String fieldName) { this.fieldName = fieldName; this.processors = new ArrayList(); } public void process(XStream instance, Class type) { for(int i=0;i < processors.size();i++) { FieldConfigProcessor node = (FieldConfigProcessor) processors.get(i); node.process(instance, type, fieldName); } } public FieldConfig with(FieldConfigProcessor []processors) { for (int i = 0; i < processors.length; i++) { FieldConfigProcessor processor = processors[i]; this.processors.add(processor); } return this; } public FieldConfig with(FieldConfigProcessor processor) { this.processors.add(processor); return this; } } ././@LongLink0000644000000000000000000000015612260544303011643 Lustar rootrootjenkins-xstream-1.4.4-jenkins-4/xstream-builder/src/java/com/thoughtworks/xstream/builder/XStreamBuilder.javajenkins-xstream-1.4.4-jenkins-4/xstream-builder/src/java/com/thoughtworks/xstream/builder/XStreamBui0000664000175000017500000000764112206661545034361 0ustar jamespagejamespage/* * Copyright (C) 2007 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 14. May 2007 by Guilherme Silveira */ package com.thoughtworks.xstream.builder; import java.util.ArrayList; import java.util.List; import com.thoughtworks.xstream.ReadOnlyXStream; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.builder.processor.AbsoluteReferencesProcessor; import com.thoughtworks.xstream.builder.processor.AliasFieldProcessor; import com.thoughtworks.xstream.builder.processor.AliasTypeProcessor; import com.thoughtworks.xstream.builder.processor.ConfigProcessor; import com.thoughtworks.xstream.builder.processor.ConverterProcessor; import com.thoughtworks.xstream.builder.processor.FieldConfigProcessor; import com.thoughtworks.xstream.builder.processor.IdReferencesProcessor; import com.thoughtworks.xstream.builder.processor.IgnoreFieldProcessor; import com.thoughtworks.xstream.builder.processor.ImplementedByProcessor; import com.thoughtworks.xstream.builder.processor.NoReferencesProcessor; import com.thoughtworks.xstream.builder.processor.TypeConfigProcessor; import com.thoughtworks.xstream.builder.processor.annotations.AnnotatedTypeProcessor; import com.thoughtworks.xstream.converters.Converter; /** * The base xstream builder. This is xstream's new entrypoint. Instantiate a builder, configure it * and invoke buildXStream at the end. * * @author Guilherme Silveira * @since upcoming */ public class XStreamBuilder { private final List childrenNodes = new ArrayList(); protected TypeConfig handle(Class type) { TypeConfig classConfig = new TypeConfig(type); childrenNodes.add(classConfig); return classConfig; } public ReadOnlyXStream buildXStream() { XStream instance = createBasicInstance(); for(int i=0;i