DOMParser.java 2.74 KB
/*
 * Decompiled with CFR 0_118.
 */
package com.day.cq.searchpromote.xml;

import com.day.cq.searchpromote.SearchPromoteException;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class DOMParser {
    public Element parseXML(InputSource xml) throws SearchPromoteException {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            String FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
            factory.setFeature(FEATURE, true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(xml);
            return document.getDocumentElement();
        }
        catch (ParserConfigurationException e) {
            throw new SearchPromoteException("Unable to create XML parser", e);
        }
        catch (SAXParseException e) {
            throw new SearchPromoteException("XML syntax error. (Line: " + e.getLineNumber() + " Column: " + e.getColumnNumber() + ")", e);
        }
        catch (SAXException e) {
            throw new SearchPromoteException("XML syntax error. ", e);
        }
        catch (IOException e) {
            throw new SearchPromoteException("XML could not be read.", e);
        }
    }

    protected Element getElement(Element parent, String name, boolean required) throws SearchPromoteException {
        NodeList children = parent.getChildNodes();
        Element found = null;
        for (int i = 0; i < children.getLength(); ++i) {
            Node child = children.item(i);
            if (child.getNodeType() != 1 || !name.equals(child.getNodeName())) continue;
            if (found != null) {
                throw new SearchPromoteException("Duplicate configuration element " + name + " in " + parent.getNodeName() + ".");
            }
            found = (Element)child;
        }
        if (required && found == null) {
            throw new SearchPromoteException("Configuration element " + name + " not found in " + parent.getNodeName() + ".");
        }
        return found;
    }

    protected String getAttribute(Element element, String name) throws SearchPromoteException {
        Attr attribute = element.getAttributeNode(name);
        if (attribute != null) {
            return attribute.getValue();
        }
        throw new SearchPromoteException("Configuration attribute " + name + " not found in " + element.getNodeName() + ".");
    }
}