Java Code Examples for org.xml.sax.XMLReader

The following examples show how to use org.xml.sax.XMLReader. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: uima-uimaj   Source File: UIMAFramework_impl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parses the factoryConfig.xml file and sets up the ResourceFactory, ResourceSpecifierFactory,
 * and XMLParser.
 * 
 * @throws ParserConfigurationException
 *           if the XML parser could not be configured
 * @throws SAXException
 *           if factoryConfig.xml could not be parsed
 * @throws ClassNotFoundException -
 * @throws IllegalAccessException -
 * @throws InstantiationException -
 * @throws IOException -
 */
protected void parseFactoryConfig() throws ParserConfigurationException, SAXException,
        IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
  FactoryConfigParseHandler handler = new FactoryConfigParseHandler();
  // TOOD: Need UtilityClassLoader here? I don't think we do; this works
  // with XML4J v3. This is a good thing, since the UtilityClassLoader writes
  // to the logger, which isn't created yet!

  SAXParserFactory factory = XMLUtils.createSAXParserFactory();
  SAXParser parser = factory.newSAXParser();
  XMLReader reader = parser.getXMLReader();

  reader.setContentHandler(handler);
  reader.setErrorHandler(handler);
  reader
          .parse(new InputSource(UIMAFramework_impl.class
                  .getResourceAsStream("factoryConfig.xml")));
}
 
