You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tuscany.apache.org by rf...@apache.org on 2009/08/10 21:24:12 UTC

svn commit: r802905 - in /tuscany/java/sca/modules/common-xml/src: main/java/org/apache/tuscany/sca/common/xml/ main/java/org/apache/tuscany/sca/common/xml/stax/ test/java/org/apache/tuscany/sca/common/xml/stax/ test/resources/ test/resources/org/ test...

Author: rfeng
Date: Mon Aug 10 19:24:12 2009
New Revision: 802905

URL: http://svn.apache.org/viewvc?rev=802905&view=rev
Log:
Add the methods to read the XML documents for certain attributes such as tns

Added:
    tuscany/java/sca/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/XMLDocumentHelper.java   (with props)
    tuscany/java/sca/modules/common-xml/src/test/resources/
    tuscany/java/sca/modules/common-xml/src/test/resources/org/
    tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/
    tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/
    tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/
    tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/
    tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/xml/
    tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/xml/stax/
    tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/xml/stax/test.wsdl   (with props)
    tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/xml/stax/test.xsd   (with props)
Modified:
    tuscany/java/sca/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/StAXHelper.java
    tuscany/java/sca/modules/common-xml/src/test/java/org/apache/tuscany/sca/common/xml/stax/StAXHelperTestCase.java

Added: tuscany/java/sca/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/XMLDocumentHelper.java
URL: http://svn.apache.org/viewvc/tuscany/java/sca/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/XMLDocumentHelper.java?rev=802905&view=auto
==============================================================================
--- tuscany/java/sca/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/XMLDocumentHelper.java (added)
+++ tuscany/java/sca/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/XMLDocumentHelper.java Mon Aug 10 19:24:12 2009
@@ -0,0 +1,152 @@
+/*
+ * 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.tuscany.sca.common.xml;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.JarURLConnection;
+import java.net.URL;
+import java.net.URLConnection;
+
+import org.xml.sax.InputSource;
+
+/**
+ * @version $Rev$ $Date$
+ */
+public class XMLDocumentHelper {
+    protected static final int BUFFER_SIZE = 256;
+
+    /**
+     * Detect the XML encoding of the document
+     * 
+     * @param is The input stream
+     * @return The encoding
+     * @throws IOException
+     */
+    public static String getEncoding(InputStream is) throws IOException {
+        if (!is.markSupported())
+            is = new BufferedInputStream(is);
+
+        byte[] buffer = readBuffer(is);
+        return getXMLEncoding(buffer);
+    }
+
+    /**
+     * Searches the array of bytes to determine the XML encoding.
+     */
+    protected static String getXMLEncoding(byte[] bytes) {
+        String javaEncoding = null;
+
+        if (bytes.length >= 4) {
+            if (((bytes[0] == -2) && (bytes[1] == -1)) || ((bytes[0] == 0) && (bytes[1] == 60)))
+                javaEncoding = "UnicodeBig";
+            else if (((bytes[0] == -1) && (bytes[1] == -2)) || ((bytes[0] == 60) && (bytes[1] == 0)))
+                javaEncoding = "UnicodeLittle";
+            else if ((bytes[0] == -17) && (bytes[1] == -69) && (bytes[2] == -65))
+                javaEncoding = "UTF8";
+        }
+
+        String header = null;
+
+        try {
+            if (javaEncoding != null)
+                header = new String(bytes, 0, bytes.length, javaEncoding);
+            else
+                header = new String(bytes, 0, bytes.length);
+        } catch (UnsupportedEncodingException e) {
+            return null;
+        }
+
+        if (!header.startsWith("<?xml"))
+            return "UTF-8";
+
+        int endOfXMLPI = header.indexOf("?>");
+        int encodingIndex = header.indexOf("encoding", 6);
+
+        if ((encodingIndex == -1) || (encodingIndex > endOfXMLPI))
+            return "UTF-8";
+
+        int firstQuoteIndex = header.indexOf("\"", encodingIndex);
+        int lastQuoteIndex;
+
+        if ((firstQuoteIndex == -1) || (firstQuoteIndex > endOfXMLPI)) {
+            firstQuoteIndex = header.indexOf("'", encodingIndex);
+            lastQuoteIndex = header.indexOf("'", firstQuoteIndex + 1);
+        } else
+            lastQuoteIndex = header.indexOf("\"", firstQuoteIndex + 1);
+
+        return header.substring(firstQuoteIndex + 1, lastQuoteIndex);
+    }
+
+    protected static byte[] readBuffer(InputStream is) throws IOException {
+        if (is.available() == 0) {
+            return new byte[0];
+        }
+
+        byte[] buffer = new byte[BUFFER_SIZE];
+        is.mark(BUFFER_SIZE);
+        int bytesRead = is.read(buffer, 0, BUFFER_SIZE);
+        int totalBytesRead = bytesRead;
+
+        while (bytesRead != -1 && (totalBytesRead < BUFFER_SIZE)) {
+            bytesRead = is.read(buffer, totalBytesRead, BUFFER_SIZE - totalBytesRead);
+
+            if (bytesRead != -1)
+                totalBytesRead += bytesRead;
+        }
+
+        if (totalBytesRead < BUFFER_SIZE) {
+            byte[] smallerBuffer = new byte[totalBytesRead];
+            System.arraycopy(buffer, 0, smallerBuffer, 0, totalBytesRead);
+            smallerBuffer = buffer;
+        }
+
+        is.reset();
+        return buffer;
+    }
+
+    public static InputSource getInputSource(URL url) throws IOException {
+        InputStream is = openStream(url);
+        return getInputSource(url, is);
+    }
+
+    private static InputStream openStream(URL url) throws IOException {
+        URLConnection connection = url.openConnection();
+        if (connection instanceof JarURLConnection) {
+            // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5041014
+            connection.setUseCaches(false);
+        }
+        InputStream is = connection.getInputStream();
+        return is;
+    }
+
+    public static InputSource getInputSource(URL url, InputStream is) throws IOException {
+        is = new BufferedInputStream(is);
+        String encoding = getEncoding(is);
+        InputSource inputSource = new InputSource(is);
+        inputSource.setEncoding(encoding);
+        // [rfeng] Make sure we set the system id as it will be used as the base URI for nested import/include 
+        inputSource.setSystemId(url.toString());
+        return inputSource;
+    }
+
+}

