Example usage for javax.xml.parsers DocumentBuilder setEntityResolver

List of usage examples for javax.xml.parsers DocumentBuilder setEntityResolver

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder setEntityResolver.

Prototype


public abstract void setEntityResolver(EntityResolver er);

Source Link

Document

Specify the EntityResolver to be used to resolve entities present in the XML document to be parsed.

Usage

From source file:org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.PomReader.java

private static DocumentBuilder getDocBuilder(EntityResolver entityResolver) {
    try {//from   ww w.  j a  v a2s . c  o m
        DocumentBuilder docBuilder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
        if (entityResolver != null) {
            docBuilder.setEntityResolver(entityResolver);
        }
        return docBuilder;
    } catch (ParserConfigurationException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}

From source file:org.gss_project.gss.server.rest.Webdav.java

/**
 * Return JAXP document builder instance.
 *
 * @return the DocumentBuilder/*from   ww w  .ja v  a  2s. c o m*/
 * @throws ServletException
 */
private DocumentBuilder getDocumentBuilder() throws ServletException {
    DocumentBuilder documentBuilder = null;
    DocumentBuilderFactory documentBuilderFactory = null;
    try {
        documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setEntityResolver(new WebdavResolver(getServletContext()));
    } catch (ParserConfigurationException e) {
        throw new ServletException("Error while creating a document builder");
    }
    return documentBuilder;
}

From source file:org.gudy.azureus2.pluginsimpl.local.utils.xml.simpleparser.SimpleXMLParserDocumentImpl.java

private void createSupport(InputStream input_stream)

        throws SimpleXMLParserDocumentException {
    try {// ww  w  . j  a v  a 2  s .c  o  m
        DocumentBuilderFactory dbf = getDBF();

        // Step 2: create a DocumentBuilder that satisfies the constraints
        // specified by the DocumentBuilderFactory

        DocumentBuilder db = dbf.newDocumentBuilder();

        // Set an ErrorHandler before parsing

        OutputStreamWriter errorWriter = new OutputStreamWriter(System.err);

        MyErrorHandler error_handler = new MyErrorHandler(new PrintWriter(errorWriter, true));

        db.setErrorHandler(error_handler);

        db.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                // System.out.println( publicId + ", " + systemId );

                // handle bad DTD external refs

                try {
                    URL url = new URL(systemId);

                    if (source_url != null) {

                        String net = AENetworkClassifier.categoriseAddress(source_url.getHost());

                        if (net != AENetworkClassifier.AT_PUBLIC) {

                            if (AENetworkClassifier.categoriseAddress(url.getHost()) != net) {

                                return new InputSource(new ByteArrayInputStream(
                                        "<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
                            }
                        }
                    }

                    String host = url.getHost();

                    InetAddress.getByName(host);

                    // try connecting too as connection-refused will also bork XML parsing

                    InputStream is = null;

                    try {
                        URLConnection con = url.openConnection();

                        con.setConnectTimeout(15 * 1000);
                        con.setReadTimeout(15 * 1000);

                        is = con.getInputStream();

                        byte[] buffer = new byte[32];

                        int pos = 0;

                        while (pos < buffer.length) {

                            int len = is.read(buffer, pos, buffer.length - pos);

                            if (len <= 0) {

                                break;
                            }

                            pos += len;
                        }

                        String str = new String(buffer, "UTF-8").trim().toLowerCase(Locale.US);

                        if (!str.contains("<?xml")) {

                            // not straightforward to check for naked DTDs, could be lots of <!-- commentry preamble which of course can occur
                            // in HTML too

                            buffer = new byte[32000];

                            pos = 0;

                            while (pos < buffer.length) {

                                int len = is.read(buffer, pos, buffer.length - pos);

                                if (len <= 0) {

                                    break;
                                }

                                pos += len;
                            }

                            str += new String(buffer, "UTF-8").trim().toLowerCase(Locale.US);

                            if (str.contains("<html") && str.contains("<head")) {

                                throw (new Exception("Bad DTD"));
                            }
                        }
                    } catch (Throwable e) {

                        return new InputSource(
                                new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));

                    } finally {

                        if (is != null) {

                            try {
                                is.close();

                            } catch (Throwable e) {

                            }
                        }
                    }
                    return (null);

                } catch (UnknownHostException e) {

                    return new InputSource(
                            new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));

                } catch (Throwable e) {

                    return (null);
                }
            }
        });

        // Step 3: parse the input file

        document = db.parse(input_stream);

        SimpleXMLParserDocumentNodeImpl[] root_nodes = parseNode(document, false);

        int root_node_count = 0;

        // remove any processing instructions such as <?xml-stylesheet

        for (int i = 0; i < root_nodes.length; i++) {

            SimpleXMLParserDocumentNodeImpl node = root_nodes[i];

            if (node.getNode().getNodeType() != Node.PROCESSING_INSTRUCTION_NODE) {

                root_node = node;

                root_node_count++;
            }
        }

        if (root_node_count != 1) {

            throw (new SimpleXMLParserDocumentException(
                    "invalid document - " + root_nodes.length + " root elements"));
        }

    } catch (Throwable e) {

        throw (new SimpleXMLParserDocumentException(e));
    }
}

