Example usage for org.dom4j.io SAXReader setValidation

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

Introduction

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

Prototype

public void setValidation(boolean validation) 

Source Link

Document

Sets the validation mode.

Usage

From source file:org.ballproject.knime.base.schemas.SchemaValidator.java

License:Open Source License

public boolean validates(InputStream xmlstream) {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    SimpleErrorHandler errorHandler = new SimpleErrorHandler();

    try {//from w  w w  .  ja  va  2  s .  c om
        factory.setSchema(schemaFactory.newSchema(getSchemaSources()));

        SAXParser parser = factory.newSAXParser();

        SAXReader reader = new SAXReader(parser.getXMLReader());
        reader.setValidation(false);

        reader.setErrorHandler(errorHandler);

        reader.read(xmlstream);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (DocumentException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }

    if (!errorHandler.isValid()) {
        error_report = errorHandler.getErrorReport();
        return false;
    }

    return true;
}

From source file:org.beangle.orm.hibernate.internal.OverrideConfiguration.java

License:Open Source License

/**
 * Just disable xml file validation.//  w  ww .  ja  v a  2s .c o  m
 */
@Override
protected Configuration doConfigure(InputStream stream, String resourceName) throws HibernateException {
    try {
        ErrorLogger errorLogger = new ErrorLogger(resourceName);
        SAXReader reader = xmlHelper.createSAXReader(errorLogger, getEntityResolver());
        reader.setValidation(false);
        Document document = reader.read(new InputSource(stream));
        if (errorLogger.hasErrors()) {
            throw new MappingException("invalid configuration", errorLogger.getErrors().get(0));
        }
        doConfigure(document);
    } catch (DocumentException e) {
        throw new HibernateException("Could not parse configuration: " + resourceName, e);
    } finally {
        try {
            stream.close();
        } catch (IOException ioe) {
            logger.error("Could not close input stream for {}", resourceName);
        }
    }
    return this;
}

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);

    // 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;
}

From source file:org.footware.server.gpx.GPXImport.java

License:Apache License

