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:com.icesoft.jasper.xmlparser.ParserUtils.java

/**
 * Parse the specified XML document, and return a <code>TreeNode</code> that
 * corresponds to the root node of the document tree.
 *
 * @param uri URI of the XML document being parsed
 * @param is  Input stream containing the deployment descriptor
 * @throws JasperException if an input/output error occurs
 * @throws JasperException if a parsing error occurs
 */// w w  w.  j  a  va  2 s  . c  o m
public TreeNode parseXMLDocument(String uri, InputStream is) throws JasperException {

    Document document = null;

    // Perform an XML parse of this document, via JAXP
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(validating);
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(entityResolver);
        builder.setErrorHandler(errorHandler);
        document = builder.parse(is);
    } catch (ParserConfigurationException ex) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", uri), ex);
    } catch (SAXParseException ex) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml.line", uri,
                Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex);
    } catch (SAXException sx) {
        if (log.isErrorEnabled()) {
            log.error("XML parsing failed for " + uri + "SAXException: " + sx.getMessage());
        }
        throw new JasperException(
                Localizer.getMessage("jsp.error.parse.xml", uri) + "SAXException: " + sx.getMessage(), sx);
    } catch (IOException io) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", uri), io);
    }

    // Convert the resulting document to a graph of TreeNodes
    return (convert(null, document.getDocumentElement()));
}

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

public List<Record> getByPubmedIDs(List<String> pubmedIDs)
        throws HttpException, IOException, ParserConfigurationException, SAXException {
    List<Record> results = new ArrayList<Record>();
    HttpGet method = null;//  w  w w .  j av a  2s  .c o m
    try {
        HttpClient client = new DefaultHttpClient();
        client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5 * timeout);

        try {
            URIBuilder uriBuilder = new URIBuilder("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi");
            uriBuilder.addParameter("db", "pubmed");
            uriBuilder.addParameter("retmode", "xml");
            uriBuilder.addParameter("rettype", "full");
            uriBuilder.addParameter("id", StringUtils.join(pubmedIDs.iterator(), ","));
            method = new HttpGet(uriBuilder.build());
        } catch (URISyntaxException ex) {
            throw new RuntimeException("Request not sent", ex);
        }

        // Execute the method.
        HttpResponse response = client.execute(method);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            throw new RuntimeException("WS call failed: " + statusLine);
        }

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

        DocumentBuilder builder = factory.newDocumentBuilder();
        Document inDoc = builder.parse(response.getEntity().getContent());

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

        for (Element xmlArticle : pubArticles) {
            Record pubmedItem = null;
            try {
                pubmedItem = PubmedUtils.convertPubmedDomToRecord(xmlArticle);
                results.add(pubmedItem);
            } catch (Exception e) {
                throw new RuntimeException("PubmedID is not valid or not exist: " + e.getMessage(), e);
            }
        }

        return results;
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:au.csiro.casda.sodalint.ValidateServiceDescriptor.java

/**
 * Run targeted verification of the service descriptor XML text, including its presence and the support for standard
 * SODA parameters.//  w  ww .  j  a  va  2  s  .  co  m
 * 
 * @param reporter
 *            The validation message destination
 * @param xmlContent
 *            The xml text of the service description.
 */
void verifyServiceDescriptor(Reporter reporter, String xmlContent) {
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setValidating(false);
        builderFactory.setNamespaceAware(true);
        builderFactory.setFeature("http://xml.org/sax/features/validation", false);
        builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        byte[] bytes = xmlContent.getBytes("UTF-8");
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        Document document = builder.parse(is);

        // Check for resource with appropriate standard ID
        Node sodaSvcNode = getSodaServiceResource(reporter, document);
        if (sodaSvcNode == null) {
            reporter.report(SodaCode.E_SDNO, "No service descriptor resource found in default sync repsonse.");
            return;
        }

        // Check that an access URL is listed
        checkSodaAccessUrl(reporter, sodaSvcNode);

        // Check input params group
        checkInputParams(reporter, sodaSvcNode);

    } catch (ParserConfigurationException | UnsupportedEncodingException | XPathExpressionException e) {
        reporter.report(SodaCode.E_SDIN, "Unexpected error processing service description", e);
    } catch (SAXException e) {
        reporter.report(SodaCode.E_SDIN, "Error parsing service description", e);
    } catch (IOException e) {
        reporter.report(SodaCode.E_SDIN, "Error reading service description", e);
    }

}

From source file:esg.security.yadis.XrdsDoc.java

