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.dspace.submit.lookup.CiNiiService.java

/**
 * Get metadata by searching CiNii RDF API with CiNii NAID
 *
 *//* w  w w  .  jav a  2s  .c o m*/
private Record search(String id, String appId) throws IOException, HttpException {
    GetMethod method = null;
    try {
        HttpClient client = new HttpClient();
        client.setTimeout(timeout);
        method = new GetMethod("http://ci.nii.ac.jp/naid/" + id + ".rdf?appid=" + appId);
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            if (statusCode == HttpStatus.SC_BAD_REQUEST)
                throw new RuntimeException("CiNii RDF is not valid");
            else
                throw new RuntimeException("CiNii RDF Http call failed: " + method.getStatusLine());
        }

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

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

            Element xmlRoot = inDoc.getDocumentElement();

            return CiNiiUtils.convertCiNiiDomToRecord(xmlRoot);
        } catch (Exception e) {
            throw new RuntimeException("CiNii RDF identifier is not valid or not exist");
        }
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

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

/**
 * Get CiNii NAIDs by searching CiNii OpenURL API with title, author and year
 *
 *//*from  w  w w  .  j  ava  2  s .c o m*/
private List<String> getCiNiiIDs(String title, String author, int year, int maxResults, String appId)
        throws IOException, HttpException {
    // Need at least one query term
    if (title == null && author == null && year == -1) {
        return null;
    }

    GetMethod method = null;
    List<String> ids = new ArrayList<String>();
    try {
        HttpClient client = new HttpClient();
        client.setTimeout(timeout);
        StringBuilder query = new StringBuilder();
        query.append("format=rss&appid=").append(appId).append("&count=").append(maxResults);
        if (title != null) {
            query.append("&title=").append(URLEncoder.encode(title, "UTF-8"));
        }
        if (author != null) {
            query.append("&author=").append(URLEncoder.encode(author, "UTF-8"));
        }
        if (year != -1) {
            query.append("&year_from=").append(String.valueOf(year));
            query.append("&year_to=").append(String.valueOf(year));
        }
        method = new GetMethod("http://ci.nii.ac.jp/opensearch/search?" + query.toString());
        // Execute the method.
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            if (statusCode == HttpStatus.SC_BAD_REQUEST)
                throw new RuntimeException("CiNii OpenSearch query is not valid");
            else
                throw new RuntimeException("CiNii OpenSearch call failed: " + method.getStatusLine());
        }

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

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

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

            int url_len = "http://ci.nii.ac.jp/naid/".length();
            for (Element item : items) {
                String about = item.getAttribute("rdf:about");
                if (about.length() > url_len) {
                    ids.add(about.substring(url_len));
                }
            }

            return ids;
        } catch (Exception e) {
            throw new RuntimeException("CiNii OpenSearch results is not valid or not exist");
        }
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

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

