List of usage examples for javax.xml.parsers DocumentBuilderFactory setAttribute
public abstract void setAttribute(String name, Object value) throws IllegalArgumentException;
From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java
/** * Validate xml.// w w w . j a va 2 s . c o m * * @param inSchemas the in schemas * @param inXml the in xml * @param schemaLanguage the schema language * * @return the xML error handler * * @throws MotuException the motu exception */ public static XMLErrorHandler validateXML(String[] inSchemas, InputStream inXml, String schemaLanguage) throws MotuException { XMLErrorHandler errorHandler = new XMLErrorHandler(); try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); // Must enable namespace processing!!!!! try { documentBuilderFactory.setXIncludeAware(true); } catch (Exception e) { // Do Nothing } // documentBuilderFactory.setExpandEntityReferences(true); documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_LANGUAGE, schemaLanguage); // final String[] srcSchemas = // {"http://schemas.opengis.net/iso/19139/20060504/srv/serviceMetadata.xsd", // }; // final String[] srcSchemas = // {"http://opendap.aviso.oceanobs.com/data/ISO_19139/srv/serviceMetadata.xsd", // "http://opendap.aviso.oceanobs.com/data/ISO_19139/gco/gco.xsd", }; // C:\Documents and Settings\dearith\Mes documents\Atoll\SchemaIso\gml // final String[] srcSchemas = // {"C:/Documents and Settings/users documents/Atoll/SchemaIso/srv/serviceMetadata.xsd", // }; // final String[] srcSchemas = {"schema/iso/srv/serviceMetadata.xsd", // }; documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_SOURCE, inSchemas); // URL url = Organizer.findResource("schema/iso/srv/srv.xsd"); // URL url = Organizer.findResource("iso/19139/20070417/srv/serviceMetadata.xsd"); // documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", // url.toString()); documentBuilderFactory.setValidating(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); // document = documentBuilder.parse(new File(xmlUrl.toURI())); documentBuilder.setErrorHandler(errorHandler); documentBuilder.parse(inXml); } catch (Exception e) { throw new MotuException(e); // instance document is invalid! } return errorHandler; }
From source file:com.amalto.webapp.core.util.Util.java
public static Document parse(String xmlString, String schema) throws Exception { // parse/* w w w . j a v a 2s.c o m*/ Document d; SAXErrorHandler seh = new SAXErrorHandler(); try { // initialize the sax parser which uses Xerces DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Schema validation based on schemaURL factory.setNamespaceAware(true); factory.setValidating((schema != null)); factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", //$NON-NLS-1$ "http://www.w3.org/2001/XMLSchema"); //$NON-NLS-1$ if (schema != null) { factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", //$NON-NLS-1$ new InputSource(new StringReader(schema))); } DocumentBuilder builder; builder = factory.newDocumentBuilder(); builder.setErrorHandler(seh); d = builder.parse(new InputSource(new StringReader(xmlString))); } catch (Exception e) { String err = "Unable to parse the document" + ": " + e.getClass().getName() + ": " //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + e.getLocalizedMessage() + "\n " //$NON-NLS-1$ + xmlString; throw new Exception(err); } // check if document parsed correctly against the schema if (schema != null) { String errors = seh.getErrors(); if (!errors.equals("")) { //$NON-NLS-1$ String err = "Document did not parse against schema: \n" + errors + "\n" + xmlString; //$NON-NLS-1$//$NON-NLS-2$ throw new Exception(err); } } return d; }
From source file:edu.internet2.middleware.shibboleth.common.config.SpringDocumentLoader.java
/** {@inheritDoc} */ public Document loadDocument(InputSource inputSource, EntityResolver entityResolver, ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); factory.setCoalescing(true);/*from w w w .java 2s. c o m*/ factory.setIgnoringComments(true); factory.setNamespaceAware(true); factory.setValidating(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new LoggingErrorHandler(log)); builder.setEntityResolver(new ClasspathResolver()); return builder.parse(inputSource); }
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 ww w . j a v a2 s. c om*/ 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:com.runwaysdk.request.ClientRequestManager.java
/** * Constructs a new ConnectionManager object by reading in an xml file detailing connections to servers and then populating a HashMap of Connection objects. *///from w w w . j a va 2 s . com private ClientRequestManager() { // initialize the connections and proxies. connections = new HashMap<String, ConnectionLabel>(); URL connectionsXmlFile; try { connectionsXmlFile = ConfigurationManager.getResource(ConfigGroup.CLIENT, "connections.xml"); } catch (RunwayConfigurationException e) { log.warn("connections.xml configuration file not found.", e); return; } InputStream connectionsSchemaFile; try { connectionsSchemaFile = ConfigurationManager.getResource(ConfigGroup.XSD, "connectionsSchema.xsd") .openStream(); } catch (IOException e) { throw new RunwayConfigurationException(e); } Document document = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); factory.setAttribute(XMLConstants.JAXP_SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA); factory.setAttribute(XMLConstants.JAXP_SCHEMA_SOURCE, connectionsSchemaFile); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); builder.setErrorHandler(new XMLConnectionsErrorHandler()); document = builder.parse(connectionsXmlFile.openStream()); } catch (ParserConfigurationException e) { throw new ClientRequestException(e); } catch (SAXException e) { throw new ClientRequestException(e); } catch (IOException e) { throw new ClientRequestException(e); } parseDocument(document); }
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 ww w .ja va 2 s . 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:dip.world.variant.VariantManager.java
/** * Initiaize the VariantManager. /* w w w.j a v a 2 s. c om*/ * <p> * An exception is thrown if no File paths are specified. A "." may be used * to specify th ecurrent directory. * <p> * Loaded XML may be validated if the isValidating flag is set to true. * */ public static synchronized void init(final List<File> searchPaths, boolean isValidating) throws javax.xml.parsers.ParserConfigurationException, NoVariantsException { long ttime = System.currentTimeMillis(); long vptime = ttime; Log.println("VariantManager.init()"); if (searchPaths == null || searchPaths.isEmpty()) { throw new IllegalArgumentException(); } if (vm != null) { // perform cleanup vm.variantMap.clear(); vm.variants = new ArrayList<Variant>(); vm.currentUCL = null; vm.currentPackageURL = null; vm.symbolPacks = new ArrayList<SymbolPack>(); vm.symbolMap.clear(); } vm = new VariantManager(); // find plugins, create plugin loader final List<URL> pluginURLs = vm.searchForFiles(searchPaths, VARIANT_EXTENSIONS); // setup document builder DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { // this may improve performance, and really only apply to Xerces dbf.setAttribute("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.FALSE); dbf.setAttribute("http://apache.org/xml/properties/input-buffer-size", new Integer(4096)); dbf.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE); } catch (Exception e) { Log.println("VM: Could not set XML feature.", e); } dbf.setValidating(isValidating); dbf.setCoalescing(false); dbf.setIgnoringComments(true); // setup variant parser XMLVariantParser variantParser = new XMLVariantParser(dbf); // for each plugin, attempt to find the "variants.xml" file inside. // if it does not exist, we will not load the file. If it does, we will parse it, // and associate the variant with the URL in a hashtable. for (final URL pluginURL : pluginURLs) { URLClassLoader urlCL = new URLClassLoader(new URL[] { pluginURL }); URL variantXMLURL = urlCL.findResource(VARIANT_FILE_NAME); if (variantXMLURL != null) { String pluginName = getFile(pluginURL); // parse variant description file, and create hash entry of variant object -> URL InputStream is = null; try { is = new BufferedInputStream(variantXMLURL.openStream()); variantParser.parse(is, pluginURL); final List<Variant> variants = variantParser.getVariants(); // add variants; variants with same name (but older versions) are // replaced with same-name newer versioned variants for (final Variant variant : variants) { addVariant(variant, pluginName, pluginURL); } } catch (IOException e) { // display error dialog ErrorDialog.displayFileIO(null, e, pluginURL.toString()); } catch (org.xml.sax.SAXException e) { // display error dialog ErrorDialog.displayGeneral(null, e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } } // if we are in webstart, search for variants within webstart jars Enumeration<URL> enum2 = null; ClassLoader cl = null; if (vm.isInWebstart) { cl = vm.getClass().getClassLoader(); try { enum2 = cl.getResources(VARIANT_FILE_NAME); } catch (IOException e) { enum2 = null; } if (enum2 != null) { while (enum2.hasMoreElements()) { URL variantURL = enum2.nextElement(); // parse variant description file, and create hash entry of variant object -> URL InputStream is = null; String pluginName = getWSPluginName(variantURL); try { is = new BufferedInputStream(variantURL.openStream()); variantParser.parse(is, variantURL); final List<Variant> variants = variantParser.getVariants(); // add variants; variants with same name (but older versions) are // replaced with same-name newer versioned variants for (final Variant variant : variants) { addVariant(variant, pluginName, variantURL); } } catch (IOException e) { // display error dialog ErrorDialog.displayFileIO(null, e, variantURL.toString()); } catch (org.xml.sax.SAXException e) { // display error dialog ErrorDialog.displayGeneral(null, e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } } // if(enum2 != null) } // check: did we find *any* variants? Throw an exception. if (vm.variantMap.isEmpty()) { StringBuffer msg = new StringBuffer(256); msg.append("No variants found on path: "); for (final File searchPath : searchPaths) { msg.append(searchPath); msg.append("; "); } throw new NoVariantsException(msg.toString()); } Log.printTimed(vptime, "VariantManager: variant parsing time: "); ///////////////// SYMBOLS ///////////////////////// // now, parse symbol packs XMLSymbolParser symbolParser = new XMLSymbolParser(dbf); // find plugins, create plugin loader final List<URL> pluginURLs2 = vm.searchForFiles(searchPaths, SYMBOL_EXTENSIONS); // for each plugin, attempt to find the "variants.xml" file inside. // if it does not exist, we will not load the file. If it does, we will parse it, // and associate the variant with the URL in a hashtable. for (final URL pluginURL : pluginURLs2) { URLClassLoader urlCL = new URLClassLoader(new URL[] { pluginURL }); URL symbolXMLURL = urlCL.findResource(SYMBOL_FILE_NAME); if (symbolXMLURL != null) { String pluginName = getFile(pluginURL); // parse variant description file, and create hash entry of variant object -> URL InputStream is = null; try { is = new BufferedInputStream(symbolXMLURL.openStream()); symbolParser.parse(is, pluginURL); addSymbolPack(symbolParser.getSymbolPack(), pluginName, pluginURL); } catch (IOException e) { // display error dialog ErrorDialog.displayFileIO(null, e, pluginURL.toString()); } catch (org.xml.sax.SAXException e) { // display error dialog ErrorDialog.displayGeneral(null, e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } } // if we are in webstart, search for variants within webstart jars enum2 = null; cl = null; if (vm.isInWebstart) { cl = vm.getClass().getClassLoader(); try { enum2 = cl.getResources(SYMBOL_FILE_NAME); } catch (IOException e) { enum2 = null; } if (enum2 != null) { while (enum2.hasMoreElements()) { URL symbolURL = enum2.nextElement(); // parse variant description file, and create hash entry of variant object -> URL InputStream is = null; String pluginName = getWSPluginName(symbolURL); try { is = new BufferedInputStream(symbolURL.openStream()); symbolParser.parse(is, symbolURL); addSymbolPack(symbolParser.getSymbolPack(), pluginName, symbolURL); } catch (IOException e) { // display error dialog ErrorDialog.displayFileIO(null, e, symbolURL.toString()); } catch (org.xml.sax.SAXException e) { // display error dialog ErrorDialog.displayGeneral(null, e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } } // if(enum2 != null) } // if(isInWebStart) // check: did we find *any* symbol packs? Throw an exception. if (vm.symbolMap.isEmpty()) { StringBuffer msg = new StringBuffer(256); msg.append("No SymbolPacks found on path: "); for (final File searchPath : searchPaths) { msg.append(searchPath); msg.append("; "); } throw new NoVariantsException(msg.toString()); } Log.printTimed(ttime, "VariantManager: total parsing time: "); }
From source file:de.interactive_instruments.ShapeChange.Target.Metadata.ApplicationSchemaMetadata.java
@Override public void initialise(PackageInfo p, Model m, Options o, ShapeChangeResult r, boolean diagOnly) throws ShapeChangeAbortException { schemaPi = p;//from w w w . ja v a 2 s.c o m schemaTargetNamespace = p.targetNamespace(); model = m; options = o; result = r; diagnosticsOnly = diagOnly; result.addDebug(this, 1, schemaPi.name()); if (!initialised) { initialised = true; outputDirectory = options.parameter(this.getClass().getName(), "outputDirectory"); if (outputDirectory == null) outputDirectory = options.parameter("outputDirectory"); if (outputDirectory == null) outputDirectory = options.parameter("."); outputFilename = "schema_metadata.xml"; // Check if we can use the output directory; create it if it // does not exist outputDirectoryFile = new File(outputDirectory); boolean exi = outputDirectoryFile.exists(); if (!exi) { try { FileUtils.forceMkdir(outputDirectoryFile); } catch (IOException e) { result.addError(null, 600, e.getMessage()); e.printStackTrace(System.err); } exi = outputDirectoryFile.exists(); } boolean dir = outputDirectoryFile.isDirectory(); boolean wrt = outputDirectoryFile.canWrite(); boolean rea = outputDirectoryFile.canRead(); if (!exi || !dir || !wrt || !rea) { result.addFatalError(null, 601, outputDirectory); throw new ShapeChangeAbortException(); } File outputFile = new File(outputDirectoryFile, outputFilename); // check if output file already exists - if so, attempt to delete it exi = outputFile.exists(); if (exi) { result.addInfo(this, 3, outputFilename, outputDirectory); try { FileUtils.forceDelete(outputFile); result.addInfo(this, 4); } catch (IOException e) { result.addInfo(null, 600, e.getMessage()); e.printStackTrace(System.err); } } // identify map entries defined in the target configuration List<ProcessMapEntry> mapEntries = options.getCurrentProcessConfig().getMapEntries(); if (mapEntries != null) { for (ProcessMapEntry pme : mapEntries) { mapEntryByType.put(pme.getType(), pme); } } // reset processed flags on all classes in the schema for (Iterator<ClassInfo> k = model.classes(schemaPi).iterator(); k.hasNext();) { ClassInfo ci = k.next(); ci.processed(getTargetID(), false); } // ====================================== // Parse configuration parameters // ====================================== // nothing to do at present // ====================================== // Set up the document and create root // ====================================== DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true); dbf.setAttribute(Options.JAXP_SCHEMA_LANGUAGE, Options.W3C_XML_SCHEMA); DocumentBuilder db; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { result.addFatalError(null, 2); throw new ShapeChangeAbortException(); } document = db.newDocument(); root = document.createElementNS(NS, "ApplicationSchemaMetadata"); document.appendChild(root); addAttribute(root, "xmlns", NS); hook = document.createComment("Created by ShapeChange - http://shapechange.net/"); root.appendChild(hook); } // create elements documenting the application schema Element e_name = document.createElement("name"); e_name.setTextContent(schemaPi.name()); Element e_tns = document.createElement("targetNamespace"); e_tns.setTextContent(schemaPi.targetNamespace()); Element e_as = document.createElement("ApplicationSchema"); e_as.appendChild(e_name); e_as.appendChild(e_tns); Element e_schema = document.createElement("schema"); e_schema.appendChild(e_as); root.appendChild(e_schema); /* * Now compute relevant metadata. */ processMetadata(e_as); }
From source file:com.qcadoo.maven.plugins.validator.ValidatorMojo.java
private void validateSchema(final String file) throws MojoFailureException { try {//w ww .j av a 2s . co m getLog().info("Validating file: " + file); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); try { URL url = new URL("http://www.qcadoo.com"); url.openConnection(); factory.setValidating(true); } catch (UnknownHostException e) { factory.setValidating(false); } catch (IOException e) { factory.setValidating(false); } factory.setValidating(false); factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); DocumentBuilder parser = factory.newDocumentBuilder(); parser.setErrorHandler(new ValidationErrorHandler()); parser.parse(new File(file)); } catch (ParserConfigurationException e) { getLog().error(e.getMessage()); throw (MojoFailureException) new MojoFailureException("We couldn't parse the file: " + file) .initCause(e); } catch (SAXException e) { getLog().error(e.getMessage()); throw (MojoFailureException) new MojoFailureException("We couldn't parse the file: " + file) .initCause(e); } catch (IOException e) { getLog().error(e.getMessage()); throw (MojoFailureException) new MojoFailureException("We couldn't parse the file: " + file) .initCause(e); } }
From source file:org.opengeoportal.proxy.controllers.DynamicOgcController.java
/** * An HTTP reverse proxy/gateway servlet. It is designed to be extended for customization * if desired. Most of the work is handled by * <a href="http://hc.apache.org/httpcomponents-client-ga/">Apache HttpClient</a>. * <p>//w w w. jav a 2s . c om * There are alternatives to a servlet based proxy such as Apache mod_proxy if that is available to you. However * this servlet is easily customizable by Java, secure-able by your web application's security (e.g. spring-security), * portable across servlet engines, and is embeddable into another web application. * </p> * <p> * Inspiration: http://httpd.apache.org/docs/2.0/mod/mod_proxy.html * </p> * * @author David Smiley dsmiley@mitre.org> */ private void createBuilder() throws ParserConfigurationException { // Create a factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //ignore validation, dtd factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setValidating(false); // Use document builder factory builder = factory.newDocumentBuilder(); }