Discussions

J2EE patterns: iXML Pattern

  1. iXML Pattern (23 messages)

    The following is the XML Representable pattern Implementation. Its very simple and extensible.

    //Interface IXMLRepresentable

    public interface IXMLRepresentable {
      
      String toXML(); //Return the XML output of the Data.
    }


    Implementing the above interface in a Java Object (Value Object is good one to work with)


    import java.io.Serializable;
    public class MyValues implements IXMLRepresentable, Serializable {

         private String firstName;
         private String lastName;


         public String getFirstName() {
            return firstName;
         }

         public void setFirstName(String value) {
            this.firstName=value;
         }

         public String getLastName() {
            return lastName;
         }

         public void setLastName(String value) {
            this.lastName=value;
         }

         public String toXML() {
     
           //Just to show the way xml is outputted

           String myString ="<xml>";
                  myString += "<childrens>";
                  myString += "<child id='firstName'>" + this.firstName + "</child>";
                  myString += "<child id='secondName'>" + this.lastName + "</child>";
                  myString += "</xml>";

    return myString;
         }

    public static void main(String args[]) {
    MyValues my = new MyValues();
    my.setFirstName("Ilya");
    my.setLastName("Netchitailo");
    System.out.println(my.toXML());
    }
    }



    Supporting Patterns:

      Value Object Pattern

    Thanks to my friend Ilya Netchitailo, since we two played a major part in designing and using the above pattern in one of our project.

    Threaded Messages (23)

  2. I know it's java centric, but why not use java.io.Externalizable to write/read to XML? Or better yet, create your own ObjectOutputStream/InputStream to write any object out as XML. You can use introspection to figure out the tag names and have it all automated. THen, your classes don't have to have any XML writing in them. Plus, it would work for sub/super classes:

    public class XMLObjectOutputStream
    {
      public void writeObject(Object o)
      {
        // test for primitive types first
        // if not primitive, then:
        Method methods[] = o.getClass().getMethods();
        for (int i=0;i<methods.length;i++)
        {
          String tagName = methodNameToTag(methods[i]);
          write('<');
          writeString(tagname);
          write('>');
          writeObject(methods[i].invoke(new Object[0]));
          write('<');
          write('/');
          writeString(tagname);
          write('>');
        }
      }
    }

    Obviously, this is pseudo-code (methodToTag needs to be implemented, but it just converts getBlah to blah), and all that but you get the idea.

    This way, your objects aren't tied to one XML representation, nor are they tied to being represented in XML at all. Plus, this automatically handles super classes as well as contained classes.
  3. iXML Pattern[ Go to top ]

    For this purpose would be better to use XML Data Binding:
    1) JSR 31 XML Data Binding Specification
    http://www.jcp.org/jsr/detail/31.jsp

    The proposed specification will define an XML data-binding facility for the JavaTM Platform. Such a facility compiles an XML schema into one or more Java classes. These automatically-generated classes handle the translation between XML documents that follow the schema and interrelated instances of the derived classes. They also ensure that the constraints expressed in the schema are maintained as instances of the classes are manipulated

    2) CASTOR http://www.castor.org/
    Castor is an open source data binding framework for Java[tm]. It's basically the shortest path between Java objects, XML documents, SQL tables and LDAP directories. Castor provides Java to XML binding, Java to SQL/LDAP persistence, and then some more.


    It will reduce your efforts to transform to/from XML - in this case needless to implement toXML() method :)

    Regards,
    Sergey Litsenko
  4. iXML Pattern[ Go to top ]

    IMHO I think tools and standards such as Castor or JAXB provide a much more flexible alternative than hardcoding the XML representation of an object in its toXML() method. If you ever have to use a full XML representation of the business domain, you'll probably wish you had some sort of repository where all the XML mappings are defined so that you could check the consistency of the whole stuff without having to dive into the code of every single domain object.

    And a complete XML architecture would probably imply both Java to XML and XML to Java transformation. This pattern adresses just a small part of the problem. Both Castor and JAXB allow XML to Java transformation.

    That said, and as far as I know, Sun's RI of JAXB makes use of generated classes to provide the XML conversion. Every XMl-representable object has to extend a base class, meaning your object representation of the domain if tightly coupled with a specific technology. Castor doesn't impose such as constraint : a single XML file is enough. Probably just a matter of taste...

    Laurent
  5. iXML Pattern[ Go to top ]

    The quality of posting is diminshing. Calling this a pattern
    is waste of time for everybody. Can you compare this to
    the Visitor pattern (multiple dispatch) which adds
    substantial amount of micro architecture wisdom in the
    practice of programming.

    In other words, I will be suspect of anything, that this
    site calls pattern. Where is the quality of intelectual
    property that I expect in this site?

    Soumen.
  6. iXML Pattern[ Go to top ]

    I agree to "Soumen".

    It would be appreciable if TheServerSide.com can
    moderate such postings titled as 'PATTERN'!

    -RK INDIA
  7. iXML Pattern[ Go to top ]

    ok cool down guyz, sorry for the thread, basically its an idea we got in one of our implementation for Caching in J2EE and I misinterpreted into the pattern threads.
  8. iXML Pattern[ Go to top ]

    Relax Venkatesh, it's not your fault :) What's mis-named is not your post, but TSS's patterns section. All the complaints about this "pattern" can be made about many of the "patterns" in this section.
    I think most of the criticism (at least mine, anyway) is directed at TSS, asking them to provide a more appropriate categorization of posts. There is no harm in posting specific ideas like yours (although I didn't like this one in particular), but when they are all posted as design patterns its hard to figure which posts are actually important design patterns and which aren't without reading each and every post. Some people don't have the time to read every post, and one of the main benefits of a developer community should be the screening of truly important ideas. I usually delete the TSS newsletter two minutes after I get it, because the "pattern" announcements are not screened either and I've been disappointed too many times...

    Gal
  9. iXML Pattern[ Go to top ]

    I don't get it, why you calling it design pattern. These days people started to call "design pattern" design idea.
  10. iXML Pattern[ Go to top ]

    I definately think using JAXB or Castor would be a better idea by far.

    Offtopic: I completely agree with Giedrius, this is not a design pattern: it solves one specific problem, not a recurring design problem. Generally I would say at least 80% of the so-called "patterns" in TSS's patterns section aren't patterns at all.

    Gal
  11. iXML Pattern[ Go to top ]

    I agree that this is not a design pattern. Wouldn't it be better if the TSS had one patterns section for the "real" and already established patterns, and another section with new pattern propositions? That would reduce the risk of having the "design pattern" term lose its proper meaning.

    RD
  12. iXML Pattern[ Go to top ]

    I used JAXB in our project to read/persist XML data. Works
    pretty well. Found some bugs. Worked around them. Do not
    know of SUN's intention of supporting JAXB through bug
    fix releases.

    I find it discouraging to hand write code to read/persist
    to XML. The approach should be declarative within a Java
    XML binding framework and code should be genberated from
    model of Java XML binding.

    Compared to existing Java XML binding framework, this
    so called "pattern" looks like child's play and
    misleading to me.

    Please take a look at JAXB and other XML binding framework
    for your needs and avoid "hand coding". Come on, a good
    programmer is supposed to be lazy by making computer a
    slave. Show some class!

    Soumen.
  13. iXML Pattern[ Go to top ]

    I agree , this is not a pattern, its
    encapsulation so that the internal XML struture may be changed ? people should program like this anyway!

  14. iXML Pattern[ Go to top ]

    I agree with Giedrius when he says it's not a pattern! People should look at what already exists, to solve their problems, instead of creating ideas and name those Design Patterns. I know there is a lot of solutions for XML better than that and I'd like to add a solution I often use here, using the "Visitor Pattern" explained in Gang-of-four's Desing Pattern Book. Basically it consists of defining a interface with save and load methods using w3c.org.dom.Document interface and w3c.org.dom.Element interface. I think the code explain by itself. The Document may be created for another class that start the process of persistance in XML. And I'm using xerces to continue this Idea.

    import org.w3c.dom.Document;
    import org.w3c.dom.Element;


    public interface IXMLPersist{

    public void save(Element parent, Document document);
    public void load(Element parent);

    }

    class DefaultXMLOperations{
    static Element selectChildName(Element element, String tagName){
    //...look for a child inside the element

    return element; //Just for compilation issues
    }
    }

    class Client implements IXMLPersist{

    private String _name;
    private String _companyName;
    private Address _address;

    //...default set get methods

    public void save(Element parent, Document document){

    Element thisElement = document.createElement("client");
    thisElement.setAttribute("name", _name);
    thisElement.setAttribute("companyName", _companyName);


    IXMLPersist xmlPersist = _address;
    xmlPersist.save(thisElement, document);
    parent.appendChild(thisElement);
    }
    public void load(Element parent){

    //There is some Xerces doing this selectChildName but let's encapsulate here;
    Element thisElement = DefaultXMLOperations.selectChildName(parent, "client");

    _name = thisElement.getAttribute("name");
    _companyName = thisElement.getAttribute("company");

    IXMLPersist xmlPersist = _address;
    xmlPersist.load(thisElement);
    }

    }
    class Address implements IXMLPersist{
    private String _address;
    private String _number;
    private String _zipCode;
    private String _state;
    public void save(Element parent, Document document){
    //Save the attribute in a new element
    //
    }
    public void load(Element parent){
    //Load attributes from the selected element;
    }
    }

    This works fine and there is some tricks for Collection issues. I hope that I collaborated with that.

    Pedro Ribeiro Jr
    pedjr2000 at hotmail dot com

    São Paulo Brazil.
  15. iXML Pattern[ Go to top ]

    Okay, you can output, but you cannot input properly.

    I think, the general idea could be borrowed from Perl - "every object is a hash" - and design all your Java objects in a hash-like manner. This way you can easily add properties without rebuilding, and XML persistence becomes obvious.

    Actually, XML itself suggests the structure. An object has attributes and children that are objects themselves - and that will be it. But not as huge as DOM suggests. Not even JDOM. It is too big. On the other hand, something like XPath or XSQL could be useful.

    Well, I've been using this kind of "pattern" (it is not a pattern!) for about two years now. It helps even more that part of my code is Java, part is Perl. Makes you abstract from language peculiarities and look more into functionality.
  16. iXML Pattern[ Go to top ]

    What about using reflection API and diving down the object composition hierarchy?? Is that do-able in general?? And both ways - i.e input and output ?? How would it perform viz-a-viz the binding and class generation schemes?? I am assuming private members have standard getters and setters!
  17. iXML Pattern[ Go to top ]

    JAXB is definitely a better solution, but JAXB still has a long way to go. JAXB is more XML document-centric than object-centric, I mean to say that in JAXB you define the document schema first then generate a class for that object. If you want xml repersentation of a JavaBean, you can use java.beans.XMLEncoder and java.beans.XMLDecoder classes.
  18. iXML Pattern[ Go to top ]

    I agree with Mandar... in this case , using XMLEncoder / XMLDecoder classes are much more easy.I think that using that classes in combination with AOP ( aspects ) could turn this "pattern" more flexible , separating the business logic from output logic.

    See http://www.aspectj.org for more reference

    Leonardo gs
  19. iXML Pattern[ Go to top ]

    Why not use JLF - Java Layered Framework or Apache Jakartas OJB? I would like to have an discussion about these frameworks, they seem pretty useful when reading and writing Java object from/to XML or an RDBMS..
  20. iXML Pattern[ Go to top ]

    Some folks built a framework around this at my company using an interface with toXml() method and a parser that used reflection to reconstitute the bean. It painfully slow and buggy. Everytime an instance variable is added to the bean, the toXml() method needs to be tweaked making maintenance more cumbersome. Also, indexed properties like lists and arrays are a pain the reflection logic, so much so, that the folks at my company didn't bother and produced hacked beans and XML.<br><br>
    Also, the XML produced it kinda flat making monster XML docs on big beans or combos of beans...<br>

  21. iXML Pattern[ Go to top ]

    Just a small thing, but the generated XML is not well formed - there is no </childrens> tag. (By the way, should probably be <children>...</children> anyway).
  22. iXML Pattern[ Go to top ]

    Well, if you are not going to use an elegant solution such as a Java XML binding framework (JAXB, Castor, etc), then at least consider using the visitor and/or builder pattern to walk your objects and generate the appropriate XML documents. That way, you can pass each object that will be a part of the XML document into the builder, have it visit the object and its children, and generate the XML appropriately. This removes the concept of external data representation from the object. For example, what happens if you decide to do CSV and tab-delimited? With this, you build a new visitor to process it appropriately rather than adding a new toCSV() and toTabDelimited() to each class.

    This just goes to show, its hard to add a lot of new design patterns as they are so fundamental that all really just build on them. And that we have a number of Java idioms posted here as "design patterns." I agree, we need to have better moderating and sections defined in TSS.
  23. iXML Pattern[ Go to top ]

    Just one word.....using toXML(), how to support parent/child relationship in case of aggregate or composite objects??? writing if()/else{}, use reflection, use everything u know...but still it is going to be a very dirty and buggy implementation.....better use Castor.....
  24. No aporta nada¡¡[ Go to top ]

    No aporta nada¡¡
    Salu2