@Override public void configurationChanged(ConfigurationEvent event) { Configuration newConfig = event.getConfiguration(); builder = new SAXBuilder(newConfig.isValidateListing()); if (newConfig.isValidateListing()) { log.debug("Using the default XML entity resolver"); builder.setEntityResolver(validationEntityResolver); } else { log.debug("Using the plain XML entity resolver"); builder.setEntityResolver(plainEntityResolver); } }
/** * Initialize all the exporters * * @param file the {@link File} with the exporters to intialize * @throws ExportException when cannot read from the file */ public static void initializeExporters(File file) throws ExportException { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); // if(reader==null) // { // String params[]={file.getAbsolutePath()}; // throw new // ExportException(StringUtilities.getReplacedString(PropertiesHandler.getResourceString("error.algorithm.file"),params)); // } SAXBuilder builder = new SAXBuilder(true); builder.setEntityResolver(new NetworkEntityResolver()); Document doc = builder.build(reader); loadFromDocument(doc); } catch (FileNotFoundException e) { throw new ExportException(e.getMessage()); } catch (JDOMException e) { throw new ExportException(e.getMessage()); } catch (Exception e) { throw new ExportException(e.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignore) { } } } }
private void loadData(File path) { if (path.isDirectory()) { File[] dataFiles = path.listFiles(new XMLFilter()); SAXBuilder builder = new SAXBuilder(); GeneratorDtdResolver resolver = new GeneratorDtdResolver(path); builder.setEntityResolver(resolver); for (int i = 0; i < dataFiles.length; i++) { try { URL url = dataFiles[i].toURI().toURL(); Document nameSet = builder.build(url); DocType dt = nameSet.getDocType(); if (dt.getElementName().equals("GENERATOR")) { loadFromDocument(nameSet); } nameSet = null; dt = null; } catch (Exception e) { Logging.errorPrint(e.getMessage(), e); JOptionPane.showMessageDialog(this, "XML Error with file " + dataFiles[i].getName()); } } loadDropdowns(); } else { JOptionPane.showMessageDialog(this, "No data files in directory " + path.getPath()); } }
public static void parse(InputStream is, XmlTagHandler tag, EntityResolver resolver) throws XmlParseException { SAXBuilder builder; Document doc; builder = new SAXBuilder(); if (resolver != null) { builder.setEntityResolver(resolver); } try { if (resolver != null) { // WTF? seems relative entity URIs are allowed // by certain xerces impls. but fully qualified // file://... URLs trigger a NullPointerException // in others. setting base here worksaround doc = builder.build(is, ""); } else { doc = builder.build(is); } } catch (JDOMException exc) { XmlParseException toThrow = new XmlParseException(exc.getMessage()); toThrow.initCause(exc); throw toThrow; } catch (IOException exc) { XmlParseException toThrow = new XmlParseException(exc.getMessage()); toThrow.initCause(exc); throw toThrow; } generalParse(tag, doc); }
/** Create a new instance of JDOMOBEXResponseParser. */ public JDOMOBEXResponseParser() { super(); /* turn on validation */ builder = new SAXBuilder(true); builder.setEntityResolver(validationEntityResolver); processorChain = new XMLVersionProcessor().setNextProcessor(new RemoveInvalidCharsProcessor()); }
/** * Merge 2 documents by XSLT. * * @param left Left hand document * @param right Right hand document * @return The merged document */ private Document merge(Document left, Document right) { try { Document doc = createUnifiedDocument(left, right); org.jdom.output.DOMOutputter outputter = new org.jdom.output.DOMOutputter(); org.w3c.dom.Document domDocument = outputter.output(doc); javax.xml.transform.Source xmlSource = new javax.xml.transform.dom.DOMSource(domDocument); if (transformer == null) { TransformerFactory tFactory = TransformerFactory.newInstance(); transformer = tFactory.newTransformer(xsltSource); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamResult xmlResult = new StreamResult(baos); transformer.transform(xmlSource, xmlResult); // PArse it back into a JDOM document SAXBuilder factory = new SAXBuilder(); factory.setValidation(false); // We don't know what the DTD of the document is, so we won't have a local // copy - so we don't want to fail if we can't get it! factory.setEntityResolver( new EntityResolver() { public InputSource resolveEntity(String thePublicId, String theSystemId) throws SAXException { return new InputSource(new StringReader("")); } }); return factory.build(new ByteArrayInputStream(baos.toByteArray())); } catch (Exception ex) { throw new CargoException("Exception whilst trying to transform documents", ex); } }
public static void deleteDataSource(File deploymentFile, String name) { Document doc; Element root; if (deploymentFile == null) { log.error("DeleteDatasource: passed file is null"); return; } if (deploymentFile.exists()) { try { SAXBuilder builder = new SAXBuilder(); SelectiveSkippingEntityResolver entityResolver = SelectiveSkippingEntityResolver.getDtdAndXsdSkippingInstance(); builder.setEntityResolver(entityResolver); doc = builder.build(deploymentFile); root = doc.getRootElement(); if (root != null) { if (!root.getName().equals("datasources")) { throw new RuntimeException( "Datasource file format exception on [" + deploymentFile + "], expected [datasources] element but found [" + root.getName() + "]"); } Element datasourceElement = findDatasourceElement(root, name); root.removeContent(datasourceElement); } updateFile(deploymentFile, doc); } catch (JDOMException e) { log.error("Parsing error occurred while deleting datasource at file: " + deploymentFile, e); } catch (IOException e) { log.error("IO error occurred while deleting datasource at file: " + deploymentFile, e); } } }
/** * @param validate * @return */ private static SAXBuilder getSAXBuilder(boolean validate) { SAXBuilder builder = getSAXBuilderWithoutXMLResolver(validate); Resolver resolver = ResolverWrapper.getInstance(); builder.setEntityResolver(resolver.getXmlResolver()); return builder; }
// Example catalog.xml file contents // // <?xml version="1.0"?> // <!-- commented out to prevent network access // !DOCTYPE catalog PUBLIC "-//OASIS//DTD Entity Resolution XML Catalog V1.0//EN" // "http://www.oasis-open.org/committees/entity/release/1.0/catalog.dtd" // --> // <catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog"> // <group prefer="public" xml:base=""> // <public // publicId="-//AIAA//DTD for Flight Dynamic Models - Functions 2.0//EN" // uri="schemas/DAVEfunc.dtd"/> // // <public // publicId="-//W3C//DTD MathML 2.0//EN" // uri="schemas/mathml2.dtd"/> // // </group> // </catalog> public Document load() throws IOException { Document doc = null; XMLCatalogResolver cr = null; String directory_uri = this.base_uri.substring(0, this.base_uri.lastIndexOf('/')); String errorLine = "No error."; boolean tryValidationFlag = true; int numberOfFailures = 0; boolean success = false; while (numberOfFailures < 2 && !success) { success = true; errorLine = "Error when attempting validation..."; // see if we can open the file first, and deal with any exceptions try { // open the XML file _inputStream = new FileInputStream(this.inputFileName); assert (_inputStream != null); } catch (IOException e) { System.err.println("Error opening file '" + this.inputFileName + "': " + e.getMessage()); System.exit(-1); } // now see if we can parse it; try with and without validation try { // Load XML into JDOM Document SAXBuilder builder = new SAXBuilder(tryValidationFlag); // must turn off Xerces desire to load external DTD regardless of validation builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); if (tryValidationFlag) { String[] catalogs; // environment variable XML_CATALOG_FILES trumps properties file String xml_catalog_files = System.getenv("XML_CATALOG_FILES"); if (xml_catalog_files == null) { xml_catalog_files = System.getProperty("xml.catalog.files"); } if (xml_catalog_files != null) { catalogs = new String[] {xml_catalog_files, "catalog.xml", "catalog", "file:/etc/xml/catalog"}; } else { catalogs = new String[] {"catalog.xml", "catalog", "file:/etc/xml/catalog"}; } cr = new XMLCatalogResolver(catalogs); // // here to test stuff // // cr.setUseLiteralSystemId(false); // // boolean preferPublic = cr.getPreferPublic(); // if (preferPublic) // System.out.println("Prefer public"); // else // System.out.println("Prefer system"); // // System.out.println("call to resolvePublic for DAVE-ML models // gives:"); // System.out.println(cr.resolvePublic("-//AIAA//DTD for Flight Dynamic // Models - Functions 2.0//EN", // "http://www.daveml.org/DTDs/2p0/DAVEfunc.dtd")); // // System.out.println(); // // System.out.println("call to resolvePublic for MathML2 namespace // gives:"); // System.out.println(cr.resolvePublic("-//W3C//DTD MathML 2.0//EN", // "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd")); // } else { cr = null; } builder.setEntityResolver(cr); doc = builder.build(_inputStream, directory_uri); } catch (java.io.FileNotFoundException e) { errorLine = errorLine + e.getMessage(); numberOfFailures++; success = false; } catch (java.net.UnknownHostException e) { errorLine = errorLine + " (network unavailable)"; numberOfFailures++; success = false; } catch (java.net.ConnectException e) { errorLine = errorLine + " (connection timed out)"; numberOfFailures++; success = false; } catch (java.io.IOException e) { errorLine = errorLine + " (general I/O problem)"; numberOfFailures++; success = false; } catch (JDOMException e) { errorLine = errorLine + "\n" + e.getMessage(); numberOfFailures++; success = false; } if (numberOfFailures == 1 && !success) { System.err.println(errorLine); System.err.println("Proceeding without validation."); tryValidationFlag = false; _inputStream.close(); } } if (!success && numberOfFailures >= 2) { _inputStream.close(); System.err.println(errorLine); System.err.println( "Unable to load file successfully (tried with and without validation), aborting."); System.exit(-1); } // if (success && this.isVerbose()) { if (success) { System.out.println("Loaded '" + this.inputFileName + "' successfully, "); org.jdom.DocType dt = doc.getDocType(); switch (numberOfFailures) { case 0: // validated against some DTD System.out.print("Validating against '"); String catalogURI = cr.resolvePublic(dt.getPublicID(), dt.getSystemID()); if (catalogURI == null) { System.out.print(dt.getSystemID()); } else { System.out.print(catalogURI); } System.out.println(".'"); break; case 1: // no validation System.out.println("WITHOUT validation."); } } return doc; }
/** * Update or create a new datasource * * @param deploymentFile * @param name * @param config * @throws JDOMException * @throws IOException */ private static void updateDatasource(File deploymentFile, String name, Configuration config) throws JDOMException, IOException { Document doc; Element root; if (deploymentFile.exists() && !deploymentFile.canWrite()) { throw new RuntimeException( "Datasource file " + deploymentFile + " is not writable. Aborting."); } if (deploymentFile.exists()) { SAXBuilder builder = new SAXBuilder(); SelectiveSkippingEntityResolver entityResolver = SelectiveSkippingEntityResolver.getDtdAndXsdSkippingInstance(); builder.setEntityResolver(entityResolver); doc = builder.build(deploymentFile); root = doc.getRootElement(); } else { doc = new Document(); root = new Element("datasources"); doc.setRootElement(root); } if (!root.getName().equals("datasources")) { throw new RuntimeException( "Datasource file format exception on [" + deploymentFile + "], expected [datasources] element but found [" + root.getName() + "]"); } Element datasourceElement = findDatasourceElement(root, name); String type = config.getSimpleValue("type", null); boolean isNewDatasource = false; if (datasourceElement == null) { datasourceElement = new Element(type); isNewDatasource = true; } else if (!type.equals(datasourceElement.getName())) { datasourceElement.setName(type); } updateElements(datasourceElement, config, COMMON_PROPS); if (type.equals(XA_TX_TYPE)) { updateElements(datasourceElement, config, XA_PROPS); updateMap(datasourceElement, config, CONNECTION_PROPERTY, XA_DATASOURCE_PROPERTY); // updateXAElements(datasourceElement, config); } else { updateElements(datasourceElement, config, NON_XA_PROPS); updateMap(datasourceElement, config, CONNECTION_PROPERTY, CONNECTION_PROPERTY); } if (isNewDatasource) { root.addContent(datasourceElement); } updateFile(deploymentFile, doc); }
public static Configuration loadDatasource(File file, String name) { /* * <local-tx-datasource> <jndi-name>RHQDS</jndi-name> * <connection-url>${rhq.server.database.connection-url}</connection-url> * <driver-class>${rhq.server.database.driver-class}</driver-class> * <user-name>${rhq.server.database.user-name}</user-name> * <password>${rhq.server.database.password}</password> * * <!-- You can include connection properties that will get passed in the * DriverManager.getConnection(props) call; look at your Driver docs to see what these might be. --> * <connection-property name="char.encoding">UTF-8</connection-property> <!-- Tells an oracle * 10.2.0.2 driver to properly implement clobs. --> <connection-property * name="SetBigStringTryClob">true</connection-property> * * <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation> * <min-pool-size>25</min-pool-size> <max-pool-size>100</max-pool-size> * <blocking-timeout-millis>5000</blocking-timeout-millis> <idle-timeout-minutes>15</idle-timeout-minutes> * <prepared-statement-cache-size>75</prepared-statement-cache-size> * * <type-mapping>${rhq.server.database.type-mapping}</type-mapping> * * </local-tx-datasource> */ try { SAXBuilder builder = new SAXBuilder(); SelectiveSkippingEntityResolver entityResolver = SelectiveSkippingEntityResolver.getDtdAndXsdSkippingInstance(); builder.setEntityResolver(entityResolver); Document doc = builder.build(file); // Get the root element Element root = doc.getRootElement(); if (!root.getName().equals("datasources")) { return null; } Element datasourceElement = findDatasourceElement(root, name); if (datasourceElement == null) { return null; } Configuration config = new Configuration(); String type = datasourceElement.getName(); config.put(new PropertySimple("type", type)); bindElements(datasourceElement, config, COMMON_PROPS); if (type.equals(XA_TX_TYPE)) { bindElements(datasourceElement, config, XA_PROPS); bindMap(datasourceElement, config, CONNECTION_PROPERTY, XA_DATASOURCE_PROPERTY); // bindXASpecialElements(datasourceElement,config); } else { bindElements(datasourceElement, config, NON_XA_PROPS); bindMap(datasourceElement, config, CONNECTION_PROPERTY, CONNECTION_PROPERTY); } return config; } catch (IOException e) { log.error("IO error occurred while reading file: " + file, e); } catch (JDOMException e) { log.error("Parsing error occurred while reading file: " + file, e); } return null; }