private List<GPXTrack> parseXML(File file) {
    LinkedList<GPXTrack> tracks = new LinkedList<GPXTrack>();
    try {//  www. j av  a 2s .  c  o m
        long startTime = System.currentTimeMillis();
        logger.info("Start parsing @" + startTime);

        // Determine GPX Version
        SAXReader xmlReader = new SAXReader();
        Document document = xmlReader.read(file);
        String version = document.getRootElement().attributeValue("version");

        File xsd = null;

        if (version.equals("1.1")) {
            logger.info("Detected gpx version " + version + "  +" + (System.currentTimeMillis() - startTime));
            xsd = new File("gpx_1_1.xsd");
            GPX_NAMESPACE_URI = GPX_NAMESPACE_URI_1_1;
        } else if (version.equals("1.0")) {
            logger.info("Detected gpx version '" + version + "'  +" + (System.currentTimeMillis() - startTime));
            xsd = new File("gpx_1_0.xsd");
            GPX_NAMESPACE_URI = GPX_NAMESPACE_URI_1_0;
        } else {
            logger.info("No supported version detected: " + version + "  +"
                    + (System.currentTimeMillis() - startTime));
            // As default we try version 1.1
            xsd = new File("gpx_1_1.xsd");
            GPX_NAMESPACE_URI = GPX_NAMESPACE_URI_1_1;
        }

        // Parse GPX
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

        factory.setSchema(schemaFactory.newSchema(xsd));

        SAXParser parser = factory.newSAXParser();
        SAXReader reader = new SAXReader(parser.getXMLReader());
        reader.setValidation(true);
        reader.setErrorHandler(new SimpleErrorHandler());

        document = reader.read(file);
        logger.info("End parsing +" + (System.currentTimeMillis() - startTime));

        // Define namespaces
        HashMap<String, String> namespacesMap = new HashMap<String, String>();
        namespacesMap.put(GPX_NS, GPX_NAMESPACE_URI);

        // Find tracks
        logger.info("Search tracks +" + (System.currentTimeMillis() - startTime));
        XPath xpathTrk = DocumentHelper.createXPath("//" + GPX_NS + ":trk");
        xpathTrk.setNamespaceURIs(namespacesMap);

        List<Element> xmlTracks = xpathTrk.selectNodes(document);
        logger.info("Found " + xmlTracks.size() + " tracks +" + (System.currentTimeMillis() - startTime));

        GPXTrack track;

        // for (Element xmlTrack : xmlTracks) {
        // Iterate about all tracks of the gpx file
        for (int currentTrackNummer = 1; currentTrackNummer <= xmlTracks.size(); currentTrackNummer++) {
            logger.info("Start track " + currentTrackNummer + " +" + (System.currentTimeMillis() - startTime));

            track = new GPXTrack();

            // Find track segments
            XPath xpathTrkseg = DocumentHelper
                    .createXPath("//" + GPX_NS + ":trk[" + currentTrackNummer + "]/" + GPX_NS + ":trkseg");
            xpathTrkseg.setNamespaceURIs(namespacesMap);

            List<Element> xmlTrackSegs = xpathTrkseg.selectNodes(document);
            logger.info("Found " + xmlTrackSegs.size() + " segments for track " + currentTrackNummer + " +"
                    + (System.currentTimeMillis() - startTime));

            // List<Element> xmlTrackSegs =
            // xmlTrack.selectNodes("//trkseg");

            GPXTrackSegment trackSegment;

            // for (Element xmlTrackSeq : xmlTrackSegs) {
            // Iterate above all segments of a track
            for (int currentTrackSegmentNummer = 1; currentTrackSegmentNummer <= xmlTrackSegs
                    .size(); currentTrackSegmentNummer++) {
                trackSegment = new GPXTrackSegment();

                // Find track points
                XPath xpathTrkPt = DocumentHelper.createXPath("//" + GPX_NS + ":trk[" + currentTrackNummer
                        + "]/" + GPX_NS + ":trkseg[" + currentTrackSegmentNummer + "]/" + GPX_NS + ":trkpt");
                xpathTrkPt.setNamespaceURIs(namespacesMap);
                List<Element> xmlTrackPts = xpathTrkPt.selectNodes(document);

                logger.info("Found " + xmlTrackPts.size() + " points for segment " + currentTrackSegmentNummer
                        + " for track " + currentTrackNummer + " +" + (System.currentTimeMillis() - startTime));

                GPXTrackPoint trackPoint;
                BigDecimal latitude;
                BigDecimal longitude;
                BigDecimal elevation;
                DateTime time;

                // Iterate above all points of a segment of a track
                for (Element xmlTrackPt : xmlTrackPts) {

                    latitude = new BigDecimal(xmlTrackPt.attributeValue(LATITUDE));
                    longitude = new BigDecimal(xmlTrackPt.attributeValue(LONGITUDE));
                    elevation = new BigDecimal(xmlTrackPt.element(ELEVATION).getText());
                    time = ISODateTimeFormat.dateTimeNoMillis()
                            .parseDateTime(xmlTrackPt.element(TIME).getText());

                    trackPoint = new GPXTrackPoint(latitude, longitude, elevation, time);
                    trackSegment.addPoint(trackPoint);
                }
                track.addTrackSegment(trackSegment);
            }
            tracks.add(track);

        }
        logger.info("Done parsing +" + (System.currentTimeMillis() - startTime));

    } catch (ParserConfigurationException e) {
        logger.error("ParserConfigurationException", e);
        e.printStackTrace();
    } catch (SAXException e) {
        logger.error("SAXException", e);
        e.printStackTrace();
    } catch (DocumentException e) {
        logger.error("DocumentException", e);
        e.printStackTrace();
    }

    return tracks;
}

From source file:org.guzz.builder.GuzzConfigFileBuilder.java

License:Apache License

protected Document loadFullConfigFile(Resource resource, String encoding)
        throws DocumentException, IOException, SAXException {
    SAXReader reader = null;
    Document document = null;/*from  w w  w.j  a  va  2 s  . com*/

    reader = new SAXReader();
    reader.setValidation(false);
    // http://apache.org/xml/features/nonvalidating/load-external-dtd"  
    reader.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);

    InputStreamReader isr = new InputStreamReader(resource.getInputStream(), encoding);

    document = reader.read(isr);
    final Element root = document.getRootElement();

    List list = document.selectNodes("//import");

    for (int i = 0; i < list.size(); i++) {
        Element n = (Element) list.get(i);

        String file = n.attribute("resource").getValue();

        //load included xml file.
        FileResource fr = new FileResource(resource, file);
        Document includedDoc = null;

        try {
            includedDoc = loadFullConfigFile(fr, encoding);
        } finally {
            CloseUtil.close(fr);
        }

        List content = root.content();
        int indexOfPos = content.indexOf(n);

        content.remove(indexOfPos);

        //appends included docs
        Element ie = includedDoc.getRootElement();
        List ie_children = ie.content();

        for (int k = ie_children.size() - 1; k >= 0; k--) {
            content.add(indexOfPos, ie_children.get(k));
        }
    }

    return document;
}

