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:com.marklogic.client.example.handle.DOM4JHandle.java

License:Apache License

protected SAXReader makeReader() {
    SAXReader reader = new SAXReader();
    reader.setValidation(false);
    return reader;
}

From source file:com.marklogic.client.example.handle.DOM4JHandleExample.java

License:Apache License

public static void runShortcut(ExampleProperties props) throws IOException, DocumentException {
    String filename = "flipper.xml";

    // register the handle from the extra library
    DatabaseClientFactory.getHandleRegistry().register(DOM4JHandle.newFactory());

    // create the client
    DatabaseClient client = DatabaseClientFactory.newClient(props.host, props.port, props.writerUser,
            props.writerPassword, props.authType);

    // create a manager for documents of any format
    XMLDocumentManager docMgr = client.newXMLDocumentManager();

    // read the example file
    InputStream docStream = Util.openStream("data" + File.separator + filename);
    if (docStream == null)
        throw new IOException("Could not read document example");

    // create an identifier for the document
    String docId = "/example/" + filename;

    // parse the example file with dom4j
    SAXReader reader = new SAXReader();
    reader.setValidation(false);
    Document writeDocument = reader.read(new InputStreamReader(docStream, "UTF-8"));

    // write the document
    docMgr.writeAs(docId, writeDocument);

    // ... at some other time ...

    // read the document content
    Document readDocument = docMgr.readAs(docId, Document.class);

    String rootName = readDocument.getRootElement().getName();

    // delete the document
    docMgr.delete(docId);/*from   w ww .j  a v  a 2  s. c om*/

    System.out.println("(Shortcut) Wrote and read /example/" + filename + " content with the <" + rootName
            + "/> root element using dom4j");

    // release the client
    client.release();
}

From source file:com.panet.imeta.trans.steps.getxmldata.GetXMLData.java

License:Open Source License

protected boolean setDocument(String StringXML, FileObject file, boolean IsInXMLField, boolean readurl)
        throws KettleException {

    try {// w  ww.j av  a2s  .com
        SAXReader reader = new SAXReader();
        data.stopPruning = false;

        // Validate XML against specified schema?
        if (meta.isValidating()) {
            reader.setValidation(true);
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
        }

        // Ignore comments?
        if (meta.isIgnoreComments())
            reader.setIgnoreComments(true);

        if (data.prunePath != null) {
            // when pruning is on: reader.read() below will wait until all
            // is processed in the handler
            if (log.isDetailed())
                logDetailed(Messages.getString("GetXMLData.Log.StreamingMode.Activated"));
            reader.addHandler(data.prunePath, new ElementHandler() {
                public void onStart(ElementPath path) {
                    // do nothing here...
                }

                public void onEnd(ElementPath path) {
                    if (isStopped()) {
                        // when a large file is processed and it should be
                        // stopped it is still reading the hole thing
                        // the only solution I see is to prune / detach the
                        // document and this will lead into a
                        // NPE or other errors depending on the parsing
                        // location - this will be treated in the catch part
                        // below
                        // any better idea is welcome
                        if (log.isBasic())
                            logBasic(Messages.getString("GetXMLData.Log.StreamingMode.Stopped"));
                        data.stopPruning = true;
                        path.getCurrent().getDocument().detach(); // trick
                        // to
                        // stop
                        // reader
                        return;
                    }

                    // process a ROW element
                    if (log.isDebug())
                        logDebug(Messages.getString("GetXMLData.Log.StreamingMode.StartProcessing"));
                    Element row = path.getCurrent();
                    try {
                        processStreaming(row.getDocument());
                    } catch (Exception e) {
                        // catch the KettleException or others and forward
                        // to caller, e.g. when applyXPath() has a problem
                        throw new RuntimeException(e);
                    }
                    // prune the tree
                    row.detach();
                    if (log.isDebug())
                        logDebug(Messages.getString("GetXMLData.Log.StreamingMode.EndProcessing"));
                }
            });
        }

        if (IsInXMLField) {
            // read string to parse
            data.document = reader.read(new StringReader(StringXML));
        } else if (readurl) {
            // read url as source
            data.document = reader.read(new URL(StringXML));
        } else {
            // get encoding. By default UTF-8
            String encoding = "UTF-8";
            if (!Const.isEmpty(meta.getEncoding()))
                encoding = meta.getEncoding();
            data.document = reader.read(KettleVFS.getInputStream(file), encoding);
        }

        if (meta.isNamespaceAware())
            prepareNSMap(data.document.getRootElement());
    } catch (Exception e) {
        if (data.stopPruning) {
            // ignore error when pruning
            return false;
        } else {
            throw new KettleException(e);
        }
    }
    return true;
}

From source file:com.petpet.c3po.utils.XMLUtils.java

License:Apache License

public static boolean validate(File f) {
    try {//from  w  w  w . j  a v a  2 s .c  om
        SAXParser parser = factory.newSAXParser();
        parser.setProperty(Constants.XML_SCHEMA_PROPERTY, Constants.XML_SCHEMA_LANGUAGE);

        SimpleErrorHandler errorHandler = new SimpleErrorHandler();

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

        reader.setErrorHandler(errorHandler);
        reader.read(f);

        return errorHandler.isValid();

    } catch (ParserConfigurationException e) {
        LOG.error("ParserConfigurationException: {}", e.getMessage());
    } catch (SAXException e) {
        LOG.error("SAXException: {}", e.getMessage());
    } catch (DocumentException e) {
        LOG.error("DocumentException: {}", e.getMessage());
    } catch (NullPointerException e) {
        LOG.warn("Factory is not initialized. Did you call init()");
    }

    return false;
}

