Example usage for org.dom4j.io SAXReader setEntityResolver

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

Introduction

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

Prototype

public void setEntityResolver(EntityResolver entityResolver) 

Source Link

Document

Sets the entity resolver used to resolve entities.

Usage

From source file:net.sf.eclipsecs.core.config.meta.MetadataFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
private static void parseMetadata(InputStream metadataStream, ResourceBundle metadataBundle)
        throws DocumentException, CheckstylePluginException {

    SAXReader reader = new SAXReader();
    reader.setEntityResolver(new XMLUtil.InternalDtdEntityResolver(PUBLIC2INTERNAL_DTD_MAP));
    Document document = reader.read(metadataStream);

    List<Element> groupElements = document.getRootElement().elements(XMLTags.RULE_GROUP_METADATA_TAG);

    for (Element groupEl : groupElements) {

        String groupName = groupEl.attributeValue(XMLTags.NAME_TAG).trim();
        groupName = localize(groupName, metadataBundle);

        RuleGroupMetadata group = getRuleGroupMetadata(groupName);

        if (group == null) {

            boolean hidden = Boolean.valueOf(groupEl.attributeValue(XMLTags.HIDDEN_TAG)).booleanValue();
            int priority = 0;
            try {
                priority = Integer.parseInt(groupEl.attributeValue(XMLTags.PRIORITY_TAG));
            } catch (Exception e) {
                CheckstyleLog.log(e);/*www .  j av  a 2 s  . c o  m*/
                priority = Integer.MAX_VALUE;
            }

            group = new RuleGroupMetadata(groupName, hidden, priority);
            sRuleGroupMetadata.put(groupName, group);
        }

        // process the modules
        processModules(groupEl, group, metadataBundle);
    }
}

From source file:net.unicon.toro.installer.tools.MergeConfiguration.java

License:Open Source License

private void mergeXmlChanges(Element el, File path) throws Exception {
    System.out.println("Merging xml changes to " + path.getAbsolutePath());
    Utils.instance().backupFile(path, true);

    SAXReader reader = new SAXReader();
    reader.setEntityResolver(new DTDResolver(target));
    Document doc = reader.read(new URL("file:" + path.getAbsolutePath()));
    Element source = doc.getRootElement();

    //saveXml(doc, new File("/tmp/before."+path.getName()));

    String xmlEncoding = doc.getXMLEncoding();

    if (log.isDebugEnabled()) {
        StringBuffer sb = new StringBuffer();
        sb.append('\n').append("children root: ").append(source.getPath()).append('\n');
        outputElement(source, sb, 1);//  w  ww.j a v a 2  s. c  o  m
        log.debug(sb.toString());
    }

    processElementValueReplacements(el, source);
    processNodeReplacements(el, source);
    //processAddToNodes(el, source);
    processNodeAddOrReplace(el, source, path);
    processNodeRemovals(el, source);

    //saveXml(doc, new File("/tmp/after."+path.getName()));
    saveXml(doc, path);
}

From source file:org.cgiar.ccafs.ap.util.ClientRepository.java

License:Open Source License

protected static Element getDocumentRoot(InputStreamReader stream) {
    try {//  w  w w . jav  a2  s  .  c om
        SAXReader saxReader = new SAXReader();
        saxReader.setEntityResolver(new DTDEntityResolver());
        saxReader.setMergeAdjacentText(true);
        return saxReader.read(stream).getRootElement();
    } catch (DocumentException de) {
        throw new RuntimeException(de);
    }
}

From source file:org.cgiar.ccafs.marlo.utils.ClientRepository.java

License:Open Source License

protected static Element getDocumentRoot(InputStreamReader stream) {
    try {//from www  .  j a  va  2 s .com
        SAXReader saxReader = new SAXReader();
        saxReader.setEntityResolver(new org.hibernate.internal.util.xml.DTDEntityResolver());
        saxReader.setMergeAdjacentText(true);
        return saxReader.read(stream).getRootElement();
    } catch (DocumentException de) {
        throw new RuntimeException(de);
    }
}

From source file:org.codehaus.aspectwerkz.definition.XmlParser.java

License:Open Source License

/**
 * Sets the entity resolver which is created based on the DTD from in the root dir of the AspectWerkz distribution.
 *
 * @param reader the reader to set the resolver in
 *///from   w ww .j a  v a 2s. c  om
