Example usage for org.dom4j.io SAXReader setFeature

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

Introduction

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

Prototype

public void setFeature(String name, boolean value) throws SAXException 

Source Link

Document

Sets a SAX feature on the underlying SAX parser.

Usage

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

License:Mozilla Public License

/**
 * Creates a new instance of RecipeFile/*w  w w  .jav  a 2 s  .  co 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.ai.tools.generator.util.SAXReaderFactory.java

License:Open Source License

public static SAXReader getInstance(boolean validate) {
    // Crimson cannot do XSD validation. See the following links:
    ////from w  ww.  j a v  a  2s.  c om
    // http://www.geocities.com/herong_yang/jdk/xsd_validation.html
    // http://www.burnthacker.com/archives/000086.html
    // http://www.theserverside.com/news/thread.tss?thread_id=22525
    SAXReader reader = null;

    try {
        reader = new SAXReader(_SAX_PARSER_IMPL, validate);

        reader.setEntityResolver(new EntityResolver());

        reader.setFeature(_FEATURES_VALIDATION, validate);
        reader.setFeature(_FEATURES_VALIDATION_SCHEMA, validate);
        reader.setFeature(_FEATURES_VALIDATION_SCHEMA_FULL_CHECKING, validate);
        reader.setFeature(_FEATURES_DYNAMIC, validate);
    } catch (Exception e) {
        _log.warn("XSD validation is diasabled because " + e.getMessage());

        reader = new SAXReader(validate);

        reader.setEntityResolver(new EntityResolver());
    }

    return reader;
}

From source file:com.alibaba.stonelab.toolkit.learning.xml.Dom4jParser.java

License:Open Source License

public static void dom4j() throws Exception {
    SAXReader reader = new SAXReader(true);
    reader.setEntityResolver(new EntityResolver());
    reader.setFeature("http://xml.org/sax/features/validation", true);
    reader.setFeature("http://apache.org/xml/features/validation/schema", true);
    Document doc = reader.read(Dom4jParser.class.getResourceAsStream(XML_LOCATION));
    System.out.println(doc);//  w  ww. ja  v  a  2 s.c o m
}

From source file:com.augmentum.common.util.SAXReaderFactory.java

License:Open Source License

public static SAXReader getInstance(boolean validate) {

    // Crimson cannot do XSD validation. See the following links:
    ///*  w  w w  . j ava2 s .  c o m*/
    // http://www.geocities.com/herong_yang/jdk/xsd_validation.html
    // http://www.burnthacker.com/archives/000086.html
    // http://www.theserverside.com/news/thread.tss?thread_id=22525

    SAXReader reader = null;

    try {
        reader = new SAXReader(_SAX_PARSER_IMPL, validate);

        reader.setEntityResolver(new EntityResolver());

        reader.setFeature(_FEATURES_VALIDATION, validate);
        reader.setFeature(_FEATURES_VALIDATION_SCHEMA, validate);
        reader.setFeature(_FEATURES_VALIDATION_SCHEMA_FULL_CHECKING, validate);
        reader.setFeature(_FEATURES_DYNAMIC, validate);
    } catch (Exception e) {
        _log.warn("XSD validation is diasabled because " + e.getMessage());

        reader = new SAXReader(validate);

        reader.setEntityResolver(new EntityResolver());
    }

    return reader;
}

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

License:Open Source License

/**
 * Creates a new SAXReader.//w w w.ja  v a2  s  .  com
 *
 * @param validate when true the reader validates the input.
 *
 * @return the reader.
 */
