List of usage examples for org.dom4j.io SAXReader setValidation
public void setValidation(boolean validation)
From source file:org.hibernate.ejb.Ejb3Configuration.java
License:Open Source License
private void addXMLEntities(List<String> xmlFiles, PersistenceUnitInfo info, List<String> entities) { //TODO handle inputstream related hbm files ClassLoader newTempClassLoader = info.getNewTempClassLoader(); if (newTempClassLoader == null) { log.warn(//from w w w .j a v a2 s.c o m "Persistence provider caller does not implement the EJB3 spec correctly. PersistenceUnitInfo.getNewTempClassLoader() is null."); return; } XMLHelper xmlHelper = new XMLHelper(); List errors = new ArrayList(); SAXReader saxReader = xmlHelper.createSAXReader("XML InputStream", errors, cfg.getEntityResolver()); try { saxReader.setFeature("http://apache.org/xml/features/validation/schema", true); //saxReader.setFeature( "http://apache.org/xml/features/validation/dynamic", true ); //set the default schema locators saxReader.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", "http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"); } catch (SAXException e) { saxReader.setValidation(false); } for (String xmlFile : xmlFiles) { InputStream resourceAsStream = newTempClassLoader.getResourceAsStream(xmlFile); if (resourceAsStream == null) continue; BufferedInputStream is = new BufferedInputStream(resourceAsStream); try { errors.clear(); org.dom4j.Document doc = saxReader.read(is); if (errors.size() != 0) { throw new MappingException("invalid mapping: " + xmlFile, (Throwable) errors.get(0)); } Element rootElement = doc.getRootElement(); if (rootElement != null && "entity-mappings".equals(rootElement.getName())) { Element element = rootElement.element("package"); String defaultPackage = element != null ? element.getTextTrim() : null; List<Element> elements = rootElement.elements("entity"); for (Element subelement : elements) { String classname = XMLContext.buildSafeClassName(subelement.attributeValue("class"), defaultPackage); if (!entities.contains(classname)) { entities.add(classname); } } elements = rootElement.elements("mapped-superclass"); for (Element subelement : elements) { String classname = XMLContext.buildSafeClassName(subelement.attributeValue("class"), defaultPackage); if (!entities.contains(classname)) { entities.add(classname); } } elements = rootElement.elements("embeddable"); for (Element subelement : elements) { String classname = XMLContext.buildSafeClassName(subelement.attributeValue("class"), defaultPackage); if (!entities.contains(classname)) { entities.add(classname); } } } else if (rootElement != null && "hibernate-mappings".equals(rootElement.getName())) { //FIXME include hbm xml entities to enhance them but entities is also used to collect annotated entities } } catch (DocumentException e) { throw new MappingException("Could not parse mapping document in input stream", e); } finally { try { is.close(); } catch (IOException ioe) { log.warn("Could not close input stream", ioe); } } } }
From source file:org.hibernate.internal.util.xml.MappingReader.java
License:LGPL
private XmlDocument legacyReadMappingDocument(EntityResolver entityResolver, InputSource source, Origin origin) {// ww w . j ava 2 s . c o m // IMPL NOTE : this is the legacy logic as pulled from the old AnnotationConfiguration code Exception failure; ErrorLogger errorHandler = new ErrorLogger(); SAXReader saxReader = new SAXReader(); saxReader.setEntityResolver(entityResolver); saxReader.setErrorHandler(errorHandler); saxReader.setMergeAdjacentText(true); saxReader.setValidation(true); Document document = null; try { // first try with orm 2.1 xsd validation setValidationFor(saxReader, "orm_2_1.xsd"); document = saxReader.read(source); if (errorHandler.hasErrors()) { throw errorHandler.getErrors().get(0); } return new XmlDocumentImpl(document, origin.getType(), origin.getName()); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debugf("Problem parsing XML using orm 2.1 xsd, trying 2.0 xsd : %s", e.getMessage()); } failure = e; errorHandler.reset(); if (document != null) { // next try with orm 2.0 xsd validation try { setValidationFor(saxReader, "orm_2_0.xsd"); document = saxReader.read(new StringReader(document.asXML())); if (errorHandler.hasErrors()) { errorHandler.logErrors(); throw errorHandler.getErrors().get(0); } return new XmlDocumentImpl(document, origin.getType(), origin.getName()); } catch (Exception e2) { if (LOG.isDebugEnabled()) { LOG.debugf("Problem parsing XML using orm 2.0 xsd, trying 1.0 xsd : %s", e2.getMessage()); } errorHandler.reset(); if (document != null) { // next try with orm 1.0 xsd validation try { setValidationFor(saxReader, "orm_1_0.xsd"); document = saxReader.read(new StringReader(document.asXML())); if (errorHandler.hasErrors()) { errorHandler.logErrors(); throw errorHandler.getErrors().get(0); } return new XmlDocumentImpl(document, origin.getType(), origin.getName()); } catch (Exception e3) { if (LOG.isDebugEnabled()) { LOG.debugf("Problem parsing XML using orm 1.0 xsd : %s", e3.getMessage()); } } } } } } throw new InvalidMappingException("Unable to read XML", origin.getType(), origin.getName(), failure); }
From source file:org.hibernate.internal.util.xml.MappingReader.java
License:LGPL
private void setValidationFor(SAXReader saxReader, String xsd) { try {/*w ww . ja v a2 s. com*/ saxReader.setFeature("http://apache.org/xml/features/validation/schema", true); // saxReader.setFeature( "http://apache.org/xml/features/validation/dynamic", true ); if ("orm_2_1.xsd".equals(xsd)) { saxReader.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", "http://xmlns.jcp.org/xml/ns/persistence/orm " + xsd); } else { saxReader.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", "http://java.sun.com/xml/ns/persistence/orm " + xsd); } } catch (SAXException e) { saxReader.setValidation(false); } }
From source file:org.hibernate.tool.xml.XMLHelper.java
License:Open Source License
private static SAXReader resolveSAXReader() { SAXReader saxReader = new SAXReader(); saxReader.setMergeAdjacentText(true); saxReader.setValidation(true); return saxReader; }
From source file:org.hibernate.util.xml.MappingReader.java
License:Open Source License
public XmlDocument readMappingDocument(EntityResolver entityResolver, InputSource source, Origin origin) { // IMPL NOTE : this is the legacy logic as pulled from the old AnnotationConfiguration code Exception failure;//from w w w . j ava 2 s. co m ErrorLogger errorHandler = new ErrorLogger(); SAXReader saxReader = new SAXReader(); saxReader.setEntityResolver(entityResolver); saxReader.setErrorHandler(errorHandler); saxReader.setMergeAdjacentText(true); saxReader.setValidation(true); Document document = null; try { // first try with orm 2.0 xsd validation setValidationFor(saxReader, "orm_2_0.xsd"); document = saxReader.read(source); if (errorHandler.getError() != null) { throw errorHandler.getError(); } return new XmlDocumentImpl(document, origin.getType(), origin.getName()); } catch (Exception orm2Problem) { log.debug("Problem parsing XML using orm 2 xsd : {}", orm2Problem.getMessage()); failure = orm2Problem; errorHandler.reset(); if (document != null) { // next try with orm 1.0 xsd validation try { setValidationFor(saxReader, "orm_1_0.xsd"); document = saxReader.read(new StringReader(document.asXML())); if (errorHandler.getError() != null) { throw errorHandler.getError(); } return new XmlDocumentImpl(document, origin.getType(), origin.getName()); } catch (Exception orm1Problem) { log.debug("Problem parsing XML using orm 1 xsd : {}", orm1Problem.getMessage()); } } } throw new InvalidMappingException("Unable to read XML", origin.getType(), origin.getName(), failure); }
From source file:org.jboss.mx.metadata.XMLMetaData.java
License:Open Source License
/** * Constructs the Model MBean metadata. This implementation reads the * document type definition from the beginning of the XML file and picks * a corresponding XML builder based on the schema name. In case no * document type is defined the latest schema builder for this JBossMX * release is used. <p>//from w w w .j a va 2 s. c o m * * The SAX parser implementation is selected by default based on JAXP * configuration. If you want to use JAXP to select the parser, you can * set the system property <tt>"javax.xml.parsers.SAXParserFactory"</tt>. * For example, to use Xerces you might define: <br><pre> * * java -Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl ... * * </pre> * * In case you can't or don't want to use JAXP to configure the SAX parser * implementation you can override the SAX parser implementation by setting * an MBean descriptor field {@link XMBeanConstants#SAX_PARSER} to the * parser class string value. * * @return initialized MBean info * @throws NotCompliantMBeanException if there were errors building the * MBean info from the given XML file. */ public MBeanInfo build() throws NotCompliantMBeanException { try { int version = NO_VERSION; if (versionString == null) { // by default, let JAXP pick the SAX parser SAXReader reader = new SAXReader(); // check if user wants to override the SAX parser property if (properties.get(SAX_PARSER) != null) { try { reader.setXMLReaderClassName(getStringProperty(SAX_PARSER)); } catch (SAXException e) { //Should log and ignore, I guess } // end of try-catch } // by default we validate reader.setValidation(true); // the user can override the validation by setting the VALIDATE property try { boolean validate = getBooleanProperty(XML_VALIDATION); reader.setValidation(validate); } catch (IllegalPropertyException e) { // FIXME: log the exception (warning) // fall through, use the default value } //supply it with our dtd locally. reader.setEntityResolver(new JBossEntityResolver()); // get the element and start parsing... Document doc = reader.read(url); element = doc.getRootElement(); DocumentType type = doc.getDocType(); version = validateVersionString(type.getPublicID()); if (version == NO_VERSION) { version = validateVersionString(type.getSystemID()); } // end of if () } else { version = validateVersionString(versionString); } // end of else if (element == null) { throw new IllegalStateException("No element supplied with explict version!"); } // These are the known schemas for us. Pick the correct one based on // schema or default to the latest.docURL.endsWith(JBOSSMX_XMBEAN_DTD_1_0) if (version == JBOSS_XMBEAN_1_0 || version == JBOSS_XMBEAN_1_1 || version == JBOSS_XMBEAN_1_2) { // jboss_xmbean_1_0.dtd is the only implemented useful xmbean return new JBossXMBean10(mmbClassName, resourceClassName, element, properties).build(); } else { throw new NotCompliantMBeanException("Unknown xmbean type " + versionString); } // end of else } catch (DocumentException e) { throw new JBossNotCompliantMBeanException("Error parsing the XML file, from XMLMetaData: ", e); } }
From source file:org.jboss.seam.wiki.util.XmlDeploymentHandler.java
License:LGPL
public Map<String, Element> getDescriptorsAsXmlElements() { // Lazy access to streams if (elements == null) { elements = new HashMap<String, Element>(); for (FileDescriptor fileDescriptor : getResources()) { try { SAXReader saxReader = new SAXReader(); saxReader.setMergeAdjacentText(true); if (isSchemaValidating()) { saxReader.setEntityResolver(new DTDEntityResolver()); saxReader.setValidation(true); saxReader.setFeature("http://apache.org/xml/features/validation/schema", true); }/*w ww .ja va2s. co m*/ elements.put(fileDescriptor.getName(), saxReader.read(fileDescriptor.getUrl().openStream()).getRootElement()); } catch (DocumentException dex) { Throwable nested = dex.getNestedException(); if (nested != null) { if (nested instanceof FileNotFoundException) { throw new RuntimeException("Can't find schema/DTD reference for file: " + fileDescriptor.getName() + "': " + nested.getMessage(), dex); } else if (nested instanceof UnknownHostException) { throw new RuntimeException("Cannot connect to host from schema/DTD reference: " + nested.getMessage() + " - check that your schema/DTD reference is current", dex); } } throw new RuntimeException("Could not parse XML file: " + fileDescriptor.getName(), dex); } catch (Exception ex) { throw new RuntimeException("Could not parse XML file: " + fileDescriptor.getName(), ex); } } } return elements; }
From source file:org.jivesoftware.sparkimpl.plugin.emoticons.EmoticonManager.java
License:Open Source License
/** * Loads an emoticon set.//from w ww . j a va 2 s. co m * * @param packName the name of the pack. */ public void addEmoticonPack(String packName) { File emoticonSet = new File(EMOTICON_DIRECTORY, packName + ".adiumemoticonset"); if (!emoticonSet.exists()) { emoticonSet = new File(EMOTICON_DIRECTORY, packName + ".AdiumEmoticonset"); } if (!emoticonSet.exists()) { emoticonSet = new File(EMOTICON_DIRECTORY, "Default.adiumemoticonset"); packName = "Default"; setActivePack("Default"); } List<Emoticon> emoticons = new ArrayList<>(); final File plist = new File(emoticonSet, "Emoticons.plist"); // Create SaxReader and set to non-validating parser. // This will allow for non-http problems to not break spark :) final SAXReader saxParser = new SAXReader(); saxParser.setValidation(false); try { saxParser.setFeature("http://xml.org/sax/features/validation", false); saxParser.setFeature("http://xml.org/sax/features/namespaces", false); saxParser.setFeature("http://apache.org/xml/features/validation/schema", false); saxParser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", false); saxParser.setFeature("http://apache.org/xml/features/validation/dynamic", false); saxParser.setFeature("http://apache.org/xml/features/allow-java-encodings", true); saxParser.setFeature("http://apache.org/xml/features/continue-after-fatal-error", true); saxParser.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); saxParser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } catch (SAXException e) { e.printStackTrace(); } Document emoticonFile; try { emoticonFile = saxParser.read(plist); } catch (DocumentException e) { Log.error(e); return; } Node root = emoticonFile.selectSingleNode("/plist/dict/dict"); List<?> keyList = root.selectNodes("key"); List<?> dictonaryList = root.selectNodes("dict"); Iterator<?> keys = keyList.iterator(); Iterator<?> dicts = dictonaryList.iterator(); while (keys.hasNext()) { Element keyEntry = (Element) keys.next(); String key = keyEntry.getText(); Element dict = (Element) dicts.next(); String name = dict.selectSingleNode("string").getText(); // Load equivilants final List<String> equivs = new ArrayList<>(); final List<?> equivilants = dict.selectNodes("array/string"); equivilants.stream().map((equivilant1) -> (Element) equivilant1) .map((equivilant) -> equivilant.getText()).forEach((equivilantString) -> { equivs.add(equivilantString); }); final Emoticon emoticon = new Emoticon(key, name, equivs, emoticonSet); emoticons.add(emoticon); } emoticonMap.put(packName, emoticons); }
From source file:org.metaeffekt.dita.maven.glossary.GlossaryMapCreator.java
License:Apache License
protected Document readDocument(File file) { SAXReader reader = new SAXReader(); reader.setValidation(false); reader.setIncludeInternalDTDDeclarations(false); reader.setIncludeExternalDTDDeclarations(false); reader.setIgnoreComments(true);// ww w . j a v a2 s . co m reader.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String arg0, String arg1) throws SAXException, IOException { return new InputSource(new InputStream() { @Override public int read() throws IOException { return -1; } }); } }); try { return reader.read(file); } catch (DocumentException e) { return null; } }
From source file:org.mule.module.xml.util.XMLUtils.java
License:Open Source License
/** * Converts an object of unknown type to an org.dom4j.Document if possible. * @return null if object cannot be converted * @throws DocumentException if an error occurs while parsing *///w ww. j a va2s. c om public static org.dom4j.Document toDocument(Object obj, String externalSchemaLocation, MuleContext muleContext) throws Exception { org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader(); if (externalSchemaLocation != null) { reader.setValidation(true); reader.setFeature(APACHE_XML_FEATURES_VALIDATION_SCHEMA, true); reader.setFeature(APACHE_XML_FEATURES_VALIDATION_SCHEMA_FULL_CHECKING, true); InputStream xsdAsStream = IOUtils.getResourceAsStream(externalSchemaLocation, XMLUtils.class); if (xsdAsStream == null) { throw new IllegalArgumentException("Couldn't find schema at " + externalSchemaLocation); } // Set schema language property (must be done before the schemaSource // is set) reader.setProperty(JAXP_PROPERTIES_SCHEMA_LANGUAGE, JAXP_PROPERTIES_SCHEMA_LANGUAGE_VALUE); // Need this one to map schemaLocation to a physical location reader.setProperty(JAXP_PROPERTIES_SCHEMA_SOURCE, xsdAsStream); } if (obj instanceof org.dom4j.Document) { return (org.dom4j.Document) obj; } else if (obj instanceof org.w3c.dom.Document) { org.dom4j.io.DOMReader domReader = new org.dom4j.io.DOMReader(); return domReader.read((org.w3c.dom.Document) obj); } else if (obj instanceof org.xml.sax.InputSource) { return reader.read((org.xml.sax.InputSource) obj); } else if (obj instanceof javax.xml.transform.Source || obj instanceof javax.xml.stream.XMLStreamReader) { // TODO Find a more direct way to do this XmlToDomDocument tr = new XmlToDomDocument(); tr.setMuleContext(muleContext); tr.setReturnDataType(DataTypeFactory.create(org.dom4j.Document.class)); return (org.dom4j.Document) tr.transform(obj); } else if (obj instanceof java.io.InputStream) { return reader.read((java.io.InputStream) obj); } else if (obj instanceof String) { return reader.read(new StringReader((String) obj)); } else if (obj instanceof byte[]) { // TODO Handle encoding/charset somehow return reader.read(new StringReader(new String((byte[]) obj))); } else if (obj instanceof File) { return reader.read((File) obj); } else { return null; } }