Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.sapia.util.xml.idefix;
  
  
  // Import of Sapia's utility classes
  // ---------------------------------
  
 // Import of Sun's JDK classes
 // ---------------------------
 import java.util.Map;


Author(s):
Jean-Cedric Desrochers
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 XmlBuffer {
   /////////////////////////////////////////////////////////////////////////////////////////
   //////////////////////////////////  CLASS ATTRIBUTES  ///////////////////////////////////
   /////////////////////////////////////////////////////////////////////////////////////////
 
  
Defines the default character encoding.
 
   public static final String DEFAULT_CHARACTER_ENCODING = "UTF-8";
 
   /////////////////////////////////////////////////////////////////////////////////////////
   /////////////////////////////////  INSTANCE ATTRIBUTES  /////////////////////////////////
   /////////////////////////////////////////////////////////////////////////////////////////
 
  
The XML scribe instance to generate the XML strings.
 
   private XmlScribe _theScribe;

  
The internal string buffer of this xml buffer.
 
   private StringBuffer _theBuffer;

  
Indicates if the buffer contains an xml declaration or not.
 
   private boolean _useXmlDeclaration;

  
The encoding of this xml buffer.
 
   private String _theCharacterEncoding;

  
The map of namespace definition by URI
 
   private Map _theNamespaceByURI;

  
The list of buffer states.
 
   private LinkedList _theStates;
 
   /////////////////////////////////////////////////////////////////////////////////////////
   ////////////////////////////////////  CONSTRUCTORS  /////////////////////////////////////
   /////////////////////////////////////////////////////////////////////////////////////////
 
  
Creates a new XmlBuffer
 
   public XmlBuffer() {
     this(false);
   }

  
Creates a new XmlBuffer
 
   public XmlBuffer(boolean insertXmlDeclaration) {
      = insertXmlDeclaration;
   }

  
Creates a new XmlBuffer.
 
   public XmlBuffer(String aCharacterEncoding) {
                   = new XmlScribe(aCharacterEncoding);
                   = new StringBuffer();
           = true;
        = aCharacterEncoding;
           = new HashMap();
                   = new LinkedList();
   }
 
   /////////////////////////////////////////////////////////////////////////////////////////
   //////////////////////////////////  ACCESSOR METHODS  ///////////////////////////////////
   /////////////////////////////////////////////////////////////////////////////////////////
 
  
Returns the namespace prefix of the URI passed in.

Parameters:
aNamespaceURI The URI of the namespace to look for.
Returns:
The associated prefix or null if the namespace URI is not found.
 
   public String getNamespacePrefix(String aNamespaceURI) {
    LinkedList someNamespaces = (LinkedList.get(aNamespaceURI);
    if (someNamespaces == null) {
      return null;
    } else {
      NamespaceReference aNamespaceRef = (NamespaceReferencesomeNamespaces.getFirst();
      return aNamespaceRef.getNamespace().getPrefix();
    }
  }

  
Returns true if this xml buffer is empty (no element has been started on this xml buffer).

Returns:
True if this xml buffer is empty.
  public boolean isEmpty() {
    return ((.length() == 0) && .isEmpty());
  }
  
  
Returns the value of the indenting output indicator of this xml buffer.

Returns:
True if this buffer indents xml output, false otherwise.
  public boolean isIndentingOuput() {
    return .isIndentingOuput();
  }
  /////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////  MUTATOR METHODS  ///////////////////////////////////
  /////////////////////////////////////////////////////////////////////////////////////////

  
Changes the value of the indenting output indicator of this xml buffer.

Parameters:
aValue The new value of the indicator.
  public void setIndentingOuput(boolean aValue) {
  }
  
  
Adds the namespace definition passed in to this xml buffer. The namespace will be use for all the future elements created by this xml buffer. To define the default namespace this method accepts either null or an empty string as the namespace prefix.

Parameters:
aNamespaceURI The URI of the namespace to add.
aNamespacePrefix The prefix associated to the namespace.
Returns:
This xml buffer instance.
Throws:
java.lang.IllegalArgumentException If the namespace URI passed in is null.
  public XmlBuffer addNamespace(String aNamespaceURIString aNamespacePrefix) {
    // Validate arguments
    if (aNamespaceURI == null) {
      throw new IllegalArgumentException("The namespace URI passed in null");
    }
    // Get the list of namespaces for the URI
    LinkedList someNamespaces = (LinkedList.get(aNamespaceURI);
    if (someNamespaces == null) {
      someNamespaces = new LinkedList();
      .put(aNamespaceURIsomeNamespaces);
    }
    // Convert for default prefix if necessary
    if (aNamespacePrefix == null) {
      aNamespacePrefix = "";
    }
    Namespace aNamespace = new Namespace(aNamespaceURIaNamespacePrefix);
    // If the list of namespaces is empty add the current namespace    
    if (someNamespaces.isEmpty()) {
      someNamespaces.addFirst(new NamespaceReference(aNamespace));
    } else {
      NamespaceReference aNamespaceRef = (NamespaceReferencesomeNamespaces.getFirst();
      // If the current state is the same namespace, increment the reference counter
      if (aNamespace.equals(aNamespaceRef.getNamespace())) {
        aNamespaceRef.addReference();
      } else {
        someNamespaces.addFirst(new NamespaceReference(aNamespace));
      }
    }
    return this;
  }

  
Removes the namespace definition from this xml buffer.

Parameters:
aNamespaceURI The URI of the namespace to remove.
Returns:
This xml buffer instance.
Throws:
java.lang.IllegalArgumentException If the namespace URI passed in is null or if the namespace URI is not found.
  public XmlBuffer removeNamespace(String aNamespaceURI) {
    // Validate the argument
    if (aNamespaceURI == null) {
      throw new IllegalArgumentException("The namespace URI passed in null");
    }
    // Retrieve the list of namespaces for the URI
    LinkedList someNamespaces = (LinkedList.get(aNamespaceURI);
    if (someNamespaces == null) {
      throw new IllegalStateException("No namespace found for the URI " +
        aNamespaceURI);
    }
    // If there is one reference left remove the namespace, otherwise decrement the ref count
    NamespaceReference aNamespaceRef = (NamespaceReferencesomeNamespaces.getFirst();
    if (aNamespaceRef.getReferenceCount() == 1) {
      someNamespaces.removeFirst();
    } else {
      aNamespaceRef.removeReference();
    }
    return this;
  }

  
Start an element in the XML buffer. The element will be create for the default namespace.

Returns:
This xml buffer instance.
Throws:
java.lang.IllegalArgumentException If the element name passed in is null.
AnElementName:
The name of the element to start.
  public XmlBuffer startElement(String anElementName) {
    return startElement(nullanElementName);
  }

  
Start an element in the XML buffer using the namespace URI passed in.

Parameters:
aNamespaceURI The namespace URI in which belong the element.
anElementName The name of the element to create.
Returns:
This xml buffer instance.
Throws:
java.lang.IllegalArgumentException If the element name passed in is null.
  public XmlBuffer startElement(String aNamespaceURIString anElementName) {
    if (anElementName == null) {
      throw new IllegalArgumentException("The element name passed in is null");
    }
    BufferState aParentState = null;
    if (!.isEmpty()) {
      aParentState = (BufferState.getFirst();
    }
    validateStartingXmlGeneration(aParentState);
    String      aPrefix    = getNamespacePrefix(aNamespaceURI);
    Namespace   aNamespace = new Namespace(aNamespaceURIaPrefix);
    BufferState aState     = new BufferState(aParentStateaNamespace,
        anElementName);
    aState.addDeclaredNamespace(aNamespace);
    .addFirst(aState);
    return this;
  }

  
Adds the string passed in as content of the current XML element.

Parameters:
aContent The content to add.
Returns:
This xml buffer instance.
Throws:
java.lang.IllegalStateException If there is no element started.
  public XmlBuffer addContent(String aContent) {
    if (.isEmpty()) {
      throw new IllegalStateException("Could not add content [" + aContent +
        "] there is no element started");
    }
    BufferState aState = (BufferState.getFirst();
    .xmlEncode(aContentaState.getContent());
    return this;
  }

  
Adds the string passed in as CData of the current XML element.

Parameters:
aContent The content to add as CData.
Returns:
This xml buffer instance.
Throws:
java.lang.IllegalStateException If there is no element started.
  public XmlBuffer addContent(CData aCData) {
    if (.isEmpty()) {
      throw new IllegalStateException("Could not add CData [" + aCData +
        "] there is no element started");
    }
    BufferState aState = (BufferState.getFirst();
    .composeCData(aCData.toString(), aState.getContent());
    return this;
  }

  
Ends the element name passed in. The element to close will be in the default namespace.

Parameters:
anElementName The name of the element to end.
Returns:
This xml buffer instance.
Throws:
java.lang.IllegalArgumentException If the element name passed in is null or if it does not match the current element name and namespace.
java.lang.IllegalStateException If there is no element started.
  public XmlBuffer endElement(String anElementName) {
    return endElement(nullanElementName);
  }

  
Ends the element name passed in the provided namespace.

Parameters:
aNamespaceURI The namespace of the element to close.
anElementName The name of the element to end.
Returns:
This xml buffer instance.
Throws:
java.lang.IllegalArgumentException If the element name passed in is null or if it does not match the current element name and namespace.
java.lang.IllegalStateException If there is no element started.
  public XmlBuffer endElement(String aNamespaceURIString anElementName) {
    if (anElementName == null) {
      throw new IllegalArgumentException("The element name passed in is null");
    } else if (.isEmpty()) {
      throw new IllegalStateException("Could not end the element [" +
        anElementName + "] on an empty xml buffer");
    }
    if (!anElementName.equals(aState.getElementName())) {
      throw new IllegalArgumentException("The element name to end [" +
        anElementName + "] does not match the starting tag [" +
        aState.getElementName() + "]");
    } else if (((aNamespaceURI != null) &&
          !aNamespaceURI.equals(aState.getElementNamespace().getURI())) ||
          ((aNamespaceURI == null) &&
          (aState.getElementNamespace().getURI() != null))) {
      throw new IllegalArgumentException("The namespace URI to end [" +
        aNamespaceURI + "] does not match the starting namespace URI [" +
        aState.getElementNamespace().getURI() + "]");
    }
    if (.isEmpty()) {
      generateCompleteXmlFor(aState);
    } else {
      BufferState aParentState = (BufferState.getFirst();
      generateCompleteXmlFor(aStateaParentState.getNestedXmlString());
    }
    return this;
  }

  
Adds the attribute passed in to the current XML element.

Parameters:
aName The name of the attribute to add.
aValue The value of the attribute to add.
Returns:
This xml buffer instance.
Throws:
java.lang.IllegalStateException If there is no current element or if the method endAttribute() was previously called for the current element.
  public XmlBuffer addAttribute(String aNameString aValue) {
    return addAttribute(nullaNameaValue);
  }

  
Adds the attribute passed in to the current XML element for the passed in namespace.

Parameters:
aNamespaceURI The namespace of the attribute to add.
aName The name of the attribute to add.
aValue The value of the attribute to add.
Returns:
This xml buffer instance.
Throws:
java.lang.IllegalStateException If there is no current element or if the method endAttribute() was previously called for the current element.
  public XmlBuffer addAttribute(String aNamespaceURIString aName,
    String aValue) {
    if (.isEmpty()) {
      throw new IllegalStateException("Could not add the attribute [" + aName +
        "] on an empty xml buffer");
    }
    BufferState aState = (BufferState.getFirst();
    if (!aState.isGettingMoreAttribute()) {
      throw new IllegalStateException("Could not add the attribute [" + aName +
        "] on element for which the endAttribute() methos was previously called");
    }
    String    aPrefix     = getNamespacePrefix(aNamespaceURI);
    Attribute anAttribute = new Attribute(aPrefixaNameaValue);
    aState.addAttribute(anAttribute);
    Namespace aNamespace = new Namespace(aNamespaceURIaPrefix);
    aState.addDeclaredNamespace(aNamespace);
    return this;
  }

  
This method tells the xml buffer that the current element will not get any further attribute. It is a hint to let the xml buffer reduce it's footprint.

Returns:
This xml buffer instance.
Throws:
java.lang.IllegalStateException If there is no current element.
  public XmlBuffer endAttribute() {
    // hint that would tell the xml buffer that no more attributes will be added.
    // upon this call it should generate the starting element of the current buffer state
    if (.isEmpty()) {
      throw new IllegalStateException("There is no current element");
    }
    BufferState aState = (BufferState.getFirst();
    aState.setIsGettingMoreAttribute(false);
    return this;
  }

  
Generates an XML string using the buffer state passed in.

Parameters:
aState The buffer state that contains the info about the XML to generate.
aBuffer The buffer into which to add the generated XML string.
  private void generateCompleteXmlFor(BufferState aStateStringBuffer aBuffer) {
    if (!aState.isStartElementGenerated()) {
      generateStartingXmlFor(aStateaBuffertrue);
      if (!aState.isElementEmpty()) {
        if (!aState.isNestedXMLEmpty()) {
          aBuffer.append(aState.getNestedXmlString().toString());
        }
        if (!aState.isContentEmpty()) {
          aBuffer.append(aState.getContent().toString());
        }
        if (aState.isNestedXMLEmpty() && !aState.isContentEmpty() && .isIndentingOuput()) {
          .setIndentingOutput(false);
          .composeEndingElement(aState.getElementNamespace().getPrefix(), aState.getElementName(), aBufferaState.getNestedLevel());
          .setIndentingOutput(true);
        } else {
          .composeEndingElement(aState.getElementNamespace().getPrefix(), aState.getElementName(), aBufferaState.getNestedLevel());
        }
      }
    } else if (!aState.isElementEmpty()) {
      if (!aState.isContentEmpty()) {
        aBuffer.append(aState.getContent().toString());
      }
        aState.getElementName(), aBufferaState.getNestedLevel());
    }
  }

  
Validates if it is necessary to generate a start element for the state passed in. If the conditions are meet, this method will call the generateStartingXmlFor() method to generate the starting element.

Parameters:
aState The buffer state to validate.
  private void validateStartingXmlGeneration(BufferState aState) {
    if ((aState != null) && !aState.isGettingMoreAttribute() &&
          !aState.isStartElementGenerated()) {
      if (aState.getParent() == null) {
        generateStartingXmlFor(aStatefalse);
        aState.setNestedXmlString();
      } else {
        generateStartingXmlFor(aStateaState.getParent().getNestedXmlString(),
          false);
        aState.setNestedXmlString(aState.getParent().getNestedXmlString());
      }
    }
  }

  
Generates an XML string using the buffer state passed in.

Parameters:
aState The buffer state that contains the info about the XML to generate.
aBuffer The buffer into which to add the generated XML string.
  private void generateStartingXmlFor(BufferState aStateStringBuffer aBuffer,
    boolean isClosingElement) {
    int anIndex = 0;
    for (Iterator it = aState.getDeclaredNamespaces().iterator(); it.hasNext();
          anIndex++) {
      Namespace aNamespace = (Namespaceit.next();
      if ((aNamespace.getPrefix() == null) ||
            (aNamespace.getPrefix().length() == 0)) {
        Attribute anAttribute = new Attribute("xmlns"aNamespace.getURI());
        aState.addAttribute(anIndexanAttribute);
      } else {
        Attribute anAttribute = new Attribute("xmlns"aNamespace.getPrefix(),
            aNamespace.getURI());
        aState.addAttribute(anIndexanAttribute);
      }
    }
    if (isClosingElement && aState.isElementEmpty()) {
        aState.getElementName(), aState.getAttributes(), trueaBufferaState.getNestedLevel());
    } else {
        aState.getElementName(), aState.getAttributes(), falseaBufferaState.getNestedLevel());
    }
    aState.setIsStartElementGenerated(true);
  }
  /////////////////////////////////////////////////////////////////////////////////////////
  //////////////////////////////////  OVERRIDEN METHODS  //////////////////////////////////
  /////////////////////////////////////////////////////////////////////////////////////////

  
Returns the string of this xml buffer.

Returns:
The string of this xml buffer.
  public String toString() {
    if () {
      StringBuffer aBuffer = new StringBuffer();
      aBuffer.append(.toString());
      return aBuffer.toString();
    } else {
      return .toString();
    }
  }
  public static class NamespaceReference {
    private Namespace _theNamespace;
    private int       _theReferenceCount;
    public NamespaceReference(Namespace aNamespace) {
              = aNamespace;
         = 1;
    }
    public int getReferenceCount() {
      return ;
    }
    public Namespace getNamespace() {
      return ;
    }
    public void addReference() {
      ++;
    }
    public void removeReference() {
      --;
    }
  }
New to GrepCode? Check out our FAQ X