Example usage for org.dom4j.io SAXReader setProperty

List of usage examples for org.dom4j.io SAXReader setProperty

Introduction

In this page you can find the example usage for org.dom4j.io SAXReader setProperty.

Prototype

public void setProperty(String name, Object value) throws SAXException 

Source Link

Document

Allows a SAX property to be set on the underlying SAX parser.

Usage

From source file:ca.coder2000.recipes.RecipeFile.java

License:Mozilla Public License

/**
 * Creates a new instance of RecipeFile//from  w w  w  .  j a v  a 2  s  .  c o  m
 * @param file the file we want this class to load and manage.
 */
public RecipeFile(File file) {
    SAXReader reader = new SAXReader(true);
    reader.setValidation(true);

    try {
        reader.setFeature("http://xml.org/sax/features/validation", true);
        reader.setFeature("http://apache.org/xml/features/validation/schema", true);
        reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
                "schemas/recipe.xsd");
        reader.setErrorHandler(new RecipeErrorHandler());
        doc = reader.read(file);
        checkVersion();
    } catch (DocumentException de) {
        JOptionPane.showMessageDialog(null, de.getMessage(),
                java.util.ResourceBundle.getBundle("recipe").getString("Error_Parsing_Recipe"),
                JOptionPane.ERROR_MESSAGE);
    } catch (SAXException sxe) {
        JOptionPane.showMessageDialog(null, sxe.getMessage(),
                java.util.ResourceBundle.getBundle("recipe").getString("Error_Parsing_Recipe"),
                JOptionPane.ERROR_MESSAGE);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.getMessage(),
                java.util.ResourceBundle.getBundle("recipe").getString("Error_Parsing_Recipe"),
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.cladonia.xml.XMLUtilities.java

License:Open Source License

public static synchronized void validate(ErrorHandler handler, BufferedReader isReader, String systemId,
        String encoding, int type, String grammarLocation) throws IOException, SAXParseException {
    if (DEBUG)/*from ww  w  . j  av  a 2  s . c om*/
        System.out.println("XMLUtilities.validate( " + isReader + ", " + systemId + ", " + encoding + ", "
                + type + ", " + grammarLocation + ")");

    if (type == XMLGrammar.TYPE_RNG || type == XMLGrammar.TYPE_RNC || type == XMLGrammar.TYPE_NRL) {
        ValidationDriver driver = null;
        String encode = encoding;

        if (type == XMLGrammar.TYPE_RNC) {
            driver = new ValidationDriver(makePropertyMap(null, handler, CHECK_ID_IDREF, false),
                    CompactSchemaReader.getInstance());
        } else if (type == XMLGrammar.TYPE_NRL) {
            driver = new ValidationDriver(makePropertyMap(null, handler, CHECK_ID_IDREF, true),
                    new AutoSchemaReader());
        } else {
            driver = new ValidationDriver(makePropertyMap(null, handler, CHECK_ID_IDREF, false));
        }

        try {
            isReader.mark(1024);
            encode = getXMLDeclaration(isReader).getEncoding();
            //         } catch ( NotXMLException e) {
            //            encode = encoding;
            //            e.printStackTrace();
        } finally {
            isReader.reset();
        }

        InputSource source = new InputSource(isReader);
        source.setEncoding(encode);

        try {
            URL url = null;

            if (systemId != null) {
                try {
                    url = new URL(systemId);
                } catch (MalformedURLException e) {
                    // does not matter really, the base url is only null ...
                    url = null;
                }
            }

            URL schemaURL = null;

            if (url != null) {
                schemaURL = new URL(url, grammarLocation);
            } else {
                schemaURL = new URL(grammarLocation);
            }

            driver.loadSchema(new InputSource(schemaURL.toString()));
            driver.validate(source);
        } catch (SAXException x) {
            x.printStackTrace();
            if (x instanceof SAXParseException) {
                SAXParseException spe = (SAXParseException) x;
                Exception ex = spe.getException();

                if (ex instanceof IOException) {
                    throw (IOException) ex;
                } else {
                    throw (SAXParseException) x;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }

    } else { // type == XMLGrammar.TYPE_DTD || type == XMLGrammar.TYPE_XSD

        try {
            SAXReader reader = createReader(true, false);
            reader.setErrorHandler(handler);
            String encode = encoding;

            try {
                isReader.mark(1024);
                encode = getXMLDeclaration(isReader).getEncoding();
                //            } catch ( NotXMLException e) {
                //               encode = encoding;
                //               e.printStackTrace();
            } finally {
                isReader.reset();
            }

            XMLReader xmlReader = createReader(isReader, encode);

            try {
                if (type == XMLGrammar.TYPE_DTD) {
                    reader.setFeature("http://apache.org/xml/features/validation/schema", false);

                    reader.setEntityResolver(new DummyEntityResolver(grammarLocation));
                } else { // type == XMLGrammar.TYPE_XSD
                    URL url = null;

                    if (systemId != null) {
                        try {
                            url = new URL(systemId);
                        } catch (MalformedURLException e) {
                            // does not matter really, the base url is only null ...
                            url = null;
                        }
                    }

                    URL schemaURL = null;

                    if (url != null) {
                        schemaURL = new URL(url, grammarLocation);
                    } else {
                        schemaURL = new URL(grammarLocation);
                    }

                    reader.setFeature("http://apache.org/xml/features/validation/schema", true);

                    reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                            "http://www.w3.org/2001/XMLSchema");
                    reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
                            new InputSource(schemaURL.toString()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //         try {
            //            System.out.println( "http://apache.org/xml/features/validation/schema = "+reader.getXMLReader().getFeature( "http://apache.org/xml/features/validation/schema"));
            //         } catch ( Exception e) {
            //            e.printStackTrace();
            //         }

            reader.read(xmlReader, systemId);

        } catch (DocumentException e) {
            Exception x = (Exception) e.getNestedException();
            //            x.printStackTrace();

            if (x instanceof SAXParseException) {
                SAXParseException spe = (SAXParseException) x;
                Exception ex = spe.getException();

                if (ex instanceof IOException) {
                    throw (IOException) ex;
                } else {
                    throw (SAXParseException) x;
                }
            } else if (x instanceof IOException) {
                throw (IOException) x;
            }
        }
    }
}

From source file:com.thoughtworks.cruise.utils.configfile.CruiseConfigDom.java

License:Apache License

static Document parse(String xml) throws DocumentException, SAXException, URISyntaxException {
    URL resource = schemaResource();
    SAXReader builder = new SAXReader();
    builder.setFeature("http://apache.org/xml/features/validation/schema", true);
    builder.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
            resource.toURI().toString());
    builder.setValidation(true);//from  w  ww . j  ava  2 s .  c  om
    Document dom = null;
    try {
        dom = builder.read(new StringReader(xml));
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("XML invalid. " + xml, e);
    }
    return dom;
}

From source file:cz.mzk.editor.server.fedora.utils.DocumentValidator.java

License:Open Source License

/**
 * Validation according to schema in url
 * /*from   w  ww  .j a v a2  s.c o m*/
 * @param documentFile
 * @param schemaUrl
 * @return
 */
public static boolean isValid(File documentFile, String schemaUrl) {
    try {
        SAXReader reader = new SAXReader(true);
        // set the validation feature to true to report validation errors
        reader.setFeature("http://xml.org/sax/features/validation", true);
        // set the validation/schema feature to true to report validation errors against a schema
        reader.setFeature("http://apache.org/xml/features/validation/schema", true);
        // set the validation/schema-full-checking feature to true to enable full schema, grammar-constraint checking
        reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
        //reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", schemaUrl);
        reader.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", schemaUrl);
        readDocument(reader, documentFile);
        return true;
    } catch (DocumentException ex) {
        logger.log(Level.SEVERE, ex.getMessage());
        return false;
    } catch (SAXException ex) {
        logger.log(Level.SEVERE, null, ex);
        return false;
    }
}

From source file:cz.mzk.editor.server.fedora.utils.DocumentValidator.java

License:Open Source License

/**
 * Validation according to schema in url
 * /*from   w  ww  .j  a  v  a2s  . c  o m*/
 * @param documentFile
 * @param schemaUrl
 * @return
 */
public static boolean isValid(File documentFile, File schemaFile) {
    try {
        SAXReader reader = new SAXReader(true);
        reader.setFeature("http://apache.org/xml/features/validation/schema", true);
        // set the validation feature to true to report validation errors
        reader.setFeature("http://xml.org/sax/features/validation", true);
        // set the validation/schema feature to true to report validation errors against a schema
        reader.setFeature("http://apache.org/xml/features/validation/schema", true);
        // set the validation/schema-full-checking feature to true to enable full schema, grammar-constraint checking
        reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
        reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
                schemaFile.getAbsolutePath());
        readDocument(reader, documentFile);
        return true;
    } catch (DocumentException ex) {
        logger.log(Level.SEVERE, ex.getMessage());
        return false;
    } catch (SAXException ex) {
        logger.log(Level.SEVERE, null, ex);
        return false;
    }
}

From source file:de.ailis.wlandsuite.utils.XmlUtils.java

License:Open Source License

/**
 * Reads a document from the specified input stream. The XML reader is fully
 * configured to validate the wlandsuite namespace.
 * // w w  w. j a v  a  2 s  . c om
 * @param stream
 *            The input stream
 * @return The validated document
 */

public static Document readDocument(InputStream stream) {
    SAXReader reader;

    reader = new SAXReader(true);
    try {
        reader.setFeature("http://xml.org/sax/features/validation", true);
        reader.setFeature("http://apache.org/xml/features/validation/schema", true);
        reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
        reader.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
                "http://ailis.de/wlandsuite classpath://de/ailis/wlandsuite/resource/wlandsuite.xsd");
        reader.setEntityResolver(ClasspathEntityResolver.getInstance());
        return reader.read(stream);
    } catch (SAXException e) {
        throw new XmlException("Unable to configure XML reader: " + e.toString(), e);
    } catch (DocumentException e) {
        throw new XmlException("Unable to read XML document: " + e.toString(), e);
    }
}

From source file:es.caib.seycon.ng.servei.PuntEntradaServiceImpl.java

protected String handleValidaXMLPUE(PuntEntrada puntEntrada) throws Exception {
    String contingut = puntEntrada.getXmlPUE();

    if (!"".equals(contingut)) { //$NON-NLS-1$

        try {//from   w  ww.  j  a  v  a 2  s  .  c o m
            // Validem el document
            // new
            // es.caib.seycon.mazinger.compiler.Compile().parse(contingut);
            org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader(true);
            // set the validation feature to true to report validation
            // errors
            reader.setFeature("http://xml.org/sax/features/validation", true); //$NON-NLS-1$

            // set the validation/schema feature to true to report
            // validation errors
            // against a schema
            reader.setFeature("http://apache.org/xml/features/validation/schema", true); //$NON-NLS-1$
            // set the validation/schema-full-checking feature to true to
            // enable
            // full schema, grammar-constraint checking
            reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", //$NON-NLS-1$
                    true);
            // set the schema
            reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", //$NON-NLS-1$
                    "/es/caib/seycon/mazinger/Mazinger.xsd"); //$NON-NLS-1$
            // set the entity resolver (to load the schema with
            // getResourceAsStream)
            reader.getXMLReader().setEntityResolver(new SchemaLoader());
            reader.setEntityResolver(new SchemaLoader());

            Document doc = reader.read(new ByteArrayInputStream(contingut.getBytes("UTF-8"))); //$NON-NLS-1$

        } catch (Exception ex) {
            return ex.getMessage(); // Retornem l'excepci com error de
                                    // Validaci
        }
    }
    return ""; //$NON-NLS-1$
}