From source file:org.guzz.builder.HbmXMLBuilder.java

License:Apache License

public static POJOBasedObjectMapping parseHbmStream(final GuzzContextImpl gf, String dbGroupName,
        BusinessValidChecker checker, String businessName, Class overridedDomainClass, Class interpreterClass,
        InputStream is) throws DocumentException, IOException, SAXException, ClassNotFoundException {

    SAXReader reader = null;
    Document document = null;/*from   w  w  w.j  av  a  2 s . c om*/

    reader = new SAXReader();
    reader.setValidation(false);
    // http://apache.org/xml/features/nonvalidating/load-external-dtd"  
    reader.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);

    document = reader.read(is);
    final Element root = document.getRootElement();

    if (StringUtil.isEmpty(dbGroupName)) {
        dbGroupName = getDomainClassDbGroup(root);
    }
    if (StringUtil.isEmpty(dbGroupName)) {
        dbGroupName = "default";
    }

    final DBGroup dbGroup = gf.getDBGroup(dbGroupName);

    final SimpleTable st = new SimpleTable(dbGroup.getDialect());
    final POJOBasedObjectMapping map = new POJOBasedObjectMapping(gf, dbGroup, st);

    if (overridedDomainClass == null) {//hbm?className
        String m_class = HbmXMLBuilder.getDomainClassName(root);

        overridedDomainClass = ClassUtil.getClass(m_class);
    }

    if (checker != null && !checker.shouldParse(overridedDomainClass)) {
        return null;
    }

    if (StringUtil.isEmpty(businessName)) {
        businessName = getDomainClassBusinessName(root);
    }

    final Business business = gf.instanceNewGhost(businessName, dbGroup.getGroupName(), interpreterClass,
            overridedDomainClass);
    if (business.getInterpret() == null) {
        throw new GuzzException("cann't create new instance of business: " + business.getName());
    }

    business.setTable(st);
    business.setMapping(map);

    //?business??
    if (business.getName() != null) {
        st.setBusinessName(business.getName());
    } else {
        st.setBusinessName(business.getDomainClass().getName());
    }

    //properties defined.
    final LinkedList props = new LinkedList();

    Visitor visitor = new VisitorSupport() {

        private String packageName;

        public void visit(Element e) {

            //package
            if ("hibernate-mapping".equalsIgnoreCase(e.getName())
                    || "guzz-mapping".equalsIgnoreCase(e.getName())) {
                this.packageName = e.attributeValue("package");

            } else if ("class".equalsIgnoreCase(e.getName())) {
                String className = e.attributeValue("name");
                String tableName = e.attributeValue("table");
                String shadow = e.attributeValue("shadow");
                boolean dynamicUpdate = StringUtil.toBoolean(e.attributeValue("dynamic-update"), false);

                if (StringUtil.notEmpty(this.packageName)) {
                    className = this.packageName + "." + className;
                }

                //business????hbml.xml?class namebusinessclass
                Class cls = business.getDomainClass();
                if (cls == null) { //?business?domainClassName
                    cls = ClassUtil.getClass(className);
                }

                Assert.assertNotNull(cls, "invalid class name");
                Assert.assertNotEmpty(tableName, "invalid table name");

                JavaBeanWrapper configBeanWrapper = BeanWrapper.createPOJOWrapper(cls);
                business.setDomainClass(cls);
                business.setConfiguredBeanWrapper(configBeanWrapper);

                map.setBusiness(business);

                //shadow?tableName?
                if (StringUtil.notEmpty(shadow)) {
                    ShadowTableView sv = (ShadowTableView) BeanCreator.newBeanInstance(shadow);
                    sv.setConfiguredTableName(tableName);

                    //CustomTableViewShadowTableView
                    if (sv instanceof CustomTableView) {
                        CustomTableView ctv = (CustomTableView) sv;
                        ctv.setConfiguredObjectMapping(map);

                        st.setCustomTableView(ctv);
                    }

                    st.setShadowTableView(sv);
                    gf.registerShadowTableView(sv);
                }

                //TODO: ???
                st.setTableName(tableName);
                st.setDynamicUpdate(dynamicUpdate);

            } else if ("id".equalsIgnoreCase(e.getName())) {
                String name = e.attributeValue("name");
                String type = e.attributeValue("type");
                String column = null;

                Element columnE = (Element) e.selectSingleNode("column");
                if (columnE != null) {
                    column = columnE.attributeValue("name");
                }

                if (StringUtil.isEmpty(column)) {
                    column = e.attributeValue("column");
                }

                if (StringUtil.isEmpty(column)) {
                    column = name;
                }

                props.addLast(name);

                TableColumn col = ObjectMappingUtil.createTableColumn(gf, map, name, column, type, null);

                st.addPKColumn(col);

            } else if ("version".equalsIgnoreCase(e.getName())) {
                //see: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html 5.1.9. Version (optional)
                //TODO: annotation?version?

                String name = e.attributeValue("name");
                String type = e.attributeValue("type");
                boolean insertIt = StringUtil.toBoolean(e.attributeValue("insert"), true);
                String column = null;

                Element columnE = (Element) e.selectSingleNode("column");
                if (columnE != null) {
                    column = columnE.attributeValue("name");
                }

                if (StringUtil.isEmpty(column)) {
                    column = e.attributeValue("column");
                }

                if (StringUtil.isEmpty(column)) {
                    column = name;
                }

                props.addLast(name);

                TableColumn col = ObjectMappingUtil.createTableColumn(gf, map, name, column, type, null);
                col.setAllowInsert(insertIt);

                st.addVersionColumn(col);

            } else if ("property".equalsIgnoreCase(e.getName())) {
                String name = e.attributeValue("name");
                String type = e.attributeValue("type");
                String nullValue = e.attributeValue("null");
                String lazy = e.attributeValue("lazy");
                String loader = e.attributeValue("loader");

                boolean insertIt = StringUtil.toBoolean(e.attributeValue("insert"), true);
                boolean updateIt = StringUtil.toBoolean(e.attributeValue("update"), true);

                String column = null;

                Element columnE = (Element) e.selectSingleNode("column");
                if (columnE != null) {
                    column = columnE.attributeValue("name");
                }

                if (StringUtil.isEmpty(column)) {
                    column = e.attributeValue("column");
                }

                if (StringUtil.isEmpty(column)) {
                    column = name;
                }

                props.addLast(name);

                TableColumn col = ObjectMappingUtil.createTableColumn(gf, map, name, column, type, loader);
                col.setNullValue(nullValue);
                col.setAllowInsert(insertIt);
                col.setAllowUpdate(updateIt);
                col.setLazy("true".equalsIgnoreCase(lazy));

                st.addColumn(col);
            }
        }
    };

    root.accept(visitor);

    //?generator
    //?generator?
    List generator = root.selectNodes("//class/id/generator");
    if (generator.size() != 1) {
        throw new GuzzException("id generator is not found for business: " + business);
    }

    Element ge = (Element) generator.get(0);

    String m_clsName = ge.attributeValue("class");

    if ("native".equalsIgnoreCase(m_clsName)) { //nativegeneratordialect?
        m_clsName = dbGroup.getDialect().getNativeIDGenerator();
    }

    String realClassName = (String) IdentifierGeneratorFactory.getGeneratorClass(m_clsName);
    if (realClassName == null) {
        realClassName = m_clsName;
    }

    IdentifierGenerator ig = (IdentifierGenerator) BeanCreator.newBeanInstance(realClassName);

    //?generator??      
    List m_params = ge.selectNodes("param");
    Properties p = new Properties();
    for (int i = 0; i < m_params.size(); i++) {
        Element mp = (Element) m_params.get(i);
        p.put(mp.attributeValue("name"), mp.getTextTrim());
    }

    if (ig instanceof Configurable) {
        ((Configurable) ig).configure(dbGroup.getDialect(), map, p);
    }

    //register callback for GuzzContext's full starting.
    if (ig instanceof GuzzContextAware) {
        gf.registerContextStartedAware((GuzzContextAware) ig);
    }

    st.setIdentifierGenerator(ig);

    return map;
}

