List of usage examples for javax.xml.parsers DocumentBuilderFactory setValidating
public void setValidating(boolean validating)
From source file:org.apache.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 * * @exception JasperException if an input/output error occurs * @exception JasperException if a parsing error occurs *//*from w ww.j a v a2s . c om*/ 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) { throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", uri), 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.apache.jk.config.WebXml2Jk.java
public static Document readXml(File xmlF) throws SAXException, IOException, ParserConfigurationException { if (!xmlF.exists()) { log.error("No xml file " + xmlF); return null; }/* w ww .j a va2s. co m*/ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setIgnoringComments(false); dbf.setIgnoringElementContentWhitespace(true); //dbf.setCoalescing(true); //dbf.setExpandEntityReferences(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); db.setEntityResolver(new NullResolver()); // db.setErrorHandler( new MyErrorHandler()); Document doc = db.parse(xmlF); return doc; }
From source file:org.apache.myfaces.shared_impl.webapp.webxml.WebXmlParser.java
public WebXml parse() { _webXml = new WebXml(); try {/*from w w w .j a v a2 s . c o m*/ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setIgnoringElementContentWhitespace(true); dbf.setIgnoringComments(true); dbf.setNamespaceAware(true); dbf.setValidating(false); // dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new _EntityResolver()); db.setErrorHandler(new MyFacesErrorHandler(log)); InputSource is = createContextInputSource(null, WEB_XML_PATH); if (is == null) { URL url = _context.getResource(WEB_XML_PATH); log.debug("No web-xml found at : " + (url == null ? " null " : url.toString())); return _webXml; } Document document = db.parse(is); Element webAppElem = document.getDocumentElement(); if (webAppElem == null || !webAppElem.getNodeName().equals("web-app")) { throw new FacesException("No valid web-app root element found!"); } readWebApp(webAppElem); return _webXml; } catch (Exception e) { log.fatal("Unable to parse web.xml", e); throw new FacesException(e); } }
From source file:org.apache.sling.its.utils.DocumentUtils.java
/** * Get the file and return a document object. * * @param requestParameter//ww w. j av a 2 s .c o m * The request parameter that holds the metadata needed to pass to * the File. * @param file * File * @return Document * A document object which holds all the xml elements. */ public static Document getDocument(final RequestParameter requestParameter, final File file) { Document doc = null; OutputStream outputStream = null; try { outputStream = new FileOutputStream(file); outputStream.write(requestParameter.get()); if (StringUtils.equals(FilenameUtils.getExtension(requestParameter.getFileName()), "html")) { final HtmlDocumentBuilder docBuilder = new HtmlDocumentBuilder(); doc = docBuilder.parse(file); } else { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(false); doc = dbf.newDocumentBuilder().parse(file); } } catch (final SAXException saxe) { LOG.error("Failed to parse document. Stack Trace:", saxe); } catch (final ParserConfigurationException pce) { LOG.error("Failed to create DocumentBuilder. Stack Trace: ", pce); } catch (final FileNotFoundException nfe) { LOG.error("File Not Found. Stack Trace: ", nfe); } catch (final IOException ioe) { LOG.error("Failed to write to file. Stack Trace: ", ioe); } finally { if (outputStream != null) { try { outputStream.close(); } catch (final IOException e) { LOG.error("Failed to close outputStream. Stack Trace: \n", e); } } } return doc; }
From source file:org.apache.sling.urlrewriter.internal.SlingUrlRewriteFilter.java
private Document createDocument(final String rules) { if (StringUtils.isBlank(rules)) { logger.warn("given rules are blank"); return null; }//from w ww.j a va2 s. co m final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); factory.setNamespaceAware(true); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); try { final String systemId = ""; final ConfHandler confHandler = new ConfHandler(systemId); final DocumentBuilder documentBuilder = factory.newDocumentBuilder(); documentBuilder.setErrorHandler(confHandler); documentBuilder.setEntityResolver(confHandler); final InputStream inputStream = new ByteArrayInputStream(rules.getBytes("UTF-8")); final Document document = documentBuilder.parse(inputStream); // , systemId); IOUtils.closeQuietly(inputStream); return document; } catch (Exception e) { logger.error("error creating document from rules property", e); return null; } }
From source file:org.apache.wiki.auth.user.XMLUserDatabase.java
private void buildDOM() { // Read DOM/*from w ww . ja v a2s .co m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setExpandEntityReferences(false); factory.setIgnoringComments(true); factory.setNamespaceAware(false); try { c_dom = factory.newDocumentBuilder().parse(c_file); log.debug("Database successfully initialized"); c_lastModified = c_file.lastModified(); c_lastCheck = System.currentTimeMillis(); } catch (ParserConfigurationException e) { log.error("Configuration error: " + e.getMessage()); } catch (SAXException e) { log.error("SAX error: " + e.getMessage()); } catch (FileNotFoundException e) { log.info("User database not found; creating from scratch..."); } catch (IOException e) { log.error("IO error: " + e.getMessage()); } if (c_dom == null) { try { // // Create the DOM from scratch // c_dom = factory.newDocumentBuilder().newDocument(); c_dom.appendChild(c_dom.createElement("users")); } catch (ParserConfigurationException e) { log.fatal("Could not create in-memory DOM"); } } }
From source file:org.apache.woden.internal.DOMWSDLReader.java
/** * Create the JAXP DocumentBuilderFactory instance.Use JAXP 1.2 API for validation. * @param namespaceAware whether the returned factory is to provide support for XML namespaces * @return the JAXP DocumentBuilderFactory * @throws ParserConfigurationException if we failed to build a proper DocumentBuilderFactory *//*w w w .j a v a 2 s . c o m*/ protected DocumentBuilderFactory createDocumentBuilderFactory(boolean namespaceAware) throws ParserConfigurationException, WSDLException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(namespaceAware); // Enable validation on the XML parser if it has been enabled // for the Woden parser. if (features.getValue(WSDLReader.FEATURE_VALIDATION)) { factory.setValidating(true); // Enforce namespace aware for XSD... factory.setNamespaceAware(true); try { factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); factory.setAttribute(JAXP_SCHEMA_SOURCE, schemas); } catch (IllegalArgumentException e) { getErrorReporter().reportError(new ErrorLocatorImpl(), //TODO line&col nos. "WSDL515", new Object[] { factory.getClass().getName() }, ErrorReporter.SEVERITY_FATAL_ERROR, e); } } else { factory.setValidating(false); } return factory; }
From source file:org.apache.xml.security.Init.java
/** * Initialise the library from a configuration file *///ww w. j a va 2 s . c om private static void fileInit(InputStream is) { try { /* read library configuration file */ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(is); Node config = doc.getFirstChild(); for (; config != null; config = config.getNextSibling()) { if ("Configuration".equals(config.getLocalName())) { break; } } if (config == null) { log.error("Error in reading configuration file - Configuration element not found"); return; } for (Node el = config.getFirstChild(); el != null; el = el.getNextSibling()) { if (el == null || Node.ELEMENT_NODE != el.getNodeType()) { continue; } String tag = el.getLocalName(); if (tag.equals("ResourceBundles")) { Element resource = (Element) el; /* configure internationalization */ Attr langAttr = resource.getAttributeNode("defaultLanguageCode"); Attr countryAttr = resource.getAttributeNode("defaultCountryCode"); String languageCode = (langAttr == null) ? null : langAttr.getNodeValue(); String countryCode = (countryAttr == null) ? null : countryAttr.getNodeValue(); I18n.init(languageCode, countryCode); } if (tag.equals("CanonicalizationMethods")) { Element[] list = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "CanonicalizationMethod"); for (int i = 0; i < list.length; i++) { String URI = list[i].getAttributeNS(null, "URI"); String JAVACLASS = list[i].getAttributeNS(null, "JAVACLASS"); try { Canonicalizer.register(URI, JAVACLASS); if (log.isDebugEnabled()) { log.debug("Canonicalizer.register(" + URI + ", " + JAVACLASS + ")"); } } catch (ClassNotFoundException e) { Object exArgs[] = { URI, JAVACLASS }; log.error(I18n.translate("algorithm.classDoesNotExist", exArgs)); } } } if (tag.equals("TransformAlgorithms")) { Element[] tranElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "TransformAlgorithm"); for (int i = 0; i < tranElem.length; i++) { String URI = tranElem[i].getAttributeNS(null, "URI"); String JAVACLASS = tranElem[i].getAttributeNS(null, "JAVACLASS"); try { Transform.register(URI, JAVACLASS); if (log.isDebugEnabled()) { log.debug("Transform.register(" + URI + ", " + JAVACLASS + ")"); } } catch (ClassNotFoundException e) { Object exArgs[] = { URI, JAVACLASS }; log.error(I18n.translate("algorithm.classDoesNotExist", exArgs)); } catch (NoClassDefFoundError ex) { log.warn("Not able to found dependencies for algorithm, I'll keep working."); } } } if ("JCEAlgorithmMappings".equals(tag)) { Node algorithmsNode = ((Element) el).getElementsByTagName("Algorithms").item(0); if (algorithmsNode != null) { Element[] algorithms = XMLUtils.selectNodes(algorithmsNode.getFirstChild(), CONF_NS, "Algorithm"); for (int i = 0; i < algorithms.length; i++) { Element element = algorithms[i]; String id = element.getAttribute("URI"); JCEMapper.register(id, new JCEMapper.Algorithm(element)); } } } if (tag.equals("SignatureAlgorithms")) { Element[] sigElems = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "SignatureAlgorithm"); for (int i = 0; i < sigElems.length; i++) { String URI = sigElems[i].getAttributeNS(null, "URI"); String JAVACLASS = sigElems[i].getAttributeNS(null, "JAVACLASS"); /** $todo$ handle registering */ try { SignatureAlgorithm.register(URI, JAVACLASS); if (log.isDebugEnabled()) { log.debug("SignatureAlgorithm.register(" + URI + ", " + JAVACLASS + ")"); } } catch (ClassNotFoundException e) { Object exArgs[] = { URI, JAVACLASS }; log.error(I18n.translate("algorithm.classDoesNotExist", exArgs)); } } } if (tag.equals("ResourceResolvers")) { Element[] resolverElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver"); for (int i = 0; i < resolverElem.length; i++) { String JAVACLASS = resolverElem[i].getAttributeNS(null, "JAVACLASS"); String Description = resolverElem[i].getAttributeNS(null, "DESCRIPTION"); if ((Description != null) && (Description.length() > 0)) { if (log.isDebugEnabled()) { log.debug("Register Resolver: " + JAVACLASS + ": " + Description); } } else { if (log.isDebugEnabled()) { log.debug("Register Resolver: " + JAVACLASS + ": For unknown purposes"); } } try { ResourceResolver.register(JAVACLASS); } catch (Throwable e) { log.warn("Cannot register:" + JAVACLASS + " perhaps some needed jars are not installed", e); } } } if (tag.equals("KeyResolver")) { Element[] resolverElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver"); List<String> classNames = new ArrayList<String>(resolverElem.length); for (int i = 0; i < resolverElem.length; i++) { String JAVACLASS = resolverElem[i].getAttributeNS(null, "JAVACLASS"); String Description = resolverElem[i].getAttributeNS(null, "DESCRIPTION"); if ((Description != null) && (Description.length() > 0)) { if (log.isDebugEnabled()) { log.debug("Register Resolver: " + JAVACLASS + ": " + Description); } } else { if (log.isDebugEnabled()) { log.debug("Register Resolver: " + JAVACLASS + ": For unknown purposes"); } } classNames.add(JAVACLASS); } KeyResolver.registerClassNames(classNames); } if (tag.equals("PrefixMappings")) { if (log.isDebugEnabled()) { log.debug("Now I try to bind prefixes:"); } Element[] nl = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "PrefixMapping"); for (int i = 0; i < nl.length; i++) { String namespace = nl[i].getAttributeNS(null, "namespace"); String prefix = nl[i].getAttributeNS(null, "prefix"); if (log.isDebugEnabled()) { log.debug("Now I try to bind " + prefix + " to " + namespace); } ElementProxy.setDefaultPrefix(namespace, prefix); } } } } catch (Exception e) { log.error("Bad: ", e); e.printStackTrace(); } }
From source file:org.apache.xml.security.samples.iaik.IAIKInterOp.java
/** * Method main//from w ww. j av a2 s. c o m * * @param unused */ public static void main(String unused[]) { if (schemaValidate) { System.out.println("We do schema-validation"); } else { System.out.println("We do not schema-validation"); } javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); if (IAIKInterOp.schemaValidate) { dbf.setAttribute("http://apache.org/xml/features/validation/schema", Boolean.TRUE); dbf.setAttribute("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.TRUE); dbf.setValidating(true); dbf.setAttribute("http://xml.org/sax/features/validation", Boolean.TRUE); dbf.setAttribute("http://apache.org/xml/properties/schema/external-schemaLocation", Constants.SignatureSpecNS + " " + IAIKInterOp.signatureSchemaFile); } dbf.setNamespaceAware(true); dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); //J- String gregorsDir = "data/at/iaik/ixsil/"; String filenames[] = { gregorsDir + "signatureAlgorithms/signatures/hMACSignature.xml", gregorsDir + "signatureAlgorithms/signatures/hMACShortSignature.xml", gregorsDir + "signatureAlgorithms/signatures/dSASignature.xml", gregorsDir + "signatureAlgorithms/signatures/rSASignature.xml", gregorsDir + "transforms/signatures/base64DecodeSignature.xml", gregorsDir + "transforms/signatures/c14nSignature.xml", gregorsDir + "coreFeatures/signatures/manifestSignature.xml", gregorsDir + "transforms/signatures/xPathSignature.xml", gregorsDir + "coreFeatures/signatures/signatureTypesSignature.xml", gregorsDir + "transforms/signatures/envelopedSignatureSignature.xml" }; //J+ verifyAnonymous(gregorsDir, dbf); for (int i = 0; i < 2; i++) { String signatureFileName = filenames[i]; try { org.apache.xml.security.samples.signature.VerifyMerlinsExamplesFifteen.verifyHMAC(dbf, signatureFileName); } catch (Exception ex) { System.out.println( "The XML signature in file " + signatureFileName + " crashed the application (bad)"); ex.printStackTrace(); System.out.println(); } } for (int i = 2; i < filenames.length; i++) { String signatureFileName = filenames[i]; try { org.apache.xml.security.samples.signature.VerifyMerlinsExamplesSixteen.verify(dbf, signatureFileName); } catch (Exception ex) { System.out.println( "The XML signature in file " + signatureFileName + " crashed the application (bad)"); ex.printStackTrace(); System.out.println(); } } for (int i = 2; i < filenames.length; i++) { String signatureFileName = filenames[i]; try { org.apache.xml.security.samples.signature.VerifyMerlinsExamplesTwentyThree.verify(dbf, signatureFileName); } catch (Exception ex) { System.out.println( "The XML signature in file " + signatureFileName + " crashed the application (bad)"); ex.printStackTrace(); System.out.println(); } } }
From source file:org.apache.xml.security.samples.signature.VerifyMerlinsExamplesFifteen.java
/** * Method main// w w w. j av a 2s .c o m * * @param unused */ public static void main(String unused[]) { if (schemaValidate) { System.out.println("We do schema-validation"); } else { System.out.println("We do not schema-validation"); } javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); if (VerifyMerlinsExamplesSixteen.schemaValidate) { dbf.setAttribute("http://apache.org/xml/features/validation/schema", Boolean.TRUE); dbf.setAttribute("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.TRUE); dbf.setValidating(true); dbf.setAttribute("http://xml.org/sax/features/validation", Boolean.TRUE); dbf.setAttribute("http://apache.org/xml/properties/schema/external-schemaLocation", Constants.SignatureSpecNS + " " + VerifyMerlinsExamplesSixteen.signatureSchemaFile); } dbf.setNamespaceAware(true); dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); //J- String merlinsDir = "data/ie/baltimore/merlin-examples/merlin-xmldsig-fifteen/"; String filenames[] = { merlinsDir + "signature-enveloping-hmac-sha1.xml", merlinsDir + "signature-enveloped-dsa.xml", merlinsDir + "signature-enveloping-b64-dsa.xml", merlinsDir + "signature-enveloping-dsa.xml", merlinsDir + "signature-enveloping-rsa.xml", merlinsDir + "signature-external-b64-dsa.xml", merlinsDir + "signature-external-dsa.xml" }; try { verifyHMAC(dbf, filenames[0]); } catch (Exception ex) { ex.printStackTrace(); } for (int i = 1; i < filenames.length; i++) { String signatureFileName = filenames[i]; try { VerifyMerlinsExamplesSixteen.verify(dbf, signatureFileName); } catch (Exception ex) { ex.printStackTrace(); } } }