private static void setEntityResolver(final SAXReader reader) {
    EntityResolver resolver = new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) {
            if (publicId.equals(DTD_PUBLIC_ID) || publicId.equals(DTD_PUBLIC_ID_ALIAS)) {
                InputStream in = DTD_STREAM;
                if (in == null) {
                    System.err.println("AspectWerkz - WARN - could not open DTD");
                    return new InputSource();
                } else {
                    return new InputSource(in);
                }
            } else {
                System.err.println("AspectWerkz - WARN - deprecated DTD " + publicId
                        + " - consider upgrading to " + DTD_PUBLIC_ID);
                return new InputSource(); // avoid null pointer exception
            }
        }
    };
    reader.setEntityResolver(resolver);
}

From source file:org.codehaus.mojo.hibernate2.MappingsAggregatorMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    try {//from   ww w  .java2  s.  c o  m
        String version = null;

        if (getBasedir() == null) {
            throw new MojoExecutionException("Required configuration missing: basedir");
        }

        File files[] = getIncludeFiles();
        if (files == null || files.length <= 0) {
            return;
        }
        File f = new File(getOutputFile());
        if (!f.exists()) {
            f.getParentFile().mkdirs();
            f.createNewFile();
        }
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileWriter(f), format);
        writer.setEntityResolver(new HibernateEntityResolver());
        //writer.setResolveEntityRefs(false);
        Document finalDoc = DocumentHelper.createDocument();
        Element rootHM = null;
        for (int i = 0; i < files.length; i++) {
            print("Parsing: " + files[i].getAbsolutePath());
            SAXReader reader = new SAXReader(false);
            reader.setEntityResolver(new HibernateEntityResolver());
            //reader.setIncludeExternalDTDDeclarations(false);
            //reader.setIncludeExternalDTDDeclarations(false);
            Document current = reader.read(files[i]);
            String currentVersion = getVersion(current);
            if (version == null) {
                version = currentVersion;
                finalDoc.setProcessingInstructions(current.processingInstructions());
                finalDoc.setDocType(current.getDocType());
                rootHM = finalDoc.addElement("hibernate-mapping");
            } else if (!version.equals(currentVersion)) {
                //LOG.warn("Mapping in " + files[i].getName() + " is not of the same mapping version as " + files[0].getName() + " mapping, so merge is impossible. Skipping");
                continue;
            }
            for (Iterator iter = current.selectSingleNode("hibernate-mapping").selectNodes("class")
                    .iterator(); iter.hasNext(); rootHM.add((Element) ((Element) iter.next()).clone())) {
            }
        }

        print("Writing aggregate file: " + f.getAbsolutePath());
        writer.write(finalDoc);
        writer.close();
    } catch (Exception ex) {
        throw new MojoExecutionException("Error in executing MappingsAgrregatorBean", ex);
    }
}

From source file:org.danann.cernunnos.xml.ReadDocumentPhrase.java

License:Apache License

/**
 * Loads a DOM4J document from the specified contact and location and returns the root Element
 *//*w w  w  .  j a va  2 s . c o  m*/
protected Element loadDocument(String ctx_str, String loc_str, EntityResolver resolver) {
    try {
        final URL ctx = new URL(ctx_str);
        final URL doc = new URL(ctx, loc_str);

        // Use an EntityResolver if provided...
        final SAXReader rdr = new SAXReader();
        if (resolver != null) {
            rdr.setEntityResolver(resolver);
        }

        // Read by passing a URL -- don't manage the URLConnection yourself...
        final Element rslt = rdr.read(doc).getRootElement();
        rslt.normalize();
        return rslt;

    } catch (Throwable t) {
        String msg = "Unable to read the specified document:" + "\n\tCONTEXT=" + ctx_str + "\n\tLOCATION="
                + loc_str;
        throw new RuntimeException(msg, t);
    }
}

From source file:org.danann.cernunnos.xml.XslTransformTask.java

License:Apache License