From source file:com.poka.util.XmlSax.java

public Document load(String f, boolean isHiberConfig) {
    Document document = null;/*from   w  w  w.  ja va  2  s .  c o m*/
    try {
        SAXReader saxReader = new SAXReader();
        //saxReader.setValidation(false);  
        //saxReader.setFeature("http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd", false);              
        //document = saxReader.read(f); //?XML,document
        if (isHiberConfig) {
            saxReader.setEntityResolver(new EntityResolver() {
                @Override
                public InputSource resolveEntity(String publicId, String systemId)
                        throws SAXException, IOException {
                    // TODO Auto-generated method stub
                    InputSource is = new InputSource(this.getClass().getClassLoader()
                            .getResourceAsStream("com/poka/images/hibernate-configuration-3.0.dtd"));
                    is.setPublicId(publicId);
                    is.setSystemId(systemId);
                    return is;
                }
            });
            saxReader.setValidation(true);
        }
        File tFile = new File(f);
        if (!tFile.exists() && !isHiberConfig) {
            document = DocumentHelper.createDocument();
            //    document.addDocType("hibernate-configuration", "-//Hibernate/Hibernate Configuration DTD 3.0//EN", "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd");

            // 
            Element root = DocumentHelper.createElement("root");
            document.setRootElement(root);
        } else {
            document = saxReader.read(tFile);
        }

    } catch (DocumentException ex) {
    }
    return document;
}

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);
    Document dom = null;/*from  ww  w.j a  v a2s.co m*/
    try {
        dom = builder.read(new StringReader(xml));
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("XML invalid. " + xml, e);
    }
    return dom;
}

From source file:com.thoughtworks.cruise.utils.DomUtil.java

License:Apache License

public static Document getDomFor(String xml) {
    registerNamespace();//from   ww  w  .  j  a  va 2 s. c o  m
    SAXReader builder = new SAXReader();
    builder.setValidation(false);
    Document dom = null;
    try {
        dom = builder.read(new StringReader(xml));
    } catch (Exception e) {
        throw new RuntimeException("XML invalid. " + xml, e);
    }
    return dom;
}

From source file:com.thoughtworks.studios.shine.cruise.stage.details.XMLArtifactImporter.java

License:Apache License

public void importFile(Graph graph, URIReference parentJob, InputStream in) {
    try {/*from  www  .j av  a2s .  c  om*/
        SAXReader saxReader = new SAXReader();
        if (systemEnvironment.get(SystemEnvironment.SHOULD_VALIDATE_XML_AGAINST_DTD)) {
            saxReader.setValidation(true);
        } else {
            saxReader.setEntityResolver(getCustomEntityResolver());
        }
        Document doc = saxReader.read(in);
        importXML(graph, parentJob, doc);
    } catch (DocumentException e) {
        LOGGER.warn("Invalid xml provided.", e);
    }
}

From source file:cz.fi.muni.xkremser.editor.server.handler.FindAltoOcrFilesHandler.java

License:Open Source License

/**
 * Scan directory structure.//from  ww  w .j a  v a2  s .  com
 * 
 * @param path
 *        the path
 * @return the list
 */
private List<String> findAltoAndTxt(String path, final String typeToFind) {

    List<String> fileNames = new ArrayList<String>();
    File pathFile = new File(path + File.separator + typeToFind + File.separator);

    FileFilter filter = new FileFilter() {

        @Override
        public boolean accept(File file) {
            if (typeToFind.equals(ALTO)) {
                //                    return file.isFile() && file.getName().toLowerCase().contains("alto")
                //&& 
                return file.isFile() && file.getName().toLowerCase().endsWith(".xml");
            } else {
                return file.isFile() && file.getName().toLowerCase().endsWith(".txt");
            }
        }
    };

    File[] files = pathFile.listFiles(filter);
    for (int i = 0; (files != null && i < files.length); i++) {

        if (typeToFind.equals(ALTO)) {
            SAXReader reader = new SAXReader();
            try {
                reader.setValidation(true);
                reader.read(files[i]);
            } catch (DocumentException e) {
            }
        }

        fileNames.add(path + File.separator + typeToFind + File.separator + files[i].getName());
    }
    return fileNames;
}

From source file:de.fct.companian.analyze.mvn.helper.PomHelper.java

License:Apache License

public PomHelper(File pomFile) throws DocumentException {
    this.pomFile = pomFile;
    this.document = null;

    SAXReader reader = new SAXReader();
    reader.setEncoding("ISO-8859-1");
    reader.setIgnoreComments(true);//w ww  .j  a va 2  s . c o  m
    reader.setValidation(false);

    try {
        this.document = reader.read(this.pomFile);
    } catch (Throwable t) {
        t.printStackTrace();
    }

    if (this.document != null) {
        Element projectElement = this.document.getRootElement();
        Namespace defaultNS = projectElement.getNamespace();
        if (logger.isDebugEnabled()) {
            logger.debug("extractPomInfo() using default namespace " + defaultNS.getURI());
        }

        Map<String, String> nsMap = new HashMap<String, String>();
        nsMap.put("mvn", defaultNS.getURI());

        this.nsContext = new SimpleNamespaceContext(nsMap);
    } else {
        throw new DocumentException("Could not create document.");
    }
}