1 11 package org.eclipse.core.internal.content; 12 13 import java.io.IOException ; 14 import java.io.StringReader ; 15 import javax.xml.parsers.*; 16 import org.xml.sax.*; 17 import org.xml.sax.ext.LexicalHandler ; 18 import org.xml.sax.helpers.DefaultHandler ; 19 20 30 public final class XMLRootHandler extends DefaultHandler implements LexicalHandler { 31 37 private class StopParsingException extends SAXException { 38 41 private static final long serialVersionUID = 1L; 42 43 47 public StopParsingException() { 48 super((String ) null); 49 } 50 } 51 52 55 private boolean checkRoot; 56 61 private String dtdFound = null; 62 67 private String elementFound = null; 68 69 public XMLRootHandler(boolean checkRoot) { 70 this.checkRoot = checkRoot; 71 } 72 73 78 public final void comment(final char[] ch, final int start, final int length) { 79 } 81 82 98 private final SAXParser createParser(SAXParserFactory parserFactory) throws ParserConfigurationException, SAXException, SAXNotRecognizedException, SAXNotSupportedException { 99 final SAXParser parser = parserFactory.newSAXParser(); 101 final XMLReader reader = parser.getXMLReader(); 102 reader.setProperty("http://xml.org/sax/properties/lexical-handler", this); try { 105 reader.setFeature("http://xml.org/sax/features/validation", false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } catch (SAXNotRecognizedException e) { 109 } catch (SAXNotSupportedException e) { 111 } 113 return parser; 114 } 115 116 121 public final void endCDATA() { 122 } 124 125 130 public final void endDTD() { 131 } 133 134 139 public final void endEntity(final String name) { 140 } 142 143 public String getDTD() { 144 return dtdFound; 145 } 146 147 public String getRootName() { 148 return elementFound; 149 } 150 151 public boolean parseContents(InputSource contents) throws IOException , ParserConfigurationException, SAXException { 152 try { 154 SAXParserFactory factory = Activator.getDefault().getFactory(); 155 if (factory == null) 156 return false; 157 final SAXParser parser = createParser(factory); 158 contents.setSystemId("/"); parser.parse(contents, this); 161 } catch (StopParsingException e) { 162 } 164 return true; 165 } 166 167 173 public InputSource resolveEntity(String publicId, String systemId) throws SAXException { 174 return new InputSource(new StringReader ("")); } 176 177 182 public final void startCDATA() { 183 } 185 186 192 public final void startDTD(final String name, final String publicId, final String systemId) throws SAXException { 193 dtdFound = systemId; 194 if (!checkRoot) 196 throw new StopParsingException(); 197 } 198 199 205 public final void startElement(final String uri, final String elementName, final String qualifiedName, final Attributes attributes) throws SAXException { 206 elementFound = elementName; 207 throw new StopParsingException(); 208 } 209 210 215 public final void startEntity(final String name) { 216 } 218 } 219 | Popular Tags |