Example usage for javax.xml.parsers DocumentBuilderFactory setValidating

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

Introduction

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

Prototype


public void setValidating(boolean validating) 

Source Link

Document

Specifies that the parser produced by this code will validate documents as they are parsed.

Usage

From source file:org.dawb.passerelle.common.utils.XMLUtils.java

public static String getXPathValue(File file, String xPath) throws Exception {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(false); // never forget this!
    docFactory.setValidating(false);
    DocumentBuilder builder = docFactory.newDocumentBuilder();

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    final XPathExpression exp = xpath.compile(xPath);

    Document doc = builder.parse(new InputSource(file.getAbsolutePath()));

    final NodeList nodeList = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
    return XMLUtils.getNodeValue(nodeList);
}

From source file:org.deegree.portal.owswatch.validator.AbstractValidator.java

/**
 * Creates a new instance of DocumentBuilder
 *
 * @return DocumentBuilder/*from   w w w . jav a  2 s.c  o  m*/
 * @throws IOException
 */
protected DocumentBuilder instantiateParser() throws IOException {

    DocumentBuilder parser = null;

    try {
        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        fac.setNamespaceAware(true);
        fac.setValidating(false);
        fac.setIgnoringElementContentWhitespace(false);
        parser = fac.newDocumentBuilder();
        return parser;
    } catch (ParserConfigurationException e) {
        throw new IOException("Unable to initialize DocumentBuilder: " + e.getMessage());
    }
}

From source file:org.dita.dost.util.DitaUtil.java

private static String getFileNameFromMap(String ditaMapPath) {

    StringBuffer fileName = new StringBuffer();

    try {/*from   w w w .  ja  va  2 s. co  m*/

        FileInputStream ditaMapStream;

        ditaMapStream = new FileInputStream(ditaMapPath);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);

        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);

        DocumentBuilder builder;

        Document doc = null;

        XPathExpression expr = null;

        builder = factory.newDocumentBuilder();

        doc = builder.parse(new InputSource(ditaMapStream));

        XPathFactory xFactory = XPathFactory.newInstance();

        XPath xpath = xFactory.newXPath();

        expr = xpath.compile("//bookmap/bookmeta/prodinfo/prodname");

        Node prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);

        if (prodNameNode != null) {

            fileName.append(prodNameNode.getTextContent());

            expr = xpath.compile("//bookmap/bookmeta/prodinfo/vrmlist");

            Element vrmlistNode = (Element) expr.evaluate(doc, XPathConstants.NODE);

            if (vrmlistNode != null) {
                NodeList versions = vrmlistNode.getElementsByTagName("vrm");
                if (versions.getLength() > 0) {

                    NamedNodeMap versionAttributes = versions.item(0).getAttributes();
                    Attr releaseAttr = (Attr) versionAttributes.getNamedItem("release");

                    if (releaseAttr != null) {
                        fileName.append(String.format("_%s", releaseAttr.getValue()));
                    }

                    Attr versionAttr = (Attr) versionAttributes.getNamedItem("version");

                    if (versionAttr != null) {
                        fileName.append(String.format("_%s", versionAttr.getValue()));
                    }
                }
            }
        } else {
            expr = xpath.compile("/bookmap");
            prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
            if (prodNameNode != null) {
                Node node = prodNameNode.getAttributes().getNamedItem("id");
                if (node != null) {
                    fileName.append(node.getTextContent());
                }
            } else {
                expr = xpath.compile("/map");
                prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
                if (prodNameNode != null) {
                    Node node = prodNameNode.getAttributes().getNamedItem("title");
                    if (node != null) {
                        fileName.append(node.getTextContent());
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
    } catch (ParserConfigurationException e) {
    } catch (SAXException e) {
    } catch (IOException e) {
    } catch (XPathExpressionException e) {
    }
    return fileName.toString();
}

From source file:org.drools.guvnor.server.jaxrs.CategoryResourceIntegrationTest.java

public Map<String, Category> fromXMLToCategoriesMap(String xml) {
    try {//w ww  .ja  v a2  s  . co m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);

        final List<String> errors = new ArrayList<String>();
        DocumentBuilder builder = factory.newDocumentBuilder();

        builder.setErrorHandler(new ErrorHandler() {

            public void warning(SAXParseException exception) throws SAXException {
                java.util.logging.Logger.getLogger(Translator.class.getName()).log(Level.WARNING,
                        "Warning parsing categories from Guvnor", exception);
            }

            public void error(SAXParseException exception) throws SAXException {
                java.util.logging.Logger.getLogger(Translator.class.getName()).log(Level.SEVERE,
                        "Error parsing categories from Guvnor", exception);
                errors.add(exception.getMessage());
            }

            public void fatalError(SAXParseException exception) throws SAXException {
                java.util.logging.Logger.getLogger(Translator.class.getName()).log(Level.SEVERE,
                        "Error parsing categories from Guvnor", exception);
                errors.add(exception.getMessage());
            }
        });

        org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));

        if (!errors.isEmpty()) {
            throw new IllegalStateException(
                    "Error parsing categories from guvnor. Check the log for errors' details.");
        }

        Map<String, Category> categories = new HashMap<String, Category>();

        //convert all catergories and add them to the list
        NodeList categoriesList = doc.getElementsByTagName("category");
        for (int i = 0; i < categoriesList.getLength(); i++) {
            Element element = (Element) categoriesList.item(i);
            Category category = new Category();

            NodeList pathNodes = element.getElementsByTagName("path");
            if (pathNodes.getLength() != 1) {
                throw new IllegalStateException(
                        "Malformed category. Expected 1 <path> tag, but found " + pathNodes.getLength());
            }
            Node pathNode = pathNodes.item(0);
            category.setPath(pathNode.getTextContent());

            NodeList refLinkNodes = element.getElementsByTagName("refLink");
            if (refLinkNodes.getLength() != 1) {
                throw new IllegalStateException(
                        "Malformed category. Expected 1 <refLink> tag, but found " + refLinkNodes.getLength());
            }
            Node refLinkNode = refLinkNodes.item(0);
            try {
                category.setRefLink(new URI(refLinkNode.getTextContent()));
            } catch (URISyntaxException e) {
                throw new RuntimeException("Error parsing categories xml", e);
            }

            categories.put(category.getPath(), category);
        }

        return categories;
    } catch (SAXException ex) {
        throw new RuntimeException("Error parsing categories xml", ex);
    } catch (IOException ex) {
        throw new RuntimeException("Error parsing categories xml", ex);
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException("Error parsing categories xml", ex);
    }
}