From source file:org.hippoecm.repository.query.lucene.ServicingSearchIndex.java

/**
 * Returns the document element of the indexing configuration or
 * <code>null</code> if there is no indexing configuration.
 *
 * @return the indexing configuration or <code>null</code> if there is
 *         none./*from w w w  .j a  v  a 2  s  . c om*/
 */
@Override
protected Element getIndexingConfigurationDOM() {
    if (indexingConfiguration != null) {
        return indexingConfiguration;
    }
    String configName = getIndexingConfiguration();
    if (configName == null) {
        return null;
    }
    InputStream configInputStream;
    if (configName.startsWith("file:/")) {
        configName = RepoUtils.stripFileProtocol(configName);
        File config = new File(configName);
        log.info("Using indexing configuration: " + configName);
        if (!config.exists()) {
            log.warn("File does not exist: " + this.getIndexingConfiguration());
            return null;
        } else if (!config.canRead()) {
            log.warn("Cannot read file: " + this.getIndexingConfiguration());
            return null;
        }
        try {
            configInputStream = new FileInputStream(config);
        } catch (FileNotFoundException ex) {
            log.warn("indexing configuration not found: " + configName);
            return null;
        }
    } else {
        log.info("Using resource repository indexing_configuration: " + configName);
        configInputStream = ServicingSearchIndex.class.getResourceAsStream(configName);
        if (configInputStream == null) {
            log.warn("indexing configuration not found: " + getClass().getName() + "/" + configName);
            return null;
        }
    }

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new IndexingConfigurationEntityResolver());
        InputSource configurationInputSource = new InputSource(configInputStream);
        indexingConfiguration = builder.parse(configurationInputSource).getDocumentElement();
    } catch (ParserConfigurationException e) {
        log.warn("Unable to create XML parser", e);
    } catch (IOException | SAXException e) {
        log.warn("Exception parsing " + this.getIndexingConfiguration(), e);
    }
    return indexingConfiguration;
}

From source file:org.infoscoop.request.filter.GadgetFilter.java

private Document gadget2dom(InputStream responseBody)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setEntityResolver(NoOpEntityResolver.getInstance());
    Document doc = builder.parse(responseBody);
    return doc;/*from  ww w .j  a  va  2s. c  om*/
}

From source file:org.infoscoop.request.filter.GadgetViewFilter.java

protected InputStream postProcess(ProxyRequest request, InputStream responseStream) throws IOException {

    Document module = null;//from   w ww .  j a  v a2 s  . co m
    try {
        DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        builder.setEntityResolver(NoOpEntityResolver.getInstance());
        module = builder.parse(responseStream);
    } catch (Exception ex) {
        log.warn("", ex);

        throw new IOException("Invalid Module");
    }

    String viewType = request.getFilterParameter("view");
    byte[] responseBytes = null;
    try {
        responseBytes = processView(module, viewType.toLowerCase());
    } catch (Exception ex) {
        log.warn("", ex); //FIXME
    }

    request.putResponseHeader("Content-Type", "text/xml");
    request.putResponseHeader("Content-Length", String.valueOf(responseBytes.length));

    return new ByteArrayInputStream(responseBytes);
}

From source file:org.infoscoop.service.GadgetResourceService.java

private byte[] validateGadgetData(String type, String path, String name, byte[] data) {
    Document gadgetDoc;/*from   w  w w  .  j  av a 2 s.c om*/

    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setValidating(false);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        builder.setEntityResolver(NoOpEntityResolver.getInstance());
        gadgetDoc = builder.parse(new ByteArrayInputStream(data));

        Element moduleNode = gadgetDoc.getDocumentElement();
        NodeList contentNodes = moduleNode.getElementsByTagName("Content");
        //The preparations for Locale tag
        NodeList modulePrefsList = gadgetDoc.getElementsByTagName("ModulePrefs");

        if (!"Module".equals(moduleNode.getTagName()) || contentNodes == null || contentNodes.getLength() == 0
                || modulePrefsList == null || modulePrefsList.getLength() == 0) {
            throw new GadgetResourceException("It is an invalid gadget module. ",
                    "ams_gadgetResourceInvalidGadgetModule");
        }

        Element iconElm = (Element) XPathAPI.selectSingleNode(gadgetDoc, "/Module/ModulePrefs/Icon");
        if (iconElm != null) {
            String iconUrl = iconElm.getTextContent();
            for (int i = 0; i < modulePrefsList.getLength(); i++) {
                Element modulePrefs = (Element) modulePrefsList.item(i);
                if (modulePrefs.hasAttribute("resource_url")) {
                    iconUrl = modulePrefs.getAttribute("resource_url") + iconUrl;
                    break;
                }
            }
            gadgetIconDAO.insertUpdate(type, iconUrl);
        } else {
            gadgetIconDAO.insertUpdate(type, "");
        }

        return XmlUtil.dom2String(gadgetDoc).getBytes("UTF-8");
    } catch (GadgetResourceException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new GadgetResourceException("It is an invalid gadget module. ",
                "ams_gadgetResourceInvalidGadgetModule", ex);
    }
}

