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.netsteadfast.greenstep.base.action.BaseSupportAction.java

private static Map<String, String> loadStrutsConstants(InputStream is) throws Exception {
    if (loadStrutsSettingConstatns != null) {
        return loadStrutsSettingConstatns;
    }/*from www  . j  a  v  a2  s .com*/
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setFeature("http://xml.org/sax/features/validation", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
    dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    dbf.setValidating(false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("constant");
    loadStrutsSettingConstatns = new HashMap<String, String>();
    for (int i = 0; nodes != null && i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        Element nodeElement = (Element) node;
        loadStrutsSettingConstatns.put(nodeElement.getAttribute("name"), nodeElement.getAttribute("value"));
    }
    return loadStrutsSettingConstatns;
}

From source file:XMLBody.java

/**
 * Load XML document and parse it into DOM.
 * /*from   ww  w  . j a  v  a2s.  com*/
 * @param input
 * @throws ParsingException
 */
public void loadXML(InputStream input) throws Exception {
    try {
        // Create Document Builder Factory
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();

        docFactory.setValidating(false);
        // Create Document Builder
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        docBuilder.isValidating();

        // Disable loading of external Entityes
        docBuilder.setEntityResolver(new EntityResolver() {
            // Dummi resolver - alvays do nothing
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                return new InputSource(new StringReader(""));
            }

        });

        // open and parse XML-file
        xmlDocument = docBuilder.parse(input);

        // Get Root xmlElement
        rootElement = xmlDocument.getDocumentElement();
    } catch (Exception e) {
        throw new Exception("Error load XML ", e);
    }

}

From source file:com.l2jfree.gameserver.instancemanager.ZoneManager.java

private void load() {
    Document doc = null;//  w  w  w  .  java 2s . c  om

    for (File f : Util.getDatapackFiles("zone", ".xml")) {
        int count = 0;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(true);
            factory.setIgnoringComments(true);
            doc = factory.newDocumentBuilder().parse(f);
        } catch (Exception e) {
            _log.fatal("ZoneManager: Error loading file " + f.getAbsolutePath(), e);
            continue;
        }
        try {
            count = parseDocument(doc);
        } catch (Exception e) {
            _log.fatal("ZoneManager: Error in file " + f.getAbsolutePath(), e);
            continue;
        }
        _log.info("ZoneManager: " + f.getName() + " loaded with " + count + " zones");
    }
}

From source file:org.cagrid.gaards.websso.utils.FileHelper.java

public Document validateXMLwithSchema(String propertiesFileName, String schemaFileName)
        throws AuthenticationConfigurationException {
    org.w3c.dom.Document document = null;
    InputStream schemaFileInputStream = getFileAsStream(schemaFileName);
    URL propertiesFileURL = getFileAsURL(propertiesFileName);

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setValidating(false);
    documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
            schemaFileInputStream);/*from   w ww  . j  a  va  2s .  co  m*/
    DocumentBuilder documentBuilder = null;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new AuthenticationConfigurationException("Error in parsing the " + propertiesFileName + " file");
    }
    try {
        document = (org.w3c.dom.Document) documentBuilder.parse(propertiesFileURL.getPath());
    } catch (SAXException e) {
        throw new AuthenticationConfigurationException("Error in parsing the " + propertiesFileName + " file");
    } catch (DOMException de) {
        throw new AuthenticationConfigurationException("Error in parsing the " + propertiesFileName + " file");
    } catch (IOException e) {
        throw new AuthenticationConfigurationException("Error in reading the " + propertiesFileName + " file");
    }
    DOMBuilder builder = new DOMBuilder();
    org.jdom.Document jdomDocument = builder.build(document);

    return jdomDocument;
}

From source file:org.jasig.springframework.security.portlet.authentication.PortletXmlMappableAttributesRetriever.java

/**
 * @return Document for the specified InputStream
 *///from w  w w  .j a v a2s. c o m
private Document getDocument(InputStream aStream) {
    Document doc;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        DocumentBuilder db = factory.newDocumentBuilder();
        db.setEntityResolver(new MyEntityResolver());
        doc = db.parse(aStream);
        return doc;
    } catch (FactoryConfigurationError e) {
        throw new RuntimeException("Unable to parse document object", e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Unable to parse document object", e);
    } catch (SAXException e) {
        throw new RuntimeException("Unable to parse document object", e);
    } catch (IOException e) {
        throw new RuntimeException("Unable to parse document object", e);
    } finally {
        try {
            aStream.close();
        } catch (IOException e) {
            logger.warn("Failed to close input stream for portlet.xml", e);
        }
    }
}

From source file:com.bdaum.juploadr.uploadapi.smugrest.upload.SmugmugUpload.java

