1 55 package org.apache.avalon.framework.configuration; 56 57 import java.io.File ; 58 import java.io.IOException ; 59 import java.io.InputStream ; 60 import javax.xml.parsers.SAXParser ; 61 import javax.xml.parsers.SAXParserFactory ; 62 import org.xml.sax.InputSource ; 63 import org.xml.sax.SAXException ; 64 import org.xml.sax.XMLReader ; 65 66 105 public class DefaultConfigurationBuilder 106 { 107 private SAXConfigurationHandler m_handler; 108 private XMLReader m_parser; 109 110 116 public DefaultConfigurationBuilder() 117 { 118 this( false ); 119 } 120 121 130 public DefaultConfigurationBuilder( final boolean enableNamespaces ) 131 { 132 try 134 { 135 final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); 136 137 if( enableNamespaces ) 138 { 139 saxParserFactory.setNamespaceAware( true ); 140 } 141 142 final SAXParser saxParser = saxParserFactory.newSAXParser(); 143 this.setParser( saxParser.getXMLReader() ); 144 } 145 catch( final Exception se ) 146 { 147 throw new Error ( "Unable to setup SAX parser" + se ); 148 } 149 } 150 151 155 public DefaultConfigurationBuilder( XMLReader parser ) 156 { 157 this.setParser( parser ); 158 } 159 160 163 private void setParser( XMLReader parser ) 164 { 165 m_parser = parser; 166 167 m_handler = getHandler(); 168 169 m_parser.setContentHandler( m_handler ); 170 m_parser.setErrorHandler( m_handler ); 171 } 172 173 177 protected SAXConfigurationHandler getHandler() 178 { 179 try 180 { 181 if( m_parser.getFeature( "http://xml.org/sax/features/namespaces" ) ) 182 { 183 return new NamespacedSAXConfigurationHandler(); 184 } 185 } 186 catch( Exception e ) 187 { 188 } 190 191 return new SAXConfigurationHandler(); 192 } 193 194 202 public Configuration buildFromFile( final String filename ) 203 throws SAXException , IOException , ConfigurationException 204 { 205 return buildFromFile( new File ( filename ) ); 206 } 207 208 216 public Configuration buildFromFile( final File file ) 217 throws SAXException , IOException , ConfigurationException 218 { 219 synchronized( this ) 220 { 221 m_handler.clear(); 222 m_parser.parse( file.toURL().toString() ); 223 return m_handler.getConfiguration(); 224 } 225 } 226 227 235 public Configuration build( final InputStream inputStream ) 236 throws SAXException , IOException , ConfigurationException 237 { 238 return build( new InputSource ( inputStream ) ); 239 } 240 241 249 public Configuration build( final String uri ) 250 throws SAXException , IOException , ConfigurationException 251 { 252 return build( new InputSource ( uri ) ); 253 } 254 255 263 public Configuration build( final InputSource input ) 264 throws SAXException , IOException , ConfigurationException 265 { 266 synchronized( this ) 267 { 268 m_handler.clear(); 269 m_parser.parse( input ); 270 return m_handler.getConfiguration(); 271 } 272 } 273 } 274 | Popular Tags |