public static SAXReader createReader(boolean validate, boolean loadExternalDTD) {
    SAXReader reader = new SAXReader(XDocumentFactory.getInstance(), validate);

    reader.setStripWhitespaceText(false);
    reader.setMergeAdjacentText(true);
    //      reader.setMergeAdjacentText( true);

    if (!validate) {
        reader.setIncludeExternalDTDDeclarations(false);
        reader.setIncludeInternalDTDDeclarations(true);

        try {
            if (loadExternalDTD) {
                reader.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", true);
                //               System.out.println( "http://apache.org/xml/features/nonvalidating/load-external-dtd = "+reader.getXMLReader().getFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd"));
                reader.setEntityResolver(getCatalogResolver());
            } else {
                reader.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
                reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        try {
            reader.getXMLReader().setFeature("http://apache.org/xml/features/validation/schema", true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return reader;
}

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

License:Open Source License

/**
 * Creates a new SAXReader.// w w w. ja va2s  .  c  o m
 *
 * @param validate when true the reader validates the input.
 *
 * @return the reader.
 */
public static SAXReader createReader(boolean validate, boolean loadExternalDTD, boolean stripWhiteSpace) {
    SAXReader reader = new SAXReader(XDocumentFactory.getInstance(), validate);

    reader.setStripWhitespaceText(stripWhiteSpace);
    reader.setMergeAdjacentText(true);
    //      reader.setMergeAdjacentText( true);

    if (!validate) {
        reader.setIncludeExternalDTDDeclarations(false);
        reader.setIncludeInternalDTDDeclarations(true);

        try {
            if (loadExternalDTD) {
                reader.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", true);
                //               System.out.println( "http://apache.org/xml/features/nonvalidating/load-external-dtd = "+reader.getXMLReader().getFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd"));
                reader.setEntityResolver(getCatalogResolver());
            } else {
                reader.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
                reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        try {
            reader.getXMLReader().setFeature("http://apache.org/xml/features/validation/schema", true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return reader;
}

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  w ww.j  a  v a 2s. c  o m*/
        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.globalsight.smartbox.bussiness.process.Usecase01PreProcess.java

License:Apache License

private void parseFile(Vector<String> p_sourceFiles) {
    // Parse Bookmark XML File to get fileProfileName and job name.
    Map<String, String> srcMap = new HashMap<String, String>();
    String fileName = null;//from w  w w.  j  ava 2 s .  com
    for (String path : p_sourceFiles) {
        String temp = path.substring(path.lastIndexOf(File.separator) + 1);
        srcMap.put(temp, path);
        if (temp.endsWith(".pdf")) {
            fileName = temp.replace(".pdf", ".xml");
        }
    }
    String path = srcMap.get(fileName);
    try {
        SAXReader saxReader = new SAXReader();
        saxReader.setValidation(false);
        saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        Document doc = saxReader.read(path);
        Element node = (Element) doc.selectSingleNode("//bookmeta/data[@datatype='GSDATA']");
        String gsDataValue = node.attributeValue("value");
        String jobName = gsDataValue.substring(0, gsDataValue.indexOf("~"));
        String customerFPName = gsDataValue.substring(gsDataValue.indexOf("~") + 1);
        FileProfile configFP = getConfigFP(customerFPName);
        if (configFP == null) {
            String message = "Can't find the fileProfileNameMapping for " + customerFPName;
            LogUtil.info(message);
            return;
        }
        fp = gsFPMap.get(configFP.getName());
        if (fp == null) {
            String message = "Can't find the file profile.";
            LogUtil.info(message);
            return;
        }

        // Get Target Locale.
        node = (Element) doc.selectSingleNode("/bookmap");
        String lang = node.attributeValue("lang");
        for (String locale : fp.getTargetLocale()) {
            if (locale.startsWith(lang)) {
                trgLocale = locale;
                break;
            }
        }
        if (trgLocale == null || trgLocale.trim().length() == 0) {
            String message = "Can't find the correct Target Locale in File Profile.";
            LogUtil.info(message);
            return;
        }

        unExtractedFP = gsFPMap.get(configFP.getGsUnExtractedFPName());
        if (unExtractedFP == null) {
            String message = "Can't find the UnExtracted file profile: " + fp.getGsUnExtractedFPName();
            LogUtil.info(message);
            return;
        }

        basicJobName = jobName + "_" + customerFPName + "_" + lang;
    } catch (Exception e) {
        String message = "Read XML error: " + path;
        LogUtil.fail(message, e);
        return;
    }
}

From source file:com.globalsight.smartbox.bussiness.process.Usecase04PreProcess.java

License:Apache License

private void parseFile(Vector<String> p_sourceFiles) {
    String path = null;//from w w w .java2 s . c  om

    try {
        // Parse Bookmark XML File to get fileProfileName and job name.
        path = getBookMapFile(p_sourceFiles);

        SAXReader saxReader = new SAXReader();
        saxReader.setValidation(false);
        saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        Document doc = saxReader.read(path);
        Element node = (Element) doc.selectSingleNode("//bookmeta/data[@datatype='GSDATA']");
        String gsDataValue = node.attributeValue("value");
        String jobName = gsDataValue.substring(0, gsDataValue.indexOf("~"));
        String customerFPName = gsDataValue.substring(gsDataValue.indexOf("~") + 1);
        FileProfile configFP = getConfigFP(customerFPName);
        if (configFP == null) {
            String message = "Can't find the fileProfileNameMapping for " + customerFPName;
            LogUtil.info(message);
            return;
        }
        fp = gsFPMap.get(configFP.getName());
        if (fp == null) {
            String message = "Can't find the file profile.";
            LogUtil.info(message);
            return;
        }

        // Get Target Locale.
        node = (Element) doc.selectSingleNode("/bookmap");
        String lang = node.attributeValue("lang");
        for (String locale : fp.getTargetLocale()) {
            if (locale.startsWith(lang)) {
                trgLocale = locale;
                break;
            }
        }
        if (trgLocale == null || trgLocale.trim().length() == 0) {
            String message = "Can't find the correct Target Locale in File Profile.";
            LogUtil.info(message);
            return;
        }

        unExtractedFP = gsFPMap.get(configFP.getGsUnExtractedFPName());
        if (unExtractedFP == null) {
            String message = "Can't find the UnExtracted file profile: " + fp.getGsUnExtractedFPName();
            LogUtil.info(message);
            return;
        }

        basicJobName = jobName + "_" + customerFPName + "_" + lang;
    } catch (FileNotFoundException e) {
        LogUtil.fail("", e);
        return;
    } catch (Exception e) {
        String message = "Read XML error: " + path;
        LogUtil.fail(message, e);
        return;
    }
}

From source file:com.mor.blogengine.xml.io.XmlDataSourceProvider.java

License:Open Source License

/**
 * Setup validation features for given reader
 *
 * @param pReader given reader//from  w ww .  ja  v  a  2 s  .c  om
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 * @throws java.io.IOException
 * @param schemaSource
 * @return
 */
private SAXReader createReaderAgainstSchema(URL schemaSource) throws SAXException, ParserConfigurationException,
        IOException, MissingPropertyException, IncorrectPropertyValueException {

    trace("Parser created OK");
    SAXReader reader = new SAXReader();
    trace("reader created OK");
    trace("set reader properties");
    // 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);
    trace("returning reader...");
    return reader;

}