Propchange: tuscany/java/sca/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/XMLDocumentHelper.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: tuscany/java/sca/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/XMLDocumentHelper.java
------------------------------------------------------------------------------
    svn:keywords = Rev Date

Modified: tuscany/java/sca/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/StAXHelper.java
URL: http://svn.apache.org/viewvc/tuscany/java/sca/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/StAXHelper.java?rev=802905&r1=802904&r2=802905&view=diff
==============================================================================
--- tuscany/java/sca/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/StAXHelper.java (original)
+++ tuscany/java/sca/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/StAXHelper.java Mon Aug 10 19:24:12 2009
@@ -18,12 +18,16 @@
  */
 package org.apache.tuscany.sca.common.xml.stax;
 
+import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.Reader;
 import java.io.StringReader;
 import java.io.StringWriter;
 import java.io.Writer;
+import java.net.JarURLConnection;
+import java.net.URL;
+import java.net.URLConnection;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
@@ -31,6 +35,7 @@
 
 import javax.xml.XMLConstants;
 import javax.xml.namespace.QName;
+import javax.xml.stream.StreamFilter;
 import javax.xml.stream.XMLInputFactory;
 import javax.xml.stream.XMLOutputFactory;
 import javax.xml.stream.XMLStreamConstants;
@@ -112,6 +117,24 @@
         StringReader reader = new StringReader(string);
         return createXMLStreamReader(reader);
     }
