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:com.thoughtworks.studios.shine.cruise.stage.details.XMLArtifactImporter.java

License:Apache License

public void importFile(Graph graph, URIReference parentJob, InputStream in) {
    try {/*  w  w w .  ja v a2s  . com*/
        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:com.xpn.xwiki.pdf.impl.PdfExportImpl.java

License:Open Source License

/**
 * Apply a CSS style sheet to an XHTML document and return the document with the resulting style properties inlined
 * in <tt>style</tt> attributes.
 * //from ww w  . jav  a  2 s  . c  om
 * @param html the valid XHTML document to style
 * @param css the style sheet to apply
 * @param context the current request context
 * @return the document with inlined style
 */
private String applyCSS(String html, String css, XWikiContext context) {
    try {
        // Prepare the input
        Reader re = new StringReader(html);
        InputSource source = new InputSource(re);
        SAXReader reader = new SAXReader(XHTMLDocumentFactory.getInstance());
        reader.setEntityResolver(new DefaultEntityResolver());
        XHTMLDocument document = (XHTMLDocument) reader.read(source);

        // Apply the style sheet
        document.setDefaultStyleSheet(new DOM4JCSSStyleSheet(null, null, null));
        document.addStyleSheet(new org.w3c.css.sac.InputSource(new StringReader(css)));
        applyInlineStyle(document.getRootElement());
        OutputFormat outputFormat = new OutputFormat("", false);
        if ((context == null) || (context.getWiki() == null)) {
            outputFormat.setEncoding("UTF-8");
        } else {
            outputFormat.setEncoding(context.getWiki().getEncoding());
        }
        StringWriter out = new StringWriter();
        XMLWriter writer = new XMLWriter(out, outputFormat);
        writer.write(document);
        String result = out.toString();
        // Debug output
        if (LOG.isDebugEnabled()) {
            LOG.debug("HTML with CSS applied: " + result);
        }
        return result;
    } catch (Exception ex) {
        LOG.warn("Failed to apply CSS: " + ex.getMessage(), ex);
        return html;
    }
}

From source file:controllers.ServiceController.java

License:Apache License

private boolean writeBodyToFile(String filename) {
    String xmlFile = filename + ".xml";
    String jsonFile = filename + ".shape.json";
    try {/*www  .  ja va 2  s. c  o  m*/
        BufferedReader br = request.getReader();

        boolean hasJson = false;
        StringBuffer buf = new StringBuffer();
        //Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xmlFile),"utf-8"));

        String inputLine;
        while ((inputLine = br.readLine()) != null) {
            if (inputLine.equals("===boundary===")) {
                /*?shapes*/
                //writer.close();
                //writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(jsonFile),"utf-8"));

                SAXReader reader = new SAXReader();
                reader.setEntityResolver(new DTDEntityResolver());
                Document document = reader.read(new StringReader(buf.toString()));
                OutputFormat format = new OutputFormat(" ", true);
                XMLWriter writer = new XMLWriter(
                        new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xmlFile), "utf-8")),
                        format);
                writer.write(document);
                writer.flush();
                writer.close();

                hasJson = true;
                buf = new StringBuffer();
                continue;
            }

            buf.append(inputLine).append("\n");

            //writer.write(inputLine);
            //writer.write("\n");
        }
        //writer.close();
        br.close();

        if (!hasJson) {
            Trace.write(Trace.Error, "write osworkflow: no json-shape define!");
            return false;
        }

        String jsonString = buf.toString();
        jsonString = formatJsonStrings(jsonString);
        if (jsonString == null) {
            Trace.write(Trace.Error, "write osworkflow[json]: " + buf.toString());
            return false;
        }

        Writer jsonWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(jsonFile), "utf-8"));
        jsonWriter.write(jsonString);
        jsonWriter.close();

        return true;
    } catch (DocumentException de) {
        Trace.write(Trace.Error, de, "write osworkflow[xml].");
    } catch (IOException e) {
        Trace.write(Trace.Error, e, "write osworkflow.");
    }

    return false;
}

From source file:de.ailis.wlandsuite.utils.XmlUtils.java

License:Open Source License

/**
 * Reads a document from the specified input stream. The XML reader is fully
 * configured to validate the wlandsuite namespace.
 * //from w  w w.j av a  2 s  . c  om
 * @param stream
 *            The input stream
 * @return The validated document
 */

public static Document readDocument(InputStream stream) {
    SAXReader reader;

    reader = new SAXReader(true);
    try {
        reader.setFeature("http://xml.org/sax/features/validation", true);
        reader.setFeature("http://apache.org/xml/features/validation/schema", true);
        reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
        reader.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
                "http://ailis.de/wlandsuite classpath://de/ailis/wlandsuite/resource/wlandsuite.xsd");
        reader.setEntityResolver(ClasspathEntityResolver.getInstance());
        return reader.read(stream);
    } catch (SAXException e) {
        throw new XmlException("Unable to configure XML reader: " + e.toString(), e);
    } catch (DocumentException e) {
        throw new XmlException("Unable to read XML document: " + e.toString(), e);
    }
}