public SmugmugUpload(ImageAttributes img, Session session, boolean replace, UploadStatusMonitor monitor) {
    super(session);
    this.image = img;
    this.replace = replace;
    this.monitor = monitor;

    handler = new SmugmugUploadResponseHandler(this);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(false);//ww  w.j  av  a2  s . c  om

}

From source file:WebAppConfig.java

/**
 * This constructor method is passed an XML file. It uses the JAXP API to
 * obtain a DOM parser, and to parse the file into a DOM Document object,
 * which is used by the remaining methods of the class.
 *//*from  w w w .j a  v  a  2  s .  c  o  m*/
public WebAppConfig(File configfile) throws IOException, SAXException, ParserConfigurationException {
    // Get a JAXP parser factory object
    javax.xml.parsers.DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // Tell the factory what kind of parser we want
    dbf.setValidating(false);
    // Use the factory to get a JAXP parser object
    javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();

    // Tell the parser how to handle errors. Note that in the JAXP API,
    // DOM parsers rely on the SAX API for error handling
    parser.setErrorHandler(new org.xml.sax.ErrorHandler() {
        public void warning(SAXParseException e) {
            System.err.println("WARNING: " + e.getMessage());
        }

        public void error(SAXParseException e) {
            System.err.println("ERROR: " + e.getMessage());
        }

        public void fatalError(SAXParseException e) throws SAXException {
            System.err.println("FATAL: " + e.getMessage());
            throw e; // re-throw the error
        }
    });

    // Finally, use the JAXP parser to parse the file. This call returns
    // A Document object. Now that we have this object, the rest of this
    // class uses the DOM API to work with it; JAXP is no longer required.
    document = parser.parse(configfile);
}

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

protected List<Record> search(String query, String arxivid, int max_result) throws IOException, HttpException {
    List<Record> results = new ArrayList<Record>();
    HttpGet method = null;//from   w w  w. jav  a  2  s.  co  m
    try {
        HttpClient client = new DefaultHttpClient();
        HttpParams params = client.getParams();
        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

        try {
            URIBuilder uriBuilder = new URIBuilder("http://export.arxiv.org/api/query");
            uriBuilder.addParameter("id_list", arxivid);
            uriBuilder.addParameter("search_query", query);
            uriBuilder.addParameter("max_results", String.valueOf(max_result));
            method = new HttpGet(uriBuilder.build());
        } catch (URISyntaxException ex) {
            throw new HttpException(ex.getMessage());
        }

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

        if (statusCode != HttpStatus.SC_OK) {
            if (statusCode == HttpStatus.SC_BAD_REQUEST)
                throw new RuntimeException("arXiv query is not valid");
            else
                throw new RuntimeException("Http call failed: " + responseStatus);
        }

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

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

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

            for (Element dataRoot : dataRoots) {
                Record crossitem = ArxivUtils.convertArxixDomToRecord(dataRoot);
                if (crossitem != null) {
                    results.add(crossitem);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("ArXiv identifier is not valid or not exist");
        }
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }

    return results;
}

From source file:ar.com.tadp.xml.rinzo.core.resources.validation.XMLStringValidator.java

private void plainTextValidate(String fileName, String fileContent) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from w w w  .  j ava 2  s  .  c  om*/
    factory.setValidating(true);
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler(this.errorHandler);
        builder.parse(new InputSource(new StringReader(fileContent)));
    } catch (Exception e) {
        //Do nothing because the errorHandler informs the error
    }
}

From source file:de.betterform.connector.file.FileURIResolver.java

/**
 * Performs link traversal of the <code>file</code> URI and returns the
 * result as a DOM document./*  www .j  ava 2s .  co  m*/
 *
 * @return a DOM node parsed from the <code>file</code> URI.
 * @throws XFormsException if any error occurred during link traversal.
 */
public Object resolve() throws XFormsException {
    try {
        // create uri
        URI uri = new URI(getURI());

        // use scheme specific part in order to handle UNC names
        String fileName = uri.getSchemeSpecificPart();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("loading file '" + fileName + "'");
        }

        // create file
        File file = new File(fileName);

        // check for directory
        if (file.isDirectory()) {
            return FileURIResolver.buildDirectoryListing(file);
        }

        // parse file
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        Document document = factory.newDocumentBuilder().parse(file);

        /*
                    Document document = CacheManager.getDocument(file);
                    if(document == null) {
            document = DOMResource.newDocumentBuilder().parse(file);
            CacheManager.putIntoFileCache(file, document);
                    }
        */

        // check for fragment identifier
        if (uri.getFragment() != null) {
            return document.getElementById(uri.getFragment());
        }

        return document;
    } catch (Exception e) {
        //todo: improve error handling as files might fail due to missing DTDs or Schemas - this won't be detected very well
        throw new XFormsException(e);
    }
}