Example usage for org.dom4j.io SAXReader SAXReader

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

Introduction

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

Prototype

public SAXReader(String xmlReaderClassName) throws SAXException 

Source Link

Usage

From source file:com.jmstoolkit.pipeline.Pipeline.java

License:Open Source License

/**
 * Determine what action the received message contains, validate that and
 * perform it. Validation is done using the JDK's Xerces implementation
 * against a DTD. The DTD should be in the user.dir location!
 *
 * @param xml The XML from the <code>Message</code>
 * @return A dom4j <code>Document</code> for further processing.
 * @throws DocumentException If the XML can not be parsed and validated.
 * @throws PipelineException If the XML contains an invalid action.
 *//*from w w w .  j a  v  a 2 s.  com*/
private Document getAction(final String xml) throws DocumentException, PipelineException {
    System.out.println("############################################");
    System.out.println("Action message received:");
    System.out.println(xml);
    System.out.println("############################################");

    // Below will all bomb with DocumentException
    // enable validation
    final SAXReader saxReader = new SAXReader(isValidated());
    // Validation is done using the JDK's bundled xerces implementation
    // against a DTD. The DTD should be in the user.dir location!
    final Document doc = saxReader.read(new StringReader(xml));
    final String name = trim(doc.valueOf("//plugin/name"));
    final String action = trim(doc.valueOf("//plugin/action"));
    final String type = trim(doc.valueOf("//plugin/type"));
    final String xversion = trim(doc.valueOf("//plugin/version"));

    LOG.log(Level.INFO, "Action message received: {0}, for service name: {1} and service type: {2}",
            new Object[] { action, name, type });

    if (!VERSION.equalsIgnoreCase(xversion)) {
        throw new PipelineException(
                "Action version: " + xversion + " does not match Pipeline version: " + VERSION);
    }

    if ("new".equalsIgnoreCase(action)) {
        if (getPlugins().containsKey(name)) {
            throw new PipelineException(
                    "Can't create new Plugin name: " + name + ". Plugin with same name already exists.");
        }
    } else if ("update".equalsIgnoreCase(action)) {
        if (!getPlugins().containsKey(name)) {
            throw new PipelineException("Can't update Plugin: " + name + ". No Plugin with that name found.");
        }
    } else if ("update".equalsIgnoreCase(action)) {
        if (!getPlugins().containsKey(name)) {
            throw new PipelineException("Can't stop Plugin: " + name + ". No Plugin with that name found.");
        }
    }
    return doc;
}

From source file:com.jmstoolkit.pipeline.plugin.XMLValueTransform.java

License:Open Source License

/**
 * Method to parse and validate the <code>work</code> XML String.
 *
 * @param work The XML to be validated./*from   www  .j a v  a 2  s. c o m*/
 * @return The validated XML.
 * @throws DocumentException When the XML fails to validation.
 * @throws XMLValueTransformException When additional validation fails.
 */
private Document getWork(final String work) throws DocumentException, XMLValueTransformException {
    // validate vs. DTD: enrich.dtd
    final SAXReader saxReader = new SAXReader(true);
    final Document doc = saxReader.read(new StringReader(work));
    // additional validation...
    try {
        Class.forName(trim(doc.valueOf("//enrich/defaultDatabase/driver")));
    } catch (ClassNotFoundException ex) {
        throw new XMLValueTransformException("Default database driver not found in classpath: " + ex);
    }
    return doc;
}

