User Tag List

Closed Thread
Results 1 to 1 of 1
  1. #1
    Registered User
    Reputation

    Join Date
    Aug 2008
    Last Online
    10-16-2011 @ 10:20 AM
    Location
    New Jersey, USA
    Posts
    27
    Thanks
    0
    Thanked 0 Times in 0 Posts

    [JAVA] xStream (using a library)

    Yes, I created these tutorials; if seen on any other forum usernames would be either Patrick, xpatx, or patrick; Otherwise DeadManH on here.

    Description
    : This tutorial will give you a brief explanation on how to use xStream. XStream is a simple library to serialize objects to XML and back again.
    Difficulty: 3/10 (Just listen)



    What is xStream?

    The Limitations of xStream
    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.3 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. (This was taken from the xStream Web site which can be located at the bottom of this post.)

    Feature's of xStream (taken from the Web site)
    1. Ease of use. A high level facade is supplied that simplifies common use cases.
    2. No mappings required. Most objects can be serialized without need for specifying mappings.
    3. 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.
    4. 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.
    5. 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.
    6. Full object graph support. Duplicate references encountered in the object-model will be maintained. Supports circular references.
    7. Integrates with other XML APIs. By implementing an interface, XStream can serialize directly to/from any tree structure (not just XML).
    8. Customizable conversion strategies. Strategies can be registered allowing customization of how particular types are represented as XML.
    9. Error messages. When an exception occurs due to malformed XML, detailed diagnostics are provided to help isolate and fix the problem.
    10. Alternative output format. The modular design allows other output formats. XStream ships currently with JSON support and morphing.


    How to use xStream?

    xStream is fairly easy to use. After you import your .JAR document's where-ever you want to place them (most likely bin/xstream.jar and bin/xpp.jar). We'll begin the lesson.

    The xStreamManager class is fairly easy written and everytime you need to enherit a new class which requires XML loading you will use xStream. I will show you the whole class first then explain bit by bit what each part of the class does.

    Code:
    package info.pat.eco.util;
    
    import info.pat.eco.model.npc.NPCSpawn;
    
    import java.io.InputStream;
    import java.io.OutputStream;
    
    import com.thoughtworks.xstream.XStream;
    
    public class xStreamManager {
    
        private static XStream xstream;
    
        static {
            xstream = new XStream();
            xstream.alias("npc", NPCSpawn.class);
        }
    
        public static void save(Object object, OutputStream out) {
            xstream.toXML(object, out);
        }
    
        public static Object load(InputStream in) {
            return xstream.fromXML(in);
        }
    
    }
    Code:
    package info.pat.eco.util;
    import info.pat.eco.model.npc.NPCSpawn;
    import java.io.InputStream;
    import java.io.OutputStream;
    import com.thoughtworks.xstream.XStream;
    The first import is used to inherit the class. The second import (NPCSpawn) is used to import the NPCSpawn class which will be used later because it uses XML structures. The third and fourth class can be classified as one import but I did them as two. It's basic IO so you don't really need explanations on that. And the last one is the xStream import which is the import in the .JAR.

    Code:
        private static XStream xstream;
    
        static {
            xstream = new XStream();
            xstream.alias("npc", NPCSpawn.class);
        }
    The first part (above static {) means instead of writing XStream everytime you can inherit the class in this class by typing xstream (basically easier). Under the static { import's the xStream class and it tells you that the NPCSpawn.class is a XML using document.

    Code:
        public static void save(Object object, OutputStream out) {
            xstream.toXML(object, out);
        }
    
        public static Object load(InputStream in) {
            return xstream.fromXML(in);
        }
    Basically it saves the output data, and load's the object (input). Not to hard to understand.

    Code:
    import java.io.FileInputStream;
    import java.util.List;
    
    public class NPCManage 
    {
        
        public static List<NPCSpawn> npcs;
    
        @SuppressWarnings("unchecked")
        public NPCManage() throws Exception {
            npcs = (List<NPCSpawn>) xStreamManager.load(new FileInputStream(
                    "./data/npc/npc.xml"));
            System.out.println(npcs.size() + " npcs loaded.");
        }
        
        public void printNPC() {
            for (NPCSpawn nc : npcs) {
                int npcID = nc.getNpcID();
                int npcX = nc.getNpcX();
                int npcY = nc.getNpcY();
                int npcHeight = nc.getNpcHeight();
    
                System.out.println("");
                System.out.println("npcID: " + npcID);
                System.out.println("npcX: " + npcX);
                System.out.println("npcY: " + npcY);
                System.out.println("npcHeight: " + npcHeight);
                System.out.println("");
            }
        }
    }
    This reads the XML file that will have the NPC's listed.

    Code:
    package info.pat.eco.model.npc;
    
    public class NPCSpawn {
    
        private int npcID;
        private int npcX;
        private int npcY;
        private int npcHeight;
    
        public int getNpcID() {
            return npcID;
        }
    
        public int getNpcX() {
            return npcX;
        }
    
        public int getNpcY() {
            return npcY;
        }
    
        public int getNpcHeight() {
            return npcHeight;
        }
    }
    This enables the variables that will be listed in the XML.

    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
    
    <list>
        <npc>
            <npcID>1</npcID>
            <npcX>3222</npcX>
            <npcY>3222</npcY>
            <npcHeight>0</npcHeight>
        </npc>
        <npc>
            <npcID>2</npcID>
            <npcX>3234</npcX>
            <npcY>3224</npcY>
            <npcHeight>0</npcHeight>
        </npc>    
    </list>
    That is the basic XML file.

    You can use xStream for many other things, so yeah..have fun using xStream :)

    Credits
    1. Patrick - for writing the tutorial
    2. xStream Web site - for copying documentation from it (Except my examples)


    If you want to learn more about xStream please click [Only registered and activated users can see links. ].
    Last edited by DeadManH; 08-07-2009 at 12:44 AM.

Closed Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts