XMLUtils.java 10.0 KB
Newer Older
J
jurgen 已提交
1
/*
J
jurgen 已提交
2
 * DBeaver - Universal Database Manager
3
 * Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
J
jurgen 已提交
4
 *
5 6 7
 * Licensed 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
J
jurgen 已提交
8
 *
9
 *     http://www.apache.org/licenses/LICENSE-2.0
J
jurgen 已提交
10
 *
11 12 13 14 15
 * 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.
J
jurgen 已提交
16 17 18 19
 */

package org.jkiss.utils.xml;

J
jurgen 已提交
20 21
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
22
import org.w3c.dom.Document;
J
jurgen 已提交
23
import org.w3c.dom.Element;
J
jurgen 已提交
24
import org.xml.sax.InputSource;
J
jurgen 已提交
25 26 27

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
28 29 30
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
J
jurgen 已提交
31 32 33 34 35 36 37
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Common XML utils
 */
38
public class XMLUtils {
J
jurgen 已提交
39

40 41 42 43
    public static Document parseDocument(String fileName)
        throws XMLException {
        return parseDocument(new java.io.File(fileName));
    }
J
jurgen 已提交
44

45 46 47 48 49 50 51
    public static Document parseDocument(java.io.File file) throws XMLException {
        try (InputStream is = new FileInputStream(file)) {
            return parseDocument(new InputSource(is));
        } catch (IOException e) {
            throw new XMLException("Error opening file '" + file + "'", e);
        }
    }
J
jurgen 已提交
52

53 54 55
    public static Document parseDocument(java.io.InputStream is) throws XMLException {
        return parseDocument(new InputSource(is));
    }
J
jurgen 已提交
56

57 58 59
    public static Document parseDocument(java.io.Reader is) throws XMLException {
        return parseDocument(new InputSource(is));
    }
J
jurgen 已提交
60

61 62 63 64 65 66 67 68 69
    public static Document parseDocument(InputSource source) throws XMLException {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder xmlBuilder = dbf.newDocumentBuilder();
            return xmlBuilder.parse(source);
        } catch (Exception er) {
            throw new XMLException("Error parsing XML document", er);
        }
    }
J
jurgen 已提交
70

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    public static Document createDocument()
        throws XMLException {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder xmlBuilder = dbf.newDocumentBuilder();
            return xmlBuilder.newDocument();
        } catch (Exception er) {
            throw new XMLException("Error creating XML document", er);
        }
    }

    public static Element getChildElement(Element element,
                                          String childName) {
        for (org.w3c.dom.Node node = element.getFirstChild(); node != null; node = node.getNextSibling()) {
            if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE &&
                ((Element) node).getTagName().equals(childName)) {
                return (Element) node;
            }
        }
        return null;
    }
J
jurgen 已提交
92

93 94 95 96 97 98 99 100 101 102 103
    @Nullable
    public static String getChildElementBody(Element element,
                                             String childName) {
        for (org.w3c.dom.Node node = element.getFirstChild(); node != null; node = node.getNextSibling()) {
            if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE &&
                ((Element) node).getTagName().equals(childName)) {
                return getElementBody((Element) node);
            }
        }
        return null;
    }
J
jurgen 已提交
104

105 106 107 108 109 110 111 112 113 114 115 116
    @Nullable
    public static String getElementBody(Element element) {
        org.w3c.dom.Node valueNode = element.getFirstChild();
        if (valueNode == null) {
            return null;
        }
        if (valueNode.getNodeType() == org.w3c.dom.Node.TEXT_NODE) {
            return valueNode.getNodeValue();
        } else {
            return null;
        }
    }
J
jurgen 已提交
117

118 119 120
    // Get list of all child elements of specified node
    @NotNull
    public static List<Element> getChildElementList(
J
jurgen 已提交
121
        Element parent,
122 123 124 125 126 127 128 129 130 131
        String nodeName) {
        List<Element> list = new ArrayList<>();
        for (org.w3c.dom.Node node = parent.getFirstChild(); node != null; node = node.getNextSibling()) {
            if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE &&
                nodeName.equals(node.getNodeName())) {
                list.add((Element) node);
            }
        }
        return list;
    }
J
jurgen 已提交
132

133 134 135 136 137 138 139 140 141 142 143 144 145 146
    // Get list of all child elements of specified node
    @NotNull
    public static Collection<Element> getChildElementListNS(
        Element parent,
        String nsURI) {
        List<Element> list = new ArrayList<>();
        for (org.w3c.dom.Node node = parent.getFirstChild(); node != null; node = node.getNextSibling()) {
            if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE &&
                node.getNamespaceURI().equals(nsURI)) {
                list.add((Element) node);
            }
        }
        return list;
    }