Example 2
Source Project: jdk8u60   Source File: DTMManagerDefault.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method returns the SAX2 parser to use with the InputSource
 * obtained from this URI.
 * It may return null if any SAX2-conformant XML parser can be used,
 * or if getInputSource() will also return null. The parser must
 * be free for use (i.e., not currently in use for another parse().
 * After use of the parser is completed, the releaseXMLReader(XMLReader)
 * must be called.
 *
 * @param inputSource The value returned from the URIResolver.
 * @return  a SAX2 XMLReader to use to resolve the inputSource argument.
 *
 * @return non-null XMLReader reference ready to parse.
 */
synchronized public XMLReader getXMLReader(Source inputSource)
{

  try
  {
    XMLReader reader = (inputSource instanceof SAXSource)
                       ? ((SAXSource) inputSource).getXMLReader() : null;

    // If user did not supply a reader, ask for one from the reader manager
    if (null == reader) {
      if (m_readerManager == null) {
          m_readerManager = XMLReaderManager.getInstance(super.useServicesMechnism());
      }

      reader = m_readerManager.getXMLReader();
    }

    return reader;

  } catch (SAXException se) {
    throw new DTMException(se.getMessage(), se);
  }
}
 
Example 3
Source Project: spring-analysis-note   Source File: Jaxb2Marshaller.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")  // on JDK 9
private Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException {
	if (logger.isDebugEnabled()) {
		logger.debug("Setting validation schema to " +
				StringUtils.arrayToCommaDelimitedString(this.schemaResources));
	}
	Assert.notEmpty(resources, "No resources given");
	Assert.hasLength(schemaLanguage, "No schema language provided");
	Source[] schemaSources = new Source[resources.length];
	XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
	xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
	for (int i = 0; i < resources.length; i++) {
		Resource resource = resources[i];
		Assert.isTrue(resource != null && resource.exists(), () -> "Resource does not exist: " + resource);
		InputSource inputSource = SaxResourceUtils.createInputSource(resource);
		schemaSources[i] = new SAXSource(xmlReader, inputSource);
	}
	SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
	if (this.schemaResourceResolver != null) {
		schemaFactory.setResourceResolver(this.schemaResourceResolver);
	}
	return schemaFactory.newSchema(schemaSources);
}
 
Example 4
Source Project: openjdk-jdk9   Source File: TrAXFilter.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void parse (InputSource input) throws SAXException, IOException
{
    XMLReader managedReader = null;

    try {
        if (getParent() == null) {
            try {
                managedReader = XMLReaderManager.getInstance(_useServicesMechanism)
                                                .getXMLReader();
                setParent(managedReader);
            } catch (SAXException  e) {
                throw new SAXException(e.toString());
            }
        }

        // call parse on the parent
        getParent().parse(input);
    } finally {
        if (managedReader != null) {
            XMLReaderManager.getInstance(_useServicesMechanism).releaseXMLReader(managedReader);
        }
    }
}
 
Example 5
/**
 * This method returns the SAX2 parser to use with the InputSource
 * obtained from this URI.
 * It may return null if any SAX2-conformant XML parser can be used,
 * or if getInputSource() will also return null. The parser must
 * be free for use (i.e., not currently in use for another parse().
 * After use of the parser is completed, the releaseXMLReader(XMLReader)
 * must be called.
 *
 * @param inputSource The value returned from the URIResolver.
 * @return  a SAX2 XMLReader to use to resolve the inputSource argument.
 *
 * @return non-null XMLReader reference ready to parse.
 */
synchronized public XMLReader getXMLReader(Source inputSource)
{

  try
  {
    XMLReader reader = (inputSource instanceof SAXSource)
                       ? ((SAXSource) inputSource).getXMLReader() : null;

    // If user did not supply a reader, ask for one from the reader manager
    if (null == reader) {
      if (m_readerManager == null) {
          m_readerManager = XMLReaderManager.getInstance(super.overrideDefaultParser());
      }

      reader = m_readerManager.getXMLReader();
    }

    return reader;

  } catch (SAXException se) {
    throw new DTMException(se.getMessage(), se);
  }
}
 
Example 6
Source Project: hadoop-gpu   Source File: HftpFileSystem.java    License: Apache License 2.0 6 votes vote down vote up
private void fetchList(String path, boolean recur) throws IOException {
  try {
    XMLReader xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    HttpURLConnection connection = openConnection("/listPaths" + path,
        "ugi=" + ugi + (recur? "&recursive=yes" : ""));
    connection.setRequestMethod("GET");
    connection.connect();

    InputStream resp = connection.getInputStream();
    xr.parse(new InputSource(resp));
  } catch(SAXException e) {
    final Exception embedded = e.getException();
    if (embedded != null && embedded instanceof IOException) {
      throw (IOException)embedded;
    }
    throw new IOException("invalid xml directory content", e);
  }
}
 
Example 7
Source Project: openjdk-8   Source File: UnmarshallerImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public <T> JAXBElement<T> unmarshal( Source source, Class<T> expectedType ) throws JAXBException {
    if (source instanceof SAXSource) {
        SAXSource ss = (SAXSource) source;

        XMLReader locReader = ss.getXMLReader();
        if (locReader == null) {
            locReader = getXMLReader();
        }

        return unmarshal(locReader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
        return unmarshal(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) {
        return unmarshal(((DOMSource) source).getNode(), expectedType);
    }

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example 8
Source Project: tomcatsrc   Source File: Digester.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return the XMLReader to be used for parsing the input document.
 *
 * FIX ME: there is a bug in JAXP/XERCES that prevent the use of a 
 * parser that contains a schema with a DTD.
 * @exception SAXException if no XMLReader can be instantiated
 */
public XMLReader getXMLReader() throws SAXException {
    if (reader == null){
        reader = getParser().getXMLReader();
    }        
                           
    reader.setDTDHandler(this);           
    reader.setContentHandler(this);        
    
    if (entityResolver == null){
        reader.setEntityResolver(this);
    } else {
        reader.setEntityResolver(entityResolver);           
    }
    
    reader.setProperty(
            "http://xml.org/sax/properties/lexical-handler", this);

    reader.setErrorHandler(this);
    return reader;
}
 
Example 9
Source Project: openjdk-jdk9   Source File: SAXTFactoryTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Unit test for TemplatesHandler setter/getter.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase13() throws Exception {
    String outputFile = USER_DIR + "saxtf013.out";
    String goldFile = GOLDEN_DIR + "saxtf013GF.out";
    try(FileInputStream fis = new FileInputStream(XML_FILE)) {
        // The transformer will use a SAX parser as it's reader.
        XMLReader reader = XMLReaderFactory.createXMLReader();

        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory) TransformerFactory.newInstance();
        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        // I have put this as it was complaining about systemid
        thandler.setSystemId("file:///" + USER_DIR);

        reader.setContentHandler(thandler);
        reader.parse(XSLT_FILE);
        XMLFilter filter
                = saxTFactory.newXMLFilter(thandler.getTemplates());
        filter.setParent(reader);

        filter.setContentHandler(new MyContentHandler(outputFile));
        filter.parse(new InputSource(fis));
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 10
public Object unmarshal0( Source source, JaxBeanInfo expectedType ) throws JAXBException {
    if (source instanceof SAXSource) {
        SAXSource ss = (SAXSource) source;

        XMLReader locReader = ss.getXMLReader();
        if (locReader == null) {
            locReader = getXMLReader();
        }

        return unmarshal0(locReader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
        return unmarshal0(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) {
        return unmarshal0(((DOMSource) source).getNode(), expectedType);
    }

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example 11
Source Project: spotbugs   Source File: Filter.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Parse and load the given filter file.
 *
 * @param fileName
 *            name of the filter file
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private void parse(String fileName, @WillClose InputStream stream) throws IOException, SAXException, ParserConfigurationException {
    try {
        SAXBugCollectionHandler handler = new SAXBugCollectionHandler(this, new File(fileName));
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        parserFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", Boolean.TRUE);
        parserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
        parserFactory.setFeature("http://xml.org/sax/features/external-general-entities", Boolean.FALSE);
        parserFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE);
        SAXParser parser = parserFactory.newSAXParser();
        XMLReader xr = parser.getXMLReader();
        xr.setContentHandler(handler);
        xr.setErrorHandler(handler);
        Reader reader = Util.getReader(stream);
        xr.parse(new InputSource(reader));
    } finally {
        Util.closeSilently(stream);
    }
}
 
Example 12
Source Project: arctic-sea   Source File: XmlToExiConverter.java    License: Apache License 2.0 6 votes vote down vote up
protected void decode(String fileName) {
        try (InputStream exiIS = FileUtils.openInputStream(getFile(fileName, EXI_EXTENSION));
                OutputStream os = FileUtils.openOutputStream(getFile(fileName, XML_EXTENSION_2))) {

            Reader reader = new InputStreamReader(exiIS,"ISO-8859-1");
            InputSource is = new InputSource(reader);
            is.setEncoding("ISO-8859-1");

            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();

            EXISource exiSource = new EXISource();
            XMLReader exiReader = exiSource.getXMLReader();
            SAXSource saxSource = new SAXSource(is);
//            SAXSource saxSource = new SAXSource(new InputSource(exiIS));
            exiSource.setXMLReader(exiReader);
            transformer.transform(saxSource, new StreamResult(os));
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }
    }
 
Example 13
public void testLegacy() throws Exception {
    ClassLoader clBackup = Thread.currentThread().getContextClassLoader();
    try {
        URL[] classUrls = { LEGACY_DIR.toUri().toURL() };
        URLClassLoader loader = new URLClassLoader(classUrls, ClassLoader.getSystemClassLoader().getParent());

        // set TCCL and try locating the provider
        Thread.currentThread().setContextClassLoader(loader);
        XMLReader reader1 = XMLReaderFactory.createXMLReader();
        assertEquals(reader1.getClass().getName(), "xp3.XMLReaderImpl");

        // now point to a random URL
        Thread.currentThread().setContextClassLoader(
                new URLClassLoader(new URL[0], ClassLoader.getSystemClassLoader().getParent()));
        // ClassNotFoundException if also trying to load class of reader1, which
        // would be the case before 8152912
        XMLReader reader2 = XMLReaderFactory.createXMLReader();
        assertEquals(reader2.getClass().getName(), "com.sun.org.apache.xerces.internal.parsers.SAXParser");
    } finally {
        Thread.currentThread().setContextClassLoader(clBackup);
    }
}
 
Example 14
Source Project: openjdk-jdk8u   Source File: Parser.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parses a stylesheet and builds the internal abstract syntax tree
 * @param input A SAX2 InputSource can be passed to a SAX reader
 * @return The root of the abstract syntax tree
 */
public SyntaxTreeNode parse(InputSource input) {
    final XMLReader reader = JdkXmlUtils.getXMLReader(_overrideDefaultParser,
            _xsltc.isSecureProcessing());

    JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, XMLConstants.ACCESS_EXTERNAL_DTD,
            _xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD), true);

    String lastProperty = "";
    try {
        XMLSecurityManager securityManager =
                (XMLSecurityManager) _xsltc.getProperty(XalanConstants.SECURITY_MANAGER);
        for (XMLSecurityManager.Limit limit : XMLSecurityManager.Limit.values()) {
            lastProperty = limit.apiProperty();
            reader.setProperty(lastProperty, securityManager.getLimitValueAsString(limit));
        }
        if (securityManager.printEntityCountInfo()) {
            lastProperty = XalanConstants.JDK_ENTITY_COUNT_INFO;
            reader.setProperty(XalanConstants.JDK_ENTITY_COUNT_INFO, XalanConstants.JDK_YES);
        }
    } catch (SAXException se) {
        XMLSecurityManager.printWarning(reader.getClass().getName(), lastProperty, se);
    }

    return (parse(reader, input));
}
 
Example 15
Source Project: openjdk-8   Source File: DTMManagerDefault.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method returns the SAX2 parser to use with the InputSource
 * obtained from this URI.
 * It may return null if any SAX2-conformant XML parser can be used,
 * or if getInputSource() will also return null. The parser must
 * be free for use (i.e., not currently in use for another parse().
 * After use of the parser is completed, the releaseXMLReader(XMLReader)
 * must be called.
 *
 * @param inputSource The value returned from the URIResolver.
 * @return  a SAX2 XMLReader to use to resolve the inputSource argument.
 *
 * @return non-null XMLReader reference ready to parse.
 */
synchronized public XMLReader getXMLReader(Source inputSource)
{

  try
  {
    XMLReader reader = (inputSource instanceof SAXSource)
                       ? ((SAXSource) inputSource).getXMLReader() : null;

    // If user did not supply a reader, ask for one from the reader manager
    if (null == reader) {
      if (m_readerManager == null) {
          m_readerManager = XMLReaderManager.getInstance(super.useServicesMechnism());
      }

      reader = m_readerManager.getXMLReader();
    }

    return reader;

  } catch (SAXException se) {
    throw new DTMException(se.getMessage(), se);
  }
}
 
Example 16
Source Project: uPods-android   Source File: BackendManager.java    License: Apache License 2.0 6 votes vote down vote up
public ArrayList<Episode> fetchEpisodes(String feedUrl, Podcast podcast) {
    try {
        Request request = new Request.Builder().url(feedUrl).build();
        String response = BackendManager.getInstance().sendSimpleSynchronicRequest(request);
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        EpisodesXMLHandler episodesXMLHandler = new EpisodesXMLHandler();
        xr.setContentHandler(episodesXMLHandler);

        //TODO could be encoding problem
        InputSource inputSource = new InputSource(new StringReader(response));
        xr.parse(inputSource);
        ArrayList<Episode> parsedEpisodes = episodesXMLHandler.getParsedEpisods();
        if (podcast != null) {
            podcast.setDescription(episodesXMLHandler.getPodcastSummary());
        }
        return parsedEpisodes;
    } catch (Exception e) {
        Logger.printError(TAG, "Can't fetch episodes for url: " + feedUrl);
        e.printStackTrace();
        return new ArrayList<Episode>();
    }
}
 
Example 17
Source Project: uPods-android   Source File: HelpFunctions.java    License: Apache License 2.0 5 votes vote down vote up
public static ArrayList<Episode> parseEpisodes(String url) throws Exception {
    Request episodesRequest = new Request.Builder().url(url).build();
    String response = BackendManager.getInstance().sendSimpleSynchronicRequest(episodesRequest);
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();
    EpisodesXMLHandler episodesXMLHandler = new EpisodesXMLHandler();
    xr.setContentHandler(episodesXMLHandler);
    InputSource inputSource = new InputSource(new StringReader(response));
    xr.parse(inputSource);
    return episodesXMLHandler.getParsedEpisods();
}
 
Example 18
Source Project: openjdk-jdk9   Source File: XMLReaderTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * No NPE expected when set error handler as null.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void errorhandler02() throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    XMLReader xmlReader = spf.newSAXParser().getXMLReader();
    xmlReader.setErrorHandler(null);
}
 
Example 19
Source Project: openjdk-jdk8u   Source File: ModelLoader.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parses a RELAX NG grammar into an annotated grammar.
 */
private Model loadRELAXNG() throws SAXException {

    // build DOM forest
    final DOMForest forest = buildDOMForest( new RELAXNGInternalizationLogic() );

    // use JAXP masquerading to validate the input document.
    // DOMForest -> ExtensionBindingChecker -> RNGOM

    XMLReaderCreator xrc = new XMLReaderCreator() {
        public XMLReader createXMLReader() {

            // foreset parser cannot change the receivers while it's working,
            // so we need to have one XMLFilter that works as a buffer
            XMLFilter buffer = new XMLFilterImpl() {
                @Override
                public void parse(InputSource source) throws IOException, SAXException {
                    forest.createParser().parse( source, this, this, this );
                }
            };

            XMLFilter f = new ExtensionBindingChecker(Const.RELAXNG_URI,opt,errorReceiver);
            f.setParent(buffer);

            f.setEntityResolver(opt.entityResolver);

            return f;
        }
    };

    Parseable p = new SAXParseable( opt.getGrammars()[0], errorReceiver, xrc );

    return loadRELAXNG(p);

}
 
Example 20
Source Project: ontopia   Source File: XTMSnifferContentHandler.java    License: Apache License 2.0 5 votes vote down vote up
public XTMSnifferContentHandler(XTMTopicMapReader reader,
                                TopicMapStoreFactoryIF store_factory,
                                XMLReader parser,
                                LocatorIF base_address) {
  this.reader = reader;
  this.store_factory = store_factory;
  this.parser = parser;
  this.base_address = base_address;
  this.entities = new HashMap();
}
 
Example 21
Source Project: cuba   Source File: Dom4j.java    License: Apache License 2.0 5 votes vote down vote up
public static SAXParser getParser() {
    SAXParser parser;
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(false);
    XMLReader xmlReader;
    try {
        parser = factory.newSAXParser();
        xmlReader = parser.getXMLReader();
    } catch (ParserConfigurationException | SAXException e) {
        throw new RuntimeException("Unable to create SAX parser", e);
    }

    setParserFeature(xmlReader, "http://xml.org/sax/features/namespaces", true);
    setParserFeature(xmlReader, "http://xml.org/sax/features/namespace-prefixes", false);

    // external entites
    setParserFeature(xmlReader, "http://xml.org/sax/properties/external-general-entities", false);
    setParserFeature(xmlReader, "http://xml.org/sax/properties/external-parameter-entities", false);

    // external DTD
    setParserFeature(xmlReader, "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    // use Locator2 if possible
    setParserFeature(xmlReader, "http://xml.org/sax/features/use-locator2", true);

    return parser;
}
 
Example 22
Source Project: TencentKona-8   Source File: JdkXmlUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private static XMLReader getXMLReaderWXMLReaderFactory() {
    try {
        return org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
    } catch (SAXException ex1) {
    }
    return null;
}
 
Example 23
Source Project: blog-codes   Source File: ExportServlet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Renders the XML to the given canvas.
 */
protected void renderXml(String xml, mxICanvas2D canvas) throws SAXException, ParserConfigurationException, IOException
{
	XMLReader reader = parserFactory.newSAXParser().getXMLReader();
	reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
	reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
	reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
	reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
	reader.setContentHandler(new mxSaxOutputHandler(canvas));
	reader.parse(new InputSource(new StringReader(xml)));
}
 
Example 24
Source Project: netbeans   Source File: XMLMIMEComponent.java    License: Apache License 2.0 5 votes vote down vote up
protected XMLReader createXMLReader() {
    XMLReader parser = null;
    
    try {
        parser = XMLUtil.createXMLReader(false, true);           
        try {
            parser.setProperty("http://xml.org/sax/properties/lexical-handler", this);  //NOI18N
        } catch (SAXException sex) {
            Logger.getLogger(XMLMIMEComponent.class.getName()).fine(NbBundle.getMessage(XMLMIMEComponent.class, "W-003"));  //NOI18N
        }
    } catch (SAXException ex) {
        Logger.getLogger(XMLMIMEComponent.class.getName()).log(Level.WARNING, null, ex);
    }
    return parser;
}
 
Example 25
Source Project: tomcatsrc   Source File: NodeCreateRule.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Implemented to replace the content handler currently in use by a 
 * NodeBuilder.
 * 
 * @param namespaceURI the namespace URI of the matching element, or an 
 *   empty string if the parser is not namespace aware or the element has
 *   no namespace
 * @param name the local name if the parser is namespace aware, or just 
 *   the element name otherwise
 * @param attributes The attribute list of this element
 * @throws Exception indicates a JAXP configuration problem
 */
@Override
public void begin(String namespaceURI, String name, Attributes attributes)
    throws Exception {

    XMLReader xmlReader = getDigester().getXMLReader();
    Document doc = documentBuilder.newDocument();
    NodeBuilder builder = null;
    if (nodeType == Node.ELEMENT_NODE) {
        Element element = null;
        if (getDigester().getNamespaceAware()) {
            element =
                doc.createElementNS(namespaceURI, name);
            for (int i = 0; i < attributes.getLength(); i++) {
                element.setAttributeNS(attributes.getURI(i),
                                       attributes.getLocalName(i),
                                       attributes.getValue(i));
            }
        } else {
            element = doc.createElement(name);
            for (int i = 0; i < attributes.getLength(); i++) {
                element.setAttribute(attributes.getQName(i),
                                     attributes.getValue(i));
            }
        }
        builder = new NodeBuilder(doc, element);
    } else {
        builder = new NodeBuilder(doc, doc.createDocumentFragment());
    }
    xmlReader.setContentHandler(builder);

}
 
Example 26
Source Project: SVG2Drawable   Source File: SVGParser.java    License: Apache License 2.0 5 votes vote down vote up
public static void getSVGFromInputStream(String packageName, String className, InputStream svgData) throws Exception {

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        SVGHandler handler = new SVGHandler(packageName, className);
        xr.setContentHandler(handler);
        xr.parse(new InputSource(svgData));
        handler.drawInstructions.print();
    }
 
Example 27
Source Project: lucene-solr   Source File: PatternParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a SAX parser using JAXP
 * 
 * @return the created SAX parser
 */
static XMLReader createParser() {
  try {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    return factory.newSAXParser().getXMLReader();
  } catch (Exception e) {
    throw new RuntimeException("Couldn't create XMLReader: " + e.getMessage());
  }
}
 
Example 28
Source Project: jdk8u60   Source File: SAXParseable.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static InputSource makeInputSource(XMLReader xr, String systemId) throws IOException, SAXException {
  EntityResolver er = xr.getEntityResolver();
  if (er != null) {
    InputSource inputSource = er.resolveEntity(null, systemId);
    if (inputSource != null)
  return inputSource;
  }
  return new InputSource(systemId);
}
 
Example 29
Source Project: buck   Source File: PositionXmlParser.java    License: Apache License 2.0 5 votes vote down vote up
@NonNull
private static Document parse(@NonNull String xml, @NonNull InputSource input, boolean checkBom,
                              boolean checkDtd)
        throws ParserConfigurationException, SAXException, IOException {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        if (checkDtd) {
            factory.setFeature(NAMESPACE_FEATURE, true);
            factory.setFeature(NAMESPACE_PREFIX_FEATURE, true);
            factory.setFeature(PROVIDE_XMLNS_URIS, true);
        } else {
            factory.setFeature(LOAD_EXTERNAL_DTD, false);
        }
        SAXParser parser = factory.newSAXParser();
        DomBuilder handler = new DomBuilder(xml);
        XMLReader xmlReader = parser.getXMLReader();
        xmlReader.setProperty(
                "http://xml.org/sax/properties/lexical-handler",
                handler
        );
        parser.parse(input, handler);
        return handler.getDocument();
    } catch (SAXException e) {
        if (checkBom && e.getMessage().contains("Content is not allowed in prolog")) {
            // Byte order mark in the string? Skip it. There are many markers
            // (see http://en.wikipedia.org/wiki/Byte_order_mark) so here we'll
            // just skip those up to the XML prolog beginning character, <
            xml = xml.replaceFirst("^([\\W]+)<","<");  //$NON-NLS-1$ //$NON-NLS-2$
            return parse(xml, new InputSource(new StringReader(xml)), false, checkDtd);
        }
        throw e;
    }
}
 
Example 30
Source Project: vi   Source File: Analyzer.java    License: Apache License 2.0 5 votes vote down vote up
public static PomInfo readPom(InputStream is) throws SAXException, IOException {

        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,true);
        PomDependencyHandler handler = new PomDependencyHandler();
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(is));
        return handler.getPomInfo();
    }