@Override
public RecordSet getRecords() throws MalformedSourceException {

    RecordSet recordSet = new RecordSet();

    try {/*from w w  w  .j av  a 2s .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();
        Element queryResult = XMLUtils.getSingleElement(xmlRoot, "query_result");
        Element body = XMLUtils.getSingleElement(queryResult, "body");
        Element dataRoot = XMLUtils.getSingleElement(body, "query");
        Record record = CrossRefUtils.convertCrossRefDomToRecord(dataRoot);
        recordSet.addRecord(convertFields(record));

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return recordSet;

}

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

@Override
public RecordSet getRecords() throws MalformedSourceException {

    RecordSet recordSet = new RecordSet();

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

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

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

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

        for (Element xmlArticle : pubArticles) {
            Record record = null;
            try {
                record = PubmedUtils.convertPubmedDomToRecord(xmlArticle);
                recordSet.addRecord(convertFields(record));
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return recordSet;

}

From source file:org.eclipse.lyo.oslc.am.resource.ResourceService.java

private String buildResponseResource(List<Map<String, RioValue>> results, Map<String, PName> propNames,
        String reqUri) throws RioServiceException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);/*from  ww  w .ja va  2  s  .c  o  m*/
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();
        Element rdf = doc.createElementNS(IConstants.RDF_NAMESPACE, IConstants.RDF_TYPE_PTERM_RDF);
        doc.appendChild(rdf);

        Set<String> namespaces = namespacePrefixes.keySet();
        for (String namespace : namespaces) {
            rdf.setAttribute("xmlns:" + namespacePrefixes.get(namespace), namespace); //$NON-NLS-1$
        }
        //If there is are parameters on the request (e.g. ?oslc.where=...), create 2 subject URIs, one for the
        //results and one to describe the query.   If this query was for the queryBase itself all predicates 
        //go under the same subject.  
        //TODO: Refactor the services for all RIO artifacts to eliminate duplicated code.

        Element resultDescr = doc.createElementNS(IConstants.RDF_NAMESPACE,
                IConstants.RDF_TYPE_PTERM_DESCRIPTION);
        rdf.appendChild(resultDescr);

        //check for oslc query parameters
        String uriSplit[] = reqUri.split("\\?", 2);
        String baseUri = uriSplit[0];
        boolean isOslcQuery = false;
        if (uriSplit.length > 1)
            isOslcQuery = hasOSLCQuery(uriSplit[1]);

        resultDescr.setAttributeNS(IConstants.RDF_NAMESPACE, IConstants.RDF_PTERM_ABOUT, baseUri);

        //if there are oslc query parameters, put the predicates under the query subject
        Element queryDescrElement = null;
        if (isOslcQuery) {
            queryDescrElement = doc.createElementNS(IConstants.RDF_NAMESPACE,
                    IConstants.RDF_TYPE_PTERM_DESCRIPTION);
            queryDescrElement.setAttributeNS(IConstants.RDF_NAMESPACE, IConstants.RDF_PTERM_ABOUT, reqUri);
            rdf.appendChild(queryDescrElement);
        } else {
            //no oslc query parameters, everything goes under the queryBase subject
            queryDescrElement = resultDescr;
        }

        Element title = doc.createElementNS(IConstants.DCTERMS_NAMESPACE, IConstants.DCTERMS_PTERM_TITLE);
        queryDescrElement.appendChild(title);
        title.setTextContent(Messages.getString("ResourceQuery.Title"));

        Element count = doc.createElementNS(IConstants.OSLC_NAMESPACE, IConstants.OSLC_PTERM_TOTALCOUNT);
        queryDescrElement.appendChild(count);
        count.setTextContent(Integer.toString(results.size()));

        Element rdfType = doc.createElementNS(IConstants.RDF_NAMESPACE, IConstants.RDF_PTERM_TYPE);
        rdfType.setAttributeNS(IConstants.RDF_NAMESPACE, IConstants.RDF_PTERM_RESOURCE,
                IConstants.OSLC_RESPONSEINFO);
        queryDescrElement.appendChild(rdfType);

        Iterator<Map<String, RioValue>> iterator = results.iterator();
        while (iterator.hasNext()) {

            Element rdfMem = doc.createElementNS(IConstants.RDFS_NAMESPACE, IConstants.RDFS_PTERM_MEMBER);
            resultDescr.appendChild(rdfMem);
            Map<String, RioValue> map = iterator.next();
            RioValue uri = map.get("uri"); //$NON-NLS-1$
            rdfMem.setAttributeNS(IConstants.RDF_NAMESPACE, IConstants.RDF_PTERM_RESOURCE, uri.stringValue());
        }

        return XmlUtils.prettyPrint(doc);

    } catch (ParserConfigurationException e) {
        throw new RioServiceException(e);
    } finally {

    }
}

From source file:org.eclipse.mdht.dita.ui.util.DitaUtil.java

private static String getFileNameFromMap(String ditaMapPath) {

    StringBuffer fileName = new StringBuffer();

    try {/*ww w.j  a  v  a  2 s . c o 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 (Exception e) {
        e.printStackTrace();
        System.out.println();
    }
    return fileName.toString();
}

From source file:org.eclipse.recommenders.jayes.io.XMLBIFReader.java

private Document obtainDocument(InputStream biffile)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setValidating(true);
    DocumentBuilder docBldr = docBuilderFactory.newDocumentBuilder();

    Document doc = docBldr.parse(biffile);
    doc.normalize();/*from   w  w  w. j  a  va  2 s .co m*/

    return doc;
}

From source file:org.eclipse.recommenders.jayes.io.XMLBIFReader.java

public BayesNet readFromString(String xmlBif) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setValidating(true);
    DocumentBuilder docBldr = docBuilderFactory.newDocumentBuilder();

    Document doc = docBldr.parse(new ByteArrayInputStream(xmlBif.getBytes()));

    return readFromDocument(doc);

}

From source file:org.exist.performance.Main.java

private static Runner configure(File xmlFile, File outFile) {
    try {// w w w .  ja va  2  s. c om
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
        TestResultWriter writer = null;
        if (outFile != null)
            writer = new TestResultWriter(outFile.getAbsolutePath());
        return new Runner(doc.getDocumentElement(), writer);
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("ERROR: " + e.getMessage());
    }
    return null;
}

From source file:org.freedesktop.mime.MIMEEntry.java

void load(FileObject file) throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);// www .jav  a 2s.c  o m
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream in = file.getContent().getInputStream();
        try {
            Document document = builder.parse(in);
            build(document);
        } finally {
            in.close();
        }
    } catch (IOException ioe) {
        throw ioe;
    } catch (Exception e) {
        IOException ioe = new IOException("Failed to parse XML.");
        ioe.initCause(e);
        throw ioe;
    }

}