Example usage for javax.xml.parsers DocumentBuilderFactory setNamespaceAware

List of usage examples for javax.xml.parsers DocumentBuilderFactory setNamespaceAware

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setNamespaceAware.

Prototype


public void setNamespaceAware(boolean awareness) 

Source Link

Document

Specifies that the parser produced by this code will provide support for XML namespaces.

Usage

From source file:dk.dbc.rawrepo.oai.OAIWorker.java

private static DocumentBuilder makeDocumentBuilder() {
    synchronized (DocumentBuilderFactory.class) {
        try {// w w  w. j a va 2  s  .  co  m
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            dbf.setIgnoringComments(true);
            dbf.setIgnoringElementContentWhitespace(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            db.setEntityResolver(new NullResolver());
            return db;
        } catch (ParserConfigurationException ex) {
            throw new RuntimeException(ex);
        }
    }
}

From source file:gov.tva.sparky.hbase.RestProxy.java

/**
 * //from   w  w  w .j  av  a2s .c o m
 * @param strTablename
 * @param strRowKey
 * @param strColumn
 * @param strQualifier
 * @return Returns the values from a data cell in HBase.
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static byte[] QueryHBaseForCell(String strTablename, String strRowKey, String strColumn,
        String strQualifier) throws ParserConfigurationException, SAXException, IOException {
    // Configuration
    Configuration conf = new Configuration(false);
    conf.addResource("hadoop-default.xml");
    conf.addResource("sparky-site.xml");
    int port = conf.getInt("sparky.hbase.restPort", 8092);
    String uri = conf.get("sparky.hbase.restURI", "http://socdvmhbase");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    // never forget this!
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    String strRestPath = uri + ":" + port + "/" + strTablename + "/" + strRowKey + "/" + strColumn + ":"
            + strQualifier;

    Document doc = null;

    try {
        doc = builder.parse(strRestPath);

    } catch (FileNotFoundException e) {
        //System.out.println("RestProxy > Exception: ( " + strRestPath + " )");
    }

    if (null == doc)
        return null;

    XPathFactory xpath_factory = XPathFactory.newInstance();
    XPath xpath = xpath_factory.newXPath();

    XPathExpression expr = null;

    try {
        expr = xpath.compile("/CellSet/Row/Cell/text()");
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Object result = null;
    try {
        result = expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    NodeList nodes = (NodeList) result;
    String cell_value = nodes.item(0).getNodeValue();

    Base64 decoder = new Base64();
    byte[] decodedValue = decoder.decode(cell_value.getBytes());

    return decodedValue;
}

From source file:com.gargoylesoftware.htmlunit.xml.XmlUtil.java

/**
 * Builds a document from the content of the web response.
 * A warning is logged if an exception is thrown while parsing the XML content
 * (for instance when the content is not a valid XML and can't be parsed).
 *
 * @param webResponse the response from the server
 * @throws IOException if the page could not be created
 * @return the parse result/*w  w  w . j  a va  2s  .  com*/
 * @throws SAXException if the parsing fails
 * @throws ParserConfigurationException if a DocumentBuilder cannot be created
 */
public static Document buildDocument(final WebResponse webResponse)
        throws IOException, SAXException, ParserConfigurationException {

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    if (webResponse == null) {
        return factory.newDocumentBuilder().newDocument();
    }

    factory.setNamespaceAware(true);
    final InputStreamReader reader = new InputStreamReader(webResponse.getContentAsStream(),
            webResponse.getContentCharset());

    // we have to do the blank input check and the parsing in one step
    final TrackBlankContentReader tracker = new TrackBlankContentReader(reader);

    final InputSource source = new InputSource(tracker);
    final DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setErrorHandler(DISCARD_MESSAGES_HANDLER);
    builder.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(final String publicId, final String systemId)
                throws SAXException, IOException {
            return new InputSource(new StringReader(""));
        }
    });
    try {
        return builder.parse(source);
    } catch (final SAXException e) {
        if (tracker.wasBlank()) {
            return factory.newDocumentBuilder().newDocument();
        }
        throw e;
    }
}

From source file:eu.europeana.uim.sugarcrmclient.internal.helpers.ClientUtils.java

/**
 * @param responseString/* w w w . j a  v a 2 s .c  o  m*/
 * @return
 */
public static String extractSimpleResponse(String responseString) {

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(new InputSource(new StringReader(responseString)));
        String sessionID = null;
        NodeList nl = document.getElementsByTagName("id");

        if (nl.getLength() > 0) {
            sessionID = nl.item(0).getTextContent();
        }

        return sessionID;

    } catch (ParserConfigurationException e) {
        logger.error(e.getMessage());
    } catch (SAXException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    }

    return null;
}

From source file:com.puppycrawl.tools.checkstyle.AllChecksTest.java

/**
 * Gets a set of names of checkstyle's checks which are referenced in checkstyle_checks.xml.
 * @param configFilePath file path of checkstyle_checks.xml.
 * @return names of checkstyle's checks which are referenced in checkstyle_checks.xml.
 * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies the configuration requested.
 * @throws IOException if any IO errors occur.
 * @throws SAXException if any parse errors occur.
 *//* ww w .  ja  v a2  s  . c  o  m*/
