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.infoscoop.service.WidgetConfService.java

public String getWidgetConfsJson(String uid, Locale locale) throws Exception {
    try {/* www  .j a  v  a2  s  .  co m*/
        List<String> useTypes = WidgetDAO.newInstance().getWidgetTypes(uid);
        List<String> widgetTypes = new ArrayList<String>();
        List<String> gadgetTypes = new ArrayList<String>();
        for (String type : useTypes) {
            if (type == null)
                type = "";

            if (type.indexOf("g_") == 0) {
                if (type.indexOf("g_upload") == 0)
                    gadgetTypes.add(type.substring(10).split("/")[0] + ".xml");
            } else {
                widgetTypes.add(type);
            }
        }
        List<WidgetConf> widgetConfs = widgetConfDAO.selectAll();

        JSONObject json = new JSONObject();
        for (WidgetConf widgetConf : widgetConfs) {
            String type = widgetConf.getType();

            json.put(type, WidgetConfUtil.widgetConf2JSONObject(widgetConf.getElement(), null, true));
        }

        if (!gadgetTypes.isEmpty()) {
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            builderFactory.setValidating(false);
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            builder.setEntityResolver(NoOpEntityResolver.getInstance());
            List<Gadget> gadgets = GadgetDAO.newInstance().selectConfsByType(gadgetTypes);
            for (Gadget gadget : gadgets) {
                if (!gadget.getName().equalsIgnoreCase(gadget.getType() + ".xml"))
                    continue;
                WidgetConfUtil.GadgetContext context = new WidgetConfUtil.GadgetContext()
                        .setUrl("upload__" + gadget.getType());
                Document gadgetDoc = builder.parse(new ByteArrayInputStream(gadget.getData()));
                JSONObject gadgetJson = WidgetConfUtil.gadget2JSONObject(gadgetDoc.getDocumentElement(),
                        context.getI18NConveter(locale, gadgetDoc), true);

                String gadgetType = "g_upload__" + gadget.getType() + "/gadget";
                gadgetJson = WidgetConfUtil.gadgetJSONtoPortalGadgetJSON(gadgetJson);
                gadgetJson.put("type", gadgetType);
                json.put(gadgetType, gadgetJson);
            }
        }
        return I18NUtil.resolve(I18NUtil.TYPE_WIDGET, json.toString(1), locale, true);
    } catch (Exception e) {
        log.error("Unexpected error occurred.", e);
        throw e;
    }
}

From source file:org.infoscoop.web.MultiRssServlet.java

/**
 * The doPost method of the servlet. <br>
 * /*from   w ww. j ava  2 s  .  c  o  m*/
 * This method is called when a form has its tag value method equals to
 * post.
 * 
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String uid = (String) request.getSession().getAttribute("Uid");
    if (uid == null)
        uid = request.getHeader("MSDPortal-SessionId");

    String widgetId = null;
    NodeList urlList = null;
    boolean clearCache = false;
    try {
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        builder.setEntityResolver(NoOpEntityResolver.getInstance());

        Document requestDoc = builder.parse(request.getInputStream());
        Element root = requestDoc.getDocumentElement();

        widgetId = root.getAttribute("widgetId");
        urlList = root.getElementsByTagName("rss");
        clearCache = "true".equalsIgnoreCase(root.getAttribute("clearCache"));
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        response.sendError(500, e.getMessage());
        return;
    }

    if (widgetId == null) {
        log.error("Must specify widgetId in request body.");
        response.sendError(500, "Must specify widgetId in request body.");
        return;
    }

    int pageSize = -1;
    String pageSizeStr = request.getHeader("X-IS-PAGESIZE");
    if (pageSizeStr != null) {
        try {
            pageSize = Integer.parseInt(pageSizeStr);
        } catch (NumberFormatException ex) {
            log.warn("init parameter \"rssPageSize\" has unjust value");
        }
    }

    //      if( pageSize < 0 )
    //         pageSize = 20;

    String pageStr = request.getHeader("X-IS-PAGE");
    try {
        if (pageStr != null) {
            int pageNum = Integer.parseInt(pageStr);
            getPageJson(response, uid, widgetId, pageNum);
        } else {
            if (clearCache)
                RssCacheDAO.newInstance().deleteCacheByUrl(uid, widgetId);

            mergeRssAnd2JSON(request, response, uid, widgetId, pageSize, urlList);//TODO: Should not be passed by NodeList.....
        }
    } catch (Exception e) {
        log.error("", e);
        response.sendError(500, e.getMessage());
    }
}

