forrest-svn mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From thors...@apache.org
Subject svn commit: r699276 - in /forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl: XMLStructurerAxiom.java helper/AXIOMXPathPatched.java
Date Fri, 26 Sep 2008 11:24:21 GMT
Author: thorsten
Date: Fri Sep 26 04:24:20 2008
New Revision: 699276

URL: http://svn.apache.org/viewvc?rev=699276&view=rev
Log:
Adding an AXIOM implementation of the structurer that supports advanced injection of content.

It actually resolves the corresponding node where one want to inject and not like in the StAX
only implementation where we are not able to do so since it 100% based on XMLEvents. 

Needed to extend some AXIOM classes (see WSCOMMONS-389) to create not existing xpath and return
a node. In the class AXIOMXPathPatched there is still one fix me to support advanced xpath
expression like [@id='example'] which currently is not supported for the generation of new
paths.

As soon I fixed this I provide a patch and if this patch makes it into the next release we
have to declare the class as deprecated and remove it in the next version of the dispatcher.

Added:
    forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/XMLStructurerAxiom.java
      - copied, changed from r697033, forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/XMLStructurer.java
    forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/helper/AXIOMXPathPatched.java
  (with props)

Copied: forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/XMLStructurerAxiom.java
(from r697033, forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/XMLStructurer.java)
URL: http://svn.apache.org/viewvc/forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/XMLStructurerAxiom.java?p2=forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/XMLStructurerAxiom.java&p1=forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/XMLStructurer.java&r1=697033&r2=699276&rev=699276&view=diff
==============================================================================
--- forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/XMLStructurer.java
(original)
+++ forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/XMLStructurerAxiom.java
Fri Sep 26 04:24:20 2008
@@ -6,424 +6,339 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.LinkedHashSet;
 
+import javax.xml.namespace.QName;
 import javax.xml.stream.XMLEventWriter;
 import javax.xml.stream.XMLStreamConstants;
 import javax.xml.stream.XMLStreamException;
 import javax.xml.stream.XMLStreamReader;
-import javax.xml.stream.events.EndElement;
-import javax.xml.stream.events.StartElement;
 import javax.xml.stream.events.XMLEvent;
 import javax.xml.stream.util.XMLEventAllocator;
 
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMAttribute;
+import org.apache.axiom.om.OMDocument;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNamespace;
+import org.apache.axiom.om.OMNode;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axiom.om.xpath.AXIOMXPath;
 import org.apache.forrest.dispatcher.api.Contract;
 import org.apache.forrest.dispatcher.api.Resolver;
 import org.apache.forrest.dispatcher.api.Structurer;
 import org.apache.forrest.dispatcher.config.DispatcherBean;
 import org.apache.forrest.dispatcher.exception.DispatcherException;
 import org.apache.forrest.dispatcher.factories.ContractFactory;
+import org.apache.forrest.dispatcher.impl.helper.AXIOMXPathPatched;
+import org.apache.forrest.dispatcher.impl.helper.Captions;
 import org.apache.forrest.dispatcher.impl.helper.StAX;
+import org.apache.forrest.dispatcher.impl.helper.StreamHelper;
 import org.apache.forrest.dispatcher.utils.CommonString;
+import org.jaxen.JaxenException;
 import org.xml.sax.InputSource;
 