+    
+    private static InputStream openStream(URL url) throws IOException {
+        URLConnection connection = url.openConnection();
+        if (connection instanceof JarURLConnection) {
+            // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5041014
+            connection.setUseCaches(false);
+        }
+        InputStream is = connection.getInputStream();
+        return is;
+    }
+    
+    public XMLStreamReader createXMLStreamReader(URL url) throws XMLStreamException {
+        try {
+            return createXMLStreamReader(openStream(url));
+        } catch (IOException e) {
+            throw new XMLStreamException(e);
+        }
+    }
 
     public String saveAsString(XMLStreamReader reader) throws XMLStreamException {
         StringWriter writer = new StringWriter();
@@ -179,6 +202,43 @@
         new StAX2SAXAdapter(false).parse(reader, contentHandler);
     }
 
+
+    /**
+     * @param url
+     * @param element
+     * @param attribute
+     * @param rootOnly
+     * @return
+     * @throws IOException
+     * @throws XMLStreamException
+     */
+    public String readAttribute(URL url, QName element, String attribute) throws IOException,
+        XMLStreamException {
+        if (attribute == null) {
+            attribute = "targetNamespace";
+        }
+        XMLStreamReader reader = createXMLStreamReader(url);
+        try {
+            return readAttributeFromRoot(reader, element, attribute);
+        } finally {
+            reader.close();
+        }
+    }
+
+    public List<String> readAttributes(URL url, QName element, String attribute) throws IOException,
+        XMLStreamException {
+        if (attribute == null) {
+            attribute = "targetNamespace";
+        }
+        XMLStreamReader reader = createXMLStreamReader(url);
+        try {
+            Attribute attr = new Attribute(element, attribute);
+            return readAttributes(reader, attr)[0].getValues();
+        } finally {
+            reader.close();
+        }
+    }
+    
     /**
      * Returns the boolean value of an attribute.
      * @param reader
@@ -296,4 +356,102 @@
         }
     }
 
+    
+    private Attribute[] readAttributes(XMLStreamReader reader, AttributeFilter filter) throws XMLStreamException {
+        XMLStreamReader newReader = inputFactory.createFilteredReader(reader, filter);
+        while (filter.proceed() && newReader.hasNext()) {
+            newReader.next();
+        }
+        return filter.attributes;
+    }
+
+    public Attribute[] readAttributes(URL url, Attribute... attributes) throws XMLStreamException {
+        XMLStreamReader reader = createXMLStreamReader(url);
+        try {
+            return readAttributes(reader, attributes);
+        } finally {
+            reader.close();
+        }
+    }
+
+    public Attribute[] readAttributes(XMLStreamReader reader, Attribute... attributes) throws XMLStreamException {
+        return readAttributes(reader, new AttributeFilter(false, attributes));
+    }
+    
+    private String readAttributeFromRoot(XMLStreamReader reader, Attribute filter) throws XMLStreamException {
+        Attribute[] attrs = readAttributes(reader, new AttributeFilter(true, filter));
+        List<String> values = attrs[0].getValues();
+        if (values.isEmpty()) {
+            return null;
+        } else {
+            return values.get(0);
+        }
+    }
+    
+    public String readAttributeFromRoot(XMLStreamReader reader, QName element, String attributeName)
+        throws XMLStreamException {
+        Attribute filter = new Attribute(element, attributeName);
+        return readAttributeFromRoot(reader, filter);
+    }
+    
+    public static class Attribute {
+        private QName element;
+        private String name;
+        private List<String> values = new ArrayList<String>();
+
+        /**
+         * @param element
+         * @param name
+         */
+        public Attribute(QName element, String name) {
+            super();
+            this.element = element;
+            this.name = name;
+        }
+
+        public List<String> getValues() {
+            return values;
+        }
+        
+    }
+    
+    private static class AttributeFilter implements StreamFilter {
+        private boolean proceed = true;
+        private Attribute[] attributes;
+        private boolean rootOnly;
+        
+        /**
+         * @param rootOnly
+         */
+        public AttributeFilter(boolean rootOnly, Attribute...attributes) {
+            super();
+            this.rootOnly = rootOnly;
+            this.attributes = attributes;
+        }
+
+        public boolean accept(XMLStreamReader reader) {
+            if(attributes==null || attributes.length==0) {
+                proceed = false;
+                return true;
+            }
+            if(reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
+                QName name = reader.getName();
+                for(Attribute attr: attributes) {
+                    if(attr.element.equals(name)) {
+                        attr.values.add(reader.getAttributeValue(null, attr.name));
+                    }
+                }
+                if (rootOnly) {
+                    proceed = false;
+                }
+            }
+            return true;
+        }
+        
+        public boolean proceed() {
+            return proceed;
+        }
+        
+    }
+
 }