private static Set<String> getCheckStyleChecksReferencedInConfig(String configFilePath)
        throws ParserConfigurationException, IOException, SAXException {

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // Validations of XML file make parsing too slow, that is why we disable all validations.
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    factory.setFeature("http://xml.org/sax/features/namespaces", false);
    factory.setFeature("http://xml.org/sax/features/validation", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document document = builder.parse(new File(configFilePath));

    // optional, but recommended
    // FYI: http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    document.getDocumentElement().normalize();

    final NodeList nodeList = document.getElementsByTagName("module");

    Set<String> checksReferencedInCheckstyleChecksXML = new HashSet<>();
    for (int i = 0; i < nodeList.getLength(); i++) {
        final Node currentNode = nodeList.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            final Element module = (Element) currentNode;
            final String checkName = module.getAttribute("name");
            if (!"Checker".equals(checkName) && !"TreeWalker".equals(checkName)
                    && !"SuppressionFilter".equals(checkName)) {
                checksReferencedInCheckstyleChecksXML.add(checkName);
            }
        }
    }
    return checksReferencedInCheckstyleChecksXML;
}

From source file:com.puppycrawl.tools.checkstyle.AllChecksTest.java

/**
 * Gets names of checkstyle's modules which are documented in xdocs.
 * @param xdocsDirectoryPath xdocs directory path.
 * @return a set of checkstyle's modules which have xdoc documentation.
 * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies the configuration requested.
 * @throws IOException if any IO errors occur.
 * @throws SAXException if any parse errors occur.
 *///  w ww  .  j  a  v a  2  s .com
private static Set<String> getModulesNamesWhichHaveXdoc(String xdocsDirectoryPath)
        throws ParserConfigurationException, IOException, SAXException {

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // Validations of XML file make parsing too slow, that is why we disable all validations.
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    factory.setFeature("http://xml.org/sax/features/namespaces", false);
    factory.setFeature("http://xml.org/sax/features/validation", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    final Set<Path> xdocsFilePaths = getXdocsFilePaths(xdocsDirectoryPath);
    final Set<String> modulesNamesWhichHaveXdoc = new HashSet<>();

    for (Path path : xdocsFilePaths) {
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document document = builder.parse(path.toFile());

        // optional, but recommended
        // FYI: http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        document.getDocumentElement().normalize();

        final NodeList nodeList = document.getElementsByTagName("section");

        for (int i = 0; i < nodeList.getLength(); i++) {
            final Node currentNode = nodeList.item(i);
            if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
                final Element module = (Element) currentNode;
                final String moduleName = module.getAttribute("name");
                if (!"Content".equals(moduleName) && !"Overview".equals(moduleName)) {
                    modulesNamesWhichHaveXdoc.add(moduleName);
                }
            }
        }
    }
    return modulesNamesWhichHaveXdoc;
}

From source file:eu.europeana.uim.sugarcrmclient.internal.helpers.ClientUtils.java

/**
 * @param responseString//from w ww.jav  a2  s.  com
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 */
public static HashMap<String, HashMap<String, String>> responseFactory(String responseString)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

    HashMap<String, HashMap<String, String>> returnMap = new HashMap<String, HashMap<String, String>>();

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

    Document document = documentBuilder.parse(new InputSource(new StringReader(responseString)));

    //String messageName = document.getFirstChild().getNodeName();

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    xpath.setNamespaceContext(new SugarCRMNamespaceContext());
    XPathExpression expr = xpath.compile("//ns1:get_entry_listResponse/return/entry_list/item");

    Object result = expr.evaluate(document, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;

    for (int i = 0; i < nodes.getLength(); i++) {

        NodeList innerNodes = nodes.item(i).getChildNodes();

        String id = innerNodes.item(0).getTextContent();

        HashMap<String, String> elementData = new HashMap<String, String>();

        NodeList infoNodes = innerNodes.item(2).getChildNodes();

        for (int z = 0; z < infoNodes.getLength(); z++) {
            String name = infoNodes.item(z).getFirstChild().getTextContent();
            String value = infoNodes.item(z).getLastChild().getTextContent();

            elementData.put(name, value);
        }
        returnMap.put(id, elementData);
    }
    return returnMap;
}

From source file:com.google.appengine.tools.mapreduce.ConfigurationTemplatePreprocessor.java

/**
 * Creates a DocumentBuilder that mirrors the settings used by Hadoop.
 *///from w  w w . ja v a  2s. c  o m
static DocumentBuilderFactory createConfigurationDocBuilderFactory() {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();

    // Mirroring the settings in org.apache.hadoop.conf.Configuration
    docBuilderFactory.setIgnoringComments(true);
    docBuilderFactory.setNamespaceAware(false);
    try {
        docBuilderFactory.setXIncludeAware(true);
    } catch (UnsupportedOperationException e) {
        // Ignore
    }
    return docBuilderFactory;
}

From source file:com.bluexml.side.form.utils.DOMUtil.java

/**
 * Gets a namespace aware non-validating DocumentBuilder object. If non existent, the object is
 * created.// w w w  . ja v  a  2s  .  c om
 * 
 * @return
 */
public static DocumentBuilder getDocumentBuilder() {
    if (documentBuilder == null) {
        try {
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            docBuilderFactory.setNamespaceAware(true); // @since 1.0.2
            docBuilderFactory.setValidating(false); // @since 1.0.2

            documentBuilder = docBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            return null;
        }
    }
    return documentBuilder;
}

From source file:com.vmware.qe.framework.datadriven.utils.XMLUtil.java

/**
 * Validates an XML file with its schema.
 * // w  w  w .  j  a  v  a 2 s.  com
 * @param xmlFileStream - the inputStream of the xml content
 * @param xsdFileStream - the inputStream of the xsd content
 * @throws Exception
 */
public static void validateXML(InputStream xmlFileStream, InputStream xsdFileStream) throws Exception {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setIgnoringElementContentWhitespace(true);
    documentBuilderFactory.setValidating(false);
    DocumentBuilder parser = documentBuilderFactory.newDocumentBuilder();
    Document document = parser.parse(xmlFileStream);
    validateDocument(document, xsdFileStream);
}