From source file:org.guzz.service.core.impl.FileDynamicSQLServiceImpl.java

License:Apache License

protected CompiledSQL loadCSFromStream(String id, InputStream is) throws Exception {
    SAXReader reader = null;
    Document document = null;/* w  w w .ja  v a 2  s  .  c  o m*/

    reader = new SAXReader();
    reader.setValidation(false);

    //http://apache.org/xml/features/nonvalidating/load-external-dtd"  
    reader.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);

    InputStreamReader isr = new InputStreamReader(is, encoding);

    document = reader.read(isr);
    final Element root = document.getRootElement();

    CompiledSQL cs = loadCompiledSQL(id, root);

    return cs;
}

From source file:org.hibernate.cfg.AnnotationConfiguration.java

License:Open Source License

@Override
public AnnotationConfiguration addInputStream(InputStream xmlInputStream) throws MappingException {
    try {/* w ww  .ja v  a 2  s  .c o m*/
        /*
         * try and parse the document:
         *  - try and validate the document with orm_2_0.xsd
          * - if it fails because of the version attribute mismatch, try and validate the document with orm_1_0.xsd
         */
        List<SAXParseException> errors = new ArrayList<SAXParseException>();
        SAXReader saxReader = new SAXReader();
        saxReader.setEntityResolver(getEntityResolver());
        saxReader.setErrorHandler(new ErrorLogger(errors));
        saxReader.setMergeAdjacentText(true);
        saxReader.setValidation(true);

        setValidationFor(saxReader, "orm_2_0.xsd");

        org.dom4j.Document doc = null;
        try {
            doc = saxReader.read(new InputSource(xmlInputStream));
        } catch (DocumentException e) {
            //the document is syntactically incorrect

            //DOM4J sometimes wraps the SAXParseException wo much interest
            final Throwable throwable = e.getCause();
            if (e.getCause() == null || !(throwable instanceof SAXParseException)) {
                throw new MappingException("Could not parse JPA mapping document", e);
            }
            errors.add((SAXParseException) throwable);
        }

        boolean isV1Schema = false;
        if (errors.size() != 0) {
            SAXParseException exception = errors.get(0);
            final String errorMessage = exception.getMessage();
            //does the error look like a schema mismatch?
            isV1Schema = doc != null && errorMessage.contains("1.0") && errorMessage.contains("2.0")
                    && errorMessage.contains("version");
        }
        if (isV1Schema) {
            //reparse with v1
            errors.clear();
            setValidationFor(saxReader, "orm_1_0.xsd");
            try {
                //too bad we have to reparse to validate again :(
                saxReader.read(new StringReader(doc.asXML()));
            } catch (DocumentException e) {
                //oops asXML fails even if the core doc parses initially
                throw new AssertionFailure("Error in DOM4J leads to a bug in Hibernate", e);
            }

        }
        if (errors.size() != 0) {
            //report errors in exception
            StringBuilder errorMessage = new StringBuilder();
            for (SAXParseException error : errors) {
                errorMessage.append("Error parsing XML (line").append(error.getLineNumber())
                        .append(" : column ").append(error.getColumnNumber()).append("): ")
                        .append(error.getMessage()).append("\n");
            }
            throw new MappingException("Invalid ORM mapping file.\n" + errorMessage.toString());
        }
        add(doc);
        return this;
    } finally {
        try {
            xmlInputStream.close();
        } catch (IOException ioe) {
            log.warn("Could not close input stream", ioe);
        }
    }
}

