summaryrefslogtreecommitdiffstats
path: root/sca-java-2.x/tags/2.0.1-RC1/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/dom/DOMHelper.java
blob: c5e70153645fece50eea2727373fea81f0d9a236 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/*
 * 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.dom;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.sax.SAXResult;
import javax.xml.transform.stream.StreamResult;

import org.apache.tuscany.sca.common.xml.dom.impl.SAX2DOMAdapter;
import org.apache.tuscany.sca.core.ExtensionPointRegistry;
import org.apache.tuscany.sca.core.FactoryExtensionPoint;
import org.apache.tuscany.sca.core.LifeCycleListener;
import org.apache.tuscany.sca.core.UtilityExtensionPoint;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;

/**
 * Helper for DOM
 *
 * @version $Rev$ $Date$
 * @tuscany.spi.extension.asclient
 */
public class DOMHelper implements LifeCycleListener {
    protected static final int INITIAL_POOL_SIZE = 8;
    protected static final int MAX_POOL_SIZE = 64;
    private DocumentBuilderFactory documentBuilderFactory;
    private TransformerFactory transformerFactory;
    protected ParserPool<DocumentBuilder> builderPool;
    protected ParserPool<Transformer> transformerPool;

    public static DOMHelper getInstance(ExtensionPointRegistry registry) {
        UtilityExtensionPoint utilities = registry.getExtensionPoint(UtilityExtensionPoint.class);
        return utilities.getUtility(DOMHelper.class);
    }

    public DOMHelper(ExtensionPointRegistry registry) {
        FactoryExtensionPoint factories = registry.getExtensionPoint(FactoryExtensionPoint.class);
        documentBuilderFactory = factories.getFactory(DocumentBuilderFactory.class);
        documentBuilderFactory.setNamespaceAware(true);
        transformerFactory = factories.getFactory(TransformerFactory.class);
    }

    /**
     * @param documentBuilderFactory
     * @param transformerFactory
     */
    public DOMHelper(DocumentBuilderFactory documentBuilderFactory, TransformerFactory transformerFactory) {
        super();
        this.documentBuilderFactory = documentBuilderFactory;
        this.transformerFactory = transformerFactory;
    }

    public Document newDocument() {
        DocumentBuilder builder = newDocumentBuilder();
        try {
            return builder.newDocument();
        } finally {
            returnDocumentBuilder(builder);
        }

    }

    public DocumentBuilder newDocumentBuilder() {
        return builderPool.borrowFromPool();
    }

    public void returnDocumentBuilder(DocumentBuilder builder) {
        builderPool.returnToPool(builder);
    }

    private DocumentBuilder createDocumentBuilder() {
        try {
            return documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public Document load(String xmlString) throws IOException, SAXException {
        DocumentBuilder builder = newDocumentBuilder();
        try {
            InputSource is = new InputSource(new StringReader(xmlString));
            return builder.parse(is);
        } finally {
            returnDocumentBuilder(builder);
        }
    }

    public Document load(Source source) {
        Transformer transformer = newTransformer();
        DOMResult result = new DOMResult(newDocument());
        try {
            transformer.transform(source, result);
        } catch (TransformerException e) {
            throw new IllegalArgumentException(e);
        } finally {
            transformerPool.returnToPool(transformer);
        }
        return (Document)result.getNode();
    }

    public NodeContentHandler createContentHandler(Node root) {
        if (root == null) {
            root = newDocument();
        }
        return new SAX2DOMAdapter(root);
    }

    public String saveAsString(Node node) {
        Transformer transformer = newTransformer();
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        try {
            transformer.transform(new DOMSource(node), result);
        } catch (TransformerException e) {
            throw new IllegalArgumentException(e);
        } finally {
            returnTransformer(transformer);
        }
        return result.getWriter().toString();
    }

    public Transformer newTransformer() {
        return transformerPool.borrowFromPool();
    }

    public void returnTransformer(Transformer transformer) {
        transformerPool.returnToPool(transformer);
    }

    private Transformer createTransformer() {
        Transformer transformer = null;
        try {
            transformer = transformerFactory.newTransformer();
        } catch (TransformerConfigurationException e) {
            throw new IllegalArgumentException(e);
        }
        return transformer;
    }

    public void saveAsSAX(Node node, ContentHandler contentHandler) {
        Transformer transformer = transformerPool.borrowFromPool();
        SAXResult result = new SAXResult(contentHandler);
        try {
            transformer.transform(new DOMSource(node), result);
        } catch (TransformerException e) {
            throw new IllegalArgumentException(e);
        } finally {
            returnTransformer(transformer);
        }
    }

    public static QName getQName(Node node) {
        String ns = node.getNamespaceURI();
        String prefix = node.getPrefix();
        String localName = node.getLocalName();
        if (localName == null) {
            localName = node.getNodeName();
        }
        if (ns == null) {
            ns = "";
        }
        if (prefix == null) {
            prefix = "";
        }
        return new QName(ns, localName, prefix);
    }

    public static Element createElement(Document document, QName name) {
        String prefix = name.getPrefix();
        String qname =
            (prefix != null && prefix.length() > 0) ? prefix + ":" + name.getLocalPart() : name.getLocalPart();
        return document.createElementNS(name.getNamespaceURI(), qname);
    }

    /**
     * Wrap an element as a DOM document
     * @param node
     * @return
     */
    public static Document promote(Node node) {
        if (node instanceof Document) {
            return (Document)node;
        }
        Element element = (Element)node;
        Document doc = element.getOwnerDocument();
        if (doc.getDocumentElement() == element) {
            return doc;
        }
        doc = (Document)element.getOwnerDocument().cloneNode(false);
        Element schema = (Element)doc.importNode(element, true);
        doc.appendChild(schema);
        Node parent = element.getParentNode();
        while (parent instanceof Element) {
            Element root = (Element)parent;
            NamedNodeMap nodeMap = root.getAttributes();
            for (int i = 0; i < nodeMap.getLength(); i++) {
                Attr attr = (Attr)nodeMap.item(i);
                String name = attr.getName();
                if ("xmlns".equals(name) || name.startsWith("xmlns:")) {
                    if (schema.getAttributeNode(name) == null) {
                        schema.setAttributeNodeNS((Attr)doc.importNode(attr, true));
                    }
                }
            }
            parent = parent.getParentNode();
        }
        return doc;
    }

    public static String getPrefix(Element element, String namespace) {
        if (element.isDefaultNamespace(namespace)) {
            return XMLConstants.DEFAULT_NS_PREFIX;
        }
        return element.lookupPrefix(namespace);
    }

    public static String getNamespaceURI(Element element, String prefix) {
        if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) {
            prefix = null;
        }
        return element.lookupNamespaceURI(prefix);
    }

    public static interface NodeContentHandler extends ContentHandler, LexicalHandler {
        Node getNode();
    }

    @Override
    public void start() {
        builderPool = new ParserPool<DocumentBuilder>(MAX_POOL_SIZE, INITIAL_POOL_SIZE) {

            @Override
            protected DocumentBuilder newInstance() {
                return createDocumentBuilder();
            }

            @Override
            protected void resetInstance(DocumentBuilder obj) {
                obj.reset();
            }
        };

        transformerPool = new ParserPool<Transformer>(64, 8) {

            @Override
            protected Transformer newInstance() {
                return createTransformer();
            }

            @Override
            protected void resetInstance(Transformer obj) {
                obj.reset();
            }
        };
    }

    @Override
    public void stop() {
        builderPool.clear();
        transformerPool.clear();
    }

}