cxf-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From cohei...@apache.org
Subject cxf-fediz git commit: Refactor of DOM parsing
Date Thu, 02 Jul 2015 16:22:08 GMT
Repository: cxf-fediz
Updated Branches:
  refs/heads/1.2.x-fixes a6a1fde66 -> 90c898335


Refactor of DOM parsing

Conflicts:
	plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataWriter.java
	services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java


Project: http://git-wip-us.apache.org/repos/asf/cxf-fediz/repo
Commit: http://git-wip-us.apache.org/repos/asf/cxf-fediz/commit/90c89833
Tree: http://git-wip-us.apache.org/repos/asf/cxf-fediz/tree/90c89833
Diff: http://git-wip-us.apache.org/repos/asf/cxf-fediz/diff/90c89833

Branch: refs/heads/1.2.x-fixes
Commit: 90c898335786211d253c0503453e2f8b93e0d3fe
Parents: a6a1fde
Author: Colm O hEigeartaigh <coheigea@apache.org>
Authored: Thu Jul 2 17:07:04 2015 +0100
Committer: Colm O hEigeartaigh <coheigea@apache.org>
Committed: Thu Jul 2 17:21:55 2015 +0100

----------------------------------------------------------------------
 .../cxf/fediz/core/metadata/MetadataWriter.java |   9 +-
 .../apache/cxf/fediz/core/util/DOMUtils.java    |  62 +--
 .../cxf/fediz/core/util/SignatureUtils.java     |  12 +-
 .../apache/cxf/fediz/core/util/XMLUtils.java    | 485 -------------------
 .../service/idp/metadata/IdpMetadataWriter.java |  47 +-
 .../idp/metadata/ServiceMetadataWriter.java     |  32 +-
 6 files changed, 44 insertions(+), 603 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/90c89833/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataWriter.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataWriter.java
b/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataWriter.java
index d55cdcf..c662124 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataWriter.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataWriter.java
@@ -30,7 +30,6 @@ import java.security.cert.X509Certificate;
 import java.util.List;
 
 import javax.servlet.http.HttpServletRequest;
-import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.stream.XMLOutputFactory;
 import javax.xml.stream.XMLStreamException;
 import javax.xml.stream.XMLStreamWriter;
