Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.sapia.util.xml.confix;
  
  
  // Import of dom4j classes
  // ----------------------
  import org.dom4j.Document;
 
 
 
 // Import of Sapia's utility classes
 // ---------------------------------
 
 // Import of Sun's JDK classes
 // ---------------------------
 
 import java.util.List;

This class creates an object graph for a given XML input stream. It internally uses Dom4J to transform the stream into a document object model, and then to create objects from the elements found in the document.

Usage:

 ObjectFactoryIF fac = new ReflectionFactory("com.newtrade.company");
 Dom4jProcessor proc = new Dom4jProcessor(fac);
 Company comp = (Company)proc.process(new FileInputStream("d:/dev/company.xml"));
 

Author(s):
Yanick Duchesne
Copyright:
Copyright &.169; 2002-2003 Sapia Open Source Software. All Rights Reserved.
License:
Read the license.txt file of the jar or visit the license page at the Sapia OSS web site
 
 public class Dom4jProcessor extends AbstractXMLProcessor {
   /////////////////////////////////////////////////////////////////////////////////////////
   ////////////////////////////////////  CONSTRUCTORS  /////////////////////////////////////
   /////////////////////////////////////////////////////////////////////////////////////////
   
  
Creates a new JDOMProcessor instance with the argument passed in.

Parameters:
anObjectFactory The object factory of this processor.
 
   public Dom4jProcessor(ObjectFactoryIF anObjectFactory) {
     super(anObjectFactory);
   }
   
   /////////////////////////////////////////////////////////////////////////////////////////
   //////////////////////////////////  OVERRIDEN METHODS  //////////////////////////////////
   /////////////////////////////////////////////////////////////////////////////////////////
   
  
This method takes an XML stream as input and returns an object representation of the passed-in XML.

Parameters:
is an XML stream
Returns:
an object representation of the XML stream.
Throws:
org.sapia.util.xml.ProcessingException
 
   public Object process(InputStream isthrows ProcessingException {
     try {
       // Build the document from the input stream
       SAXReader  builder = new SAXReader();
       builder.setStripWhitespaceText(false);
       builder.setMergeAdjacentText(false);
       Document   doc = builder.read(is);
       
       // Process the document
       Object aResult = process(nulldoc.getRootElement());
       
       return aResult;
     } catch (DocumentException de) {
       String aMessage = "Error parsing the XML of the input stream.";
       throw new ProcessingException(aMessagede);
     } finally {
       try {
         if (is != null) {
           is.close();
         }
      } catch (IOException ioe) {
        String aMessage = "Error closing the input stream to process.";
        
        throw new ProcessingException(aMessageioe);
      }
    }
  }
  
  
This method takes an object and assigns to it the object representation of the passed XML stream.

Parameters:
root an Object that is the root of the object graph to create from the given XML.
is an XML InputStream.
Throws:
org.sapia.util.xml.ProcessingException if an error occurs while processing the given XML stream.
  public void process(Object rootInputStream isthrows ProcessingException {
    try {
      // Build the document from the input stream
      SAXReader reader = new SAXReader();
      Document   doc = reader.read(is);
      
      // Process the document
      Object aResult = process(rootdoc.getRootElement());
    } catch (DocumentException de) {
      String aMessage = "Error parsing the XML of the input stream.";
      throw new ProcessingException(aMessagede);
    } finally {
      try {
        if (is != null) {
          is.close();
        }
      } catch (IOException ioe) {
        String aMessage = "Error closing the input stream to process.";
        
        throw new ProcessingException(aMessageioe);
      }
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////  HELPER METHODS  ////////////////////////////////////
  /////////////////////////////////////////////////////////////////////////////////////////
  
  
This method will process the dom element passed in to create an object.

Parameters:
aParent The parent object of the one to create.
anElement The dom element to process.
Throws:
org.sapia.util.xml.ProcessingException If an error occurs while processing the dom tree.
  public Object process(Object aParentElement anElement)
  throws ProcessingException {
    return process(aParentanElementnull);
  }
  
  private Object process(Object aParentElement anElementString setterName)
  throws ProcessingException {
    String aName = anElement.getName();
    
    if (setterName == null) {
      setterName = aName;
    }
    
    CreationStatus status = null;
    
    try {
      status = getObjectFactory().newObjectFor(anElement.getNamespace()
      .getPrefix(),
        anElement.getNamespace().getURI(), aNameaParent);
    } catch (ObjectCreationException oce) {
      if (aParent == null) {
        String aMessage = "Unable to create an object for the element " +
          anElement;
        
        throw new ProcessingException(aMessageoce);
      }
      List children;
      if ((aParent != null) &&
        (containsMethod("set"aParentaName) ||
        containsMethod("add"aParentaName)) &&
        ((children = anElement.elements()).size() == 1)) {
        Element child = (Elementchildren.get(0);
        process(aParentchildsetterName);
        
        return aParent;
      }
      
      try {
        String aValue = anElement.getTextTrim();
        
        invokeSetter(aParent.getClass().getName(), aParentaNameaValue);
        
        return aParent;
      } catch (ConfigurationException ce) {
        String aMessage =
          "Unable to create an object nor to call a setter for the element " +
          anElement;
        oce.printStackTrace();
        throw new ProcessingException(aMessagece);
      }
    }
    
    String text = anElement.getTextTrim();
    
    if (text.length() > 0) {
      try {
        invokeSetter(aNamestatus.getCreated(), "Text"text);
      } catch (ConfigurationException ce) {
        String aMessage = "The object '" + aName +
          "' does not accept free text";
        
        throw new ProcessingException(aMessagece);
      }
    }
    
    try {
      // Process the attributes of the DOM element
      for (Iterator it = anElement.attributeIterator(); it.hasNext();) {
        Attribute attr = (Attributeit.next();
        
        invokeSetter(aNamestatus.getCreated(), attr.getName(), attr.getValue());
      }
      
      // Process the child elements
      for (Iterator it = anElement.elementIterator(); it.hasNext();) {
        Element child = (Elementit.next();
        
        if (status.getCreated() instanceof Dom4jHandlerIF) {
          ((Dom4jHandlerIFstatus.getCreated()).handleElement(child);
        } else if(status.getCreated() instanceof XMLConsumer) {
          XMLConsumer cons = (XMLConsumer)status.getCreated();
          ByteArrayOutputStream bos = new ByteArrayOutputStream();
          XMLWriter writer;
          try{
            writer = new XMLWriter(bos, OutputFormat.createPrettyPrint());
          }catch(UnsupportedEncodingException e){
            throw new ProcessingException("Could not instantiate XMLWriter"e);
          }
          
          try{
            Element copy = child.createCopy();
            copy.setDocument(null);
            writer.write(DocumentHelper.createDocument(copy));
            ByteArrayInputStream in = new ByteArrayInputStream(bos.toByteArray());
            InputSource is = new InputSource(in);
            cons.consume(is);
          }catch(Exception e){
            throw new ProcessingException("Could not pipe content of element: " + child.getQualifiedName() + " to XMLConsumer"e);
          }
        } else {
          process(status.getCreated(), child);
        }
      }
      
      // before assigning to parent, check if object
      // implements ObjectCreationCallback.
      if (status.getCreated() instanceof ObjectCreationCallback) {
        status._created = ((ObjectCreationCallbackstatus.getCreated()).onCreate();
      }
      
      // assign obj to parent through setXXX or addXXX
      if ((aParent != null) && !status.wasAssigned() &&
        !(status.getCreated() instanceof NullObject)) {
        assignToParent(aParentstatus.getCreated(), setterName);
      }
      
      if (status.getCreated() instanceof NullObject) {
        return null;
      }
      
      return status.getCreated();
    } catch (ConfigurationException ce) {
      String aMessage = "Unable to process the content of the element " +
        aName;
      
      throw new ProcessingException(aMessagece);
    }
  }
New to GrepCode? Check out our FAQ X