Modified: tuscany/java/sca/modules/common-xml/src/test/java/org/apache/tuscany/sca/common/xml/stax/StAXHelperTestCase.java
URL: http://svn.apache.org/viewvc/tuscany/java/sca/modules/common-xml/src/test/java/org/apache/tuscany/sca/common/xml/stax/StAXHelperTestCase.java?rev=802905&r1=802904&r2=802905&view=diff
==============================================================================
--- tuscany/java/sca/modules/common-xml/src/test/java/org/apache/tuscany/sca/common/xml/stax/StAXHelperTestCase.java (original)
+++ tuscany/java/sca/modules/common-xml/src/test/java/org/apache/tuscany/sca/common/xml/stax/StAXHelperTestCase.java Mon Aug 10 19:24:12 2009
@@ -21,10 +21,16 @@
 
 import static org.junit.Assert.assertNotNull;
 
+import java.net.URL;
+import java.util.List;
+
+import javax.xml.namespace.QName;
 import javax.xml.stream.XMLStreamReader;
 
+import org.apache.tuscany.sca.common.xml.stax.StAXHelper.Attribute;
 import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry;
 import org.custommonkey.xmlunit.XMLAssert;
+import org.junit.Assert;
 import org.junit.Test;
 import org.w3c.dom.Node;
 
@@ -37,6 +43,9 @@
     private static final String XML =
         "<a:foo xmlns:a='http://a' name='foo'><bar name='bar'>" + "<doo a:name='doo' xmlns:a='http://doo'/>"
             + "</bar></a:foo>";
+    public static final QName WSDL11 = new QName("http://schemas.xmlsoap.org/wsdl/", "definitions");
+    public static final QName WSDL20 = new QName("http://www.w3.org/ns/wsdl", "description");
+    public static final QName XSD = new QName("http://www.w3.org/2001/XMLSchema", "schema");
 
     @Test
     public void testHelper() throws Exception {
@@ -54,4 +63,38 @@
         XMLAssert.assertXMLEqual(XML, xml);
     }
 
+    @Test
+    public void testIndex() throws Exception {
+        StAXHelper helper = new StAXHelper(new DefaultExtensionPointRegistry());
+        URL xsd = getClass().getResource("test.xsd");
+        String tns = helper.readAttribute(xsd, XSD, "targetNamespace");
+        Assert.assertEquals("http://www.example.org/test/", tns);
+
+        List<String> tnsList = helper.readAttributes(xsd, XSD, "targetNamespace");
+        Assert.assertEquals(1, tnsList.size());
+        Assert.assertEquals("http://www.example.org/test/", tnsList.get(0));
+
+        URL wsdl = getClass().getResource("test.wsdl");
+        tns = helper.readAttribute(wsdl, WSDL11, "targetNamespace");
+        Assert.assertEquals("http://www.example.org/test/wsdl", tns);
+
+        tns = helper.readAttribute(wsdl, XSD, "targetNamespace");
+        Assert.assertNull(tns);
+
+        tnsList = helper.readAttributes(wsdl, XSD, "targetNamespace");
+        Assert.assertEquals(2, tnsList.size());
+        Assert.assertEquals("http://www.example.org/test/xsd1", tnsList.get(0));
+        Assert.assertEquals("http://www.example.org/test/xsd2", tnsList.get(1));
+
+        Attribute attr1 = new Attribute(WSDL11, "targetNamespace");
+        Attribute attr2 = new Attribute(XSD, "targetNamespace");
+        Attribute[] attrs = helper.readAttributes(wsdl, attr1, attr2);
+
+        Assert.assertEquals(2, attrs.length);
+        Assert.assertEquals("http://www.example.org/test/wsdl", attrs[0].getValues().get(0));
+        Assert.assertEquals("http://www.example.org/test/xsd1", attrs[1].getValues().get(0));
+        Assert.assertEquals("http://www.example.org/test/xsd2", attrs[1].getValues().get(1));
+
+    }
+
 }

