1 7 8 package org.dom4j.io; 9 10 import org.xml.sax.SAXException ; 11 import org.xml.sax.SAXNotRecognizedException ; 12 import org.xml.sax.SAXNotSupportedException ; 13 import org.xml.sax.XMLReader ; 14 import org.xml.sax.helpers.XMLReaderFactory ; 15 16 25 class SAXHelper { 26 private static boolean loggedWarning = true; 27 28 protected SAXHelper() { 29 } 30 31 public static boolean setParserProperty(XMLReader reader, 32 String propertyName, Object value) { 33 try { 34 reader.setProperty(propertyName, value); 35 36 return true; 37 } catch (SAXNotSupportedException e) { 38 } catch (SAXNotRecognizedException e) { 40 } 42 43 return false; 44 } 45 46 public static boolean setParserFeature(XMLReader reader, 47 String featureName, boolean value) { 48 try { 49 reader.setFeature(featureName, value); 50 51 return true; 52 } catch (SAXNotSupportedException e) { 53 } catch (SAXNotRecognizedException e) { 55 } 57 58 return false; 59 } 60 61 73 public static XMLReader createXMLReader(boolean validating) 74 throws SAXException { 75 XMLReader reader = null; 76 77 if (reader == null) { 78 reader = createXMLReaderViaJAXP(validating, true); 79 } 80 81 if (reader == null) { 82 try { 83 reader = XMLReaderFactory.createXMLReader(); 84 } catch (Exception e) { 85 if (isVerboseErrorReporting()) { 86 System.out.println("Warning: Caught exception attempting " 89 + "to use SAX to load a SAX XMLReader "); 90 System.out.println("Warning: Exception was: " + e); 91 System.out 92 .println("Warning: I will print the stack trace " 93 + "then carry on using the default " 94 + "SAX parser"); 95 e.printStackTrace(); 96 } 97 98 throw new SAXException (e); 99 } 100 } 101 102 if (reader == null) { 103 throw new SAXException ("Couldn't create SAX reader"); 104 } 105 106 return reader; 107 } 108 109 121 protected static XMLReader createXMLReaderViaJAXP(boolean validating, 122 boolean namespaceAware) { 123 try { 125 return JAXPHelper.createXMLReader(validating, namespaceAware); 126 } catch (Throwable e) { 127 if (!loggedWarning) { 128 loggedWarning = true; 129 130 if (isVerboseErrorReporting()) { 131 System.out.println("Warning: Caught exception attempting " 134 + "to use JAXP to load a SAX XMLReader"); 135 System.out.println("Warning: Exception was: " + e); 136 e.printStackTrace(); 137 } 138 } 139 } 140 141 return null; 142 } 143 144 protected static boolean isVerboseErrorReporting() { 145 try { 146 String flag = System.getProperty("org.dom4j.verbose"); 147 148 if ((flag != null) && flag.equalsIgnoreCase("true")) { 149 return true; 150 } 151 } catch (Exception e) { 152 } 155 156 return true; 157 } 158 } 159 160 196 | Popular Tags |