SlideShare uma empresa Scribd logo
1 de 47
Baixar para ler 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

Mais conteúdo relacionado

Mais procurados

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
OdessaJS Conf
 

Mais procurados (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
 

Semelhante a XStream

SXML: S-expression eXtensible Markup Language
SXML: S-expression eXtensible Markup LanguageSXML: S-expression eXtensible Markup Language
SXML: S-expression eXtensible Markup Language
elliando dias
 
JSR 172: XML Parsing in MIDP
JSR 172: XML Parsing in MIDPJSR 172: XML Parsing in MIDP
JSR 172: XML Parsing in MIDP
Jussi Pohjolainen
 

Semelhante a 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
 

Mais de Angelin R

Agile SCRUM Methodology
Agile SCRUM MethodologyAgile SCRUM Methodology
Agile SCRUM Methodology
Angelin R
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practices
Angelin R
 
Tamil Christian Worship Songs
Tamil Christian Worship SongsTamil Christian Worship Songs
Tamil Christian Worship Songs
Angelin R
 

Mais de 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
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

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