Added: tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/xml/stax/test.wsdl
URL: http://svn.apache.org/viewvc/tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/xml/stax/test.wsdl?rev=802905&view=auto
==============================================================================
--- tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/xml/stax/test.wsdl (added)
+++ tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/xml/stax/test.wsdl Mon Aug 10 19:24:12 2009
@@ -0,0 +1,60 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * 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.    
+-->
+<wsdl:definitions name="TestDefinition" 
+    targetNamespace="http://www.example.org/test/wsdl" 
+    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
+    xmlns:tns="http://www.example.org/test/wsdl"
+    xmlns:xsd1="http://www.example.org/test/xsd1" 
+    xmlns:xsd2="http://www.example.org/test/xsd2"
+    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+    <wsdl:types>
+        <xsd:schema targetNamespace="http://www.example.org/test/xsd1">
+            <xsd:element name="test">
+                <xsd:complexType>
+                    <xsd:sequence>
+                        <xsd:element name="in" type="xsd:string"></xsd:element>
+                    </xsd:sequence>
+                </xsd:complexType>
+            </xsd:element>
+            <xsd:element name="testResponse">
+                <xsd:complexType>
+                    <xsd:sequence>
+                        <xsd:element name="out" type="xsd:string"></xsd:element>
+                    </xsd:sequence>
+                </xsd:complexType>
+            </xsd:element>
+        </xsd:schema>
+        <xsd:schema targetNamespace="http://www.example.org/test/xsd2">
+            <xsd:element name="test2" type="xsd:string"></xsd:element>
+        </xsd:schema>
+    </wsdl:types>
+    <wsdl:message name="testRequest">
+        <wsdl:part name="parameters" element="xsd1:test"></wsdl:part>
+    </wsdl:message>
+    <wsdl:message name="testResponse">
+        <wsdl:part name="parameters" element="xsd1:testResponse"></wsdl:part>
+    </wsdl:message>
+    <wsdl:portType name="Test">
+        <wsdl:operation name="test">
+            <wsdl:input message="tns:testRequest"></wsdl:input>
+            <wsdl:output message="tns:testResponse"></wsdl:output>
+        </wsdl:operation>
+    </wsdl:portType>
+</wsdl:definitions>

Propchange: tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/xml/stax/test.wsdl
------------------------------------------------------------------------------
    svn:keywords = Rev Date

Added: tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/xml/stax/test.xsd
URL: http://svn.apache.org/viewvc/tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/xml/stax/test.xsd?rev=802905&view=auto
==============================================================================
--- tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/xml/stax/test.xsd (added)
+++ tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/xml/stax/test.xsd Mon Aug 10 19:24:12 2009
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * 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.    
+-->
+<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.example.org/test/" targetNamespace="http://www.example.org/test/">
+
+    <element name="root" type="tns:Name"></element>
+    <complexType name="Name">
+            <sequence>
+            <element name="firstName" type="string"/>
+            <element name="lastName" type="string"/>
+        </sequence>
+    </complexType>
+    
+</schema>

Propchange: tuscany/java/sca/modules/common-xml/src/test/resources/org/apache/tuscany/sca/common/xml/stax/test.xsd
------------------------------------------------------------------------------
    svn:keywords = Rev Date