From source file:net.sf.jguard.core.util.XMLUtils.java

License:Open Source License

/**
 * read the xml data storage file for users and associated principals.
 *
 * @param xml    file location to read//from   w  w  w.  j  a  v  a  2 s.  c om
 * @param schema
 * @return xml content
 */
public static Document read(URL xml, InputSource schema) {

    SAXReader reader = new SAXReader(true);
    Document document;

    try {
        //activate schema validation
        reader.setFeature(XML_VALIDATION, true);
        reader.setFeature(APACHE_VALIDATION, true);
        reader.setProperty(JAXP_SCHEMA_LANGUAGE, JAXP_XML_SCHEMA_LANGUAGE);
        reader.setProperty(JAXP_SCHEMA_SOURCE, schema);

    } catch (SAXException ex) {
        logger.error("read(String) : " + ex.getMessage(), ex);
        throw new IllegalArgumentException(ex.getMessage(), ex);
    }

    try {
        document = reader.read(xml);
    } catch (DocumentException e1) {
        logger.error("read(String) : " + e1, e1);
        throw new IllegalArgumentException(e1.getMessage(), e1);
    }

    if (document == null) {
        logger.warn("we create a default document");
        document = DocumentHelper.createDocument();
    }
    return document;
}

From source file:org.dentaku.gentaku.tools.cgen.plugin.GenGenPlugin.java

License:Apache License

private Document validate(Document xsdDoc, Reader fileReader)
        throws IOException, SAXException, DocumentException {
    File temp = File.createTempFile("schema", ".xsd");
    temp.deleteOnExit();//from   w w w  . ja  va2 s. c  o  m
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write(xsdDoc.asXML());
    out.flush();
    out.close();

    SAXReader saxReader = new SAXReader(true);
    saxReader.setFeature("http://apache.org/xml/features/validation/schema", true);
    URL schemaPath = temp.toURL();
    saxReader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
            schemaPath.toString());
    return saxReader.read(fileReader);
}

From source file:org.dom4j.samples.validate.XercesDemo.java

License:Open Source License

protected Document parse(String uri) throws Exception {
    SAXReader reader = new SAXReader();

    reader.setValidation(true);/*from  ww w  .ja  va  2 s.  c  om*/

    // specify the schema to use
    reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
            "personal.xsd");

    // add an error handler which turns any errors into XML
    XMLErrorHandler errorHandler = new XMLErrorHandler();
    reader.setErrorHandler(errorHandler);

    // now lets parse the document
    Document document = reader.read(uri);

    // now lets output the errors as XML
    XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
    writer.write(errorHandler.getErrors());

    return document;
}