From source file:org.drugis.addis.util.ConvertDiabetesDatasetUtil.java

private Document getPubMedXML(PubMedIdList pubmed)
        throws ParserConfigurationException, IOException, SAXException {
    String id = pubmed.get(0).getId();
    String url = PubMedIDRetriever.PUBMED_API + "efetch.fcgi?db=pubmed&id=" + id + "&retmode=xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    dbf.setNamespaceAware(false);//from  w w  w.  ja  v a2s.  c  o m
    dbf.setIgnoringElementContentWhitespace(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputStream openStream = PubMedIDRetriever.openUrl(url);
    Document doc = db.parse(openStream);
    return doc;
}

From source file:org.dspace.app.sherpa.SHERPAResponse.java

public SHERPAResponse(InputStream xmlData) {
    try {//  w  w w  .j a va  2s .  com
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder db = factory.newDocumentBuilder();
        Document inDoc = db.parse(xmlData);

        Element xmlRoot = inDoc.getDocumentElement();
        Element headersElement = XMLUtils.getSingleElement(xmlRoot, "header");
        Element journalsElement = XMLUtils.getSingleElement(xmlRoot, "journals");
        Element publishersElement = XMLUtils.getSingleElement(xmlRoot, "publishers");

        message = XMLUtils.getElementValue(headersElement, "message");

        if (StringUtils.isNotBlank(message)) {
            error = true;
            return;
        }

        license = XMLUtils.getElementValue(headersElement, "license");
        licenseURL = XMLUtils.getElementValue(headersElement, "licenseurl");
        disclaimer = XMLUtils.getElementValue(headersElement, "disclaimer");

        List<Element> journalsList = XMLUtils.getElementList(journalsElement, "journal");
        List<Element> publishersList = XMLUtils.getElementList(publishersElement, "publisher");

        if (journalsList != null) {
            journals = new LinkedList<SHERPAJournal>();
            for (Element journalElement : journalsList) {
                journals.add(new SHERPAJournal(XMLUtils.getElementValue(journalElement, "jtitle"),
                        XMLUtils.getElementValue(journalElement, "issn"),
                        XMLUtils.getElementValue(journalElement, "zetopub"),
                        XMLUtils.getElementValue(journalElement, "romeopub")));
            }
        }

        if (publishersList != null) {
            publishers = new LinkedList<SHERPAPublisher>();
            for (Element publisherElement : publishersList) {
                Element preprintsElement = XMLUtils.getSingleElement(publisherElement, "preprints");
                Element preprintsRestrictionElement = XMLUtils.getSingleElement(publisherElement,
                        "prerestrictions");

                Element postprintsElement = XMLUtils.getSingleElement(publisherElement, "postprints");
                Element postprintsRestrictionElement = XMLUtils.getSingleElement(publisherElement,
                        "postrestrictions");

                Element pdfversionElement = XMLUtils.getSingleElement(publisherElement, "pdfversion");
                Element pdfversionRestrictionElement = XMLUtils.getSingleElement(publisherElement,
                        "pdfrestrictions");

                Element conditionsElement = XMLUtils.getSingleElement(publisherElement, "conditions");
                Element paidaccessElement = XMLUtils.getSingleElement(publisherElement, "paidaccess");

                Element copyrightlinksElement = XMLUtils.getSingleElement(publisherElement, "copyrightlinks");

                publishers.add(new SHERPAPublisher(XMLUtils.getElementValue(publisherElement, "name"),
                        XMLUtils.getElementValue(publisherElement, "alias"),
                        XMLUtils.getElementValue(publisherElement, "homeurl"),

                        XMLUtils.getElementValue(preprintsElement, "prearchiving"),
                        XMLUtils.getElementValueList(preprintsRestrictionElement, "prerestriction"),

                        XMLUtils.getElementValue(postprintsElement, "postarchiving"),
                        XMLUtils.getElementValueList(postprintsRestrictionElement, "postrestriction"),

                        XMLUtils.getElementValue(pdfversionElement, "pdfarchiving"),
                        XMLUtils.getElementValueList(pdfversionRestrictionElement, "pdfrestriction"),

                        XMLUtils.getElementValueList(conditionsElement, "condition"),
                        XMLUtils.getElementValue(paidaccessElement, "paidaccessurl"),
                        XMLUtils.getElementValue(paidaccessElement, "paidaccessname"),
                        XMLUtils.getElementValue(paidaccessElement, "paidaccessnotes"),
                        XMLUtils.getElementValueArrayList(copyrightlinksElement, "copyrightlink",
                                "copyrightlinktext", "copyrightlinkurl"),
                        XMLUtils.getElementValue(publisherElement, "romeocolour"),
                        XMLUtils.getElementValue(publisherElement, "dateadded"),
                        XMLUtils.getElementValue(publisherElement, "dateupdated")));
            }
        }
    } catch (Exception e) {
        error = true;
    }
}

From source file:org.dspace.app.util.DCInputsReader.java

private void buildInputs(String fileName) throws DCInputsReaderException {
    formDefns = new HashMap<String, List<Map<String, String>>>();
    valuePairs = new HashMap<String, List<String>>();

    String uri = "file:" + new File(fileName).getAbsolutePath();

    try {/*from   w w  w . j  a  v  a2 s. c  o  m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(uri);
        doNodes(doc);
        checkValues();
    } catch (FactoryConfigurationError fe) {
        throw new DCInputsReaderException("Cannot create Submission form parser", fe);
    } catch (Exception e) {
        throw new DCInputsReaderException("Error creating submission forms: " + e);
    }
}

From source file:org.dspace.app.util.SubmissionConfigReader.java

/**
 * Parse an XML encoded item submission configuration file.
 * <P>//  w  w w . j av  a2s.  c om
 * Creates two main hashmaps:
 * <ul>
 * <li>Hashmap of Collection to Submission definition mappings -
 * defines which Submission process a particular collection uses
 * <li>Hashmap of all Submission definitions.  List of all valid
 * Submision Processes by name.
 * </ul>
 */
private void buildInputs(String fileName) throws SubmissionConfigReaderException {
    collectionToSubmissionConfig = new HashMap<String, String>();
    submitDefns = new HashMap<String, List<Map<String, String>>>();

    String uri = "file:" + new File(fileName).getAbsolutePath();

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(uri);
        doNodes(doc);
    } catch (FactoryConfigurationError fe) {
        throw new SubmissionConfigReaderException("Cannot create Item Submission Configuration parser", fe);
    } catch (Exception e) {
        throw new SubmissionConfigReaderException("Error creating Item Submission Configuration: " + e);
    }
}

From source file:org.dspace.submit.lookup.ArXivFileDataLoader.java

@Override
public RecordSet getRecords() throws MalformedSourceException {

    RecordSet recordSet = new RecordSet();

    try {//from  w  w  w  .  ja  v a 2 s .  c  o m
        InputStream inputStream = new FileInputStream(new File(filename));

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder db = factory.newDocumentBuilder();
        Document inDoc = db.parse(inputStream);

        Element xmlRoot = inDoc.getDocumentElement();
        List<Element> dataRoots = XMLUtils.getElementList(xmlRoot, "entry");

        for (Element dataRoot : dataRoots) {
            Record record = ArxivUtils.convertArxixDomToRecord(dataRoot);
            if (record != null) {
                recordSet.addRecord(convertFields(record));
            }
        }
    } catch (FileNotFoundException e) {
        log.error(e.getMessage(), e);
    } catch (ParserConfigurationException e) {
        log.error(e.getMessage(), e);
    } catch (SAXException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    return recordSet;
}

From source file:org.dspace.submit.lookup.CiNiiFileDataLoader.java

@Override
public RecordSet getRecords() throws MalformedSourceException {

    RecordSet recordSet = new RecordSet();

    try {/*from  w ww  . j  a  v  a2 s.c  o  m*/
        InputStream inputStream = new FileInputStream(new File(filename));

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder db = factory.newDocumentBuilder();
        Document inDoc = db.parse(inputStream);

        Element xmlRoot = inDoc.getDocumentElement();

        // There is no element to represent an record, so we can not process 
        // multi records at once.
        Record record = CiNiiUtils.convertCiNiiDomToRecord(xmlRoot);
        if (record != null) {
            recordSet.addRecord(convertFields(record));
        }
    } catch (FileNotFoundException e) {
        log.error(e.getMessage(), e);
    } catch (ParserConfigurationException e) {
        log.error(e.getMessage(), e);
    } catch (SAXException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    return recordSet;
}