From source file:de.ingrid.portal.interfaces.impl.WMSInterfaceImpl.java

License:EUPL

/**
 * @see de.ingrid.portal.interfaces.WMSInterface#getWMSServices(java.lang.String)
 *///w ww  . ja  v a  2s .  c  o  m
public Collection getWMSServices(String sessionID) {
    URL url;
    SAXReader reader = new SAXReader(false);
    ArrayList result = new ArrayList();

    try {

        // workaround for wrong dtd location

        EntityResolver resolver = new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                if (systemId.indexOf("portalCommunication.dtd") > 0) {

                    InputStream in = getClass().getResourceAsStream("wms_interface.dtd");

                    return new InputSource(in);
                }
                return null;
            }
        };
        reader.setEntityResolver(resolver);

        // END workaround for wrong dtd location

        url = new URL(config
                .getString("interface_url", "http://localhost/mapbender/php/mod_portalCommunication_gt.php")
                .concat("?PREQUEST=getWMSServices").concat("&PHPSESSID=" + sessionID));

        reader.setValidation(false);
        Document document = reader.read(url);

        // check for valid server response
        if (document.selectSingleNode("//portal_communication") == null) {
            throw new Exception("WMS Server Response is not valid!");
        }
        // check for valid server response
        String error = document.valueOf("//portal_communication/error");
        if (error != null && error.length() > 0) {
            throw new Exception("WMS Server Error: " + error);
        }
        // get the wms services
        List nodes = document.selectNodes("//portal_communication/wms_services/wms");
        String serviceURL = null;
        for (Iterator i = nodes.iterator(); i.hasNext();) {
            Node node = (Node) i.next();
            serviceURL = node.valueOf("url");
            if (mapBenderVersion.equals(MAPBENDER_VERSION_2_1)) {
                serviceURL = serviceURL.replace(',', '&');
            }
            WMSServiceDescriptor wmsServiceDescriptor = new WMSServiceDescriptor(node.valueOf("name"),
                    serviceURL);
            result.add(wmsServiceDescriptor);
        }

        return result;

    } catch (Exception e) {
        log.error(e.toString());
    }

    return null;
}

From source file:de.ingrid.portal.interfaces.impl.WMSInterfaceImpl.java

License:EUPL

/**
 * @see de.ingrid.portal.interfaces.WMSInterface#getWMSSearchParameter(java.lang.String)
 *///from  ww w .j a  v a  2 s .co  m
public WMSSearchDescriptor getWMSSearchParameter(String sessionID) {
    URL url;
    SAXReader reader = new SAXReader(false);

    try {

        // workaround for wrong dtd location

        EntityResolver resolver = new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                if (systemId.indexOf("portalCommunication.dtd") > 0) {

                    InputStream in = getClass().getResourceAsStream("wms_interface.dtd");

                    return new InputSource(in);
                }
                return null;
            }
        };
        reader.setEntityResolver(resolver);

        // END workaround for wrong dtd location

        String urlStr = config.getString("interface_url",
                "http://localhost/mapbender/php/mod_portalCommunication_gt.php");

        if (urlStr.indexOf("?") > 0) {
            urlStr = urlStr.concat("&PREQUEST=getWMSSearch").concat("&PHPSESSID=" + sessionID);
        } else {
            urlStr = urlStr.concat("?PREQUEST=getWMSSearch").concat("&PHPSESSID=" + sessionID);
        }

        url = new URL(urlStr);

        reader.setValidation(false);
        Document document = reader.read(url);

        // check for valid server response
        if (document.selectSingleNode("//portal_communication") == null) {
            throw new Exception("WMS Server Response is not valid!");
        }
        // check for valid server response
        String error = document.valueOf("//portal_communication/error");
        if (error != null && error.length() > 0) {
            throw new Exception("WMS Server Error: " + error);
        }

        // get search type
        String searchType = document.valueOf("//portal_communication/search/@type");
        if (searchType == null
                || (!searchType.equalsIgnoreCase("bbox") && !searchType.equalsIgnoreCase("gkz"))) {
            throw new Exception("WMS Interface: unsupported search type (" + searchType + ")");
        }

        WMSSearchDescriptor wmsSearchDescriptor = new WMSSearchDescriptor();
        if (searchType.equalsIgnoreCase("bbox")) {
            wmsSearchDescriptor.setType(WMSSearchDescriptor.WMS_SEARCH_BBOX);
            wmsSearchDescriptor
                    .setTypeOfCoordinates(document.valueOf("//portal_communication/search/bbox/@cootype"));
            wmsSearchDescriptor
                    .setMinX(Double.parseDouble(document.valueOf("//portal_communication/search/bbox/minx")));
            wmsSearchDescriptor
                    .setMinY(Double.parseDouble(document.valueOf("//portal_communication/search/bbox/miny")));
            wmsSearchDescriptor
                    .setMaxX(Double.parseDouble(document.valueOf("//portal_communication/search/bbox/maxx")));
            wmsSearchDescriptor
                    .setMaxY(Double.parseDouble(document.valueOf("//portal_communication/search/bbox/maxy")));
        } else if (searchType.equalsIgnoreCase("gkz")) {
            wmsSearchDescriptor.setType(WMSSearchDescriptor.WMS_SEARCH_COMMUNITY_CODE);
            wmsSearchDescriptor.setCommunityCode(document.valueOf("//portal_communication/search/gkz"));
        }

        return wmsSearchDescriptor;

    } catch (Exception e) {
        log.error(e.toString());
    }

    return null;
}

