List of usage examples for org.xml.sax EntityResolver EntityResolver
EntityResolver
From source file:edu.ku.brc.specify.tools.AppendHelp.java
/** * Reads a DOM from a stream//from ww w.jav a2s. c o m * @param fileinputStream the stream to be read * @return the root element of the DOM */ public Element readFileToDOM4J(final File file) throws IOException, DocumentException { SAXReader saxReader = new SAXReader(); try { saxReader.setValidation(false); saxReader.setStripWhitespaceText(true); //saxReader.setIncludeExternalDTDDeclarations(false); //saxReader.setIncludeInternalDTDDeclarations(false); saxReader.setIgnoreComments(true); //saxReader.setXMLFilter(new TransparentFilter(saxReader.getXMLReader())); EntityResolver entityResolver = new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) { return new InputSource(""); } }; saxReader.setEntityResolver(entityResolver); //saxReader.getXMLFilter().setDTDHandler(null); } catch (Exception ex) { ex.printStackTrace(); } org.dom4j.Document document = saxReader.read(new FileInputStream(file)); return document.getRootElement(); }
From source file:com.microsoft.windowsazure.messaging.Registration.java
/** * Creates an XML representation of the Registration * @throws Exception/* ww w. ja v a 2 s .com*/ */ String toXml() throws Exception { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return null; } }); Document doc = builder.newDocument(); Element entry = doc.createElement("entry"); entry.setAttribute("xmlns", "http://www.w3.org/2005/Atom"); doc.appendChild(entry); appendNodeWithValue(doc, entry, "id", getURI()); appendNodeWithValue(doc, entry, "updated", getUpdatedString()); appendContentNode(doc, entry); return getXmlString(doc.getDocumentElement()); }
From source file:com.sap.prd.mobile.ios.mios.xcodeprojreader.jaxb.JAXBPlistParser.java
private SAXSource createSAXSource(InputSource project, final InputSource dtd) throws SAXException, ParserConfigurationException { XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); xmlReader.setEntityResolver(new EntityResolver() { @Override// w ww . j a v a 2s.c o m public InputSource resolveEntity(String pid, String sid) throws SAXException { if (sid.equals("http://www.apple.com/DTDs/PropertyList-1.0.dtd")) return dtd; throw new SAXException("unable to resolve remote entity, sid = " + sid); } }); SAXSource ss = new SAXSource(xmlReader, project); return ss; }
From source file:com.firegnom.valkyrie.map.tiled.TiledZoneLoader.java
@Override public Zone load(String name) { long startTime, stopTime; try {/*from w w w .j a v a 2s . c o m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new ByteArrayInputStream(new byte[0])); } }); startTime = System.currentTimeMillis(); // map version JSONObject obj; int version = 0; try { obj = new JSONObject(convertStreamToString(rl.getResourceAsStreamDownload(name + ".json"))); version = obj.getInt("version"); } catch (JSONException e) { throw new ValkyrieRuntimeException(e); } InputStream inputStream = new GZIPInputStream( rl.getResourceAsStream(name + "-ver_" + version + ".tmx.gz", true)); Document doc = builder.parse(inputStream); Element docElement = doc.getDocumentElement(); stopTime = System.currentTimeMillis(); Log.d(TAG, "Loaded Zone tmx file in in :" + ((stopTime - startTime) / 1000) + " secondsand " + ((stopTime - startTime) % 1000) + " miliseconds"); System.gc(); String orient = docElement.getAttribute("orientation"); if (!orient.equals("orthogonal")) { throw new TiledLoaderException("Only orthogonal maps supported, found: " + orient); } int width = Integer.parseInt(docElement.getAttribute("width")); int height = Integer.parseInt(docElement.getAttribute("height")); int tileWidth = Integer.parseInt(docElement.getAttribute("tilewidth")); int tileHeight = Integer.parseInt(docElement.getAttribute("tileheight")); Zone zone = new Zone(name, width, height, tileWidth, tileHeight); // now read the map properties startTime = System.currentTimeMillis(); getZoneProperties(zone, docElement); stopTime = System.currentTimeMillis(); Log.d(TAG, "Loaded Zone Properties in in :" + ((stopTime - startTime) / 1000) + " secondsand " + ((stopTime - startTime) % 1000) + " miliseconds"); System.gc(); startTime = System.currentTimeMillis(); StringTileSet tileSet = null; NodeList setNodes = docElement.getElementsByTagName("tileset"); int i; for (i = 0; i < setNodes.getLength(); i++) { Element current = (Element) setNodes.item(i); tileSet = getTileSet(zone, current, c); tileSet.index = i; Log.d(TAG, "Adding tileset to zone tilestets firstGID =" + tileSet.firstGID + ",lastGID=" + tileSet.lastGID + ", name=" + tileSet.imageName); zone.tileSets.add(tileSet.firstGID, tileSet.lastGID, tileSet); } stopTime = System.currentTimeMillis(); Log.d("performance", "Loaded Zone tilesets in in :" + ((stopTime - startTime) / 1000) + " secondsand " + ((stopTime - startTime) % 1000) + " miliseconds"); System.gc(); startTime = System.currentTimeMillis(); NodeList layerNodes = docElement.getElementsByTagName("layer"); Element current; for (i = 0; i < layerNodes.getLength(); i++) { current = (Element) layerNodes.item(i); Layer layer = getLayer(zone, current); layer.index = i; zone.layers.add(layer); } stopTime = System.currentTimeMillis(); Log.d(TAG, "Loaded Zone Layers in in :" + ((stopTime - startTime) / 1000) + " secondsand " + ((stopTime - startTime) % 1000) + " miliseconds"); NodeList objectGroupNodes = docElement.getElementsByTagName("objectgroup"); for (i = 0; i < objectGroupNodes.getLength(); i++) { current = (Element) objectGroupNodes.item(i); if (current.getAttribute("name").equals("_ContextActions")) { zone.contextActions = getActionIndex(current); } else { appendMapObjects(current, zone.mapObjects); } } System.gc(); return zone; } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:mx.itesm.mexadl.metrics.util.Util.java
/** * Transform a logging report from XML to HTML format. * //from w ww. ja va 2 s . co m * @param xmlFile * @param xsltFile * @param outputFile * @param componentTypes * @throws TransformerException * @throws SAXException * @throws IOException */ public static void transformXMLReport2Html(final File xmlFile, final InputStream xsltFile, final File outputFile, final Map<String, String> componentTypes) throws TransformerException, SAXException, IOException { Source xmlSource; Source xsltSource; Result outputTarget; XMLReader xmlReader; String reportContents; Transformer transformer; // Blank reader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId.endsWith(".dtd")) { StringReader stringInput = new StringReader(" "); return new InputSource(stringInput); } else { return null; // use default behavior } } }); xmlSource = new SAXSource(xmlReader, new InputSource(new FileInputStream(xmlFile))); xsltSource = new StreamSource(xsltFile); outputTarget = new StreamResult(outputFile); // Generate output file transformer = transformerFactory.newTransformer(xsltSource); transformer.transform(xmlSource, outputTarget); // Add components type information reportContents = FileUtils.readFileToString(outputFile, "UTF-8"); for (String componentType : componentTypes.keySet()) { reportContents = reportContents.replace("[ " + componentType + " ]", componentTypes.get(componentType)); } FileUtils.writeStringToFile(outputFile, reportContents); }
From source file:com.gargoylesoftware.htmlunit.xml.XmlUtil.java
/** * Builds a document from the content of the web response. * A warning is logged if an exception is thrown while parsing the XML content * (for instance when the content is not a valid XML and can't be parsed). * * @param webResponse the response from the server * @throws IOException if the page could not be created * @return the parse result/* w w w .j av a 2s .c o m*/ * @throws SAXException if the parsing fails * @throws ParserConfigurationException if a DocumentBuilder cannot be created */ public static Document buildDocument(final WebResponse webResponse) throws IOException, SAXException, ParserConfigurationException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); if (webResponse == null) { return factory.newDocumentBuilder().newDocument(); } factory.setNamespaceAware(true); final InputStreamReader reader = new InputStreamReader(webResponse.getContentAsStream(), webResponse.getContentCharset()); // we have to do the blank input check and the parsing in one step final TrackBlankContentReader tracker = new TrackBlankContentReader(reader); final InputSource source = new InputSource(tracker); final DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(DISCARD_MESSAGES_HANDLER); builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(final String publicId, final String systemId) throws SAXException, IOException { return new InputSource(new StringReader("")); } }); try { return builder.parse(source); } catch (final SAXException e) { if (tracker.wasBlank()) { return factory.newDocumentBuilder().newDocument(); } throw e; } }
From source file:com.mgmtp.jfunk.data.generator.Generator.java
public void parseXml(final IndexedFields theIndexedFields) throws IOException, JDOMException { this.indexedFields = theIndexedFields; final String generatorFile = configuration.get(GeneratorConstants.GENERATOR_CONFIG_FILE); if (StringUtils.isBlank(generatorFile)) { LOGGER.info("No generator configuration file found"); return;//from www . j a v a 2s . c om } SAXBuilder builder = new SAXBuilder(); builder.setValidation(true); builder.setIgnoringElementContentWhitespace(false); builder.setFeature("http://apache.org/xml/features/validation/schema/normalized-value", false); builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(final String publicId, final String systemId) throws IOException { String resolvedSystemId = configuration.processPropertyValue(systemId); URI uri = URI.create(resolvedSystemId); File file = uri.isAbsolute() ? toFile(uri.toURL()) : new File(uri.toString()); return new InputSource(ResourceLoader.getBufferedReader(file, Charsets.UTF_8.name())); } }); InputStream in = ResourceLoader.getConfigInputStream(generatorFile); Document doc = null; try { String systemId = ResourceLoader.getConfigDir() + '/' + removeExtension(generatorFile) + ".dtd"; doc = builder.build(in, systemId); Element root = doc.getRootElement(); Element charsetsElement = root.getChild(XMLTags.CHARSETS); @SuppressWarnings("unchecked") List<Element> charsetElements = charsetsElement.getChildren(XMLTags.CHARSET); for (Element element : charsetElements) { CharacterSet.initCharacterSet(element); } @SuppressWarnings("unchecked") List<Element> constraintElements = root.getChild(XMLTags.CONSTRAINTS).getChildren(XMLTags.CONSTRAINT); constraints = Lists.newArrayListWithExpectedSize(constraintElements.size()); for (Element element : constraintElements) { constraints.add(constraintFactory.createModel(random, element)); } } finally { closeQuietly(in); } LOGGER.info("Generator was successfully initialized"); }
From source file:de.ingrid.portal.interfaces.impl.WMSInterfaceImpl.java
/** * @see de.ingrid.portal.interfaces.WMSInterface#getWMSServices(java.lang.String) *///from ww w . ja v a 2s . com 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:com.google.code.docbook4j.renderer.BaseRenderer.java
public InputStream render() throws Docbook4JException { assertNotNull(xmlResource, "Value of the xml source should be not null!"); FileObject xsltResult = null; FileObject xmlSourceFileObject = null; FileObject xslSourceFileObject = null; FileObject userConfigXmlSourceFileObject = null; try {/*from w ww .ja va 2 s . c o m*/ xmlSourceFileObject = FileObjectUtils.resolveFile(xmlResource); if (xslResource != null) { xslSourceFileObject = FileObjectUtils.resolveFile(xslResource); } else { xslSourceFileObject = getDefaultXslStylesheet(); } if (userConfigXmlResource != null) { userConfigXmlSourceFileObject = FileObjectUtils.resolveFile(userConfigXmlResource); } SAXParserFactory factory = createParserFactory(); final XMLReader reader = factory.newSAXParser().getXMLReader(); EntityResolver resolver = new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { log.debug("Resolving file {}", systemId); FileObject inc = FileObjectUtils.resolveFile(systemId); return new InputSource(inc.getContent().getInputStream()); } }; // prepare xml sax source ExpressionEvaluatingXMLReader piReader = new ExpressionEvaluatingXMLReader(reader, vars); piReader.setEntityResolver(resolver); SAXSource source = new SAXSource(piReader, new InputSource(xmlSourceFileObject.getContent().getInputStream())); source.setSystemId(xmlSourceFileObject.getURL().toExternalForm()); // prepare xslt result xsltResult = FileObjectUtils.resolveFile("tmp://" + UUID.randomUUID().toString()); xsltResult.createFile(); // create transofrmer and do transformation final Transformer transformer = createTransformer(xmlSourceFileObject, xslSourceFileObject); transformer.transform(source, new StreamResult(xsltResult.getContent().getOutputStream())); // do post processing FileObject target = postProcess(xmlSourceFileObject, xslSourceFileObject, xsltResult, userConfigXmlSourceFileObject); FileObjectUtils.closeFileObjectQuietly(xsltResult); FileObjectUtils.closeFileObjectQuietly(target); return target.getContent().getInputStream(); } catch (FileSystemException e) { throw new Docbook4JException("Error transofrming xml!", e); } catch (SAXException e) { throw new Docbook4JException("Error transofrming xml!", e); } catch (ParserConfigurationException e) { throw new Docbook4JException("Error transofrming xml!", e); } catch (TransformerException e) { throw new Docbook4JException("Error transofrming xml!", e); } catch (IOException e) { throw new Docbook4JException("Error transofrming xml !", e); } finally { FileObjectUtils.closeFileObjectQuietly(xmlSourceFileObject); FileObjectUtils.closeFileObjectQuietly(xslSourceFileObject); } }
From source file:de.tudarmstadt.ukp.dkpro.wsd.senseval.reader.SensevalReader.java
@Override public void initialize(UimaContext context) throws ResourceInitializationException { super.initialize(context); textCount = 0;//from ww w. j av a2 s . co m // EntityResolver resolver = new EntityResolver() { // public InputSource resolveEntity(String publicId, String systemId) { // try { // URL url; // if (publicId == null) { // url = ResourceUtils.resolveLocation(systemId, this, null); // } // else { // url = ResourceUtils.resolveLocation(publicId, this, null); // } // return new InputSource(url.openStream()); // } catch (IOException e) { // e.printStackTrace(); // return null; // } // } // }; Document documentCollection = null; SAXReader reader = new SAXReader(); // TODO: We can't figure out how to get the XML parser to read DTDs in // all cases (i.e., whether they are in a directory or in a JAR) so the // following code just forces the SAXReader to ignore DTDs. This is // not an optimal solution as it prevents the XML files from being // validated. EntityResolver resolver = new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) { return new InputSource(new StringReader("")); } }; reader.setEntityResolver(resolver); InputStream is = null; try { fileURL = ResourceUtils.resolveLocation(fileName, this, context); is = fileURL.openStream(); // The following line fails on Jenkins but not locally // documentCollection = reader.read(fileURL.getFile()); documentCollection = reader.read(is); } catch (DocumentException e) { throw new ResourceInitializationException(e); } catch (IOException e) { throw new ResourceInitializationException(e); } finally { IOUtils.closeQuietly(is); } // Get the (root) corpus element so we can iterate over its elements corpus = documentCollection.getRootElement(); if (corpus.getName().equals(CORPUS_ELEMENT_NAME) == false) { throw new ResourceInitializationException("unknown_element", new Object[] { corpus.getName() }); } }