protected Document parseXmlInput(String input) throws XrdsParseException {
    if (input == null)
        throw new XrdsParseException("No XML message set");

    try {/*from   w w  w  .  java2s.  c o m*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(true);
        dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        dbf.setAttribute(JAXP_SCHEMA_SOURCE, new Object[] { this.getClass().getResourceAsStream(XRD_SCHEMA),
                this.getClass().getResourceAsStream(XRDS_SCHEMA), });
        DocumentBuilder builder = dbf.newDocumentBuilder();
        builder.setErrorHandler(new ErrorHandler() {
            public void error(SAXParseException exception) throws SAXException {
                throw exception;
            }

            public void fatalError(SAXParseException exception) throws SAXException {
                throw exception;
            }

            public void warning(SAXParseException exception) throws SAXException {
                throw exception;
            }
        });

        return builder.parse(new ByteArrayInputStream(input.getBytes()));
    } catch (ParserConfigurationException e) {
        throw new XrdsParseException("Parser configuration error", e);
    } catch (SAXException e) {
        throw new XrdsParseException("Error parsing XML document", e);
    } catch (IOException e) {
        throw new XrdsParseException("Error reading XRDS document", e);
    }
}

From source file:com.janoz.usenet.searchers.impl.NzbsOrgConnectorImpl.java

private List<NZB> fetchFeed(Collection<NameValuePair> params) throws SearchException, DOMException {
    THROTTLER.throttle();//www . ja va2 s .  c  o m
    Document document = null;
    try {
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.addAll(params);
        qparams.add(new BasicNameValuePair("dl", "1"));
        URI uri = getUri("rss.php", qparams);
        synchronized (builderSemaphore) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            DocumentBuilder builder = factory.newDocumentBuilder();
            int attempts = RETRY_ATTEMPTS;
            boolean retry;
            do
                try {
                    retry = false;
                    document = builder.parse(uri.toString());
                } catch (IOException ioe) {
                    if (attempts == 0
                            || !ioe.getMessage().startsWith("Server returned HTTP response code: 503")) {
                        throw ioe;
                    } else {
                        attempts--;
                        retry = true;
                        THROTTLER.throttleBig();
                    }
                }
            while (retry);
        }
    } catch (IOException ioe) {
        throw new SearchException("Error connecting to Nzbs.org.", ioe);
    } catch (SAXException se) {
        throw new SearchException("Error parsing rss from Nzbs.org.", se);
    } catch (ParserConfigurationException pce) {
        throw new SearchException("Error configuring XML parser.", pce);
    } catch (URISyntaxException e) {
        throw new SearchException("Error parsing URI.", e);
    }
    Node rss = document.getFirstChild();
    if (!"rss".equalsIgnoreCase(rss.getNodeName())) {
        throw new SearchException("Result was not RSS but " + rss.getNodeName());
    }
    Node channel = rss.getFirstChild();
    while (channel != null && "#text".equals(channel.getNodeName())) {
        channel = channel.getNextSibling();
    }
    NodeList list = channel.getChildNodes();
    DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.CANADA);
    List<NZB> result = new ArrayList<NZB>();
    UrlBasedSupplier supplier = new UrlBasedSupplier();
    supplier.setThrottler(THROTTLER);
    for (int i = 0; i < list.getLength(); i++) {
        Node n = list.item(i);
        if ("item".equals(n.getNodeName())) {
            LazyNZB nzb = new LazyNZB("tmpName", supplier);
            try {
                for (int j = 0; j < n.getChildNodes().getLength(); j++) {
                    Node n2 = n.getChildNodes().item(j);
                    if ("title".equalsIgnoreCase(n2.getNodeName())) {
                        nzb.setName(n2.getTextContent());
                        nzb.setFilename(Util.saveFileName(n2.getTextContent()) + ".nzb");
                    }
                    if ("pubdate".equalsIgnoreCase(n2.getNodeName())) {
                        nzb.setPostDate(df.parse(n2.getTextContent()));
                    }
                    if ("link".equalsIgnoreCase(n2.getNodeName())) {
                        nzb.setUrl(n2.getTextContent());
                    }
                }
                result.add(nzb);
            } catch (ParseException e) {
                LOG.info("Skipping " + nzb.getName() + " because of date error.", e);
            }
        }
    }
    THROTTLER.setThrottleForNextAction();
    return result;
}

From source file:org.ambraproject.service.XMLServiceTest.java

@BeforeClass
protected void setUp() throws Exception {

    DocumentBuilderFactory documentBuilderfactory = DocumentBuilderFactory
            .newInstance("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl", getClass().getClassLoader());
    documentBuilderfactory.setNamespaceAware(true);
    documentBuilderfactory.setValidating(false);
    documentBuilderfactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    Map<String, String> xmlFactoryProperties = new HashMap<String, String>();
    xmlFactoryProperties.put("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
    xmlFactoryProperties.put("javax.xml.transform.Transformer", "net.sf.saxon.Controller");

    XMLUnit.setControlDocumentBuilderFactory(documentBuilderfactory);
    XMLUnit.setTestDocumentBuilderFactory(documentBuilderfactory);
    XMLUnit.setIgnoreComments(true);/*from  w w w .j  av a 2  s  . c o  m*/
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setTransformerFactory("net.sf.saxon.TransformerFactoryImpl");
    XMLUnit.setXSLTVersion("2.0");

    Configuration configiration = new BaseConfiguration();
    configiration.setProperty("ambra.platform.appContext", "test-context");

}

From source file:de.betterform.connector.ant.AntSubmissionHandler.java

public Map submit(Submission submission, Node instance) throws XFormsException {
    LOGGER.debug("AntSubmissionHandler.submit()");
    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    if (submission.getMethod().equals("get")) {
        try {/* ww w.ja  v  a2s. co m*/
            String uri = getURI();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ByteArrayOutputStream errorStream = new ByteArrayOutputStream();

            String buildFilePath = (new URI(uri)).getSchemeSpecificPart()
                    .substring((new URI(uri)).getSchemeSpecificPart().indexOf(':') + 1);
            if (!"".equals(buildFilePath)) {
                File buildFile = new File(buildFilePath);
                String target = null;
                if (uri.contains("#")) {
                    //got Traget from uri
                    target = uri.substring(uri.indexOf('#') + 1);
                } else if (((Document) instance).getElementsByTagName("target").item(0) != null) {
                    //got target from xform
                    target = ((Document) instance).getElementsByTagName("target").item(0).getTextContent();
                } else {
                    // use default target
                    target = "default";
                }

                LOGGER.debug("AntSubmissionHandler.runTarget() BuildFile: " + buildFile.getAbsolutePath()
                        + " with Target:" + target);
                runTarget(buildFile, target, outputStream, errorStream);

                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(true);
                factory.setValidating(false);
                Document document = factory.newDocumentBuilder().newDocument();
                document.appendChild(document.createElementNS(null, "ant"));

                Element rootElement = document.getDocumentElement();
                Attr filename = document.createAttribute("fileName");
                filename.setValue(buildFile.getName());
                rootElement.setAttributeNode(filename);
                Element element = document.createElement("buildFile");
                DOMUtil.setElementValue(element, buildFile.getAbsolutePath());
                rootElement.appendChild(element);

                element = document.createElement("target");
                DOMUtil.setElementValue(element, target);
                rootElement.appendChild(element);

                element = document.createElement("output-stream");
                DOMUtil.setElementValue(element, outputStream.toString());
                rootElement.appendChild(element);

                element = document.createElement("error-stream");
                DOMUtil.setElementValue(element, errorStream.toString());
                rootElement.appendChild(element);
                DOMUtil.prettyPrintDOM(document, stream);
            } else {
                throw new XFormsException("submission method '" + submission.getMethod() + "' at: "
                        + DOMUtil.getCanonicalPath(submission.getElement()) + " not supported");
            }
        } catch (Exception e) {
            throw new XFormsException(e);
        }
    } else {
        throw new XFormsException("submission method '" + submission.getMethod() + "' at: "
                + DOMUtil.getCanonicalPath(submission.getElement()) + " not supported");
    }

    Map response = new HashMap();
    response.put(XFormsProcessor.SUBMISSION_RESPONSE_STREAM, new ByteArrayInputStream(stream.toByteArray()));
    return response;
}

From source file:org.bigtester.ate.model.data.TestDatabaseInitializer.java

/**
 * Combine init xml files./*from  w ww.jav  a 2  s .  c  o m*/
 *
 * @return the input stream
 */
private InputStream combineInitXmlFiles() {
    if (getInitXmlFiles().isEmpty()) {
        throw GlobalUtils.createNotInitializedException("xml data files are not populated");
    } else {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        DocumentBuilder dbuilder;
        try {
            dbuilder = dbf.newDocumentBuilder();

            Document retDoc = dbuilder.newDocument();
            Document doc0;

            doc0 = dbuilder.parse(getInitXmlFiles().get(0));

            Node firstDataset = retDoc.importNode(doc0.getFirstChild(), true);
            retDoc.appendChild(firstDataset);
            for (int i = 1; i < getInitXmlFiles().size(); i++) {
                Document doc2 = dbuilder.parse(getInitXmlFiles().get(i));
                Node root = doc2.getFirstChild();
                NodeList list = root.getChildNodes();
                for (int index = 0; index < list.getLength(); index++) {
                    Node copiedNode = retDoc.importNode(list.item(index), true);
                    retDoc.getDocumentElement().appendChild(copiedNode);
                }
            }

            DOMSource source = new DOMSource(retDoc);
            StringWriter xmlAsWriter = new StringWriter();

            StreamResult result = new StreamResult(xmlAsWriter);

            TransformerFactory.newInstance().newTransformer().transform(source, result);

            // write changes
            return new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8"));

        } catch (SAXException | IOException | ParserConfigurationException e) {
            throw GlobalUtils.createNotInitializedException("xml data files are not correctly populated", e);
        } catch (TransformerException | TransformerFactoryConfigurationError transE) {
            throw GlobalUtils.createInternalError("xml transformer error!", transE);
        }

    }
}

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

public List<Record> search(String query) throws IOException, HttpException {
    List<Record> results = new ArrayList<>();
    if (!ConfigurationManager.getBooleanProperty(SubmissionLookupService.CFG_MODULE, "remoteservice.demo")) {
        HttpGet method = null;// ww  w  . j av  a2 s.  c  o  m
        try {
            HttpClient client = new DefaultHttpClient();
            client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

            URIBuilder uriBuilder = new URIBuilder("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi");
            uriBuilder.addParameter("db", "pubmed");
            uriBuilder.addParameter("datetype", "edat");
            uriBuilder.addParameter("retmax", "10");
            uriBuilder.addParameter("term", query);
            method = new HttpGet(uriBuilder.build());

            // Execute the method.
            HttpResponse response = client.execute(method);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                throw new RuntimeException("WS call failed: " + statusLine);
            }

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

            DocumentBuilder builder;
            try {
                builder = factory.newDocumentBuilder();

                Document inDoc = builder.parse(response.getEntity().getContent());

                Element xmlRoot = inDoc.getDocumentElement();
                Element idList = XMLUtils.getSingleElement(xmlRoot, "IdList");
                List<String> pubmedIDs = XMLUtils.getElementValueList(idList, "Id");
                results = getByPubmedIDs(pubmedIDs);
            } catch (ParserConfigurationException e1) {
                log.error(e1.getMessage(), e1);
            } catch (SAXException e1) {
                log.error(e1.getMessage(), e1);
            }
        } catch (Exception e1) {
            log.error(e1.getMessage(), e1);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
    } else {
        InputStream stream = null;
        try {
            File file = new File(ConfigurationManager.getProperty("dspace.dir")
                    + "/config/crosswalks/demo/pubmed-search.xml");
            stream = new FileInputStream(file);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setIgnoringComments(true);
            factory.setIgnoringElementContentWhitespace(true);

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

            Element xmlRoot = inDoc.getDocumentElement();
            Element idList = XMLUtils.getSingleElement(xmlRoot, "IdList");
            List<String> pubmedIDs = XMLUtils.getElementValueList(idList, "Id");
            results = getByPubmedIDs(pubmedIDs);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return results;
}

From source file:de.betterform.xml.config.DefaultConfig.java

/**
 * Creates and loads a new configuration.
 * /*from w  ww .j  av a 2s  . c om*/
 * @param stream
 *            InputStream to read XML data in the default format.
 */
public DefaultConfig(InputStream stream) throws XFormsConfigException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(false);
        factory.setValidating(false);

        Document document = factory.newDocumentBuilder().parse(stream);

        NodeInfo context = getDocumentElementContext(document);

        this.properties = load(context, "properties/property", "name", "value");
        this.uriResolvers = load(context, "connectors/uri-resolver", "scheme", "class");
        this.submissionHandlers = load(context, "connectors/submission-handler", "scheme", "class");
        this.errorMessages = load(context, "error-messages/message", "id", "value");

        //this.actions = load (context,"actions/action", "name", "class");
        //this.generators = load(context, "generators/generator", "name",
        // "class");
        //         this.extensionFunctions = loadExtensionFunctions(context,
        //               "extension-functions/function");
        this.customElements = loadCustomElements(context, "custom-elements/element");

        this.connectorFactory = load(context, "connectors", "factoryClass");

        this.instanceSerializerMap = loadSerializer(context, "register-serializer/instance-serializer",
                "scheme", "method", "mediatype", "class");

    } catch (Exception e) {
        throw new XFormsConfigException(e);
    }
}