J
jurgen 已提交
147

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    // Get list of all child elements of specified node
    public static Collection<Element> getChildElementListNS(
        Element parent,
        String nodeName,
        String nsURI) {
        List<Element> list = new ArrayList<>();
        for (org.w3c.dom.Node node = parent.getFirstChild(); node != null; node = node.getNextSibling()) {
            if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE &&
                node.getLocalName().equals(nodeName) &&
                node.getNamespaceURI().equals(nsURI)) {
                list.add((Element) node);
            }
        }
        return list;
    }
J
jurgen 已提交
163

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    // Get list of all child elements of specified node
    @NotNull
    public static Collection<Element> getChildElementList(
        Element parent,
        String[] nodeNameList) {
        List<Element> list = new ArrayList<>();
        for (org.w3c.dom.Node node = parent.getFirstChild(); node != null; node = node.getNextSibling()) {
            if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                for (int i = 0; i < nodeNameList.length; i++) {
                    if (node.getNodeName().equals(nodeNameList[i])) {
                        list.add((Element) node);
                    }
                }
            }
        }
        return list;
    }
J
jurgen 已提交
181

182 183 184 185 186 187 188 189 190 191 192
    // Find one child element with specified name
    @Nullable
    public static Element findChildElement(
        Element parent) {
        for (org.w3c.dom.Node node = parent.getFirstChild(); node != null; node = node.getNextSibling()) {
            if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                return (Element) node;
            }
        }
        return null;
    }
J
jurgen 已提交
193

194 195 196 197 198 199 200 201 202
    public static Object escapeXml(Object obj) {
        if (obj == null) {
            return null;
        } else if (obj instanceof CharSequence) {
            return escapeXml((CharSequence) obj);
        } else {
            return obj;
        }
    }
J
jurgen 已提交
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
    public static String escapeXml(CharSequence str) {
        if (str == null) {
            return null;
        }
        StringBuilder res = null;
        int strLength = str.length();
        for (int i = 0; i < strLength; i++) {
            char c = str.charAt(i);
            String repl = encodeXMLChar(c);
            if (repl == null) {
                if (res != null) {
                    res.append(c);
                }
            } else {
                if (res == null) {
                    res = new StringBuilder(str.length() + 5);
                    for (int k = 0; k < i; k++) {
                        res.append(str.charAt(k));
                    }
                }
                res.append(repl);
            }
        }
        return res == null ? str.toString() : res.toString();
    }
J
jurgen 已提交
229

230 231 232
    public static boolean isValidXMLChar(char c) {
        return (c >= 32 || c == '\n' || c == '\r' || c == '\t');
    }
J
jurgen 已提交
233

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    /**
     * Encodes a char to XML-valid form replacing &,',",<,> with special XML encoding.
     *
     * @param ch char to convert
     * @return XML-encoded text
     */
    public static String encodeXMLChar(char ch) {
        switch (ch) {
            case '&':
                return "&amp;";
            case '\"':
                return "&quot;";
            case '\'':
                return "&#39;";
            case '<':
                return "&lt;";
            case '>':
                return "&gt;";
            default:
                return null;
        }
    }
J
jurgen 已提交
256

257
    public static XMLException adaptSAXException(Exception toCatch) {
J
jurgen 已提交
258
        if (toCatch instanceof XMLException) {
259
            return (XMLException) toCatch;
J
jurgen 已提交
260 261
        } else if (toCatch instanceof org.xml.sax.SAXException) {
            String message = toCatch.getMessage();
262
            Exception embedded = ((org.xml.sax.SAXException) toCatch).getException();
J
jurgen 已提交
263 264 265 266 267
            if (embedded != null && embedded.getMessage() != null && embedded.getMessage().equals(message)) {
                // Just SAX wrapper - skip it
                return adaptSAXException(embedded);
            } else {
                return new XMLException(
268 269
                    message,
                    embedded != null ? adaptSAXException(embedded) : null);
J
jurgen 已提交
270 271 272 273 274 275
            }
        } else {
            return new XMLException(toCatch.getMessage(), toCatch);
        }
    }

276 277 278 279 280 281 282 283 284
    public static Collection<Element> getChildElementList(Element element) {
        List<Element> children = new ArrayList<>();
        for (org.w3c.dom.Node node = element.getFirstChild(); node != null; node = node.getNextSibling()) {
            if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                children.add((Element) node);
            }
        }
        return children;
    }
J
jurgen 已提交
285
}