From source file:org.infoscoop.widgetconf.MessageBundle.java

private static Map<String, String> parseResourceBundle(InputStream in)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);/* w  w w .j a  va2  s .com*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setEntityResolver(NoOpEntityResolver.getInstance());

    Document doc = builder.parse(in);
    NodeList msgs = doc.getElementsByTagName("msg");

    Map<String, String> map = new HashMap<String, String>();
    for (int j = 0; j < msgs.getLength(); j++) {
        Element msg = (Element) msgs.item(j);
        String name = msg.getAttribute("name");
        String msgStr = XmlUtil.getChildText(msg).trim();
        map.put(name, msgStr);
    }

    return map;
}

From source file:org.jasig.portal.plugin.deployer.AbstractExtractingEarDeployer.java

/**
 * Gets the EAR descriptor from the {@link JarFile}.
 * /*w  ww.  ja  va2 s . c o  m*/
 * @param earFile The EAR to get the descriptor from.
 * @return The descriptor DOM for the EAR.
 * @throws IOException If there is any problem reading the descriptor from the EAR.
 */
protected Document getDescriptorDom(final JarFile earFile) throws MojoFailureException {
    final ZipEntry descriptorEntry = earFile.getEntry(DESCRIPTOR_PATH);
    if (descriptorEntry == null) {
        throw new IllegalArgumentException(
                "JarFile '" + earFile + "' does not contain a descriptor at '" + DESCRIPTOR_PATH + "'");
    }

    InputStream descriptorStream = null;
    try {
        descriptorStream = earFile.getInputStream(descriptorEntry);

        final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();

        final DocumentBuilder docBuilder;
        try {
            docBuilder = docBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException pce) {
            throw new RuntimeException("Failed to create DocumentBuilder to parse EAR descriptor.", pce);
        }

        docBuilder.setEntityResolver(new ClasspathEntityResolver(this.getLogger()));

        final Document descriptorDom;
        try {
            descriptorDom = docBuilder.parse(descriptorStream);
            return descriptorDom;
        } catch (SAXException e) {
            throw new MojoFailureException(
                    "Failed to parse descriptor '" + DESCRIPTOR_PATH + "' from EAR '" + earFile.getName() + "'",
                    e);
        }
    } catch (IOException e) {
        throw new MojoFailureException(
                "Failed to read descriptor '" + DESCRIPTOR_PATH + "' from EAR '" + earFile.getName() + "'", e);
    } finally {
        IOUtils.closeQuietly(descriptorStream);
    }
}

From source file:org.jboss.ejb3.entity.PersistenceXmlLoader.java

private static Document loadURL(URL configURL, EntityResolver resolver) throws Exception {
    InputStream is = configURL != null ? configURL.openStream() : null;
    if (is == null) {
        throw new IOException("Failed to obtain InputStream from url: " + configURL);
    }/*from www. j a v  a2s  .com*/
    List errors = new ArrayList();
    DocumentBuilderFactory docBuilderFactory = null;
    docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setValidating(true);
    docBuilderFactory.setNamespaceAware(true);
    try {
        //otherwise Xerces fails in validation
        docBuilderFactory.setAttribute("http://apache.org/xml/features/validation/schema", true);
    } catch (IllegalArgumentException e) {
        docBuilderFactory.setValidating(false);
        docBuilderFactory.setNamespaceAware(false);
    }
    InputSource source = new InputSource(is);
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    docBuilder.setEntityResolver(resolver);
    docBuilder.setErrorHandler(new PersistenceXmlLoader.ErrorLogger("XML InputStream", errors, resolver));
    Document doc = docBuilder.parse(source);
    if (errors.size() != 0) {
        throw new PersistenceException("invalid persistence.xml", (Throwable) errors.get(0));
    }
    return doc;
}

