List of usage examples for javax.xml.parsers DocumentBuilderFactory setAttribute
public abstract void setAttribute(String name, Object value) throws IllegalArgumentException;
From source file:org.kuali.rice.kew.xml.DocumentTypeXmlParserTest.java
private boolean validate(String docName) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(true);// ww w .jav a2s .com dbf.setNamespaceAware(true); dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", XMLConstants.W3C_XML_SCHEMA_NS_URI); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new org.kuali.rice.core.impl.impex.xml.ClassLoaderEntityResolver()); db.setErrorHandler(new DefaultHandler() { @Override public void error(SAXParseException e) throws SAXException { this.fatalError(e); } @Override public void fatalError(SAXParseException e) throws SAXException { super.fatalError(e); } }); try { db.parse(getClass().getResourceAsStream(docName + ".xml")); return true; } catch (SAXException se) { log.error("Error validating " + docName + ".xml", se); return false; } }
From source file:org.plasma.sdo.helper.PlasmaXMLHelper.java
private void validateDOM(InputStream inputStream, String locationURI, XMLOptions options) throws IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);//from w w w . ja v a 2 s. co m factory.setValidating(true); try { factory.setAttribute(XMLConstants.JAXP_SCHEMA_LANGUAGE, SchemaConstants.XMLSCHEMA_NAMESPACE_URI); factory.setValidating(true); //factory.setNamespaceAware(true); //factory.setFeature("http://apache.org/xml/features/validation/schema",true); //factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); } catch (IllegalArgumentException e) { log.warn("parser does not support JAXP 1.2"); } /*catch (ParserConfigurationException e) { throw new PlasmaDataObjectException(e); }*/ if (locationURI != null) { factory.setAttribute(XMLConstants.JAXP_NO_NAMESPACE_SCHEMA_SOURCE, locationURI); } try { DocumentBuilder builder = factory.newDocumentBuilder(); if (options.getErrorHandler() == null) builder.setErrorHandler(new DefaultErrorHandler(options)); else builder.setErrorHandler(options.getErrorHandler()); if (log.isDebugEnabled()) log.debug("validating..."); builder.parse(inputStream); } catch (ParserConfigurationException e) { throw new PlasmaDataObjectException(e); } catch (SAXException e) { throw new PlasmaDataObjectException(e); } }
From source file:org.soybeanMilk.core.config.parser.ConfigurationParser.java
/** * ??xml??//from w w w . ja va 2 s . c o m * @param in * @return * @throws ParseException */ protected Document parseDocument(InputStream in) { Document doc = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(false); //?? dbf.setValidating(false); dbf.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); doc = dbf.newDocumentBuilder().parse(in); in.close(); return doc; } catch (Exception e) { throw new ParseException("", e); } }
From source file:org.springframework.beans.factory.xml.DefaultDocumentLoader.java
/** * Create the {@link DocumentBuilderFactory} instance. * @param validationMode the type of validation: {@link XmlValidationModeDetector#VALIDATION_DTD DTD} * or {@link XmlValidationModeDetector#VALIDATION_XSD XSD}) * @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 *///from w w w. jav a2 s. co m protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware) throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(namespaceAware); if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) { factory.setValidating(true); if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) { // Enforce namespace aware for XSD... factory.setNamespaceAware(true); try { factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE); } catch (IllegalArgumentException ex) { ParserConfigurationException pcex = new ParserConfigurationException( "Unable to validate using XSD: Your JAXP provider [" + factory + "] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " + "Upgrade to Apache Xerces (or Java 1.5) for full XSD support."); pcex.initCause(ex); throw pcex; } } } return factory; }
From source file:org.springframework.webflow.engine.model.builder.xml.DefaultDocumentLoader.java
public Document loadDocument(Resource resource) throws IOException, ParserConfigurationException, SAXException { InputStream is = null;/*from www. java 2s . co m*/ try { is = resource.getInputStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(isValidating()); factory.setNamespaceAware(true); try { factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE); } catch (IllegalArgumentException ex) { throw new IllegalStateException("Unable to validate using XSD: Your JAXP provider [" + factory + "] does not support XML Schema. " + "Are you running on Java 1.4 or below with Apache Crimson? " + "If so you must upgrade to Apache Xerces (or Java 5 or >) for full XSD support."); } DocumentBuilder docBuilder = factory.newDocumentBuilder(); docBuilder.setErrorHandler(new SimpleSaxErrorHandler(logger)); docBuilder.setEntityResolver(getEntityResolver()); return docBuilder.parse(is); } finally { if (is != null) { is.close(); } } }
From source file:org.viafirma.nucleo.firma.imp.FirmaOpenocesAppletBridgeImp.java
/** * Preprocesa el documento que se va a enviar al usuario para su firma. El * documento es canonizado y se eliminan todos los elementos Signature que * aparecen en el//from w w w. j a v a2s. co m * * @param documento * @param request */ public void preprocessXadesEpesEnveloped(Documento documento, HttpServletRequest request) { if (TypeFormatSign.XADES_EPES_ENVELOPED.equals(documento.getTypeFormatSign())) { request.setAttribute("viafirmaSignFormat", TypeFormatSign.XADES_EPES_ENVELOPED.name()); // Parsea el documento original para buscar posibles elementos de // tipo // Signature InputSource ioXml = new InputSource(new ByteArrayInputStream(documento.getDatos())); javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); javax.xml.parsers.DocumentBuilder db; try { db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse(ioXml); // Recuperamos todos los elementos de tipo signature. Element nscontext = XMLUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS); NodeList nodeList = XPathAPI.selectNodeList(doc, "//ds:Signature", nscontext); // Extrae los hijos que ds:signature for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); node.getParentNode().removeChild(node); } if (nodeList.getLength() > 0) { log.debug( "Hay Signatures eliminados del documento XAdes que deberan ser aadidos posteriormente."); request.getSession().setAttribute(Constantes.SIGNATURE_PRINCIPAL, nodeList.item(0)); } // Debido a dificutades en la canonizacin desde el applet le // pasamos al // applet un xml ya canonizado para facilitar el proceso. documento.setDatos(XmlSignUtil.getInstance().canonizar(doc)); } catch (ParserConfigurationException e) { log.warn("Problemas al prerocesar el XAdes.", e); } catch (SAXException e) { log.warn("Problemas al prerocesar el XAdes.", e); } catch (IOException e) { log.warn("Problemas al prerocesar el XAdes.", e); } catch (TransformerException e) { log.warn("Problemas al prerocesar el XAdes.", e); } } }
From source file:org.viafirma.nucleo.validacion.ValidadorHandler.java
/** * Chequea el hash del documento original coincide con el hash del documento * custodiado.//w w w .ja v a 2 s .c o m * * @param originalData * @param id * @param xmlSig * @return */ public boolean checkHash(byte[] originalData, String id, XMLSignature xmlSig) { // Realiza el digest del documento custodiado String digestCustodiadoString = XmlSignUtil.getInstance().getDigest(xmlSig, id)[1]; // Lo pasamos a Byte[] byte[] digestCustodiado = Base64.decode(digestCustodiadoString); // Bytes del documento original preprocesados ( Canonizados si fuese // necesario) byte[] originalDataPreprocess = null; try { // Recuperamos el tipo de documento a comprobar TypeFormatSign typeFormatSign = XmlSignUtil.getTypeFormatSign(id); if (typeFormatSign == TypeFormatSign.XMLSIG_ENVELOPING) { // Para este tipo de formato no es necesario canonizar, ej: // binario de un PDF originalDataPreprocess = originalData; } else if (typeFormatSign == TypeFormatSign.XADES_EPES_ENVELOPED) { // Recupera el documento custodiado InputStream input = new ByteArrayInputStream(originalData); // Reader readerXML = new InputStreamReader(input); InputSource ioXml = new InputSource(input); // parser javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory .newInstance(); javax.xml.parsers.DocumentBuilder db; dbf.setNamespaceAware(true); dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse(ioXml); org.w3c.dom.Element nscontext = XMLUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS); NodeList nodeIterator = XPathAPI.selectNodeList(doc, "//ds:Signature", nscontext); // Extrae los hijos que ds:signature for (int i = 0; i < nodeIterator.getLength(); i++) { Node node = nodeIterator.item(i); node.getParentNode().removeChild(node); } // Canoniza el documento originalDataPreprocess = XmlSignUtil.getInstance().canonizar(doc); } else { throw new UnsupportedOperationException( "El tipo de firma no es soportado para su verificacion. " + typeFormatSign); } // Digiere los datos a comprobar byte[] digestOriginal = DigestUtils.sha(originalDataPreprocess); // Comprueba que los disges son efectivamente iguales if (Arrays.equals(digestCustodiado, digestOriginal)) { return true; } return false; } catch (ParserConfigurationException e) { log.error("Error con el configurador al parsear el documento ", e); } catch (SAXException e) { log.error("Error de nivel Sax al parsear el documento ", e); } catch (IOException e) { log.error("Error de flujo al parsear el documento", e); } catch (TransformerException e) { log.error("Error al transformar el documento", e); } catch (ExcepcionErrorInterno e) { log.error("Error de seguridad al digerir el documento", e); } return false; }
From source file:org.viafirma.util.XmlSignUtil.java
/** * Parsea el xml asociado//w ww . j av a 2 s . co m * * @param xmldoc_b64 * @return * @throws ExcepcionManejoCertificado */ public Document parseDocument(Reader readerXml) throws ExcepcionErrorInterno { try { // parser InputSource ioXml = new InputSource(readerXml); // InputStream in=ioXml.getByteStream(); javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); dbf.setValidating(false); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse(ioXml); return doc; } catch (ParserConfigurationException e) { throw new ExcepcionErrorInterno("ParserConfigurationException", e); } catch (SAXException e) { throw new ExcepcionErrorInterno("ParserConfigurationException", e); } catch (IOException e) { throw new ExcepcionErrorInterno("ParserConfigurationException", e); } finally { if (readerXml != null) { try { readerXml.close(); } catch (IOException e) { log.warn("No se puede cerrar el InputStream para el XmlSignature"); } } } }
From source file:org.webical.plugin.xml.PluginManifestReader.java
/** * Validates the pluginManifest to the webicalPluginSchemaSource * @param pluginManifest the manifest to validate * @return the Domdocument build to validate * @throws ParserConfigurationException on error * @throws SAXException on error/* w w w . j a v a 2 s. c o m*/ * @throws IOException on error */ private Document validatePluginManifest(File pluginManifest) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); if (log.isDebugEnabled()) { log.debug("Xsd resource property: " + webicalPluginSchema); log.debug("Setting xsd to: " + webicalPluginSchema); } factory.setAttribute(JAXP_SCHEMA_SOURCE, webicalPluginSchema); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); documentBuilder.setErrorHandler(new PluginValidationErrorHandler(pluginManifest)); return documentBuilder.parse(pluginManifest); }
From source file:org.wso2.balana.ctx.InputParser.java
/** * Tries to Parse the given output as a Context document. * /* w ww .ja v a2s . c om*/ * @param input the stream to parse * @param rootTage either "Request" or "Response" * * @return the root node of the request/response * * @throws ParsingException if a problem occurred parsing the document */ public static Node parseInput(InputStream input, String rootTag) throws ParsingException { NodeList nodes = null; try { DocumentBuilderFactory factory = Utils.getSecuredDocumentBuilderFactory(); factory.setIgnoringComments(true); DocumentBuilder builder = null; // as of 1.2, we always are namespace aware factory.setNamespaceAware(true); if (ipReference == null) { // we're not validating factory.setValidating(false); builder = factory.newDocumentBuilder(); } else { // we are validating factory.setValidating(true); factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); factory.setAttribute(JAXP_SCHEMA_SOURCE, ipReference.schemaFile); builder = factory.newDocumentBuilder(); builder.setErrorHandler(ipReference); } Document doc = builder.parse(input); nodes = doc.getElementsByTagName(rootTag); } catch (Exception e) { throw new ParsingException("Error tring to parse " + rootTag + "Type", e); } if (nodes.getLength() != 1) throw new ParsingException("Only one " + rootTag + "Type allowed " + "at the root of a Context doc"); return nodes.item(0); }