List of usage examples for org.xml.sax EntityResolver EntityResolver
EntityResolver
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;/*from w w w. j a va2s . c o m*/ Document feed; 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.lockss.plugin.clockss.wolterskluwer.WoltersKluwerXPathXmlMetadataParser.java
@Override protected DocumentBuilder makeDocumentBuilder(DocumentBuilderFactory dbf) throws ParserConfigurationException { DocumentBuilder db = super.makeDocumentBuilder(dbf); db.setEntityResolver(new EntityResolver() { @Override//from w w w . jav a 2 s . c om public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId.contains("ovidbase.dtd")) { return new InputSource(getClass().getResourceAsStream("sgmlentities.dtd")); } return null; } }); return db; }
From source file:org.mapfish.print.map.readers.WMSServerInfo.java
protected static WMSServerInfo parseCapabilities(InputStream stream) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); //we don't want the DTD to be checked and it's the only way I found documentBuilder.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new StringReader("")); }/*from ww w. ja va 2 s.c om*/ }); Document doc = documentBuilder.parse(stream); NodeList tileSets = doc.getElementsByTagName("TileSet"); boolean isTileCache = (tileSets.getLength() > 0); final WMSServerInfo result = new WMSServerInfo(); if (isTileCache) { result.tileCacheLayers = new HashMap<String, TileCacheLayerInfo>(); NodeList layers = doc.getElementsByTagName("Layer"); for (int i = 0; i < tileSets.getLength(); ++i) { final Node tileSet = tileSets.item(i); final Node layer = layers.item(i + 1); String resolutions = DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet, "Resolutions")); int width = Integer.parseInt(DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet, "Width"))); int height = Integer .parseInt(DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet, "Height"))); Element bbox = DOMUtil.getFirstChildElement(layer, "BoundingBox"); float minX = Float.parseFloat(DOMUtil.getAttrValue(bbox, "minx")); float minY = Float.parseFloat(DOMUtil.getAttrValue(bbox, "miny")); float maxX = Float.parseFloat(DOMUtil.getAttrValue(bbox, "maxx")); float maxY = Float.parseFloat(DOMUtil.getAttrValue(bbox, "maxy")); String format = DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet, "Format")); String layerName = DOMUtil.getChildText(DOMUtil.getFirstChildElement(layer, "Name")); final TileCacheLayerInfo info = new TileCacheLayerInfo(resolutions, width, height, minX, minY, maxX, maxY, format); result.tileCacheLayers.put(layerName, info); } } return result; }
From source file:org.metaeffekt.dita.maven.glossary.GlossaryMapCreator.java
protected Document readDocument(File file) { SAXReader reader = new SAXReader(); reader.setValidation(false);// w ww .j av a 2 s . co m reader.setIncludeInternalDTDDeclarations(false); reader.setIncludeExternalDTDDeclarations(false); reader.setIgnoreComments(true); reader.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String arg0, String arg1) throws SAXException, IOException { return new InputSource(new InputStream() { @Override public int read() throws IOException { return -1; } }); } }); try { return reader.read(file); } catch (DocumentException e) { return null; } }
From source file:org.openmrs.migration.MigrationHelper.java
public static Document parseXml(String xml) throws ParserConfigurationException { DocumentBuilder builder = factory.newDocumentBuilder(); try {/* w w w. j a va 2 s . c o m*/ // Disable resolution of external entities. See TRUNK-3942 builder.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) { return new InputSource(new StringReader("")); } }); return builder.parse(new InputSource(new StringReader(xml))); } catch (IOException ex) { return null; } catch (SAXException e) { return null; } }
From source file:org.openmrs.module.ModuleFileParser.java
/** * Get the module// ww w. j a va 2s . com * * @return new module object */ public Module parse() throws ModuleException { Module module = null; JarFile jarfile = null; InputStream configStream = null; try { try { jarfile = new JarFile(moduleFile); } catch (IOException e) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.cannotGetJarFile"), moduleFile.getName(), e); } // look for config.xml in the root of the module ZipEntry config = jarfile.getEntry("config.xml"); if (config == null) { throw new ModuleException(Context.getMessageSourceService().getMessage("Module.error.noConfigFile"), moduleFile.getName()); } // get a config file stream try { configStream = jarfile.getInputStream(config); } catch (IOException e) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.cannotGetConfigFileStream"), moduleFile.getName(), e); } // turn the config file into an xml document Document configDoc = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // When asked to resolve external entities (such as a // DTD) we return an InputSource // with no data at the end, causing the parser to ignore // the DTD. return new InputSource(new StringReader("")); } }); configDoc = db.parse(configStream); } catch (Exception e) { log.error("Error parsing config.xml: " + configStream.toString(), e); OutputStream out = null; String output = ""; try { out = new ByteArrayOutputStream(); // Now copy bytes from the URL to the output stream byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = configStream.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } output = out.toString(); } catch (Exception e2) { log.warn("Another error parsing config.xml", e2); } finally { try { out.close(); } catch (Exception e3) { } } log.error("config.xml content: " + output); throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.cannotParseConfigFile"), moduleFile.getName(), e); } Element rootNode = configDoc.getDocumentElement(); String configVersion = rootNode.getAttribute("configVersion").trim(); if (!validConfigVersions.contains(configVersion)) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.invalidConfigVersion", new Object[] { configVersion }, Context.getLocale()), moduleFile.getName()); } String name = getElement(rootNode, configVersion, "name").trim(); String moduleId = getElement(rootNode, configVersion, "id").trim(); String packageName = getElement(rootNode, configVersion, "package").trim(); String author = getElement(rootNode, configVersion, "author").trim(); String desc = getElement(rootNode, configVersion, "description").trim(); String version = getElement(rootNode, configVersion, "version").trim(); // do some validation if (name == null || name.length() == 0) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.nameCannotBeEmpty"), moduleFile.getName()); } if (moduleId == null || moduleId.length() == 0) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.idCannotBeEmpty"), name); } if (packageName == null || packageName.length() == 0) { throw new ModuleException( Context.getMessageSourceService().getMessage("Module.error.packageCannotBeEmpty"), name); } // create the module object module = new Module(name, moduleId, packageName, author, desc, version); // find and load the activator class module.setActivatorName(getElement(rootNode, configVersion, "activator").trim()); module.setRequireDatabaseVersion( getElement(rootNode, configVersion, "require_database_version").trim()); module.setRequireOpenmrsVersion(getElement(rootNode, configVersion, "require_version").trim()); module.setUpdateURL(getElement(rootNode, configVersion, "updateURL").trim()); module.setRequiredModulesMap(getRequiredModules(rootNode, configVersion)); module.setAwareOfModulesMap(getAwareOfModules(rootNode, configVersion)); module.setStartBeforeModulesMap(getStartBeforeModules(rootNode, configVersion)); module.setAdvicePoints(getAdvice(rootNode, configVersion, module)); module.setExtensionNames(getExtensions(rootNode, configVersion)); module.setPrivileges(getPrivileges(rootNode, configVersion)); module.setGlobalProperties(getGlobalProperties(rootNode, configVersion)); module.setMessages(getMessages(rootNode, configVersion, jarfile, moduleId, version)); module.setMappingFiles(getMappingFiles(rootNode, configVersion, jarfile)); module.setPackagesWithMappedClasses(getPackagesWithMappedClasses(rootNode, configVersion)); module.setConfig(configDoc); module.setMandatory(getMandatory(rootNode, configVersion, jarfile)); module.setFile(moduleFile); module.setConditionalResources(getConditionalResources(rootNode)); } finally { try { jarfile.close(); } catch (Exception e) { log.warn("Unable to close jarfile: " + jarfile, e); } if (configStream != null) { try { configStream.close(); } catch (Exception io) { log.error("Error while closing config stream for module: " + moduleFile.getAbsolutePath(), io); } } } return module; }
From source file:org.openmrs.module.SqlDiffFileParser.java
/** * Get the diff map. Return a sorted map<version, sql statements> * * @return SortedMap<String, String> * @throws ModuleException//from w w w . j a va 2 s . c om */ public static SortedMap<String, String> getSqlDiffs(Module module) throws ModuleException { if (module == null) { throw new ModuleException("Module cannot be null"); } SortedMap<String, String> map = new TreeMap<String, String>(new VersionComparator()); InputStream diffStream = null; // get the diff stream JarFile jarfile = null; try { try { jarfile = new JarFile(module.getFile()); } catch (IOException e) { throw new ModuleException("Unable to get jar file", module.getName(), e); } diffStream = ModuleUtil.getResourceFromApi(jarfile, module.getModuleId(), module.getVersion(), SQLDIFF_CHANGELOG_FILENAME); if (diffStream == null) { // Try the old way. Loading from the root of the omod ZipEntry diffEntry = jarfile.getEntry(SQLDIFF_CHANGELOG_FILENAME); if (diffEntry == null) { log.debug("No sqldiff.xml found for module: " + module.getName()); return map; } else { try { diffStream = jarfile.getInputStream(diffEntry); } catch (IOException e) { throw new ModuleException("Unable to get sql diff file stream", module.getName(), e); } } } try { // turn the diff stream into an xml document Document diffDoc = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // When asked to resolve external entities (such as a DTD) we return an InputSource // with no data at the end, causing the parser to ignore the DTD. return new InputSource(new StringReader("")); } }); diffDoc = db.parse(diffStream); } catch (Exception e) { throw new ModuleException("Error parsing diff sqldiff.xml file", module.getName(), e); } Element rootNode = diffDoc.getDocumentElement(); String diffVersion = rootNode.getAttribute("version"); if (!validConfigVersions().contains(diffVersion)) { throw new ModuleException("Invalid config version: " + diffVersion, module.getModuleId()); } NodeList diffNodes = getDiffNodes(rootNode, diffVersion); if (diffNodes != null && diffNodes.getLength() > 0) { int i = 0; while (i < diffNodes.getLength()) { Element el = (Element) diffNodes.item(i++); String version = getElement(el, diffVersion, "version"); String sql = getElement(el, diffVersion, "sql"); map.put(version, sql); } } } catch (ModuleException e) { if (diffStream != null) { try { diffStream.close(); } catch (IOException io) { log.error("Error while closing config stream for module: " + module.getModuleId(), io); } } // rethrow the moduleException throw e; } } finally { try { if (jarfile != null) { jarfile.close(); } } catch (IOException e) { log.warn("Unable to close jarfile: " + jarfile.getName()); } } return map; }
From source file:org.openmrs.module.UpdateFileParser.java
/** * Parse the contents of the update.rdf file. * * @throws ModuleException/*from w w w . j a va2 s .c om*/ */ public void parse() throws ModuleException { StringReader stringReader = null; try { Document updateDoc = null; try { stringReader = new StringReader(content); InputSource inputSource = new InputSource(stringReader); inputSource.setSystemId("./"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); // Disable resolution of external entities. See TRUNK-3942 db.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) { return new InputSource(new StringReader("")); } }); updateDoc = db.parse(inputSource); } catch (Exception e) { log.warn("Unable to parse content"); throw new ModuleException("Error parsing update.rdf file: " + content, e); } Element rootNode = updateDoc.getDocumentElement(); String configVersion = rootNode.getAttribute("configVersion"); if (!validConfigVersions().contains(configVersion)) { throw new ModuleException( "Invalid configVersion: '" + configVersion + "' found In content: " + content); } if ("1.0".equals(configVersion)) { // the only update in the xml file is the 'best fit' this.moduleId = getElement(rootNode, configVersion, "moduleId"); this.currentVersion = getElement(rootNode, configVersion, "currentVersion"); this.downloadURL = getElement(rootNode, configVersion, "downloadURL"); } else if ("1.1".equals(configVersion)) { this.moduleId = rootNode.getAttribute("moduleId"); NodeList nodes = rootNode.getElementsByTagName("update"); this.currentVersion = ""; // default to the lowest version possible // loop over all 'update' tags for (Integer i = 0; i < nodes.getLength(); i++) { Element currentNode = (Element) nodes.item(i); String currentVersion = getElement(currentNode, configVersion, "currentVersion"); // if the currently saved version is less than the current tag if (ModuleUtil.compareVersion(this.currentVersion, currentVersion) < 0) { String requireOpenMRSVersion = getElement(currentNode, configVersion, "requireOpenMRSVersion"); // if the openmrs code version is compatible, this node is a winner if (requireOpenMRSVersion == null || ModuleUtil.matchRequiredVersions( OpenmrsConstants.OPENMRS_VERSION_SHORT, requireOpenMRSVersion)) { this.currentVersion = currentVersion; this.downloadURL = getElement(currentNode, configVersion, "downloadURL"); } } } } } catch (ModuleException e) { // rethrow the moduleException throw e; } finally { if (stringReader != null) { stringReader.close(); } } }
From source file:org.openmrs.module.web.WebModuleUtil.java
/** * @param inputStream//from w ww .j av a 2 s .c om * @param realPath * @return */ private static Document getDWRModuleXML(InputStream inputStream, String realPath) { Document dwrmodulexml = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // When asked to resolve external entities (such as a DTD) we return an InputSource // with no data at the end, causing the parser to ignore the DTD. return new InputSource(new StringReader("")); } }); dwrmodulexml = db.parse(inputStream); } catch (Exception e) { throw new ModuleException("Error parsing dwr-modules.xml file", e); } return dwrmodulexml; }
From source file:org.openmrs.web.Listener.java
/** * Convenience method to empty out the dwr-modules.xml file to fix any errors that might have * occurred in it when loading or unloading modules. * * @param servletContext//from w w w . j av a 2s.c om */ private void clearDWRFile(ServletContext servletContext) { Log log = LogFactory.getLog(Listener.class); String realPath = servletContext.getRealPath(""); String absPath = realPath + "/WEB-INF/dwr-modules.xml"; File dwrFile = new File(absPath.replace("/", File.separator)); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // When asked to resolve external entities (such as a DTD) we return an InputSource // with no data at the end, causing the parser to ignore the DTD. return new InputSource(new StringReader("")); } }); Document doc = db.parse(dwrFile); Element elem = doc.getDocumentElement(); elem.setTextContent(""); OpenmrsUtil.saveDocument(doc, dwrFile); } catch (Exception e) { // got here because the dwr-modules.xml file is empty for some reason. This might // happen because the servlet container (i.e. tomcat) crashes when first loading this file log.debug("Error clearing dwr-modules.xml", e); dwrFile.delete(); FileWriter writer = null; try { writer = new FileWriter(dwrFile); writer.write( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE dwr PUBLIC \"-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN\" \"http://directwebremoting.org/schema/dwr20.dtd\">\n<dwr></dwr>"); } catch (IOException io) { log.error("Unable to clear out the " + dwrFile.getAbsolutePath() + " file. Please redeploy the openmrs war file", io); } finally { if (writer != null) { try { writer.close(); } catch (IOException io) { log.warn("Couldn't close Writer: " + io); } } } } }