From source file:de.innovationgate.wga.common.beans.hdbmodel.ModelDefinition.java

License:Open Source License

public static ModelDefinition read(InputStream in) throws Exception {

    // First read XML manually and validate against the DTD provided in this OpenWGA distribution (to prevent it being loaded from the internet, which might not work, see #00003612) 
    SAXReader reader = new SAXReader();
    reader.setIncludeExternalDTDDeclarations(true);
    reader.setIncludeInternalDTDDeclarations(true);
    reader.setEntityResolver(new EntityResolver() {

        @Override//from  ww  w .  jav  a 2 s.  c  om
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

            if (systemId.equals("http://doc.openwga.com/hdb-model-definition-6.0.dtd")) {
                return new InputSource(ModelDefinition.class.getClassLoader().getResourceAsStream(
                        WGUtils.getPackagePath(ModelDefinition.class) + "/hdb-model-definition-6.0.dtd"));
            } else {
                // use the default behaviour
                return null;
            }

        }

    });

    org.dom4j.Document domDoc = reader.read(in);

    // Remove doctype (we already have validated) and provide the resulting XML to the serializer
    domDoc.setDocType(null);
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out);
    writer.write(domDoc);
    String xml = out.toString();

    return _serializer.read(ModelDefinition.class, new StringReader(xml));
}

From source file:de.jwic.base.JWicRuntime.java

License:Apache License

/**
 * Setup the JWicRuntime from the jwic-setup.xml file. The setup
 * defines the available renderer and global settings.
 * @param in/*from ww w.j a v a 2  s .c o  m*/
 */
public void setupRuntime(InputStream stream) {

    try {
        SAXReader reader = new SAXReader();
        reader.setEntityResolver(new DTDEntityResolver(DTD_PUBLICID, DTD_SYSTEMID, DTD_RESOURCEPATH));
        reader.setIncludeExternalDTDDeclarations(false);

        Document document = reader.read(stream);

        readDocument(document);

        sessionManager = new SessionManager(getSavePath());
        sessionManager.setStoreTime(sessionStoreTime);

    } catch (NoClassDefFoundError ncdfe) {
        if (ncdfe.getMessage().indexOf("dom4j") != -1) {
            log.error("Can not read jwic-setup.xml: the dom4j library is not in the classpath.");
            throw new RuntimeException(
                    "Can not read jwic-setup.xml: the dom4j library is not in the classpath.", ncdfe);
        }
        log.error("Error reading jwic-setup.xml.", ncdfe);
        throw new RuntimeException("Error reading jwic-setup.xml: " + ncdfe, ncdfe);
    } catch (Exception e) {
        throw new RuntimeException("Error reading jwic-setup.xml: " + e, e);
    }

}

From source file:de.jwic.base.XmlApplicationSetup.java

License:Apache License

/**
 * Create an ApplicationSetup from the specified file.
 * @param filename//from  ww w .ja  va  2 s  . c  om
 */
public XmlApplicationSetup(String filename) {

    try {
        SAXReader reader = new SAXReader();
        reader.setEntityResolver(new DTDEntityResolver(PUBLICID, SYSTEMID, DTD_RESOURCEPATH));
        reader.setIncludeExternalDTDDeclarations(false);

        Document document = reader.read(new File(filename));

        readDocument(document);

    } catch (Exception e1) {
        throw new RuntimeException("Error reading applicationSetup: " + e1, e1);
    }

}

From source file:de.jwic.base.XmlApplicationSetup.java

License:Apache License

/**
 * Create an ApplicationSetup from the specified stream.
 * @param filename/*from  ww w. jav a  2s  .c o  m*/
 */
public XmlApplicationSetup(InputStream stream) {

    try {
        SAXReader reader = new SAXReader();
        reader.setEntityResolver(new DTDEntityResolver(PUBLICID, SYSTEMID, DTD_RESOURCEPATH));
        reader.setIncludeExternalDTDDeclarations(false);

        Document document = reader.read(stream);

        readDocument(document);

    } catch (Exception e1) {
        throw new RuntimeException("Error reading applicationSetup: " + e1, e1);
    }

}