-public class XMLStructurer extends StAX implements Structurer {
+public class XMLStructurerAxiom extends StAX implements Structurer {
 
-  public static final String NS = "http://apache.org/forrest/templates/2.0";
-
-  public static final String STRUCTURER_ELEMENT = "structurer";
-
-  public static final String STRUCTURE_ELEMENT = "structure";
-
-  public static final String TYPE_ATT = "type";
-
-  public static final String HOOKS_ATT = "hooksXpath";
-
-  public static final String CONTRACT_ELEMENT = "contract";
-
-  public static final String NAME_ATT = "name";
-
-  public static final String DATA_ATT = "dataURI";
-
-  public static final String PROPERTY_ELEMENT = "property";
-
-  public static final String HOOK_ELEMENT = "hook";
-
-  private static final Object VALUE_ATT = "value";
-
-  private static final Object CONTRACT_RESULT_XPATH = "xpath";
-
-  private final boolean dom;
+  private static final String PATH_PREFIX = "/result";
 
   private final Resolver resolver;
 
   private final boolean allowXmlProperties;
-  
+
   private final ContractFactory contractRep;
 
-  private LinkedHashMap<String, LinkedHashSet<XMLEvent>> resultTree = new LinkedHashMap<String,
LinkedHashSet<XMLEvent>>();
-  
-  private String currentPath = "";
+  private LinkedHashMap<String, LinkedHashSet<OMNode>> resultTree = new LinkedHashMap<String,
LinkedHashSet<OMNode>>();
+
+  private OMFactory factory;
 
-  public XMLStructurer(DispatcherBean config) {
-    this.dom= config.isDomEnabled();
+  private OMElement root;
+
+  public XMLStructurerAxiom(DispatcherBean config) {
     this.contractRep = new ContractFactory(config);
     this.resolver = config.getResolver();
     this.allowXmlProperties = config.isAllowXmlProperties();
+    this.factory = OMAbstractFactory.getOMFactory();
   }
 
-  /* 
-   * @see org.apache.forrest.dispatcher.impl.Structurer#execute(java.io.InputStream, java.lang.String)
+  /*
+   * @see
+   * org.apache.forrest.dispatcher.impl.Structurer#execute(java.io.InputStream,
+   * java.lang.String)
    */
-  public InputStream execute(InputStream structurerStream, String format) throws DispatcherException
{
+  public InputStream execute(InputStream structurerStream, String format)
+      throws DispatcherException {
     BufferedInputStream stream = null;
+    ByteArrayOutputStream out = new ByteArrayOutputStream();
+    /*
+     * Preparing the model by creating a root document/element. Afterward we
+     * need to strip the root element again.
+     */
+    OMDocument doc = factory.createOMDocument();
+    root = factory.createOMElement("result", null);
+    doc.addChild(root);
+    String currentPath = PATH_PREFIX;
     try {
+      /*
+       * Preparing the processing.
+       */
       XMLStreamReader reader = getReader(structurerStream);
-      boolean process = true;
-      while (process) {
-        int event = reader.next();
-        switch (event) {
-        case XMLStreamConstants.END_DOCUMENT:
-          process = false;
-          break;
-
-        case XMLStreamConstants.START_ELEMENT:
-          String elementName = reader.getLocalName();
-          if (elementName.equals(STRUCTURE_ELEMENT)) {
-            String m_type = "", path = "";
-            // Get attribute names
-            for (int i = 0; i < reader.getAttributeCount(); i++) {
-              String localName = reader.getAttributeLocalName(i);
-              if (localName.equals(TYPE_ATT)) {
-                // Return value
-                m_type = reader.getAttributeValue(i);
-              } else if (localName.equals(HOOKS_ATT)) {
-                path = reader.getAttributeValue(i);
-              }
-            }
-            if (m_type.equals(format)) {
-              log.debug("matched - need to process");
-              // adding the default path
-              if (!"/".equals(String.valueOf(path.charAt(0)))) {
-                path = "/" + path;
-              }
-              currentPath = path;
-              stream = processStructure(reader);
-            } else {
-              log.debug("no-matched");
+      StAXOMBuilder builder = new StAXOMBuilder(reader);
+      OMElement strucuturer = builder.getDocumentElement();
+      Iterator<OMNode> structures = strucuturer.getChildrenWithName(new QName(
+          Captions.NS, Captions.STRUCTURE_ELEMENT));
+      /*
+       * process all structure elements within this structurer file.
+       */
+      while (structures.hasNext()) {
+        String m_type = "", path = "";
+        OMNode node = (OMNode) structures.next();
+        if (isElement(node)) {
+          OMElement structure = (OMElement) node;
+          m_type = structure.getAttributeValue(qIt(Captions.TYPE_ATT));
+          path = structure.getAttributeValue(qIt(Captions.HOOKS_ATT));
+          if (format.equals(m_type)) {
+            log.debug("matched - need to process");
+            // adding the default path
+            if (!"/".equals(String.valueOf(path.charAt(0)))) {
+              path = "/" + path;
             }
+            currentPath += path;
+            AXIOMXPathPatched xpath = new AXIOMXPathPatched(currentPath);
+            Object pathNode = (OMElement) xpath.selectSingleNode(root, true);
+            processStructure(structure, (OMElement) pathNode);
           }
-          break;
-
-        default:
-          break;
         }
       }
+      /*
+       * In case it strike you odd that we just use the first node this is
+       * because the output of a structurer needs to be well-formed and there
+       * should only be one child in any circumstance.
+       */
+      root.getFirstElement().serialize(out);
+      // debug hook
+      // next line will get the whole result document
+      //root.serialize(out);
     } catch (XMLStreamException e) {
       throw new DispatcherException(e);
+    } catch (JaxenException e) {
+      throw new DispatcherException(e);
     } catch (IOException e) {
       throw new DispatcherException(e);
-    }finally{
-      if (null!=structurerStream){
+    } finally {
+      if (null != structurerStream) {
         try {
           structurerStream.close();
         } catch (IOException e) {
           throw new DispatcherException(e);
-        };
+        }
+        ;
       }
     }
+    stream = StreamHelper.switchStream(out);
+    log.debug(out.toString());
     return stream;
   }
 
-  private BufferedInputStream processStructure(XMLStreamReader reader)
-      throws XMLStreamException, DispatcherException, IOException {
-    boolean process = true;
-    String elementName = null;
-    ByteArrayOutputStream out = new ByteArrayOutputStream();
-    while (process) {
-      int event = reader.next();
-      switch (event) {
-      case XMLStreamConstants.END_ELEMENT:
-        elementName = reader.getLocalName();
-        if (elementName.equals(STRUCTURE_ELEMENT)) {
-          if(dom){
-            // TODO implement me.
-          }else{
-            XMLEventWriter writer = getWriter(out);
-            createResultStax(writer);
-          }
-          resultTree.clear();
-          process = false;
-        }else if (elementName.equals(HOOK_ELEMENT)){
-          processHook(reader, false);
-        }
-        break;
-
-      case XMLStreamConstants.START_ELEMENT:
-        elementName = reader.getLocalName();
-        if (elementName.equals(CONTRACT_ELEMENT)) {
-          log.debug("Path " + currentPath);
-          processContract(reader);
-        } else if (elementName.equals(HOOK_ELEMENT)) {
-          log.debug("HOOKS " + elementName);
-          processHook(reader, true);
-          log.info("HOOKS transformation NOT YET IMPLEMENTED");
-        }
-        break;
-
-      default:
-        break;
+  /**
+   * @param node
+   * @return
+   */
+  private boolean isElement(OMNode node) {
+    return node.getType() == OMNode.ELEMENT_NODE;
+  }
 
+  /**
+   * @param structure
+   * @param pathNode
+   * @throws XMLStreamException
+   * @throws DispatcherException
+   * @throws IOException
+   * @throws JaxenException
+   */
+  private void processStructure(OMElement structure, OMElement pathNode)
+      throws XMLStreamException, DispatcherException, IOException,
+      JaxenException {
+    Iterator<OMNode> strucutrerElements = structure.getChildren();
+    while (strucutrerElements.hasNext()) {
+      OMNode node = (OMNode) strucutrerElements.next();
+      if (isElement(node)) {
+        computeNodes((OMElement) node, pathNode);
       }
     }
-    log.debug(out.toString());
-    return (out != null) ? new BufferedInputStream(new ByteArrayInputStream(out
-        .toByteArray())) : null;
+
   }
-  
+
   /**
-   * Create the outcome of the hooks and contracts.
-   * Here we need to find the injectionPoints that 
-   * can be defined in the different contracts.
+   * This is the main iterating process here we process all contracts and hooks.
    * 
-   * This injectionPoints can be within or extending other. 
+   * @param node
+   *          current node
+   * @param pathNode
+   *          the model representing the current path
+   * @throws DispatcherException
+   * @throws XMLStreamException
+   * @throws IOException
+   * @throws JaxenException
    */
-
-  private void createResultStax(XMLEventWriter writer)
-      throws XMLStreamException {
-    // We start with creating a new result document
-    writer.add(getEventFactory().createStartDocument("UTF-8", "1.0"));
-    // get a iterator about the injectionPoints we use
-    Iterator<String> iterator = resultTree.keySet().iterator();
-    // create an path array 
-    String[] paths = resultTree.keySet().toArray(new String[1]);
-    // determine the common root path for all paths
-    String rootPath = CommonString.common(paths);
-    // Prepare the creation of the root path  
-    String[] tokenizer = rootPath.split("/");
-    // create the events related to the root path
-    openPaths(writer, tokenizer);
-    while (iterator.hasNext()) {
-      String element = iterator.next();
-      final String replaceFirst = element.replaceFirst(rootPath, "");
-      final String[] split = replaceFirst.split("/");
-      if (split.length > 1) {
-        openPaths(writer, split);
-        injectResult(writer, element);
-        closingPaths(writer, split);
-      } else {
-        StartElement start = getEventFactory().createStartElement("", "",
-            replaceFirst);
-        writer.add((XMLEvent) start);
-
-        injectResult(writer, element);
-        EndElement end = getEventFactory().createEndElement("", "",
-            replaceFirst);
-        writer.add((XMLEvent) end);
-      }
-
+  private void computeNodes(OMElement component, OMElement pathNode)
+      throws DispatcherException, XMLStreamException, IOException,
+      JaxenException {
+    if (component.getQName().equals(
+        new QName(Captions.NS, Captions.CONTRACT_ELEMENT))) {
+      processContract(component, pathNode);
+    } else if (component.getQName().equals(
+        new QName(Captions.NS, Captions.HOOK_ELEMENT))) {
+      processHook(component, pathNode);
     }
-    closingPaths(writer, tokenizer);
-    writer.add(getEventFactory().createEndDocument());
   }
 
-  private void processContract(XMLStreamReader reader)
-      throws XMLStreamException, DispatcherException, IOException {
-    boolean process = true;
-    String elementName = null;
-    String name = "", data= null;
-    // Get attribute names
-    for (int i = 0; i < reader.getAttributeCount(); i++) {
-      String localName = reader.getAttributeLocalName(i);
-      if (localName.equals(NAME_ATT)) {
-        // Return value
-        name = reader.getAttributeValue(i);
-      } else if (localName.equals(DATA_ATT)) {
-        data = reader.getAttributeValue(i);
+  /**
+   * @param component
+   * @param pathNode
+   * @throws DispatcherException
+   * @throws XMLStreamException
+   * @throws IOException
+   * @throws JaxenException
+   */
+  private void processHook(OMElement component, OMElement pathNode)
+      throws DispatcherException, XMLStreamException, IOException,
+      JaxenException {
+    OMElement element = factory.createOMElement(component.getLocalName(),
+        component.getNamespace().getNamespaceURI(), "forrest");
+    Iterator<OMAttribute> attributes = component.getAllAttributes();
+    while (attributes.hasNext()) {
+      OMAttribute attribute = attributes.next();
+      element.addAttribute(attribute);
+
+    }
+    pathNode.addChild(element);
+    Iterator<OMNode> childs = component.getChildren();
+    while (childs.hasNext()) {
+      OMNode node = (OMNode) childs.next();
+      if (isElement(node)) {
+        computeNodes((OMElement) node, element);
       }
     }
-    log.debug("data "+data);
-    InputStream dataStream=null;
-    if(null != data && !data.equals("")){
+  }
+
+  /**
+   * @param component
+   * @throws DispatcherException
+   * @throws XMLStreamException
+   * @throws IOException
+   * @throws JaxenException
+   */
+  private void processContract(OMElement component, OMElement pathNode)
+      throws DispatcherException, XMLStreamException, IOException,
+      JaxenException {
+    String name = "", data = null;
+    name = component.getAttributeValue(qIt(Captions.NAME_ATT));
+    data = component.getAttributeValue(qIt(Captions.DATA_ATT));
+    log.debug("Contract: " + name + "\ndataUri: " + data);
+    InputStream dataStream = null;
+    if (null != data && !data.equals("")) {
       dataStream = resolver.resolve(data);
     }
     Contract contract = contractRep.resolve(name);
-
     HashMap<String, ?> param = new HashMap();
-    while (process) {
-      int event = reader.next();
-      switch (event) {
-      case XMLStreamConstants.END_ELEMENT:
-        elementName = reader.getLocalName();
-        if (elementName.equals(CONTRACT_ELEMENT)) {
-          InputStream resultStream = contract.execute(dataStream, param);
-          if (null != dataStream) {
-            dataStream.close();
-          }
-          processContractResult(resultStream);
-          if (null != resultStream) {
-            resultStream.close();
-          }
-          process = false;
-        }
-        break;
-
-      case XMLStreamConstants.START_ELEMENT:
-        elementName = reader.getLocalName();
-        if (elementName.equals(PROPERTY_ELEMENT)) {
-          processProperty(reader, param);
-        }
-        break;
-
-      default:
-        break;
-
-      }
-    }
+    OMElement properties = component
+        .getFirstChildWithName(qIt(Captions.PROPERTY_ELEMENT));
+    if (properties != null) {
+      processProperty(properties, param);
+    }
+    InputStream resultStream = contract.execute(dataStream, param);
+    StreamHelper.closeStream(dataStream);
+    processContractResult(resultStream, pathNode);
+    StreamHelper.closeStream(resultStream);
   }
 
-  private void processContractResult(InputStream resultStream)
-      throws XMLStreamException {
+  /**
+   * @param resultStream
+   * @param pathNode
+   * @throws XMLStreamException
+   * @throws JaxenException
+   */
+  private void processContractResult(InputStream resultStream,
+      OMElement pathNode) throws XMLStreamException, JaxenException {
     XMLStreamReader contractResultReader = getReader(resultStream);
-    String xpath = "", injectionPoint = "";
-    LinkedHashSet<XMLEvent> pathElement = null;
-    boolean process = true;
-    while (process) {
-      int resultEvent = contractResultReader.next();
-      switch (resultEvent) {
-      case XMLStreamConstants.START_ELEMENT:
-        if (contractResultReader.getLocalName().equals("part")) {
-          // Get attribute names
-          for (int i = 0; i < contractResultReader.getAttributeCount(); i++) {
-            String localName = contractResultReader.getAttributeLocalName(i);
-            if (localName.equals(CONTRACT_RESULT_XPATH)) {
-              // Return value
-              xpath = contractResultReader.getAttributeValue(i);
-            }
-          }
-          if (xpath.equals("")) {
-            // iterate through the children and add them
-            // to the pathElement
-            if (resultTree.containsKey(currentPath)){
-              pathElement = resultTree.get(currentPath);
-            }else{
-              pathElement = new LinkedHashSet<XMLEvent>();
-            }
-            injectionPoint = currentPath;
-            inject(pathElement, contractResultReader, injectionPoint);
-            // as soon as you find the end element add
-            // it back to the resultTree
-          } else {
-            // iterate through the children and add them
-            // to the xpath defined
-            if (resultTree.containsKey(xpath))
-              pathElement = resultTree.get(xpath);
-            else
-              pathElement = new LinkedHashSet<XMLEvent>();
-            injectionPoint = xpath;
-            inject(pathElement, contractResultReader, injectionPoint);
-          }
+    StAXOMBuilder builder = new StAXOMBuilder(contractResultReader);
+    OMElement content = builder.getDocumentElement();
+    /*
+     *  For full blown ns support we need to get all ns from the
+     *  result. This will be passed later to the XPath processor.
+     */
+    Iterator<OMNamespace> ns = content.getAllDeclaredNamespaces();
+    HashSet<OMNamespace> spaces = new HashSet<OMNamespace>();
+    while (ns.hasNext()) {
+      OMNamespace space =  ns.next();
+      spaces.add(space);
+    }
+    Iterator<OMElement> parts = content.getChildrenWithName(new QName(
+        Captions.NS_CONTRACTS, Captions.PART_ELEMENT));
+    while (parts.hasNext()) {
+      OMElement part = parts.next();
+      String xpath = part.getAttributeValue(qIt(Captions.RESULT_XPATH));
+      Iterator<OMNode> children = part.getChildren();
+      if (xpath == null) {
+        while (children.hasNext()) {
+          OMNode child = (OMNode) children.next();
+          pathNode.addChild(child);
+        }
+      } else {
+        xpath = PATH_PREFIX + xpath;
+        // we need to feed the xpathSelector with the ns we may have
+        AXIOMXPathPatched xpathSelector = new AXIOMXPathPatched(xpath);
+        
+        for (OMNamespace space : spaces) {
+          xpathSelector.addNamespace(space.getPrefix(), space.getNamespaceURI());
+        }
+        OMElement injectionPoint = (OMElement) xpathSelector.selectSingleNode(
+            root, true);
+        while (children.hasNext()) {
+          OMNode child = (OMNode) children.next();
+          injectionPoint.addChild(child);
         }
-        break;
-      case XMLStreamConstants.END_DOCUMENT:
-        process = false;
-
-      default:
-        break;
 
       }
     }
   }
-  
-  private void processHook(XMLStreamReader reader, boolean start) throws XMLStreamException
{
-    
-    /*log.debug("currentPath: "+currentPath);
-    if(start){
-      String xpath= calculateXpathFromAtrributes(reader);
-      //currentPath+="/"+
-      log.debug(currentPath+"/"+HOOK_ELEMENT.toUpperCase()+xpath);
-      currentPath+="/"+HOOK_ELEMENT;
-    }*/
-    LinkedHashSet<XMLEvent> pathElement;
-    if (resultTree.containsKey(currentPath)){
-      pathElement = resultTree.get(currentPath);
-    }else{
-      pathElement = new LinkedHashSet<XMLEvent>();
-    }
-    XMLEventAllocator allocator = getEventAllocator();
-    XMLEvent currentEvent = allocator.allocate(reader);
-    pathElement.add(currentEvent);
-    resultTree.put(currentPath, pathElement);
-    /*if(!start){
-      currentPath=currentPath.substring(0,currentPath.lastIndexOf(("/"+HOOK_ELEMENT)));
-    }
-    log.debug("currentPath (after): "+currentPath);*/
-  }
-
-  private String calculateXpathFromAtrributes(XMLStreamReader reader) {
-    String xpath="";
-    for (int i = 0; i < reader.getAttributeCount(); i++) {
-      // Get attribute name
-      String key = reader.getAttributeLocalName(i);
-      String  value = reader.getAttributeValue(i);
-      xpath="@"+key+":"+value;
-    }
-    if(!xpath.equals("")){
-      xpath="["+xpath+"]";
-    }
-    return xpath;
-  }
-
-  private void inject(LinkedHashSet<XMLEvent> pathElement,
-      XMLStreamReader parser, String injectionPoint) throws XMLStreamException {
-    log.debug("injectionPoint " + injectionPoint);
-    XMLEventAllocator allocator = getEventAllocator();
-    boolean process = true;
-    while (process) {
-      int event = parser.next();
 
-      XMLEvent currentEvent = allocator.allocate(parser);
-      switch (event) {
-      case XMLStreamConstants.END_ELEMENT:
-        if (parser.getLocalName().equals("part")) {
-          log.debug("Trying to add to hash " + injectionPoint);
-          resultTree.put(injectionPoint, pathElement);
-          process = false;
-        } else {
-          pathElement.add(currentEvent);
-        }
-        break;
-
-      default:
-        pathElement.add(currentEvent);
-        break;
-      }
-    }
+  /**
+   * @param name
+   * @return
+   */
+  private QName qIt(String name) {
+    return new QName(name);
   }
 
-  private void processProperty(XMLStreamReader reader, HashMap param)
+  /**
+   * @param properties
+   * @param param
+   * @throws XMLStreamException
+   */
+  private void processProperty(OMElement properties, HashMap param)
       throws XMLStreamException {
     String propertyName = null, propertyValue = null;
-    // Get attribute names
-    for (int i = 0; i < reader.getAttributeCount(); i++) {
-      String localName = reader.getAttributeLocalName(i);
-      if (localName.equals(NAME_ATT)) {
-        // Return value
-        propertyName = reader.getAttributeValue(i);
-      } else if (localName.equals(VALUE_ATT)) {
-        propertyValue = reader.getAttributeValue(i);
-      }
-    }
+    propertyName = properties.getAttributeValue(qIt(Captions.NAME_ATT));
+    propertyValue = properties.getAttributeValue(qIt(Captions.VALUE_ATT));
     if (allowXmlProperties) {
-      param.put(propertyName, recordXmlProperies(reader));
+      param.put(propertyName, recordXmlProperies(properties
+          .getXMLStreamReader()));
     } else if (null != propertyValue && null != propertyName) {
       param.put(propertyName, propertyValue);
     }
-
   }
 
+  /**
+   * @param reader
+   * @return
+   * @throws XMLStreamException
+   */
   private InputSource recordXmlProperies(XMLStreamReader reader)
       throws XMLStreamException {
     ByteArrayOutputStream out = new ByteArrayOutputStream();
@@ -437,7 +352,7 @@
       currentEvent = allocator.allocate(reader);
       switch (event) {
       case XMLStreamConstants.END_ELEMENT:
-        if (reader.getLocalName().equals(PROPERTY_ELEMENT)) {
+        if (reader.getLocalName().equals(Captions.PROPERTY_ELEMENT)) {
           writerProperty.add(currentEvent);
           writerProperty.flush();
           writerProperty.close();
@@ -456,36 +371,4 @@
         .toByteArray()));
     return value;
   }
-
-  private void openPaths(XMLEventWriter writer, String[] tokenizer)
-      throws XMLStreamException {
-    for (String string : tokenizer) {
-      if (!string.equals("")) {
-        StartElement value = getEventFactory().createStartElement("", "",
-            string);
-        writer.add((XMLEvent) value);
-      }
-    }
-  }
-
-  private void closingPaths(XMLEventWriter writer, String[] tokenizer)
-      throws XMLStreamException {
-    // closing the initial paths again
-    for (int j = tokenizer.length - 1; j >= 0; j--) {
-      if (!tokenizer[j].equals("")) {
-        EndElement value = getEventFactory().createEndElement("", "",
-            tokenizer[j]);
-        writer.add((XMLEvent) value);
-      }
-    }
-  }
-
-  private void injectResult(XMLEventWriter writer, String element)
-      throws XMLStreamException {
-    LinkedHashSet<XMLEvent> part = resultTree.get(element);
-    Object[] partResult = part.toArray();
-    for (int i = 0; i < partResult.length; i++) {
-      writer.add((XMLEvent) partResult[i]);
-    }
-  }
 }

Added: forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/helper/AXIOMXPathPatched.java
URL: http://svn.apache.org/viewvc/forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/helper/AXIOMXPathPatched.java?rev=699276&view=auto
==============================================================================
--- forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/helper/AXIOMXPathPatched.java
(added)
+++ forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/helper/AXIOMXPathPatched.java
Fri Sep 26 04:24:20 2008
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.forrest.dispatcher.impl.helper;
+
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.impl.OMNamespaceImpl;
+import org.apache.axiom.om.xpath.AXIOMXPath;
+import org.jaxen.JaxenException;
+
+/**
+ * Issue: WSCOMMONS-389
+ * 
+ * As soon the above issue is fixed we need to drop this implementation 
+ * since it will be in the AXIOMXPath.
+ * 
+ * The process should be 
+ * <ol>
+ * <li> stripping this class that it is only extending super and mark this class as
deprecated
+ * <li> remove it the next release.
+ *  
+ * @version 1.0
+ *
+ */
+public class AXIOMXPathPatched extends AXIOMXPath {
+
+  private static final long serialVersionUID = -4670206430863692541L;
+  private String xpathExpr;
+  private OMFactory factory;
+
+  public AXIOMXPathPatched(String xpathExpr) throws JaxenException {
+    super(xpathExpr);
+    this.xpathExpr = xpathExpr;
+    this.factory = OMAbstractFactory.getOMFactory();
+  }
+
+  public Object selectSingleNode(OMElement root, boolean create)
+      throws JaxenException {
+    Object xpathNode = super.selectSingleNode(root);
+    if (xpathNode == null && create) {
+      int endIndex = xpathExpr.lastIndexOf("/");
+      String xpath = xpathExpr.substring(0, endIndex);
+      String rest = xpathExpr.substring(endIndex + 1);
+      xpathNode = createNode(root, xpath, rest);
+    }
+    return xpathNode;
+  }
+
+  private Object createNode(OMElement root, String path, String rest)
+      throws JaxenException {
+    String m_xpath = path;
+    Object xpathNode = null;
+    while (true) {
+      AXIOMXPath xpath = getNsXPath(m_xpath);
+      xpathNode = xpath.selectSingleNode(root);
+      if (xpathNode == null) {
+        int endIndex = path.lastIndexOf("/");
+        m_xpath = path.substring(0, endIndex);
+        rest = path.substring(endIndex + 1) + "/" + rest;
+      } else if (xpathNode != null) {
+        xpathNode = calculatePath(root, (OMElement) xpathNode, rest);
+        break;
+      }
+
+    }
+    return xpathNode;
+  }
+
+  /**
+   * @param root
+   * @param node
+   * @param rest
+   * @return
+   */
+  private Object calculatePath(OMElement root, OMElement node, String rest) {
+    String[] tokenizer = rest.split("/");
+    LinkedHashSet<OMElement> pathNodes = new LinkedHashSet<OMElement>();
+    for (String pathPart : tokenizer) {
+      if (!pathPart.equals("")) {
+        calculateNsElements(pathNodes, pathPart);
+      }
+    }// now we have all nodes created but with no hierarchy
+    OMElement[] elements = new OMElement[0];
+    elements = pathNodes.toArray(new OMElement[pathNodes.size()]);
+    // create the hierarchy by adding the last node to the
+    // previous one till we reached the first one.
+    for (int j = elements.length - 1; j > 0; j--) {
+      elements[j - 1].addChild(elements[j]);
+    }
+    // Get rid of the overhead and expose just one node
+    OMElement firstNode = elements[0];
+    if (node == null) {
+      root.addChild(firstNode);
+    } else {
+      node.addChild(firstNode);
+    }
+    // get the last not since it is the one we are looking for
+    OMElement lastNode = elements[elements.length - 1];
+    return lastNode;
+  }
+
+  /**
+   * @param pathNodes
+   * @param pathPart
+   */
+  private void calculateNsElements(LinkedHashSet<OMElement> pathNodes,
+      String pathPart) {
+    
+    /*
+     * FIXME: Need to test xpath expression such as [@id='example']
+     * I think their are NOT generated correctly!
+     */
+    OMElement element = null;
+    OMNamespaceImpl localSpace = null;
+    String localName = pathPart;
+    String[] nameSpacedNode = localName.split(":");
+    if (nameSpacedNode.length == 2) {
+      final String prefix = nameSpacedNode[0];
+      final String uri = (String) getNamespaces().get(prefix);
+      localSpace = new OMNamespaceImpl(uri, prefix);
+      localName = nameSpacedNode[1];
+    }
+    element = factory.createOMElement(localName, localSpace);
+    pathNodes.add(element);
+  }
+
+  /**
+   * @param path
+   * @return
+   * @throws JaxenException
+   */
+  private AXIOMXPath getNsXPath(String path) throws JaxenException {
+    AXIOMXPath xpath = new AXIOMXPath(path);
+    Iterator iterator = this.getNamespaces().keySet().iterator();
+    while (iterator.hasNext()) {
+      String key = (String) iterator.next();
+      String value = (String) getNamespaces().get(key);
+      xpath.addNamespace(key, value);
+    }
+    return xpath;
+  }
+
+}

Propchange: forrest/trunk/whiteboard/dispatcher/java/org/apache/forrest/dispatcher/impl/helper/AXIOMXPathPatched.java
------------------------------------------------------------------------------
    svn:eol-style = native



Mime
View raw message