From source file:org.hibernate.cfg.AnnotationConfiguration.java

License:Open Source License

private void setValidationFor(SAXReader saxReader, String xsd) {
    try {//from w  w  w. j  a  va2  s.c  o  m
        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 " + xsd);
    } catch (SAXException e) {
        saxReader.setValidation(false);
    }
}

From source file:org.hibernate.eclipse.console.utils.OpenMappingUtils.java

License:Open Source License

/**
 * Trying to find hibernate console config mapping file,
 * which is corresponding to provided element.
 *   /*from  w  w w.j a va  2 s.c om*/
 * @param configXMLFile
 * @param entityResolver
 * @return
 */
public static Document getDocument(java.io.File configXMLFile, EntityResolver entityResolver) {
    Document doc = null;
    if (configXMLFile == null) {
        return doc;
    }
    InputStream stream = null;
    try {
        stream = new FileInputStream(configXMLFile);
    } catch (FileNotFoundException e) {
        HibernateConsolePlugin.getDefault().logErrorMessage("Configuration file not found", e); //$NON-NLS-1$
    }
    try {
        List<SAXParseException> errors = new ArrayList<SAXParseException>();
        XMLHelper helper = new XMLHelper();
        SAXReader saxReader = helper.createSAXReader(configXMLFile.getPath(), errors, entityResolver);
        saxReader.setValidation(false);
        doc = saxReader.read(new InputSource(stream));
        if (errors.size() != 0) {
            HibernateConsolePlugin.getDefault().logErrorMessage("invalid configuration", //$NON-NLS-1$
                    (Throwable[]) errors.toArray(new Throwable[0]));
        }
    } catch (DocumentException e) {
        HibernateConsolePlugin.getDefault().logErrorMessage("Could not parse configuration", e); //$NON-NLS-1$
    } finally {
        try {
            if (stream != null)
                stream.close();
        } catch (IOException ioe) {
            HibernateConsolePlugin.getDefault().logErrorMessage("could not close input stream for", ioe); //$NON-NLS-1$
        }
    }
    return doc;
}