From source file:com.josephalevin.gwtplug.maven.InheritModulesMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {//from  w  w  w . j av a2 s.  c o m
        Set<Artifact> artifacts = getProject().createArtifacts(getArtifactFactory(), null, null);

        ArtifactResolutionResult arr = getArtifactResolver().resolveTransitively(artifacts,
                getProject().getArtifact(), getProject().getRemoteArtifactRepositories(), getLocalRepository(),
                artifactMetadataSource);

        Set<Artifact> dependencies = arr.getArtifacts();

        List<URL> urls = new ArrayList<URL>();

        for (Artifact art : dependencies) {
            URL url = art.getFile().toURI().toURL();
            System.out.println(url);
            urls.add(url);
        }

        List<File> modules = new ArrayList<File>();
        Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(urls)
                .setScanners(new ResourcesScanner(), new GWTModuleScanner(modules)));

        if (reflections == null) {
            throw new IllegalStateException("Failed to execute reflections.");
        }

        List<String> advertiedModules = new ArrayList<String>();
        for (File file : modules) {
            //                System.out.println(file.getName());
            //                System.out.println(file.getRelativePath());

            if (file.getRelativePath().startsWith("com/google/gwt")) {
                //System.out.println(String.format("Skipping Google Module: %s", file.getRelativePath()));
                continue;
            }
            //                System.out.println(String.format("Scanning: %s", file.getRelativePath()));

            try {
                SAXReader sax = new SAXReader(false);

                Document doc = sax.read(file.getInputStream());
                Node node = doc
                        .selectSingleNode("/module/set-configuration-property[@name='gwtplug.advertised']");

                if (node instanceof Element) {
                    Element element = (Element) node;
                    Boolean advertised = false;
                    try {
                        advertised = Boolean.valueOf(element.attributeValue("value"));
                        if (advertised) {
                            String module = file.getRelativePath().replace("/", ".");
                            module = module.replaceAll("\\.gwt\\.xml$", "");
                            advertiedModules.add(module);
                            System.out.println(module);
                        }
                    } catch (Exception e) {
                        advertised = false;
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        System.out.println(createModule);

        java.io.File file = new java.io.File(generateDirectory, createModule.replace(".", "/") + ".gwt.xml");
        file.getParentFile().mkdirs();

        StringBuilder buffer = new StringBuilder();
        buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        buffer.append("\n");
        buffer.append("<module>");
        for (String mod : advertiedModules) {
            buffer.append(String.format("<inherits name=\"%s\"/>", mod));
        }
        buffer.append("</module>");
        buffer.append("\n");
        FileWriter writer = null;
        try {
            writer = new FileWriter(file);
            writer.write(buffer.toString());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    getProject().addCompileSourceRoot(generateDirectory.getAbsolutePath());

}

From source file:com.liferay.maven.plugins.util.SAXReaderUtil.java

License:Open Source License

public static Document read(File file, boolean validate) throws Exception {
    SAXReader saxReader = new SAXReader(validate);

    saxReader.setEntityResolver(_entityResolver);

    return saxReader.read(file);
}

From source file:com.liferay.petra.xml.Dom4jUtil.java

License:Open Source License

public static String toString(String xml, String indent) throws DocumentException, IOException {

    XMLReader xmlReader = null;//  w  w  w . j av  a2s .c o m

    if (SecureXMLFactoryProviderUtil.getSecureXMLFactoryProvider() != null) {

        xmlReader = SecureXMLFactoryProviderUtil.newXMLReader();
    }

    SAXReader saxReader = new SAXReader(xmlReader);

    Document document = saxReader.read(new UnsyncStringReader(xml));

    return toString(document, indent);
}

From source file:com.metaware.guihili.GuihiliParser.java

License:Open Source License

public static Document parse(InputSource input) throws DocumentException {
    SAXReader reader = new SAXReader(XMLReaderFactory.makeReader());
    return reader.read(input);
}

From source file:com.mgmtp.perfload.core.common.xml.Dom4jReader.java

License:Apache License

/**
 * Creates a DOM4J documents from the specified {@link InputSource} and validates it against the
 * given schema./*from  w ww  .  java2s. com*/
 * 
 * @param xmlSource
 *            the source for the XML document
 * @param schemaSource
 *            the source for the schema
 * @param xIncludeAware
 *            specifies whether XIncludes should be supported
 * @return the DOM4J document
 */
public static Document loadDocument(final InputSource xmlSource, final Source schemaSource,
        final boolean xIncludeAware, final String encoding)
        throws ParserConfigurationException, SAXException, DocumentException {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true); // turn on validation
    factory.setNamespaceAware(true);

    //      factory.setFeature("http://apache.org/xml/features/validation/schema", true);
    if (xIncludeAware) {
        // allow XIncludes
        factory.setFeature("http://apache.org/xml/features/xinclude", true);
        factory.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false);
    }

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    factory.setSchema(schemaFactory.newSchema(schemaSource));

    SAXParser parser = factory.newSAXParser();
    SAXReader reader = new SAXReader(parser.getXMLReader());
    reader.setEncoding(encoding);

    return reader.read(xmlSource);
}