SlideShare a Scribd company logo
1 of 47
Download to read offline
Presented by
Angelin
 Lightweightand easy-to-use open source
 Java™ library

 Usedfor serializing java objects into XML and
 de-serializing XML back into java objects

 Usesreflection API for serialization and
 deserialization
 xstream-[version].jarand xpp3-[version].jar
 are required in the classpath.

 Instantiate
            the XStream class:
      XStream xstream = new XStream();
 To   Serialize an object to a XML String use:
        xstream.toXML(Object obj);


 ToDeserialize an object from an XML String
 use:
        xstream.fromXML(String xml);
import com.thoughtworks.xstream.XStream;
public class HelloWorld {
  public static void main(String[] args) {
        XStream xstream = new XStream();
        String salutation = "Hello, World!";
        String xml = xstream.toXML(salutation);
        System.out.print(xml);
  }
}

Output
<string>Hello, World!</string>
Output
<com.example.Person>
       <name>Joe</name>
       <age>23</age>
       <phone>
               <code>123</code>
               <number>123456</number>
       </phone>
       <fax>
               <code>123</code>
               <number>112233</number>
       </fax>
</com.example.Person>

Name: Joe
Age: 23
Phone:123-123456
Fax:123-112233
   Syntax: xstream.useAttributeFor(Class definedIn, String fieldName);
 Aliasingenables us to use different tag or
  attribute names in the generated XML.
 The different types of aliasing that Xstream
  supports are:
     Class aliasing
     Field aliasing
     Attribute aliasing
     Package aliasing
     Omitting fields and root tag of collection
 Xstream  default serialization nature:
  fully qualified class name <> element name
  corresponding to the class
 Use Class Aliasing to get the class name
  (without the package name) as the XML
  element name
 To create alias for any class' name, use
       xstream.alias(String alias, Class clsname);
   Syntax:
    xstream.alias(String alias, Class clsName);
   Example:
    xstream.alias(“Person", Person.class);

Before Class Aliasing                   After Class Aliasing
<com.example.Person>                    <Person>
        <name>Joe</name>                <name>Joe</name>
        <age>23</age>                   <age>23</age>
        <phone>                         <phone>
          <code>123</code>                <code>123</code>
          <number>123456</number>         <number>123456</number>
        </phone>                        </phone>
        <fax>                           <fax>
          <code>123</code>                <code>123</code>
          <number>112233</number>         <number>112233</number>
        </fax>                          </fax>
</com.example.Person>                   </Person>
   Syntax:
    xstream.aliasField(String alias, Class definedIn, String fieldName);
   Example:
    xstream.aliasField("Name", Person.class, "name");

Before Field Aliasing                   After Field Aliasing
<Person>                                <Person>
<name>Joe</name>                        <Name>Joe</Name>
<age>23</age>                           <age>23</age>
<phone>                                 <phone>
  <code>123</code>                        <code>123</code>
  <number>123456</number>                 <number>123456</number>
</phone>                                </phone>
<fax>                                   <fax>
  <code>123</code>                        <code>123</code>
  <number>112233</number>                 <number>112233</number>
</fax>                                  </fax>
</Person>                               </Person>
   Syntax:
    xstream.aliasAttribute(Class definedIn, String fieldName, String
      alias); // makes field as attribute and sets an alias name for it
   Example:
    xstream.aliasAttribute(PhoneNumber.class, "code", "AreaCode");
    xstream.aliasAttribute(PhoneNumber.class, "number", "Number");

Before Attribute Aliasing         After Attribute Aliasing
<Person>                          <Person>
<name>Joe</name>                  <Name>Joe</Name>
<age>23</age>                     <age>23</age>
<phone>                           <phone AreaCode="123" Number="123456"/>
  <code>123</code>                <fax AreaCode="123" Number="112233"/>
  <number>123456</number>         </Person>
</phone>
<fax>
  <code>123</code>
  <number>112233</number>
</fax>
</Person>
xstream.aliasAttribute(PhoneNumber.class, "code", "AreaCode");
xstream.aliasAttribute(PhoneNumber.class, "number", "Number");


Is equivalent to


xstream.useAttributeFor(PhoneNumber.class, "code");
xstream.aliasField("AreaCode", PhoneNumber.class, "code");


xstream.useAttributeFor(PhoneNumber.class, "number");
xstream.aliasField("Number", PhoneNumber.class, "number");
   Syntax:
    xstream.aliasPackage(String alias, String packageName);
   Example:
    xstream.aliasPackage("my.company", "com.example");

Before Field Aliasing                  After Field Aliasing
<com.example.Person>                   <my.company.Person>
<name>Joe</name>                       <name>Joe</name>
<age>23</age>                          <age>23</age>
<phone>                                <phone>
  <code>123</code>                       <code>123</code>
  <number>123456</number>                <number>123456</number>
</phone>                               </phone>
<fax>                                  <fax>
  <code>123</code>                       <code>123</code>
  <number>112233</number>                <number>112233</number>
</fax>                                 </fax>
</com.example.Person>                  </my.company.Person>
   Syntax:
    xstream.omitField(Class definedIn, String fieldName);
   Syntax:
    xstream.addImplicitCollection(Class definedIn, String collectionName);
 For converting particular types of objects
  found in the object graph, to and from XML.
 Xstream provides converters for primitives,
  String, File, Collections, arrays, and Dates.
 Types:
     Converters for converting common basic types in
      Java into a single String, with no nested
      elements
     Converters for converting items in collections
      such as arrays, Lists, Sets and Maps into nested
      elements
 To customize the information being serialized
  or deserialized.
 They can be implemented and registered
  using the
       XStream.registerConverter() method
 Converters for objects that can store all
  information in a single value should
  implement SingleValueConverter.
   Annotations simplify the process of setting aliases and
    registering converters etc.
   Annotations do not provide more functionality, but may
    improve convenience.

Annotation Types        Description
@XStreamAlias           Annotation used to define an XStream class or
                        field value.
@XStreamAsAttribute     Defines that a field should be serialized as an
                        attribute.
@XStreamConverter       Annotation to declare a converter.
@XStreamImplicit        An annotation for marking a field as an
                        implicit collection.
@XStreamInclude         Annotation to force automated processing of
                        further classes.
@XStreamOmitField       Declares a field to be omitted.
 processAnnotation() method to configure
  Xstream to process annotations defined in
  classes
 All super types, implemented interfaces, the
  class types of the members and all their generic
  types will be processed.
 For e.g. the statement
       xstream.processAnnotations(Person.class);
  will also process the annotations of its member
  of type Company. So there is no need to
  explicitly configure processAnnotation() for the
  class Company.
 XStream  can also be run in a lazy mode,
  where it auto-detects the annotations while
  processing the object graph and configures
  the XStream instance on-the-fly.
 Example:
   XStream xstream = new XStream() {
      {
        autodetectAnnotations(true);
      }
   };
Implications of using autodetectAnnotations
 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
 May cause thread-unsafe operation
 will slow down the marshalling process until all
  processed types have been examined once.
   Annotation used to define an XStream class or field value.

Xstream method                        Equivalent Xstream
                                      Annotation
xstream.alias("Person", Person.class); @XStreamAlias("Person")
                                       public class Person {
                                       ...
                                       ...
                                       }
   Defines that a field should be serialized as an attribute.

Xstream method                         Equivalent Xstream
                                       Annotation
xstream.aliasAttribute(Person.class,   @XStreamAlias("Person")
"company", "Company");                 public class Person {
                                       ...
                                       ...
                                       @XStreamAsAttribute
                                       @XStreamAlias("Company")
                                       private Company company;
                                       ...
                                       ...
                                       }
   Annotation to declare a converter.

Xstream method                  Equivalent Xstream Annotation
xstream.registerConverter(new   @XStreamConverter(CompanyConverter.class)
CompanyConverter());            public class Company {
                                ...
                                }

   To register the custom converter locally, i.e. only for the
    member variable company defined in the Person class
Xstream method                   Equivalent Xstream Annotation

xstream.registerConverter(new    @XStreamAlias("Person")
CompanyConverter());             public class Person {
                                 ...
                                 @XStreamAsAttribute
                                 @XstreamAlias("Company")
                                 @XStreamConverter(CompanyConverter.class)
                                 private Company company;
                                 ...
                                 }
   An annotation for marking a field as an implicit collection.

Xstream method                     Equivalent Xstream Annotation
xstream.addImplicitCollection(Cu @XStreamAlias("Customers")
stomers.class, "customers");     public class Customers {
                                 @XStreamImplicit
                                 private List customers;
                                 ...
                                 ...
                                 }
   Declares a field to be omitted.

Xstream method                    Equivalent Xstream Annotation
xstream.omitField(Person.class,   @XStreamAlias("Person")
"phone");                         public class Person {
                                  ...
                                  @XStreamOmitField
                                  private PhoneNumber phone;
                                  @XStreamOmitField
                                  private PhoneNumber fax;
                                  ...
                                  }
   Used by base classes to improve annotation processing when
    deserializing.
   Example:
   Annotation processing using autodetectAnnotations
   Annotation processing using processAnnotations
XStream
XStream

More Related Content

What's hot

Why is Haskell so hard! (And how to deal with it?)
Why is Haskell so hard! (And how to deal with it?)Why is Haskell so hard! (And how to deal with it?)
Why is Haskell so hard! (And how to deal with it?)Saurabh Nanda
 
Core (Data Model) of WordPress Core
Core (Data Model) of WordPress CoreCore (Data Model) of WordPress Core
Core (Data Model) of WordPress CoreJake Goldman
 
The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212Mahmoud Samir Fayed
 
DeprecatedAPI로 알아보는 SwiftUI
DeprecatedAPI로 알아보는 SwiftUIDeprecatedAPI로 알아보는 SwiftUI
DeprecatedAPI로 알아보는 SwiftUIBongwon Lee
 
Sql server difference faqs- 3
Sql server difference faqs- 3Sql server difference faqs- 3
Sql server difference faqs- 3Umar Ali
 
Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3Karsten Dambekalns
 
The Ring programming language version 1.5.3 book - Part 37 of 184
The Ring programming language version 1.5.3 book - Part 37 of 184The Ring programming language version 1.5.3 book - Part 37 of 184
The Ring programming language version 1.5.3 book - Part 37 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 28 of 88
The Ring programming language version 1.3 book - Part 28 of 88The Ring programming language version 1.3 book - Part 28 of 88
The Ring programming language version 1.3 book - Part 28 of 88Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 49 of 196
The Ring programming language version 1.7 book - Part 49 of 196The Ring programming language version 1.7 book - Part 49 of 196
The Ring programming language version 1.7 book - Part 49 of 196Mahmoud Samir Fayed
 
David Kopal - Unleash the power of the higher-order components
David Kopal - Unleash the power of the higher-order componentsDavid Kopal - Unleash the power of the higher-order components
David Kopal - Unleash the power of the higher-order componentsOdessaJS Conf
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapHoward Lewis Ship
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v RubyJano Suchal
 

What's hot (20)

Why is Haskell so hard! (And how to deal with it?)
Why is Haskell so hard! (And how to deal with it?)Why is Haskell so hard! (And how to deal with it?)
Why is Haskell so hard! (And how to deal with it?)
 
Core (Data Model) of WordPress Core
Core (Data Model) of WordPress CoreCore (Data Model) of WordPress Core
Core (Data Model) of WordPress Core
 
Xm lparsers
Xm lparsersXm lparsers
Xm lparsers
 
The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212
 
Python Day1
Python Day1Python Day1
Python Day1
 
DeprecatedAPI로 알아보는 SwiftUI
DeprecatedAPI로 알아보는 SwiftUIDeprecatedAPI로 알아보는 SwiftUI
DeprecatedAPI로 알아보는 SwiftUI
 
Sql server difference faqs- 3
Sql server difference faqs- 3Sql server difference faqs- 3
Sql server difference faqs- 3
 
Database security
Database securityDatabase security
Database security
 
[Amis] SET in SQL
[Amis] SET in SQL[Amis] SET in SQL
[Amis] SET in SQL
 
Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3
 
Clojure Deep Dive
Clojure Deep DiveClojure Deep Dive
Clojure Deep Dive
 
The Ring programming language version 1.5.3 book - Part 37 of 184
The Ring programming language version 1.5.3 book - Part 37 of 184The Ring programming language version 1.5.3 book - Part 37 of 184
The Ring programming language version 1.5.3 book - Part 37 of 184
 
The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185
 
jQuery
jQueryjQuery
jQuery
 
Prototype Framework
Prototype FrameworkPrototype Framework
Prototype Framework
 
The Ring programming language version 1.3 book - Part 28 of 88
The Ring programming language version 1.3 book - Part 28 of 88The Ring programming language version 1.3 book - Part 28 of 88
The Ring programming language version 1.3 book - Part 28 of 88
 
The Ring programming language version 1.7 book - Part 49 of 196
The Ring programming language version 1.7 book - Part 49 of 196The Ring programming language version 1.7 book - Part 49 of 196
The Ring programming language version 1.7 book - Part 49 of 196
 
David Kopal - Unleash the power of the higher-order components
David Kopal - Unleash the power of the higher-order componentsDavid Kopal - Unleash the power of the higher-order components
David Kopal - Unleash the power of the higher-order components
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter Bootstrap
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 

Similar to XStream

Native XML processing in C++ (BoostCon'11)
Native XML processing in C++ (BoostCon'11)Native XML processing in C++ (BoostCon'11)
Native XML processing in C++ (BoostCon'11)Sumant Tambe
 
Java architecture for xml binding
Java architecture for xml bindingJava architecture for xml binding
Java architecture for xml bindingHosein Zare
 
Generation_XSD_Article - Part 4.pdf
Generation_XSD_Article - Part 4.pdfGeneration_XSD_Article - Part 4.pdf
Generation_XSD_Article - Part 4.pdfDavid Harrison
 
SAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginnersSAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginnersHicham QAISSI
 
More Stored Procedures and MUMPS for DivConq
More Stored Procedures and  MUMPS for DivConqMore Stored Procedures and  MUMPS for DivConq
More Stored Procedures and MUMPS for DivConqeTimeline, LLC
 
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML SchemaRaji Ghawi
 
Generation_XSD_Article - Part 3.pdf
Generation_XSD_Article - Part 3.pdfGeneration_XSD_Article - Part 3.pdf
Generation_XSD_Article - Part 3.pdfDavid Harrison
 
Advanced Web Programming Chapter 12
Advanced Web Programming Chapter 12Advanced Web Programming Chapter 12
Advanced Web Programming Chapter 12RohanMistry15
 
Generation_XSD_Article - Part 2.pdf
Generation_XSD_Article - Part 2.pdfGeneration_XSD_Article - Part 2.pdf
Generation_XSD_Article - Part 2.pdfDavid Harrison
 
SXML: S-expression eXtensible Markup Language
SXML: S-expression eXtensible Markup LanguageSXML: S-expression eXtensible Markup Language
SXML: S-expression eXtensible Markup Languageelliando dias
 
JSR 172: XML Parsing in MIDP
JSR 172: XML Parsing in MIDPJSR 172: XML Parsing in MIDP
JSR 172: XML Parsing in MIDPJussi Pohjolainen
 
Cassandra Client Tutorial
Cassandra Client TutorialCassandra Client Tutorial
Cassandra Client TutorialJoe McTee
 
C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLMohammad Shaker
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعةشرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعةجامعة القدس المفتوحة
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 

Similar to XStream (20)

Native XML processing in C++ (BoostCon'11)
Native XML processing in C++ (BoostCon'11)Native XML processing in C++ (BoostCon'11)
Native XML processing in C++ (BoostCon'11)
 
Java architecture for xml binding
Java architecture for xml bindingJava architecture for xml binding
Java architecture for xml binding
 
Generation_XSD_Article - Part 4.pdf
Generation_XSD_Article - Part 4.pdfGeneration_XSD_Article - Part 4.pdf
Generation_XSD_Article - Part 4.pdf
 
SAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginnersSAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginners
 
More Stored Procedures and MUMPS for DivConq
More Stored Procedures and  MUMPS for DivConqMore Stored Procedures and  MUMPS for DivConq
More Stored Procedures and MUMPS for DivConq
 
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML Schema
 
Generation_XSD_Article - Part 3.pdf
Generation_XSD_Article - Part 3.pdfGeneration_XSD_Article - Part 3.pdf
Generation_XSD_Article - Part 3.pdf
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
 
Advanced Web Programming Chapter 12
Advanced Web Programming Chapter 12Advanced Web Programming Chapter 12
Advanced Web Programming Chapter 12
 
Generation_XSD_Article - Part 2.pdf
Generation_XSD_Article - Part 2.pdfGeneration_XSD_Article - Part 2.pdf
Generation_XSD_Article - Part 2.pdf
 
SXML: S-expression eXtensible Markup Language
SXML: S-expression eXtensible Markup LanguageSXML: S-expression eXtensible Markup Language
SXML: S-expression eXtensible Markup Language
 
JSR 172: XML Parsing in MIDP
JSR 172: XML Parsing in MIDPJSR 172: XML Parsing in MIDP
JSR 172: XML Parsing in MIDP
 
03 structures
03 structures03 structures
03 structures
 
Cassandra Client Tutorial
Cassandra Client TutorialCassandra Client Tutorial
Cassandra Client Tutorial
 
C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XML
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعةشرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
XSS - Attacks & Defense
XSS - Attacks & DefenseXSS - Attacks & Defense
XSS - Attacks & Defense
 
.NET F# Class constructor
.NET F# Class constructor.NET F# Class constructor
.NET F# Class constructor
 
Overloading of io stream operators
Overloading of io stream operatorsOverloading of io stream operators
Overloading of io stream operators
 

More from Angelin R

Comparison of Java Web Application Frameworks
Comparison of Java Web Application FrameworksComparison of Java Web Application Frameworks
Comparison of Java Web Application FrameworksAngelin R
 
[DOC] Java - Code Analysis using SonarQube
[DOC] Java - Code Analysis using SonarQube[DOC] Java - Code Analysis using SonarQube
[DOC] Java - Code Analysis using SonarQubeAngelin R
 
Java Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQubeJava Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQubeAngelin R
 
The principles of good programming
The principles of good programmingThe principles of good programming
The principles of good programmingAngelin R
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Angelin R
 
A Slice of Me
A Slice of MeA Slice of Me
A Slice of MeAngelin R
 
Team Leader - 30 Essential Traits
Team Leader - 30 Essential TraitsTeam Leader - 30 Essential Traits
Team Leader - 30 Essential TraitsAngelin R
 
Action Script
Action ScriptAction Script
Action ScriptAngelin R
 
Agile SCRUM Methodology
Agile SCRUM MethodologyAgile SCRUM Methodology
Agile SCRUM MethodologyAngelin R
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practicesAngelin R
 
Tamil Christian Worship Songs
Tamil Christian Worship SongsTamil Christian Worship Songs
Tamil Christian Worship SongsAngelin R
 
Flex MXML Programming
Flex MXML ProgrammingFlex MXML Programming
Flex MXML ProgrammingAngelin R
 
Introduction to Adobe Flex
Introduction to Adobe FlexIntroduction to Adobe Flex
Introduction to Adobe FlexAngelin R
 
Software Development Life Cycle (SDLC)
Software Development Life Cycle (SDLC)Software Development Life Cycle (SDLC)
Software Development Life Cycle (SDLC)Angelin R
 
Restful Web Services
Restful Web ServicesRestful Web Services
Restful Web ServicesAngelin R
 
Effective Team Work Model
Effective Team Work ModelEffective Team Work Model
Effective Team Work ModelAngelin R
 
Team Building Activities
Team Building ActivitiesTeam Building Activities
Team Building ActivitiesAngelin R
 

More from Angelin R (17)

Comparison of Java Web Application Frameworks
Comparison of Java Web Application FrameworksComparison of Java Web Application Frameworks
Comparison of Java Web Application Frameworks
 
[DOC] Java - Code Analysis using SonarQube
[DOC] Java - Code Analysis using SonarQube[DOC] Java - Code Analysis using SonarQube
[DOC] Java - Code Analysis using SonarQube
 
Java Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQubeJava Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQube
 
The principles of good programming
The principles of good programmingThe principles of good programming
The principles of good programming
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)
 
A Slice of Me
A Slice of MeA Slice of Me
A Slice of Me
 
Team Leader - 30 Essential Traits
Team Leader - 30 Essential TraitsTeam Leader - 30 Essential Traits
Team Leader - 30 Essential Traits
 
Action Script
Action ScriptAction Script
Action Script
 
Agile SCRUM Methodology
Agile SCRUM MethodologyAgile SCRUM Methodology
Agile SCRUM Methodology
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practices
 
Tamil Christian Worship Songs
Tamil Christian Worship SongsTamil Christian Worship Songs
Tamil Christian Worship Songs
 
Flex MXML Programming
Flex MXML ProgrammingFlex MXML Programming
Flex MXML Programming
 
Introduction to Adobe Flex
Introduction to Adobe FlexIntroduction to Adobe Flex
Introduction to Adobe Flex
 
Software Development Life Cycle (SDLC)
Software Development Life Cycle (SDLC)Software Development Life Cycle (SDLC)
Software Development Life Cycle (SDLC)
 
Restful Web Services
Restful Web ServicesRestful Web Services
Restful Web Services
 
Effective Team Work Model
Effective Team Work ModelEffective Team Work Model
Effective Team Work Model
 
Team Building Activities
Team Building ActivitiesTeam Building Activities
Team Building Activities
 

Recently uploaded

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Recently uploaded (20)

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

XStream

  • 2.  Lightweightand easy-to-use open source Java™ library  Usedfor serializing java objects into XML and de-serializing XML back into java objects  Usesreflection API for serialization and deserialization
  • 3.  xstream-[version].jarand xpp3-[version].jar are required in the classpath.  Instantiate the XStream class: XStream xstream = new XStream();
  • 4.  To Serialize an object to a XML String use: xstream.toXML(Object obj);  ToDeserialize an object from an XML String use: xstream.fromXML(String xml);
  • 5. import com.thoughtworks.xstream.XStream; public class HelloWorld { public static void main(String[] args) { XStream xstream = new XStream(); String salutation = "Hello, World!"; String xml = xstream.toXML(salutation); System.out.print(xml); } } Output <string>Hello, World!</string>
  • 6.
  • 7.
  • 8.
  • 9.
  • 10. Output <com.example.Person> <name>Joe</name> <age>23</age> <phone> <code>123</code> <number>123456</number> </phone> <fax> <code>123</code> <number>112233</number> </fax> </com.example.Person> Name: Joe Age: 23 Phone:123-123456 Fax:123-112233
  • 11. Syntax: xstream.useAttributeFor(Class definedIn, String fieldName);
  • 12.  Aliasingenables us to use different tag or attribute names in the generated XML.  The different types of aliasing that Xstream supports are:  Class aliasing  Field aliasing  Attribute aliasing  Package aliasing  Omitting fields and root tag of collection
  • 13.  Xstream default serialization nature: fully qualified class name <> element name corresponding to the class  Use Class Aliasing to get the class name (without the package name) as the XML element name  To create alias for any class' name, use xstream.alias(String alias, Class clsname);
  • 14. Syntax: xstream.alias(String alias, Class clsName);  Example: xstream.alias(“Person", Person.class); Before Class Aliasing After Class Aliasing <com.example.Person> <Person> <name>Joe</name> <name>Joe</name> <age>23</age> <age>23</age> <phone> <phone> <code>123</code> <code>123</code> <number>123456</number> <number>123456</number> </phone> </phone> <fax> <fax> <code>123</code> <code>123</code> <number>112233</number> <number>112233</number> </fax> </fax> </com.example.Person> </Person>
  • 15. Syntax: xstream.aliasField(String alias, Class definedIn, String fieldName);  Example: xstream.aliasField("Name", Person.class, "name"); Before Field Aliasing After Field Aliasing <Person> <Person> <name>Joe</name> <Name>Joe</Name> <age>23</age> <age>23</age> <phone> <phone> <code>123</code> <code>123</code> <number>123456</number> <number>123456</number> </phone> </phone> <fax> <fax> <code>123</code> <code>123</code> <number>112233</number> <number>112233</number> </fax> </fax> </Person> </Person>
  • 16. Syntax: xstream.aliasAttribute(Class definedIn, String fieldName, String alias); // makes field as attribute and sets an alias name for it  Example: xstream.aliasAttribute(PhoneNumber.class, "code", "AreaCode"); xstream.aliasAttribute(PhoneNumber.class, "number", "Number"); Before Attribute Aliasing After Attribute Aliasing <Person> <Person> <name>Joe</name> <Name>Joe</Name> <age>23</age> <age>23</age> <phone> <phone AreaCode="123" Number="123456"/> <code>123</code> <fax AreaCode="123" Number="112233"/> <number>123456</number> </Person> </phone> <fax> <code>123</code> <number>112233</number> </fax> </Person>
  • 17. xstream.aliasAttribute(PhoneNumber.class, "code", "AreaCode"); xstream.aliasAttribute(PhoneNumber.class, "number", "Number"); Is equivalent to xstream.useAttributeFor(PhoneNumber.class, "code"); xstream.aliasField("AreaCode", PhoneNumber.class, "code"); xstream.useAttributeFor(PhoneNumber.class, "number"); xstream.aliasField("Number", PhoneNumber.class, "number");
  • 18. Syntax: xstream.aliasPackage(String alias, String packageName);  Example: xstream.aliasPackage("my.company", "com.example"); Before Field Aliasing After Field Aliasing <com.example.Person> <my.company.Person> <name>Joe</name> <name>Joe</name> <age>23</age> <age>23</age> <phone> <phone> <code>123</code> <code>123</code> <number>123456</number> <number>123456</number> </phone> </phone> <fax> <fax> <code>123</code> <code>123</code> <number>112233</number> <number>112233</number> </fax> </fax> </com.example.Person> </my.company.Person>
  • 19. Syntax: xstream.omitField(Class definedIn, String fieldName);
  • 20.
  • 21.
  • 22.
  • 23. Syntax: xstream.addImplicitCollection(Class definedIn, String collectionName);
  • 24.
  • 25.  For converting particular types of objects found in the object graph, to and from XML.  Xstream provides converters for primitives, String, File, Collections, arrays, and Dates.  Types:  Converters for converting common basic types in Java into a single String, with no nested elements  Converters for converting items in collections such as arrays, Lists, Sets and Maps into nested elements
  • 26.
  • 27.
  • 28.
  • 29.  To customize the information being serialized or deserialized.  They can be implemented and registered using the XStream.registerConverter() method  Converters for objects that can store all information in a single value should implement SingleValueConverter.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34. Annotations simplify the process of setting aliases and registering converters etc.  Annotations do not provide more functionality, but may improve convenience. Annotation Types Description @XStreamAlias Annotation used to define an XStream class or field value. @XStreamAsAttribute Defines that a field should be serialized as an attribute. @XStreamConverter Annotation to declare a converter. @XStreamImplicit An annotation for marking a field as an implicit collection. @XStreamInclude Annotation to force automated processing of further classes. @XStreamOmitField Declares a field to be omitted.
  • 35.  processAnnotation() method to configure Xstream to process annotations defined in classes  All super types, implemented interfaces, the class types of the members and all their generic types will be processed.  For e.g. the statement xstream.processAnnotations(Person.class); will also process the annotations of its member of type Company. So there is no need to explicitly configure processAnnotation() for the class Company.
  • 36.  XStream can also be run in a lazy mode, where it auto-detects the annotations while processing the object graph and configures the XStream instance on-the-fly.  Example: XStream xstream = new XStream() { { autodetectAnnotations(true); } };
  • 37. Implications of using autodetectAnnotations  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  May cause thread-unsafe operation  will slow down the marshalling process until all processed types have been examined once.
  • 38. Annotation used to define an XStream class or field value. Xstream method Equivalent Xstream Annotation xstream.alias("Person", Person.class); @XStreamAlias("Person") public class Person { ... ... }
  • 39. Defines that a field should be serialized as an attribute. Xstream method Equivalent Xstream Annotation xstream.aliasAttribute(Person.class, @XStreamAlias("Person") "company", "Company"); public class Person { ... ... @XStreamAsAttribute @XStreamAlias("Company") private Company company; ... ... }
  • 40. Annotation to declare a converter. Xstream method Equivalent Xstream Annotation xstream.registerConverter(new @XStreamConverter(CompanyConverter.class) CompanyConverter()); public class Company { ... }  To register the custom converter locally, i.e. only for the member variable company defined in the Person class Xstream method Equivalent Xstream Annotation xstream.registerConverter(new @XStreamAlias("Person") CompanyConverter()); public class Person { ... @XStreamAsAttribute @XstreamAlias("Company") @XStreamConverter(CompanyConverter.class) private Company company; ... }
  • 41. An annotation for marking a field as an implicit collection. Xstream method Equivalent Xstream Annotation xstream.addImplicitCollection(Cu @XStreamAlias("Customers") stomers.class, "customers"); public class Customers { @XStreamImplicit private List customers; ... ... }
  • 42. Declares a field to be omitted. Xstream method Equivalent Xstream Annotation xstream.omitField(Person.class, @XStreamAlias("Person") "phone"); public class Person { ... @XStreamOmitField private PhoneNumber phone; @XStreamOmitField private PhoneNumber fax; ... }
  • 43. Used by base classes to improve annotation processing when deserializing.  Example:
  • 44. Annotation processing using autodetectAnnotations
  • 45. Annotation processing using processAnnotations