@@ -61,11 +60,6 @@ public class MetadataWriter {
     private static final Logger LOG = LoggerFactory.getLogger(MetadataWriter.class);
     
     private static final XMLOutputFactory XML_OUTPUT_FACTORY = XMLOutputFactory.newInstance();
-    private static final DocumentBuilderFactory DOC_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
-    
-    static {
-        DOC_BUILDER_FACTORY.setNamespaceAware(true);
-    }
 
     //CHECKSTYLE:OFF
     public Document getMetaData(
@@ -130,8 +124,9 @@ public class MetadataWriter {
                 LOG.info("No signingKey element found in config: " + ex.getMessage());
             }
             if (hasSigningKey) {
+                Document doc = DOMUtils.readXml(is);
                 Document result = SignatureUtils.signMetaInfo(
-                    config.getSigningKey().getCrypto(), config.getSigningKey().getKeyAlias(),
config.getSigningKey().getKeyPassword(), is, referenceID);
+                    config.getSigningKey().getCrypto(), config.getSigningKey().getKeyAlias(),
config.getSigningKey().getKeyPassword(), doc, referenceID);
                 if (result != null) {
                     return result;
                 } else {

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/90c89833/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/DOMUtils.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/DOMUtils.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/DOMUtils.java
index 5efc6e1..acfa972 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/DOMUtils.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/DOMUtils.java
@@ -75,11 +75,13 @@ public final class DOMUtils {
             loader = DOMUtils.class.getClassLoader();
         }
         if (loader == null) {
-            return XMLUtils.getParser();
+            DocumentBuilderFactory dbf = createDocumentBuilderFactory();
+            return dbf.newDocumentBuilder();
         }
         DocumentBuilder builder = DOCUMENT_BUILDERS.get(loader);
         if (builder == null) {
-            builder = XMLUtils.getParser();
+            DocumentBuilderFactory dbf = createDocumentBuilderFactory();
+            builder = dbf.newDocumentBuilder();
             DOCUMENT_BUILDERS.put(loader, builder);
         }
         return builder;
@@ -421,13 +423,10 @@ public final class DOMUtils {
             return new InputSource(new StringReader(""));
         }
     }
-
-    /**
-     * Read XML as DOM.
-     */
-    public static Document readXml(InputStream is) throws SAXException, IOException,
-        ParserConfigurationException {
+    
+    private static DocumentBuilderFactory createDocumentBuilderFactory() throws ParserConfigurationException
{
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING , true);
 
         dbf.setValidating(false);
         dbf.setIgnoringComments(false);
@@ -435,62 +434,39 @@ public final class DOMUtils {
         dbf.setNamespaceAware(true);
         // dbf.setCoalescing(true);
         // dbf.setExpandEntityReferences(true);
+        
+        return dbf;
+    }
 
-        DocumentBuilder db = null;
-        db = dbf.newDocumentBuilder();
-        db.setEntityResolver(new NullResolver());
-
-        // db.setErrorHandler( new MyErrorHandler());
-
+    /**
+     * Read XML as DOM.
+     */
+    public static Document readXml(InputStream is) throws SAXException, IOException,
+        ParserConfigurationException {
+        DocumentBuilder db = getBuilder();
         return db.parse(is);
     }
 
     public static Document readXml(Reader is) throws SAXException, IOException, ParserConfigurationException
{
-        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-
-        dbf.setValidating(false);
-        dbf.setIgnoringComments(false);
-        dbf.setIgnoringElementContentWhitespace(true);
-        dbf.setNamespaceAware(true);
-        // dbf.setCoalescing(true);
-        // dbf.setExpandEntityReferences(true);
-
-        DocumentBuilder db = null;
-        db = dbf.newDocumentBuilder();
-        db.setEntityResolver(new NullResolver());
-
-        // db.setErrorHandler( new MyErrorHandler());
         InputSource ips = new InputSource(is);
+        DocumentBuilder db = getBuilder();
         return db.parse(ips);
     }
 
     public static Document readXml(StreamSource is) throws SAXException, IOException,
         ParserConfigurationException {
-
-        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-
-        dbf.setValidating(false);
-        dbf.setIgnoringComments(false);
-        dbf.setIgnoringElementContentWhitespace(true);
-        dbf.setNamespaceAware(true);
-        // dbf.setCoalescing(true);
-        // dbf.setExpandEntityReferences(true);
-
-        DocumentBuilder db = null;
-        db = dbf.newDocumentBuilder();
-        db.setEntityResolver(new NullResolver());
-
-        // db.setErrorHandler( new MyErrorHandler());
         InputSource is2 = new InputSource();
         is2.setSystemId(is.getSystemId());
         is2.setByteStream(is.getInputStream());
         is2.setCharacterStream(is.getReader());
 
+        DocumentBuilder db = getBuilder();
         return db.parse(is2);
     }
 
     public static void writeXml(Node n, OutputStream os) throws TransformerException {
         TransformerFactory tf = TransformerFactory.newInstance();
+        tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING , true);
         // identity
         Transformer t = tf.newTransformer();
         t.setOutputProperty(OutputKeys.INDENT, "yes");

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/90c89833/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/SignatureUtils.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/SignatureUtils.java
b/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/SignatureUtils.java
index 9107e6b..ddd4793 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/SignatureUtils.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/SignatureUtils.java
@@ -19,7 +19,6 @@
 
 package org.apache.cxf.fediz.core.util;
 
-import java.io.InputStream;
 import java.security.PrivateKey;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
@@ -40,7 +39,6 @@ import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
 import javax.xml.crypto.dsig.keyinfo.X509Data;
 import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
 import javax.xml.crypto.dsig.spec.TransformParameterSpec;
-import javax.xml.parsers.DocumentBuilderFactory;
 
 import org.w3c.dom.Document;
 
@@ -53,18 +51,12 @@ public final class SignatureUtils {
     private static final Logger LOG = LoggerFactory.getLogger(SignatureUtils.class);
     
     private static final XMLSignatureFactory XML_SIGNATURE_FACTORY = XMLSignatureFactory.getInstance("DOM");
-    private static final DocumentBuilderFactory DOC_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
-    
-    static {
-        DOC_BUILDER_FACTORY.setNamespaceAware(true);
-    }
     
     private SignatureUtils() {
     }
     
-    
     public static Document signMetaInfo(Crypto crypto, String keyAlias, String keyPassword,
-                                              InputStream metaInfo, String referenceID) throws
Exception {
+                                              Document doc, String referenceID) throws Exception
{
         if (keyAlias == null || "".equals(keyAlias)) {
             keyAlias = crypto.getDefaultX509Identifier();
         }
@@ -143,8 +135,6 @@ public final class SignatureUtils {
         KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
 
         // step3
-        // Instantiate the document to be signed.
-        Document doc = DOC_BUILDER_FACTORY.newDocumentBuilder().parse(metaInfo);
 
         // Create a DOMSignContext and specify the RSA PrivateKey and
         // location of the resulting XMLSignature's parent element.

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/90c89833/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/XMLUtils.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/XMLUtils.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/XMLUtils.java
deleted file mode 100644
index 9b0dbf5..0000000
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/XMLUtils.java
+++ /dev/null
@@ -1,485 +0,0 @@
-/**
- * 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.cxf.fediz.core.util;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.util.Collections;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.WeakHashMap;
-import javax.xml.namespace.QName;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Source;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerConfigurationException;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMResult;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
-import org.w3c.dom.Attr;
-import org.w3c.dom.DOMImplementation;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.Text;
-import org.w3c.dom.bootstrap.DOMImplementationRegistry;
-import org.w3c.dom.ls.DOMImplementationLS;
-import org.w3c.dom.ls.LSOutput;
-import org.w3c.dom.ls.LSSerializer;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-/**
- * Few simple utils. This is originally from the CXF project.
- */
-@SuppressWarnings("PMD")
-public final class XMLUtils {
-
-    // private static final Logger LOG = LogUtils.getL7dLogger(XMLUtils.class);
-
-    private static final Map<ClassLoader, DocumentBuilderFactory> DOCUMENT_BUILDER_FACTORIES
= Collections
-        .synchronizedMap(new WeakHashMap<ClassLoader, DocumentBuilderFactory>());
-
-    private static final Map<ClassLoader, TransformerFactory> TRANSFORMER_FACTORIES
= Collections
-        .synchronizedMap(new WeakHashMap<ClassLoader, TransformerFactory>());
-
-    private XMLUtils() {
-    }
-
-    private static TransformerFactory getTransformerFactory() {
-        ClassLoader loader = Thread.currentThread().getContextClassLoader();
-        if (loader == null) {
-            loader = XMLUtils.class.getClassLoader();
-        }
-        if (loader == null) {
-            return TransformerFactory.newInstance();
-        }
-        TransformerFactory factory = TRANSFORMER_FACTORIES.get(loader);
-        if (factory == null) {
-            factory = TransformerFactory.newInstance();
-            TRANSFORMER_FACTORIES.put(loader, factory);
-        }
-        return factory;
-    }
-
-    private static DocumentBuilderFactory getDocumentBuilderFactory() {
-        ClassLoader loader = Thread.currentThread().getContextClassLoader();
-        if (loader == null) {
-            loader = XMLUtils.class.getClassLoader();
-        }
-        if (loader == null) {
-            return DocumentBuilderFactory.newInstance();
-        }
-        DocumentBuilderFactory factory = DOCUMENT_BUILDER_FACTORIES.get(loader);
-        if (factory == null) {
-            factory = DocumentBuilderFactory.newInstance();
-            factory.setNamespaceAware(true);
-            DOCUMENT_BUILDER_FACTORIES.put(loader, factory);
-        }
-        return factory;
-    }
-
-    public static Transformer newTransformer() throws TransformerConfigurationException {
-        return getTransformerFactory().newTransformer();
-    }
-
-    public static Transformer newTransformer(int indent) throws TransformerConfigurationException
{
-        if (indent > 0) {
-            TransformerFactory f = TransformerFactory.newInstance();
-            try {
-                // sun way of setting indent
-                f.setAttribute("indent-number", Integer.toString(indent));
-            } catch (Throwable t) {
-                // ignore
-            }
-            return f.newTransformer();
-        }
-        return getTransformerFactory().newTransformer();
-    }
-
-    public static DocumentBuilder getParser() throws ParserConfigurationException {
-        return getDocumentBuilderFactory().newDocumentBuilder();
-    }
-
-    public static Document parse(InputSource is) throws ParserConfigurationException, SAXException,
-        IOException {
-        return getParser().parse(is);
-    }
-
-    public static Document parse(File is) throws ParserConfigurationException, SAXException,
IOException {
-        return getParser().parse(is);
-    }
-
-    public static Document parse(InputStream in) throws ParserConfigurationException, SAXException,
-        IOException {
-        return getParser().parse(in);
-    }
-
-    public static Document parse(String in) throws ParserConfigurationException, SAXException,
IOException {
-        return parse(in.getBytes());
-    }
-
-    public static Document parse(byte[] in) throws ParserConfigurationException, SAXException,
IOException {
-        if (in == null) {
-            return null;
-        }
-        return getParser().parse(new ByteArrayInputStream(in));
-    }
-
-    public static Document newDocument() throws ParserConfigurationException {
-        return getParser().newDocument();
-    }
-
-    public static void writeTo(Node node, OutputStream os) {
-        writeTo(new DOMSource(node), os);
-    }
-
-    public static void writeTo(Node node, OutputStream os, int indent) {
-        writeTo(new DOMSource(node), os, indent);
-    }
-
-    public static void writeTo(Source src, OutputStream os) {
-        writeTo(src, os, -1);
-    }
-
-    public static void writeTo(Node node, Writer os) {
-        writeTo(new DOMSource(node), os);
-    }
-
-    public static void writeTo(Node node, Writer os, int indent) {
-        writeTo(new DOMSource(node), os, indent);
-    }
-
-    public static void writeTo(Source src, Writer os) {
-        writeTo(src, os, -1);
-    }
-
-    public static void writeTo(Source src, OutputStream os, int indent) {
-        String enc = null;
-        if (src instanceof DOMSource && ((DOMSource)src).getNode() instanceof Document)
{
-            try {
-                enc = ((Document)((DOMSource)src).getNode()).getXmlEncoding();
-            } catch (Exception ex) {
-                // ignore - not DOM level 3
-            }
-        }
-        writeTo(src, os, indent, enc, "no");
-    }
-
-    public static void writeTo(Source src, Writer os, int indent) {
-        String enc = null;
-        if (src instanceof DOMSource && ((DOMSource)src).getNode() instanceof Document)
{
-            try {
-                enc = ((Document)((DOMSource)src).getNode()).getXmlEncoding();
-            } catch (Exception ex) {
-                // ignore - not DOM level 3
-            }
-        }
-        writeTo(src, os, indent, enc, "no");
-    }
-
-    public static void writeTo(Source src, OutputStream os, int indent, String charset, String
omitXmlDecl) {
-        Transformer it;
-        try {
-            if (StringUtils.isEmpty(charset)) {
-                charset = "utf-8";
-            }
-
-            it = newTransformer(indent);
-            it.setOutputProperty(OutputKeys.METHOD, "xml");
-            if (indent > -1) {
-                it.setOutputProperty(OutputKeys.INDENT, "yes");
-                it.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent));
-            }
-            it.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXmlDecl);
-            it.setOutputProperty(OutputKeys.ENCODING, charset);
-            it.transform(src, new StreamResult(os));
-        } catch (TransformerException e) {
-            throw new RuntimeException("Failed to configure TRaX", e);
-        }
-    }
-
-    public static void writeTo(Source src, Writer os, int indent, String charset, String
omitXmlDecl) {
-        Transformer it;
-        try {
-            if (StringUtils.isEmpty(charset)) {
-                charset = "utf-8";
-            }
-
-            it = newTransformer(indent);
-            it.setOutputProperty(OutputKeys.METHOD, "xml");
-            if (indent > -1) {
-                it.setOutputProperty(OutputKeys.INDENT, "yes");
-                it.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent));
-            }
-            it.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXmlDecl);
-            it.setOutputProperty(OutputKeys.ENCODING, charset);
-            it.transform(src, new StreamResult(os));
-        } catch (TransformerException e) {
-            throw new RuntimeException("Failed to configure TRaX", e);
-        }
-    }
-
-    public static String toString(Source source) throws TransformerException, IOException
{
-        return toString(source, null);
-    }
-
-    public static String toString(Source source, Properties props) throws TransformerException,
IOException {
-        StringWriter bos = new StringWriter();
-        StreamResult sr = new StreamResult(bos);
-        Transformer trans = newTransformer();
-        if (props == null) {
-            props = new Properties();
-            props.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
-        }
-        trans.setOutputProperties(props);
-        trans.transform(source, sr);
-        bos.close();
-        return bos.toString();
-    }
-
-    public static String toString(Node node, int indent) {
-        ByteArrayOutputStream out = new ByteArrayOutputStream();
-        writeTo(node, out, indent);
-        return out.toString();
-    }
-
-    public static String toString(Node node) {
-        ByteArrayOutputStream out = new ByteArrayOutputStream();
-        writeTo(node, out);
-        return out.toString();
-    }
-
-    public static void printDOM(Node node) {
-        printDOM("", node);
-    }
-
-    public static void printDOM(String words, Node node) {
-        System.out.println(words);
-        System.out.println(toString(node));
-    }
-
-    public static Attr getAttribute(Element el, String attrName) {
-        return el.getAttributeNode(attrName);
-    }
-
-    public static void replaceAttribute(Element element, String attr, String value) {
-        if (element.hasAttribute(attr)) {
-            element.removeAttribute(attr);
-        }
-        element.setAttribute(attr, value);
-    }
-
-    public static boolean hasAttribute(Element element, String value) {
-        NamedNodeMap attributes = element.getAttributes();
-        for (int i = 0; i < attributes.getLength(); i++) {
-            Node node = attributes.item(i);
-            if (value.equals(node.getNodeValue())) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    public static void printAttributes(Element element) {
-        NamedNodeMap attributes = element.getAttributes();
-        for (int i = 0; i < attributes.getLength(); i++) {
-            Node node = attributes.item(i);
-            System.err.println("## prefix=" + node.getPrefix() + " localname:" + node.getLocalName()
-                               + " value=" + node.getNodeValue());
-        }
-    }
-
-    public static QName getNamespace(Map<String, String> namespaces, String str, String
defaultNamespace) {
-        String prefix = null;
-        String localName = null;
-
-        StringTokenizer tokenizer = new StringTokenizer(str, ":");
-        if (tokenizer.countTokens() == 2) {
-            prefix = tokenizer.nextToken();
-            localName = tokenizer.nextToken();
-        } else if (tokenizer.countTokens() == 1) {
-            localName = tokenizer.nextToken();
-        }
-
-        String namespceURI = defaultNamespace;
-        if (prefix != null) {
-            namespceURI = (String)namespaces.get(prefix);
-        }
-        return new QName(namespceURI, localName);
-    }
-
-    public static void generateXMLFile(Element element, Writer writer) {
-        try {
-            Transformer it = newTransformer();
-
-            it.setOutputProperty(OutputKeys.METHOD, "xml");
-            it.setOutputProperty(OutputKeys.INDENT, "yes");
-            it.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
-            it.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
-            it.transform(new DOMSource(element), new StreamResult(writer));
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-    }
-
-    public static Element createElementNS(Node node, QName name) {
-        return createElementNS(node.getOwnerDocument(), name.getNamespaceURI(), name.getLocalPart());
-    }
-
-    public static Element createElementNS(Document root, QName name) {
-        return createElementNS(root, name.getNamespaceURI(), name.getLocalPart());
-    }
-
-    public static Element createElementNS(Document root, String namespaceURI, String qualifiedName)
{
-        return root.createElementNS(namespaceURI, qualifiedName);
-    }
-
-    public static Text createTextNode(Document root, String data) {
-        return root.createTextNode(data);
-    }
-
-    public static Text createTextNode(Node node, String data) {
-        return createTextNode(node.getOwnerDocument(), data);
-    }
-
-    public static void removeContents(Node parent) {
-        Node node = parent.getFirstChild();
-        while (node != null) {
-            parent.removeChild(node);
-            node = node.getNextSibling();
-        }
-    }
-
-    public static InputStream getInputStream(Document doc) throws Exception {
-        DOMImplementationLS impl = null;
-        DOMImplementation docImpl = doc.getImplementation();
-        // Try to get the DOMImplementation from doc first before
-        // defaulting to the sun implementation.
-        if (docImpl != null && docImpl.hasFeature("LS", "3.0")) {
-            impl = (DOMImplementationLS)docImpl.getFeature("LS", "3.0");
-        } else {
-            DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
-            impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
-            if (impl == null) {
-                System.setProperty(DOMImplementationRegistry.PROPERTY,
-                                   "com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
-                registry = DOMImplementationRegistry.newInstance();
-                impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
-            }
-        }
-        LSOutput output = impl.createLSOutput();
-        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
-        output.setByteStream(byteArrayOutputStream);
-        LSSerializer writer = impl.createLSSerializer();
-        writer.write(doc, output);
-        byte[] buf = byteArrayOutputStream.toByteArray();
-        return new ByteArrayInputStream(buf);
-    }
-
-    public static Element fetchElementByNameAttribute(Element parent, String targetName,
String nameValue) {
-
-        List<Element> elemList = DOMUtils.findAllElementsByTagName(parent, targetName);
-        for (Element elem : elemList) {
-            if (elem.getAttribute("name").equals(nameValue)) {
-                return elem;
-            }
-        }
-        return null;
-    }
-
-    public static QName getQName(String value, Node node) {
-        if (value == null) {
-            return null;
-        }
-
-        int index = value.indexOf(":");
-
-        if (index == -1) {
-            return new QName(value);
-        }
-
-        String prefix = value.substring(0, index);
-        String localName = value.substring(index + 1);
-        String ns = node.lookupNamespaceURI(prefix);
-
-        if (ns == null || localName == null) {
-            throw new RuntimeException("Invalid QName in mapping: " + value);
-        }
-
-        return new QName(ns, localName, prefix);
-    }
-
-    public static Node fromSource(Source src) throws Exception {
-
-        Transformer trans = TransformerFactory.newInstance().newTransformer();
-        DOMResult res = new DOMResult();
-        trans.transform(src, res);
-        return res.getNode();
-    }
-
-    public static QName convertStringToQName(String expandedQName) {
-        return convertStringToQName(expandedQName, "");
-    }
-
-    public static QName convertStringToQName(String expandedQName, String prefix) {
-        int ind1 = expandedQName.indexOf('{');
-        if (ind1 != 0) {
-            return new QName(expandedQName);
-        }
-
-        int ind2 = expandedQName.indexOf('}');
-        if (ind2 <= ind1 + 1 || ind2 >= expandedQName.length() - 1) {
-            return null;
-        }
-        String ns = expandedQName.substring(ind1 + 1, ind2);
-        String localName = expandedQName.substring(ind2 + 1);
-        return new QName(ns, localName, prefix);
-    }
-
-    public static Set<QName> convertStringsToQNames(List<String> expandedQNames)
{
-        Set<QName> dropElements = Collections.emptySet();
-        if (expandedQNames != null) {
-            dropElements = new LinkedHashSet<QName>(expandedQNames.size());
-            for (String val : expandedQNames) {
-                dropElements.add(XMLUtils.convertStringToQName(val));
-            }
-        }
-        return dropElements;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/90c89833/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
index cb2f779..0d9b0b1 100644
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
+++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
@@ -19,15 +19,8 @@
 
 package org.apache.cxf.fediz.service.idp.metadata;
 
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
 import java.security.cert.X509Certificate;
 
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.stream.XMLOutputFactory;
 import javax.xml.stream.XMLStreamException;
 import javax.xml.stream.XMLStreamWriter;
 
@@ -36,7 +29,9 @@ import org.apache.cxf.fediz.core.util.CertsUtils;
 import org.apache.cxf.fediz.core.util.SignatureUtils;
 import org.apache.cxf.fediz.service.idp.domain.Claim;
 import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.staxutils.W3CDOMStreamWriter;
 import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.util.DOM2Writer;
 import org.apache.xml.security.stax.impl.util.IDGenerator;
 import org.apache.xml.security.utils.Base64;
 import org.slf4j.Logger;
@@ -51,29 +46,20 @@ public class IdpMetadataWriter {
     
     private static final Logger LOG = LoggerFactory.getLogger(IdpMetadataWriter.class);
     
-    private static final XMLOutputFactory XML_OUTPUT_FACTORY = XMLOutputFactory.newInstance();
-    private static final DocumentBuilderFactory DOC_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
-    
-    static {
-        DOC_BUILDER_FACTORY.setNamespaceAware(true);
-    }
-
     //CHECKSTYLE:OFF
     public Document getMetaData(Idp config) throws RuntimeException {
-        //Return as text/xml
         try {
+            //Return as text/xml
             Crypto crypto = CertsUtils.createCrypto(config.getCertificate());
-            
-            ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
-            Writer streamWriter = new OutputStreamWriter(bout, "UTF-8");
-            XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(streamWriter);
+
+            W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
 
             writer.writeStartDocument("UTF-8", "1.0");
 
             String referenceID = IDGenerator.generateID("_");
             writer.writeStartElement("md", "EntityDescriptor", SAML2_METADATA_NS);
             writer.writeAttribute("ID", referenceID);
-                      
+
             writer.writeAttribute("entityID", config.getIdpUrl().toString());
 
             writer.writeNamespace("md", SAML2_METADATA_NS);
@@ -81,37 +67,34 @@ public class IdpMetadataWriter {
             writer.writeNamespace("wsa", WS_ADDRESSING_NS);
             writer.writeNamespace("auth", WS_FEDERATION_NS);
             writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS);
-            
+
             writeFederationMetadata(writer, config, crypto);
-            
+
             writer.writeEndElement(); // EntityDescriptor
 
             writer.writeEndDocument();
-            streamWriter.flush();
-            bout.flush();
+
+            writer.close();
 
             if (LOG.isDebugEnabled()) {
-                String out = new String(bout.toByteArray());
+                String out = DOM2Writer.nodeToString(writer.getDocument());
                 LOG.debug("***************** unsigned ****************");
                 LOG.debug(out);
                 LOG.debug("***************** unsigned ****************");
             }
-            
-            InputStream is = new ByteArrayInputStream(bout.toByteArray());
-            
-            Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(),
is, referenceID);
+
+            Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(),

+                                                          writer.getDocument(), referenceID);
             if (result != null) {
                 return result;
             } else {
                 throw new RuntimeException("Failed to sign the metadata document: result=null");
             }
-        } catch (RuntimeException e) {
-            throw e;
         } catch (Exception e) {
             LOG.error("Error creating service metadata information ", e);
             throw new RuntimeException("Error creating service metadata information: " +
e.getMessage());
         }
-        
+
     }
     
     private void writeFederationMetadata(

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/90c89833/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
index a732511..4b138e8 100644
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
+++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
@@ -19,28 +19,22 @@
 
 package org.apache.cxf.fediz.service.idp.metadata;
 
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
 import java.security.cert.X509Certificate;
 import java.util.Map;
 
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.stream.XMLOutputFactory;
 import javax.xml.stream.XMLStreamException;
 import javax.xml.stream.XMLStreamWriter;
 
 import org.w3c.dom.Document;
-
 import org.apache.cxf.fediz.core.exception.ProcessingException;
 import org.apache.cxf.fediz.core.util.CertsUtils;
 import org.apache.cxf.fediz.core.util.SignatureUtils;
 import org.apache.cxf.fediz.service.idp.domain.Idp;
 import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
 import org.apache.cxf.fediz.service.idp.protocols.TrustedIdpSAMLProtocolHandler;
+import org.apache.cxf.staxutils.W3CDOMStreamWriter;
 import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.util.DOM2Writer;
 import org.apache.xml.security.stax.impl.util.IDGenerator;
 import org.apache.xml.security.utils.Base64;
 import org.slf4j.Logger;
@@ -54,13 +48,6 @@ import static org.apache.cxf.fediz.core.FedizConstants.WS_FEDERATION_NS;
 public class ServiceMetadataWriter {
     
     private static final Logger LOG = LoggerFactory.getLogger(ServiceMetadataWriter.class);
-    
-    private static final XMLOutputFactory XML_OUTPUT_FACTORY = XMLOutputFactory.newInstance();
-    private static final DocumentBuilderFactory DOC_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
-    
-    static {
-        DOC_BUILDER_FACTORY.setNamespaceAware(true);
-    }
 
     //CHECKSTYLE:OFF
     public Document getMetaData(Idp config, TrustedIdp serviceConfig) throws ProcessingException
{
@@ -68,9 +55,7 @@ public class ServiceMetadataWriter {
         try {
             Crypto crypto = CertsUtils.createCrypto(config.getCertificate());
             
-            ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
-            Writer streamWriter = new OutputStreamWriter(bout, "UTF-8");
-            XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(streamWriter);
+            W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
 
             writer.writeStartDocument("UTF-8", "1.0");
 
@@ -97,20 +82,17 @@ public class ServiceMetadataWriter {
 
             writer.writeEndDocument();
             
-            streamWriter.flush();
-            bout.flush();
-            //
+            writer.close();
 
             if (LOG.isDebugEnabled()) {
-                String out = new String(bout.toByteArray());
+                String out = DOM2Writer.nodeToString(writer.getDocument());
                 LOG.debug("***************** unsigned ****************");
                 LOG.debug(out);
                 LOG.debug("***************** unsigned ****************");
             }
 
-            InputStream is = new ByteArrayInputStream(bout.toByteArray());
-            
-            Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(),
is, referenceID);
+            Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(),

+                                                          writer.getDocument(), referenceID);
             if (result != null) {
                 return result;
             } else {


Mime
View raw message