List of usage examples for org.xml.sax EntityResolver EntityResolver
EntityResolver
From source file:org.apache.ojb.broker.ant.DdlUtilsDataHandling.java
/** * Creates a new data handling object.//from w ww. j a va 2 s.co m */ public DdlUtilsDataHandling() { _digester = new Digester(); _digester.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) { // we don't care about the DTD for data files return new InputSource(new StringReader("")); } }); _digester.setNamespaceAware(true); _digester.setValidating(false); _digester.setUseContextClassLoader(true); _digester.setRules(new ExtendedBaseRules()); _digester.addRuleSet(new DataRuleSet()); }
From source file:org.codehaus.enunciate.modules.BasicAppModule.java
/** * Loads the node model for merging xml. * * @param inputStream The input stream of the xml. * @return The node model./*from w ww. ja va 2s. co m*/ */ protected Document loadMergeXml(InputStream inputStream) throws EnunciateException { Document doc; try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(false); //no namespace for the merging... builderFactory.setValidating(false); DocumentBuilder builder = builderFactory.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { //we don't want to validate or parse external dtds... return new InputSource(new StringReader("")); } }); doc = builder.parse(inputStream); } catch (Exception e) { throw new EnunciateException("Error parsing web.xml file for merging", e); } return doc; }
From source file:org.codehaus.enunciate.modules.docs.DocumentationDeploymentModule.java
private NodeModel loadNodeModel(File xml) throws EnunciateException { Document doc;// w w w. j a va 2s. c om try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(false); builderFactory.setValidating(false); DocumentBuilder builder = builderFactory.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { //we don't want to validate or parse external dtds... return new InputSource(new StringReader("")); } }); doc = builder.parse(new FileInputStream(xml)); } catch (Exception e) { throw new EnunciateException("Error parsing " + xml, e); } NodeModel.simplify(doc); return NodeModel.wrap(doc.getDocumentElement()); }
From source file:org.cruxframework.crux.core.declarativeui.ViewProcessor.java
/** * Initializes the static resources//from www.j a v a 2 s . c o m */ private static void init() { if (documentBuilder == null) { lock.lock(); if (documentBuilder == null) { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); builderFactory.setIgnoringComments(true); builderFactory.setIgnoringElementContentWhitespace(true); documentBuilder = builderFactory.newDocumentBuilder(); documentBuilder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId.contains("crux-view.dtd")) { return new InputSource(new ByteArrayInputStream(getValidEntities().getBytes())); } else { return null; } } private String getValidEntities() { StringBuffer sb = new StringBuffer(); sb.append("<!ENTITY quot \""\">"); sb.append("<!ENTITY amp \"&\">"); sb.append("<!ENTITY apos \"'\">"); sb.append("<!ENTITY lt \"<\">"); sb.append("<!ENTITY gt \">\">"); sb.append("<!ENTITY nbsp \" \">"); return sb.toString(); } }); initializePreProcessors(); } catch (Throwable e) { log.error("Error initializing cruxToHtmlTransformer.", e); } finally { lock.unlock(); } } } }
From source file:org.cruxframework.crux.core.rebind.module.ModulesScanner.java
/** * //from w ww . jav a2 s . c o m */ private ModulesScanner() { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); this.documentBuilder = documentBuilderFactory.newDocumentBuilder(); this.documentBuilder.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId.contains("gwt-module.dtd")) { return new InputSource( new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes())); } else { return null; } } }); } catch (ParserConfigurationException e) { throw new ModuleException("Error creating modules scanner. Can not create builder object.", e); } catch (Exception e) { throw new ModuleException("Can not find the web classes dir.", e); } }
From source file:org.gudy.azureus2.pluginsimpl.local.utils.xml.simpleparser.SimpleXMLParserDocumentImpl.java
private void createSupport(InputStream input_stream) throws SimpleXMLParserDocumentException { try {//from w ww . ja v a2 s . com 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.hyperic.hq.product.server.session.PluginManagerImpl.java
private Document getDocument(Reader reader, final Map<String, Reader> xmlReaders) throws JDOMException, IOException { final SAXBuilder builder = new SAXBuilder(); builder.setEntityResolver(new EntityResolver() { // systemId = file:///pdk/plugins/process-metrics.xml public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { final File entity = new File(systemId); for (final Entry<String, Reader> entry : xmlReaders.entrySet()) { final String filename = entry.getKey(); if (entity.getAbsolutePath().contains(filename)) { return new InputSource(entry.getValue()); }/*from w w w. j a v a2s. c om*/ } final String filename = entity.getName().replaceAll(AGENT_PLUGIN_DIR, ""); File file = new File(getCustomPluginDir(), filename); if (!file.exists()) { file = new File(getServerPluginDir(), filename); } return (file.exists()) ? new InputSource(file.toURI().toString()) : new InputSource(xmlReaders.get(filename)); } }); return builder.build(reader); }
From source file:org.java.plugin.registry.xml.ManifestParser.java
private static EntityResolver getDtdEntityResolver() { return new EntityResolver() { public InputSource resolveEntity(final String publicId, final String systemId) { if (publicId == null) { log.debug("can't resolve entity, public ID is NULL, systemId=" + systemId); //$NON-NLS-1$ return null; }// ww w.java 2 s . c o m if (PLUGIN_DTD_1_0 == null) { return null; } if (publicId.equals("-//JPF//Java Plug-in Manifest 1.0") //$NON-NLS-1$ || publicId.equals("-//JPF//Java Plug-in Manifest 0.7") //$NON-NLS-1$ || publicId.equals("-//JPF//Java Plug-in Manifest 0.6") //$NON-NLS-1$ || publicId.equals("-//JPF//Java Plug-in Manifest 0.5") //$NON-NLS-1$ || publicId.equals("-//JPF//Java Plug-in Manifest 0.4") //$NON-NLS-1$ || publicId.equals("-//JPF//Java Plug-in Manifest 0.3") //$NON-NLS-1$ || publicId.equals("-//JPF//Java Plug-in Manifest 0.2")) { //$NON-NLS-1$ if (log.isDebugEnabled()) { log.debug("entity resolved to plug-in manifest DTD, publicId=" //$NON-NLS-1$ + publicId + ", systemId=" + systemId); //$NON-NLS-1$ } return new InputSource(new StringReader(PLUGIN_DTD_1_0)); } if (log.isDebugEnabled()) { log.debug("entity not resolved, publicId=" //$NON-NLS-1$ + publicId + ", systemId=" + systemId); //$NON-NLS-1$ } return null; } }; }
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. ja v a2 s . co 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// www . ja va 2s . 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()); } }