public void perform(TaskRequest req, TaskResponse res) {
    final String contextLocation = (String) context.evaluate(req, res);
    final String stylesheetLocation = (String) stylesheet.evaluate(req, res);
    final Tuple<String, String> transformerKey = new Tuple<String, String>(contextLocation, stylesheetLocation);
    final Templates templates = this.transformerCache.getCachedObject(req, res, transformerKey,
            this.transformerFactory);

    Element srcElement = null;//from ww w  .ja v a  2 s .  c o m
    Node nodeReagentEvaluated = node != null ? (Node) node.evaluate(req, res) : null;
    if (nodeReagentEvaluated != null) {
        // Reading from the NODE reagent is preferred...
        srcElement = (Element) nodeReagentEvaluated;
    } else {
        // But read from LOCATION if NODE isn't set...
        final String locationStr = (String) location.evaluate(req, res);
        final URL loc;
        try {
            final URL ctx;
            try {
                ctx = new URL(contextLocation);
            } catch (MalformedURLException mue) {
                throw new RuntimeException("Failed to parse context '" + contextLocation + "' into URL", mue);
            }

            loc = new URL(ctx, locationStr);
        } catch (MalformedURLException mue) {
            throw new RuntimeException("Failed to parse location '" + locationStr + "' with context '"
                    + contextLocation + "' into URL", mue);
        }

        // Use an EntityResolver if provided...
        SAXReader rdr = new SAXReader();
        EntityResolver resolver = (EntityResolver) entityResolver.evaluate(req, res);
        if (resolver != null) {
            rdr.setEntityResolver(resolver);
        }

        final Document document;
        try {
            document = rdr.read(loc);
        } catch (DocumentException de) {
            throw new RuntimeException("Failed to read XML Document for XSLT from " + loc.toExternalForm(), de);
        }
        srcElement = document.getRootElement();
    }

    DocumentFactory dfac = new DocumentFactory();
    Document ddoc = dfac.createDocument((Element) srcElement.clone());
    DOMWriter dwriter = new DOMWriter();

    DocumentResult rslt = new DocumentResult();

    final Transformer trans;
    try {
        trans = templates.newTransformer();
    } catch (TransformerConfigurationException tce) {
        throw new RuntimeException("Failed to retrieve Transformer for XSLT", tce);
    }

    try {
        trans.transform(new DOMSource(dwriter.write(ddoc)), rslt);
    } catch (TransformerException te) {
        throw new RuntimeException("Failed to perform XSL transformation", te);
    } catch (DocumentException de) {
        throw new RuntimeException("Failed to translate JDOM Document to W3C Document", de);
    }

    final Element rootElement = rslt.getDocument().getRootElement();

    if (to_file != null) {
        File f = new File((String) to_file.evaluate(req, res));
        if (f.getParentFile() != null) {
            // Make sure the necessary directories are in place...
            f.getParentFile().mkdirs();
        }

        final XMLWriter writer;
        try {
            writer = new XMLWriter(new FileOutputStream(f), new OutputFormat("  ", true));
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("Failed to create XML writer", uee);
        } catch (FileNotFoundException fnfe) {
            throw new RuntimeException("Could not create file for XML output: " + f, fnfe);
        }

        try {
            writer.write(rootElement);
        } catch (IOException ioe) {
            throw new RuntimeException("Failed to write transformed XML document to: " + f, ioe);
        }
    } else {
        // default behavior...
        res.setAttribute(Attributes.NODE, rootElement);
    }

    super.performSubtasks(req, res);

}

From source file:org.directwebremoting.convert.DOM4JConverter.java

License:Apache License

public Object convertInbound(Class<?> paramType, InboundVariable data) throws ConversionException {
    if (data.isNull()) {
        return null;
    }//from   ww  w. jav a  2s . c  o  m

    String value = data.urlDecode();

    try {
        SAXReader xmlReader = new SAXReader();

        // Protect us from hackers, see:
        // https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Processing
        xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
        xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        try {
            xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        } catch (Exception ex) {
            // XML parser doesn't have this setting, never mind
        }

        // Extra protection from external entity hacking
        xmlReader.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                return new InputSource(); // no lookup, just return empty
            }
        });

        Document doc = xmlReader.read(new StringReader(value));

        if (paramType == Document.class) {
            return doc;
        } else if (paramType == Element.class) {
            return doc.getRootElement();
        }

        throw new ConversionException(paramType);
    } catch (ConversionException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ConversionException(paramType, ex);
    }
}

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

License:Open Source License

@Override
public AnnotationConfiguration addInputStream(InputStream xmlInputStream) throws MappingException {
    try {/*from  ww  w.  jav a  2s  .co 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);
        }
    }
}