From source file:org.infoscoop.service.GadgetService.java

public JSONObject getGadgetJson(String type, Locale locale) throws Exception {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setValidating(false);

    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    builder.setEntityResolver(NoOpEntityResolver.getInstance());

    Gadget gadget = gadgetDAO.select(type);
    Document gadgetDoc = builder.parse(new ByteArrayInputStream(gadget.getData()));
    Element gadgetEl = gadgetDoc.getDocumentElement();
    JSONObject confJson = WidgetConfUtil.gadget2JSONObject(gadgetEl, null);
    return confJson;
}

From source file:org.infoscoop.service.GadgetService.java

private static String gadget2JSON(List<Gadget> gadgetList, boolean isUpdate, Locale locale, int timeout,
        boolean enableI18N) throws Exception {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setValidating(false);

    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    builder.setEntityResolver(NoOpEntityResolver.getInstance());

    JSONObject json = new JSONObject();
    for (int i = 0; i < gadgetList.size(); i++) {
        Gadget gadget = gadgetList.get(i);
        try {/*ww w .  j a  va 2 s  .c om*/
            //TODO:enocoding
            Document gadgetDoc = (Document) XmlUtil
                    .string2DomWithBomCode(new String(gadget.getData(), "UTF-8"));
            Element gadgetEl = gadgetDoc.getDocumentElement();
            String type = gadget.getType();

            I18NConverter i18n = new I18NConverter(locale,
                    new MessageBundle.Factory.Upload(timeout, type).createBundles(gadgetDoc));

            JSONObject confJson = WidgetConfUtil.gadget2JSONObject(gadgetEl, i18n);
            if (!type.startsWith("upload__"))
                type = "upload__" + type;

            json.put(type, confJson);
        } catch (Exception ex) {
            log.error("UploadGadget Parse failed: [" + gadget.getType() + "]", ex);
        }
    }
    String jsonStr = json.toString(1);
    if (enableI18N) {
        jsonStr = I18NUtil.resolve(I18NUtil.TYPE_WIDGET, jsonStr, locale);
    }
    return jsonStr;
}

From source file:org.infoscoop.service.GadgetService.java

/**
 * @param type//from   ww  w. j  a  v  a  2 s  .  com
 * @param widgetConfJSON a widgetConf whose form is JSON.
 * @throws Exception
 */
public void updateGadget(String type, String gadgetJSON) throws Exception {
    if (type.startsWith("upload__"))
        type = type.substring(8);

    if (log.isInfoEnabled())
        log.info("uploadGadget type=" + type);
    try {

        Gadget gadget = gadgetDAO.select(type);
        JSONObject json = new JSONObject(gadgetJSON);

        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setValidating(false);

        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        builder.setEntityResolver(NoOpEntityResolver.getInstance());
        Document gadgetDoc = builder.parse(new ByteArrayInputStream(gadget.getData()));
        Element gadgetEl = gadgetDoc.getDocumentElement();
        String resourceUrl = "";
        if (json.has("ModulePrefs")) {
            JSONObject modulePrefs = json.getJSONObject("ModulePrefs");
            for (Iterator<String> prefNames = modulePrefs.keys(); prefNames.hasNext();) {
                String prefName = prefNames.next();
                if (!("autoRefresh".equals(prefName) || "title".equals(prefName)
                        || "directory_title".equals(prefName) || "title_url".equals(prefName)
                        || "height".equals(prefName) || "scrolling".equals(prefName)
                        || "singleton".equals(prefName) || "resource_url".equals(prefName)))
                    continue;

                String value = modulePrefs.getString(prefName);
                if (log.isInfoEnabled())
                    log.info("Modify Gadget's ModulePrefs@" + prefName + " to " + value + ".");
                Element modulePrefsEl = (Element) gadgetEl.getElementsByTagName("ModulePrefs").item(0);
                modulePrefsEl.setAttribute(prefName, value);

                if (prefName.equals("resource_url"))
                    resourceUrl = value;
            }
        }
        Element iconElm = (Element) XPathAPI.selectSingleNode(gadgetDoc, "/Module/ModulePrefs/Icon");

        if (iconElm != null) {
            String iconUrl = resourceUrl + iconElm.getTextContent();
            GadgetIconDAO.newInstance().insertUpdate(type, iconUrl);
        } else {
            GadgetIconDAO.newInstance().insertUpdate(type, "");
        }

        updateUserPrefNodes(gadgetDoc, json);

        if (json.has("WidgetPref"))
            WidgetConfService.updateWidgetPrefNode(gadgetDoc, gadgetEl, json.getJSONObject("WidgetPref"));

        gadgetDAO.update(type, "/", type + ".xml", XmlUtil.dom2String(gadgetDoc).getBytes("UTF-8"));
    } catch (Exception e) {
        log.error("update of widet configuration \"" + type + "\" failed.", e);
        throw e;
    }
}