From source file:org.kepler.moml.KeplerMetadataExtractor.java

/** Get the metadata from an input stream optionally printing output if a parsing error occurs.
 *  @param actorStream the input stream//from w  w w .j a  v a2 s .c  o m
 *  @param printError if true, print a stack trace and error message if a parsing error occurs.
 */
public static KeplerActorMetadata extractActorMetadata(InputStream actorStream, boolean printError)
        throws Exception {
    //if (isTracing)
    //log.trace("ActorCacheObject(" + actorStream.getClass().getName()
    //+ ")");

    KeplerActorMetadata kam = new KeplerActorMetadata();

    ByteArrayOutputStream byteout;
    try {
        // Copy 1024 bytes from actorStream to byteout
        byteout = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int numread = actorStream.read(b, 0, 1024);
        while (numread != -1) {
            byteout.write(b, 0, numread);
            numread = actorStream.read(b, 0, 1024);
        }
        kam.setActorString(byteout.toString());

        // need to get actor name and id from the string
        // thus build a DOM representation
        String nameStr = null;
        try {
            //if (isTracing) log.trace(kam.getActorString());
            StringReader strR = new StringReader(kam.getActorString());

            InputSource xmlIn = new InputSource(strR);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver(new EntityResolver() {
                public InputSource resolveEntity(String publicId, String systemId)
                        throws SAXException, IOException {
                    if (MOML_PUBLIC_ID_1.equals(publicId)) {
                        return new InputSource(MoMLParser.class.getResourceAsStream("MoML_1.dtd"));
                    } else {
                        return null;
                    }
                }
            });

            // TODO 
            // this causes http://bugzilla.ecoinformatics.org/show_bug.cgi?id=4671
            // when File => Save Archive w/ wf w/ actor w/ < in the name:
            Document doc = builder.parse(xmlIn);
            //if (isTracing) log.trace(doc.toString());

            Element rootNode = doc.getDocumentElement();
            kam.setRootName(rootNode.getNodeName());

            // Get the value of the name attribute of the root node
            NamedNodeMap nnm = rootNode.getAttributes();
            Node namenode = nnm.getNamedItem("name");
            nameStr = namenode.getNodeValue();
            kam.setName(nameStr);

            boolean emptyKeplerDocumentation = true;
            boolean foundKeplerDocumentation = false;
            boolean foundUserLevelDocumentation = false;
            boolean foundAuthor = false;

            // Cycle through the children of the root node
            NodeList probNodes = rootNode.getChildNodes();
            for (int i = 0; i < probNodes.getLength(); i++) {
                Node child = probNodes.item(i);

                if (child.hasAttributes()) {

                    NamedNodeMap childAttrs = child.getAttributes();
                    Node idNode = childAttrs.getNamedItem("name");
                    if (idNode != null) {

                        // the entityId
                        String nameval = idNode.getNodeValue();
                        if (nameval.equals(NamedObjId.NAME)) {
                            Node idNode1 = childAttrs.getNamedItem("value");
                            String idval = idNode1.getNodeValue();
                            kam.setLsid(new KeplerLSID(idval));
                        }

                        // the class name
                        if (nameval.equals("class")) {
                            Node idNode3 = childAttrs.getNamedItem("value");
                            String classname = idNode3.getNodeValue();
                            kam.setClassName(classname);
                        }

                        // the semantic types
                        if (nameval.startsWith("semanticType")) {
                            Node idNode2 = childAttrs.getNamedItem("value");
                            String semtype = idNode2.getNodeValue();
                            kam.addSemanticType(semtype);
                        }

                        // userLevelDocumentation must be contained in KeplerDocumentation 
                        if (nameval.equals("userLevelDocumentation")) {
                            log.warn(nameStr
                                    + " userLevelDocumentation property should be contained in a KeplerDocumentation property.");
                        } else if (nameval.equals("KeplerDocumentation")) {

                            foundKeplerDocumentation = true;

                            final NodeList keplerDocNodeList = child.getChildNodes();
                            if (keplerDocNodeList.getLength() > 0) {

                                emptyKeplerDocumentation = false;

                                for (int j = 0; j < keplerDocNodeList.getLength(); j++) {
                                    final Node docChildNode = keplerDocNodeList.item(j);
                                    final NamedNodeMap docChildNamedNodeMap = docChildNode.getAttributes();

                                    if (docChildNamedNodeMap != null) {

                                        final Node docChildChildName = docChildNamedNodeMap
                                                .getNamedItem("name");

                                        if (docChildChildName != null) {

                                            final String docChildChildNameValue = docChildChildName
                                                    .getNodeValue();

                                            if (docChildChildNameValue.equals("userLevelDocumentation")) {

                                                foundUserLevelDocumentation = true;
                                                final String text = docChildNode.getTextContent();
                                                if (text == null || text.trim().isEmpty()) {
                                                    log.debug(nameStr + " has empty userLevelDocumentation.");
                                                }

                                            } else if (docChildChildNameValue.equals("author")) {
                                                foundAuthor = true;

                                                final String text = docChildNode.getTextContent();
                                                if (text == null || text.trim().isEmpty()) {
                                                    log.debug(nameStr + " has empty author documentation.");
                                                }

                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (nameval.startsWith(COPY_ATTRIBUTE_PREFIX)) {
                            String value = childAttrs.getNamedItem("value").getNodeValue();
                            kam.addAttribute(nameval, value);
                        }
                    }
                }
            }

            // check documentation
            if (!foundKeplerDocumentation) {
                log.debug(nameStr + " is missing KeplerDocumentation.");
            } else if (emptyKeplerDocumentation) {
                log.debug(nameStr + " KeplerDocumentation is empty.");
            } else if (!foundUserLevelDocumentation && !foundAuthor) {
                log.debug(nameStr + " is missing userLevelDocumentation and author documentation.");
            } else if (!foundUserLevelDocumentation) {
                log.debug(nameStr + " is missing userLevelDocumentation.");
            } else if (!foundAuthor) {
                log.debug(nameStr + " is missing author documentation.");
            }

        } catch (Exception e) {
            if (printError) {
                e.printStackTrace();
                System.out.println("Error parsing Actor KAR DOM \""
                        + ((nameStr == null) ? byteout.toString().substring(0, 300) + "..." : nameStr) + "\": "
                        + e.getMessage());
            }
            kam = null;
        } finally {
            actorStream.close();
            byteout.close();
        }
    } catch (Exception e) {
        kam = null;
        throw new Exception("Error extracting Actor Metadata: " + e.getMessage());
    }

    return kam;
}

From source file:org.kepler.objectmanager.cache.ActorCacheObject.java

/**
 * deserialize this class/* w w  w.  ja v  a2 s. c o  m*/
 * 
 *@param in
 *            Description of the Parameter
 *@exception IOException
 *                Description of the Exception
 *@exception ClassNotFoundException
 *                Description of the Exception
 */
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    if (isDebugging)
        log.debug("readExternal(" + in.getClass().getName() + ")");

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] b = new byte[1024];
    int numread = in.read(b, 0, 1024);
    while (numread != -1) {
        bos.write(b, 0, numread);
        numread = in.read(b, 0, 1024);
    }
    bos.flush();
    _actorString = bos.toString();
    try {
        StringReader strR = new StringReader(_actorString);
        InputSource xmlIn = new InputSource(strR);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                if (MOML_PUBLIC_ID_1.equals(publicId)) {
                    return new InputSource(MoMLParser.class.getResourceAsStream("MoML_1.dtd"));
                } else {
                    return null;
                }
            }
        });
        Document doc = builder.parse(xmlIn);
        Node rootNode = doc.getDocumentElement();
        _rootname = rootNode.getNodeName();
        NamedNodeMap nnm = rootNode.getAttributes();
        Node namenode = nnm.getNamedItem("name");
        String nameStr = namenode.getNodeValue();
        this._name = nameStr;
        NodeList probNodes = rootNode.getChildNodes();
        for (int i = 0; i < probNodes.getLength(); i++) {
            Node child = probNodes.item(i);
            if (child.hasAttributes()) {
                NamedNodeMap childAttrs = child.getAttributes();
                Node idNode = childAttrs.getNamedItem("name");
                if (idNode != null) {
                    String nameval = idNode.getNodeValue();
                    if (nameval.equals(NamedObjId.NAME)) {
                        Node idNode1 = childAttrs.getNamedItem("value");
                        String idval = idNode1.getNodeValue();
                        this._lsid = new KeplerLSID(idval);
                    }
                    if (nameval.equals("class")) {
                        Node idNode3 = childAttrs.getNamedItem("value");
                        String classname = idNode3.getNodeValue();
                        this._className = classname;
                    }
                    if (nameval.startsWith("semanticType")) {
                        Node idNode2 = childAttrs.getNamedItem("value");
                        String semtype = idNode2.getNodeValue();
                        _semanticTypes.add(semtype);
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException("Error in ActorCacheObject(ReadExternal): " + e.getMessage());
    }
}

From source file:org.kmallan.azureus.rssfeed.Scheduler.java

public synchronized void runFeed(final UrlBean urlBean) {
    String url = urlBean.getLocation();
    String title, link, description;

    ListGroup listBeans = urlBean.getGroup();

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setIgnoringComments(true);
    docFactory.setIgnoringElementContentWhitespace(true);
    DocumentBuilder docBuild;
    Document feed;/*from   www . java 2 s  .  c o m*/

    File xmlTmp = null;
    try {
        docBuild = docFactory.newDocumentBuilder();
        Downloader downloader = new Downloader();
        downloader.addListener(new DownloaderListener() {
            public boolean completed = false, error = false;

            public void downloaderUpdate(int state, int percent, int amount, String err) {
                if (completed || error)
                    return;
                String status = new String("Pending");
                switch (state) {
                case Downloader.DOWNLOADER_NON_INIT:
                    status = "Pending";
                    break;
                case Downloader.DOWNLOADER_INIT:
                    status = "Connecting";
                    break;
                case Downloader.DOWNLOADER_START:
                    status = "Download Starting";
                    break;
                case Downloader.DOWNLOADER_DOWNLOADING:
                    status = "Downloading";
                    break;
                case Downloader.DOWNLOADER_FINISHED:
                    status = "Download Finished";
                    completed = true;
                    break;
                case Downloader.DOWNLOADER_NOTMODIFIED:
                    status = "Not modified";
                    completed = true;
                    break;
                case Downloader.DOWNLOADER_ERROR:
                    status = "Error";
                    error = true;
                    break;
                }
                urlBean.setStatus(status);
                if (percent > 0)
                    urlBean.setPercent(percent);
                if (amount > 0)
                    urlBean.setAmount(amount);
                if (!err.equalsIgnoreCase(""))
                    urlBean.setError(err);

                if (view.isOpen() && view.display != null && !view.display.isDisposed())
                    view.display.asyncExec(new Runnable() {
                        public void run() {
                            if (view.listTable == null || view.listTable.isDisposed())
                                return;
                            ListTreeItem listGroup = view.treeViewManager.getItem(urlBean);
                            listGroup.setText(1, urlBean.getStatus() + " " + (!urlBean.getError()
                                    .equalsIgnoreCase("") && urlBean.getStatus() == "Error"
                                            ? "- " + urlBean.getError()
                                            : (urlBean.getStatus() == "Downloading" ? (urlBean.getPercent() > 0
                                                    ? Integer.toString(urlBean.getPercent()) + "%"
                                                    : (urlBean.getAmount() > 0 ? Double.toString(Math.floor(
                                                            new Integer(urlBean.getAmount()).doubleValue()
                                                                    / (double) 1024 * (double) 100)
                                                            / (double) 100) + "KB" : ""))
                                                    : "")));
                            if (!urlBean.getError().equalsIgnoreCase(""))
                                listGroup.setForeground(new Color(view.display, 255, 0, 0));
                            else
                                listGroup.resetForeground();
                        }
                    });
            }
        });
        downloader.init(url, "text/xml, text/html, text/plain, application/x-httpd-php", null,
                (urlBean.getUseCookie() ? urlBean.getCookie() : null), urlBean.getLastModifed(),
                urlBean.getLastEtag());

        if (downloader.getState() == Downloader.DOWNLOADER_ERROR)
            return;

        if (downloader.getState() == Downloader.DOWNLOADER_NOTMODIFIED) {
            // no change, add the old items again
            for (Iterator iter = listBeans.getPreviousItems().iterator(); iter.hasNext();) {
                addTableElement(urlBean, listBeans, (ListBean) iter.next());
            }
            addBacklogElements(urlBean);
            downloader.notModified();
            // use the last seen TTL value if available
            if (urlBean.getObeyTTL() && listBeans.getPreviousDelay() > 0)
                listBeans.setDelay(listBeans.getPreviousDelay());
            return;
        }

        Plugin.debugOut(
                urlBean.getName() + " Last-Modified: " + downloader.lastModified + " ETag: " + downloader.etag);

        urlBean.setLastModifed(downloader.lastModified);
        urlBean.setLastEtag(downloader.etag);

        xmlTmp = new File(Plugin.getPluginDirectoryName(), "tmp-" + urlBean.getID() + ".xml");
        xmlTmp.createNewFile();
        FileOutputStream fileout = new FileOutputStream(xmlTmp, false);

        byte[] buf = new byte[2048];
        int read = 0;
        do {
            if (downloader.getState() == Downloader.DOWNLOADER_CANCELED)
                break;
            read = downloader.read(buf);
            if (read > 0) {
                System.err.print(".");
                fileout.write(buf, 0, read);
            } else if (read == 0) {
                System.err.print("?");
                try {
                    long numMillisecondsToSleep = 100;
                    Thread.sleep(numMillisecondsToSleep);
                } catch (InterruptedException e) {
                }
            }
        } while (read >= 0);

        fileout.flush();
        fileout.close();

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

                // handle bad DTD external refs

                if (Plugin.getProxyOption() == Plugin.PROXY_TRY_PLUGIN) {

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

                try {
                    URL url = new URL(systemId);

                    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);
                }
            }
        });

        try {
            feed = docBuild.parse(xmlTmp);

        } catch (Exception e) {

            feed = null;

            String msg = Debug.getNestedExceptionMessage(e);

            if ((msg.contains("entity") && msg.contains("was referenced"))
                    || msg.contains("entity reference")) {

                FileInputStream fis = new FileInputStream(xmlTmp);

                try {

                    feed = docBuild.parse(new EntityFudger(fis));

                } catch (Throwable f) {

                } finally {

                    fis.close();
                }
            }

            if (feed == null) {
                if (e instanceof ParserConfigurationException) {
                    throw ((ParserConfigurationException) e);
                } else if (e instanceof SAXException) {
                    throw ((SAXException) e);
                } else if (e instanceof IOException) {
                    throw ((IOException) e);
                } else {
                    throw (new IOException(msg));
                }
            }
        }

        xmlTmp.delete();
        downloader.done();

        if (downloader.getState() == Downloader.DOWNLOADER_ERROR)
            return;
    } catch (ParserConfigurationException e) {
        if (xmlTmp != null)
            xmlTmp.delete();
        urlBean.setError("Malformed RSS XML: " + e.getMessage());
        return;
    } catch (SAXException e) {
        if (xmlTmp != null)
            xmlTmp.delete();
        urlBean.setError("Malformed RSS XML: " + e.getMessage());
        return;
    } catch (IOException e) {
        if (xmlTmp != null)
            xmlTmp.delete();
        urlBean.setError("IO Exception: " + e.getMessage());
        return;
    }

    if (urlBean.getObeyTTL()) {
        NodeList feedTTL = feed.getElementsByTagName("ttl");
        if (feedTTL.getLength() == 1) {
            int newDelay = Integer.parseInt(getText(feedTTL.item(0))) * 60;
            if (newDelay > 0)
                urlBean.getGroup().setDelay(newDelay, true);
        }
    }

    // Parse the channel's "item"s
    NodeList feedItems = feed.getElementsByTagName("item");
    int feedItemLen = feedItems.getLength();
    for (int iLoop = 0; iLoop < feedItemLen; iLoop++) {
        Node item = feedItems.item(iLoop);
        NodeList params = item.getChildNodes();
        int paramsLen = params.getLength();

        title = link = description = "";

        for (int i = 0; i < paramsLen; i++) {
            Node param = params.item(i);
            if (param.getNodeType() == Node.ELEMENT_NODE) {
                if (param.getNodeName().equalsIgnoreCase("title")) {
                    title = getText(param);
                } else if (param.getNodeName().equalsIgnoreCase("enclosure") && param.hasAttributes()) {
                    if ((((param.getAttributes()).getNamedItem("type")).getNodeValue())
                            .equalsIgnoreCase("application/x-bittorrent")) {
                        link = ((param.getAttributes()).getNamedItem("url")).getNodeValue();
                    }
                } else if (param.getNodeName().equalsIgnoreCase("link") && link.length() == 0) {
                    link = getText(param);
                } else if (param.getNodeName().equalsIgnoreCase("description")) {
                    description = getText(param);
                    if (description != null && description.trim().startsWith("<")) {
                        // strip html tags and entity references from description
                        HtmlAnalyzer parser = new HtmlAnalyzer();
                        try {
                            new ParserDelegator().parse(new StringReader(description), parser, true);
                            description = parser.getPlainText();
                        } catch (IOException e) {
                        }
                    }
                    description += "\n";
                }
            }
        }

        if (link.length() == 0)
            continue;
        if (link.indexOf("://") < 0 && !link.toLowerCase().startsWith("magnet")) {
            try {
                link = HtmlAnalyzer.resolveRelativeURL(urlBean.getLocation(), link);
            } catch (MalformedURLException e) {
                Plugin.debugOut("Bad link URL: " + link + " -> " + e.getMessage());
                continue;
            }
        }

        int state = ListBean.NO_DOWNLOAD;

        String titleTest = title.toLowerCase();
        String linkTest = link.toLowerCase();

        FilterBean curFilter = null;
        for (int i = 0; i < view.rssfeedConfig.getFilterCount(); i++) {
            curFilter = view.rssfeedConfig.getFilter(i);
            if (curFilter == null)
                continue;
            if (curFilter.matches(urlBean.getID(), titleTest, linkTest)) {
                if (curFilter.getMode().equalsIgnoreCase("Pass")) {
                    state = ListBean.DOWNLOAD_INCL;
                } else {
                    state = ListBean.DOWNLOAD_EXCL;
                }
                break;
            }
        }
        Episode e = null;
        Movie m = null;
        final FilterBean filterBean = curFilter;
        if (filterBean != null) {
            if ("TVShow".equalsIgnoreCase(filterBean.getType())) {
                try {
                    e = FilterBean.getSeason(titleTest);
                } catch (Exception ee) {
                }
                try {
                    if (e == null) {
                        e = FilterBean.getSeason(linkTest);
                    }
                } catch (Exception ee) {
                }
            } else if ("Movie".equalsIgnoreCase(filterBean.getType())) {
                m = FilterBean.getMovie(titleTest);
                if (m == null) {
                    m = FilterBean.getMovie(linkTest);
                }
                Plugin.debugOut("Download is a movie: " + m);
            }
        }

        if (state == ListBean.DOWNLOAD_INCL) {
            Plugin.debugOut("testing for download: " + linkTest);
            if (filterBean.getUseSmartHistory()) {
                for (int i = 0; i < view.rssfeedConfig.getHistoryCount(); i++) {
                    HistoryBean histBean = view.rssfeedConfig.getHistory(i);
                    if (linkTest.equalsIgnoreCase(histBean.getLocation())) {
                        Plugin.debugOut("found location match: " + histBean);
                        state = ListBean.DOWNLOAD_HIST;
                        break;
                    }

                    if (e != null && histBean.getSeasonStart() >= 0 && filterBean.getUseSmartHistory()) {
                        final String showTitle = histBean.getTitle();

                        // Old history beans may not have set showTitle so keep using the old way of matching
                        if (showTitle == null ? (histBean.getFiltID() == filterBean.getID())
                                : showTitle.equalsIgnoreCase(e.showTitle)) {
                            // "Proper" episode is not skipped unless history is also proper
                            if (histBean.isProper() || !e.isProper()) {
                                int seasonStart = histBean.getSeasonStart();
                                int episodeStart = histBean.getEpisodeStart();
                                int seasonEnd = histBean.getSeasonEnd();
                                int episodeEnd = histBean.getEpisodeEnd();
                                Plugin.debugOut(e + " vs s" + seasonStart + "e" + episodeStart + " - s"
                                        + seasonEnd + "e" + episodeEnd);
                                if (e.inRange(seasonStart, episodeStart, seasonEnd, episodeEnd)) {
                                    Plugin.debugOut("found filter and episode match: " + e);
                                    state = ListBean.DOWNLOAD_HIST;
                                    break;
                                }
                            }
                        }
                    } else if (m != null && m.getTitle().equals(histBean.getTitle())
                            && m.getYear() == histBean.getYear()) {
                        if (histBean.isProper() || !m.isProper()) {
                            Plugin.debugOut("found movie match: " + m);
                            state = ListBean.DOWNLOAD_HIST;
                        }
                    }
                }
            } else
                Plugin.debugOut("Filter doesn't use smart history: " + filterBean);
        }

        final ListBean listBean = addTableElement(urlBean, listBeans, title, link, description, state);

        if (state == ListBean.DOWNLOAD_INCL) {
            // Add the feed
            final String curLink = link;
            boolean success = view.torrentDownloader.addTorrent(curLink, urlBean, filterBean, listBean);
            if (success && filterBean.getType().equalsIgnoreCase("Other") && filterBean.getDisableAfter())
                filterBean.setEnabled(false);

            if (view.isOpen() && view.display != null && !view.display.isDisposed())
                view.display.asyncExec(new Runnable() {
                    public void run() {
                        ListTreeItem listItem = view.treeViewManager.getItem(listBean);
                        if (listItem != null)
                            listItem.update();
                    }
                });
        }
    }
}

From source file:org.kuali.kfs.sys.context.CheckModularization.java

protected Document generateDwrConfigDocument(String fileName) throws Exception {
    DefaultResourceLoader resourceLoader = new DefaultResourceLoader(ClassLoaderUtils.getDefaultClassLoader());
    InputStream in = resourceLoader.getResource(fileName).getInputStream();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);/*from   w w  w. ja  va 2  s.  c  o m*/

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new DTDEntityResolver());
    db.setErrorHandler(new LogErrorHandler());

    Document doc = db.parse(in);
    return doc;
}

From source file:org.kuali.rice.core.impl.impex.xml.XmlIngesterServiceImpl.java

private static void validate(final XmlDoc xmlDoc, EntityResolver resolver)
        throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);// w ww .j a  va  2s .com
    dbf.setNamespaceAware(true);
    dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            XMLConstants.W3C_XML_SCHEMA_NS_URI);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(resolver);
    db.setErrorHandler(new ErrorHandler() {
        public void warning(SAXParseException se) {
            LOG.warn("Warning parsing xml doc " + xmlDoc, se);
            addProcessingException(xmlDoc, "Warning parsing xml doc " + xmlDoc, se);
        }

        public void error(SAXParseException se) throws SAXException {
            LOG.error("Error parsing xml doc " + xmlDoc, se);
            addProcessingException(xmlDoc, "Error parsing xml doc " + xmlDoc, se);
            throw se;
        }

        public void fatalError(SAXParseException se) throws SAXException {
            LOG.error("Fatal error parsing xml doc " + xmlDoc, se);
            addProcessingException(xmlDoc, "Fatal error parsing xml doc " + xmlDoc, se);
            throw se;
        }
    });
    db.parse(xmlDoc.getStream());
}