Java Code Examples for org.xml.sax.XMLReader

The following are top voted examples for showing how to use org.xml.sax.XMLReader. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: poiji   File: XSSFUnmarshaller.java   Source Code and License 8 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> List<T> processSheet(StylesTable styles, ReadOnlySharedStringsTable readOnlySharedStringsTable,
                                 Class<T> type, InputStream sheetInputStream) {

    DataFormatter formatter = new DataFormatter();
    InputSource sheetSource = new InputSource(sheetInputStream);
    try {
        XMLReader sheetParser = SAXHelper.newXMLReader();
        PoijiHandler poijiHandler = new PoijiHandler(type, options);
        ContentHandler contentHandler =
                new XSSFSheetXMLHandler(styles, null, readOnlySharedStringsTable, poijiHandler, formatter, false);
        sheetParser.setContentHandler(contentHandler);
        sheetParser.parse(sheetSource);
        return poijiHandler.getDataset();
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new PoijiException("Problem occurred while reading data", e);
    }
}
 
Example 2
Project: openjdk-jdk10   File: SAXTFactoryTest.java   Source Code and License 8 votes vote down vote up
/**
 * Test newTransformerHandler with a Template Handler.
 *
 * @throws Exception If any errors occur.
 */
public void testcase08() throws Exception {
    String outputFile = USER_DIR + "saxtf008.out";
    String goldFile = GOLDEN_DIR + "saxtf008GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory)TransformerFactory.newInstance();

        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        reader.setContentHandler(thandler);
        reader.parse(XSLT_FILE);
        TransformerHandler tfhandler
                = saxTFactory.newTransformerHandler(thandler.getTemplates());

        Result result = new StreamResult(fos);
        tfhandler.setResult(result);

        reader.setContentHandler(tfhandler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 3
Project: lams   File: JspDocumentParser.java   Source Code and License 8 votes vote down vote up
private static SAXParser getSAXParser(
    boolean validating,
    JspDocumentParser jspDocParser)
    throws Exception {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);

    // Preserve xmlns attributes
    factory.setFeature(
        "http://xml.org/sax/features/namespace-prefixes",
        true);
    factory.setValidating(validating);
    //factory.setFeature(
    //    "http://xml.org/sax/features/validation",
    //    validating);
    
    // Configure the parser
    SAXParser saxParser = factory.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    xmlReader.setProperty(LEXICAL_HANDLER_PROPERTY, jspDocParser);
    xmlReader.setErrorHandler(jspDocParser);

    return saxParser;
}
 
Example 4
Project: MakiLite   File: RssReader.java   Source Code and License 7 votes vote down vote up
public static RssFeed read(InputStream stream) throws SAXException, IOException {

        try {

            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();
            RssHandler handler = new RssHandler();
            InputSource input = new InputSource(stream);

            reader.setContentHandler(handler);
            reader.parse(input);

            return handler.getResult();

        } catch (ParserConfigurationException e) {
            throw new SAXException();
        }

    }
 
Example 5
Project: powertext   File: SyntaxScheme.java   Source Code and License 7 votes vote down vote up
public static SyntaxScheme load(Font baseFont, InputStream in)
		throws IOException {
	SyntaxSchemeLoader parser = null;
	try {
		XMLReader reader = XMLReaderFactory.createXMLReader();
		parser = new SyntaxSchemeLoader(baseFont);
		parser.baseFont = baseFont;
		reader.setContentHandler(parser);
		InputSource is = new InputSource(in);
		is.setEncoding("UTF-8");
		reader.parse(is);
	} catch (SAXException se) {
		throw new IOException(se.toString());
	}
	return parser.scheme;
}
 
Example 6
Project: mobile-store   File: RepoDetails.java   Source Code and License 7 votes vote down vote up
@NonNull
public static RepoDetails getFromFile(InputStream inputStream, int pushRequests) {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        RepoDetails repoDetails = new RepoDetails();
        MockRepo mockRepo = new MockRepo(100, pushRequests);
        RepoXMLHandler handler = new RepoXMLHandler(mockRepo, repoDetails);
        reader.setContentHandler(handler);
        InputSource is = new InputSource(new BufferedInputStream(inputStream));
        reader.parse(is);
        return repoDetails;
    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
        fail();

        // Satisfies the compiler, but fail() will always throw a runtime exception so we never
        // reach this return statement.
        return null;
    }
}
 
Example 7
Project: openjdk-jdk10   File: AstroProcessor.java   Source Code and License 6 votes vote down vote up
private XMLReader getXMLReader() throws Exception {
    SAXParser parser = spf.newSAXParser();
    parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    parser.setProperty(JAXP_SCHEMA_SOURCE, "catalog.xsd");
    XMLReader catparser = parser.getXMLReader();
    catparser.setErrorHandler(new CatalogErrorHandler());
    return catparser;
}
 
Example 8
Project: TuLiPA-frames   File: TransformPolarity.java   Source Code and License 6 votes vote down vote up
public void xsltprocess(String[] args) throws TransformerException, TransformerConfigurationException, FileNotFoundException, IOException {
    // 1. Instantiate a TransformerFactory.
    SAXTransformerFactory tFactory = (SAXTransformerFactory) TransformerFactory.newInstance();
    
    // 2. Use the TransformerFactory to process the stylesheet Source and
    //    generate a Transformer.
    InputStream is = getClass().getResourceAsStream("xmg2pol.xsl");
    Transformer transformer = tFactory.newTransformer (new StreamSource(is));
    transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "polarities.dtd,xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    
    // 3. Use the Transformer to transform an XML Source and send the
    //    output to a Result object.
    try {
	    String input = args[0];
	    String output= args[1];
	    SAXSource saxs = new SAXSource(new InputSource(input));
		XMLReader saxReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
		saxReader.setEntityResolver(new MyEntityResolver());
		saxs.setXMLReader(saxReader);
	    transformer.transform(saxs, new StreamResult(new OutputStreamWriter(new FileOutputStream(output), "utf-8")));
   	} catch (Exception e) {
   		e.printStackTrace();
   	}
}
 
Example 9
Project: openjdk-jdk10   File: SAXTFactoryTest.java   Source Code and License 6 votes vote down vote up
/**
 * Unit test for contentHandler setter/getter.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase12() throws Exception {
    String outputFile = USER_DIR + "saxtf012.out";
    String goldFile = GOLDEN_DIR + "saxtf012GF.out";
    // The transformer will use a SAX parser as it's reader.
    XMLReader reader = XMLReaderFactory.createXMLReader();

    InputSource is = new InputSource(new FileInputStream(XSLT_FILE));
    SAXSource saxSource = new SAXSource();
    saxSource.setInputSource(is);

    SAXTransformerFactory saxTFactory = (SAXTransformerFactory)TransformerFactory.newInstance();
    XMLFilter filter = saxTFactory.newXMLFilter(saxSource);

    filter.setParent(reader);
    filter.setContentHandler(new MyContentHandler(outputFile));

    // Now, when you call transformer.parse, it will set itself as
    // the content handler for the parser object (it's "parent"), and
    // will then call the parse method on the parser.
    filter.parse(new InputSource(XML_FILE));
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 10
Project: ExcelKit   File: XlsxReader.java   Source Code and License 6 votes vote down vote up
private void processAll(OPCPackage pkg)
		throws IOException, OpenXML4JException, InvalidFormatException, SAXException {
	XSSFReader xssfReader = new XSSFReader(pkg);
	mStylesTable = xssfReader.getStylesTable();
	SharedStringsTable sst = xssfReader.getSharedStringsTable();
	XMLReader parser = this.fetchSheetParser(sst);
	Iterator<InputStream> sheets = xssfReader.getSheetsData();
	while (sheets.hasNext()) {
		mCurrentRowIndex = 0;
		mSheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
	pkg.close();
}
 
Example 11
Project: incubator-netbeans   File: LibrarySupport.java   Source Code and License 6 votes vote down vote up
private Map<String,Map<String,List<Map<String,String>>>> getItems () {
    if (items == null)
        try {
            XMLReader reader = XMLUtil.createXMLReader ();
            Handler handler = new Handler ();
            reader.setEntityResolver (handler);
            reader.setContentHandler (handler);
            ClassLoader loader = (ClassLoader) Lookup.getDefault ().
                lookup (ClassLoader.class);
            InputStream is = loader.getResourceAsStream (resourceName);
            try {
                reader.parse (new InputSource (is));
            } finally {
                is.close ();
            }
            items = handler.result;
        } catch (Exception ex) {
            ErrorManager.getDefault ().notify (ex);
            items = Collections.<String,Map<String,List<Map<String,String>>>> emptyMap ();
        }
    return items;
}
 
Example 12
Project: openjdk-jdk10   File: Parser.java   Source Code and License 6 votes vote down vote up
@Override
public GraphDocument parse() throws IOException {
    if (monitor != null) {
        monitor.setState("Starting parsing");
    }
    try {
        XMLReader reader = createReader();
        reader.setContentHandler(new XMLParser(xmlDocument, monitor));
        reader.parse(new InputSource(Channels.newInputStream(channel)));
    } catch (SAXException ex) {
        if (!(ex instanceof SAXParseException) || !"XML document structures must start and end within the same entity.".equals(ex.getMessage())) {
            throw new IOException(ex);
        }
    }
    if (monitor != null) {
        monitor.setState("Finished parsing");
    }
    return graphDocument;
}
 
Example 13
Project: openjdk-jdk10   File: XMLReaderNSTableTest.java   Source Code and License 6 votes vote down vote up
/**
 * Namespace processing is enabled. Hence namespace-prefix is
 * expected to be automatically off. So it is a True-False combination.
 * The test is to test XMLReader with these conditions.
 *
 * @throws Exception If any errors occur.
 */
public void testWithTrueFalse() throws Exception {
    String outputFile = USER_DIR + "XRNSTableTF.out";
    String goldFile = GOLDEN_DIR + "NSTableTFGF.out";

    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    SAXParser saxParser = spf.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();

    try (FileInputStream fis = new FileInputStream(xmlFile);
        MyNSContentHandler handler = new MyNSContentHandler(outputFile)) {
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(fis));
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 14
Project: openjdk-jdk10   File: CDataChunkSizeTest.java   Source Code and License 6 votes vote down vote up
@Test(dataProvider = "xml-data")
public void testSAX(String xml, int chunkSize, int numOfChunks, boolean withinLimit) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    XMLReader reader = spf.newSAXParser().getXMLReader();
    MyHandler handler = new MyHandler(chunkSize);
    reader.setContentHandler(handler);
    reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

    if (chunkSize > 0) {
        reader.setProperty(CDATA_CHUNK_SIZE, chunkSize);
    }

    reader.parse(new InputSource(new StringReader(xml)));
    System.out.println("CData num of chunks:" + handler.getNumOfCDataChunks());
    System.out.println("CData size within limit:" + handler.chunkSizeWithinLimit());
    Assert.assertEquals(handler.getNumOfCDataChunks(), numOfChunks);
    Assert.assertEquals(handler.chunkSizeWithinLimit(), withinLimit);

}
 
Example 15
Project: openjdk-jdk10   File: ContentHandlerTest.java   Source Code and License 6 votes vote down vote up
/**
 * Content event handler visit all nodes to print to output file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase01() throws Exception {
    String outputFile = USER_DIR + "Content.out";
    String goldFile = GOLDEN_DIR + "ContentGF.out";
    String xmlFile = XML_DIR + "namespace1.xml";

    try(FileInputStream instream = new FileInputStream(xmlFile);
            MyContentHandler cHandler = new MyContentHandler(outputFile)) {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        XMLReader xmlReader = spf.newSAXParser().getXMLReader();
        xmlReader.setContentHandler(cHandler);
        xmlReader.parse(new InputSource(instream));
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 16
Project: AdronEngine   File: TMXLoader.java   Source Code and License 6 votes vote down vote up
/**
 * Reads XML file from assets and returns a TileMapData structure describing its contents
 *
 * @param	filename	path to the file in assets
 * @param	c			context of the application to resolve assets folder
 * @return				data structure containing map data
 */
public static TileMapData readTMX(String filename, Context c){
    TileMapData t = null;

    // Initialize SAX
    try{

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser parser = spf.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        // Create an instance of the TMX XML handler
        // that will create a TileMapData object
        TMXHandler handler = new TMXHandler();

        reader.setContentHandler(handler);

        AssetManager assetManager = c.getAssets();

        reader.parse((new InputSource(assetManager.open(filename))));

        // Extract the created object
        t = handler.getData();


    } catch(ParserConfigurationException pce) {
        Log.e("SAX XML", "sax parse error", pce);
    } catch(SAXException se) {
        Log.e("SAX XML", "sax error", se);
    } catch(IOException ioe) {
        Log.e("SAX XML", "sax parse io error", ioe);
    }finally{

    }


    return t;
}
 
Example 17
Project: OpenJSharp   File: DTMManagerDefault.java   Source Code and License 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 18
Project: iBase4J-Common   File: Excel2007Reader.java   Source Code and License 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @param filename string
 * @throws Exception  if an error occurred
 */
public void process(String filename) throws Exception {
	OPCPackage pkg = OPCPackage.open(filename);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);
	Iterator<InputStream> sheets = r.getSheetsData();
	while (sheets.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
}
 
Example 19
Project: iBase4J-Common   File: Excel2007Reader.java   Source Code and License 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @param stream
 * @throws Exception if an error occurred
 */
public void process(InputStream stream) throws Exception {
	OPCPackage pkg = OPCPackage.open(stream);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);
	Iterator<InputStream> sheets = r.getSheetsData();
	while (sheets.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
}
 
Example 20
Project: Aequorea   File: HtmlTagHandler.java   Source Code and License 6 votes vote down vote up
private void startTag(String tag, Editable out, XMLReader reader) {
    switch (tag.toLowerCase()) {
        case "ul":
            list.push(true);
            out.append('\n');
            break;
        case "ol":
            list.push(false);
            out.append('\n');
            break;
        case "pre":
            break;
        default:
            break;
    }
}
 
Example 21
Project: automat   File: Excel2007Reader.java   Source Code and License 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @param filename
 * @throws Exception
 */
public void process(String filename) throws Exception {
	OPCPackage pkg = OPCPackage.open(filename);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);
	Iterator<InputStream> sheets = r.getSheetsData();
	while (sheets.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
}
 
Example 22
Project: openjdk-jdk10   File: SAXTFactoryTest.java   Source Code and License 6 votes vote down vote up
/**
 * SAXTFactory.newTransformerhandler() method which takes SAXSource as
 * argument can be set to XMLReader. SAXSource has input XML file as its
 * input source. XMLReader has a content handler which write out the result
 * to output file. Test verifies output file is same as golden file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase02() throws Exception {
    String outputFile = USER_DIR + "saxtf002.out";
    String goldFile = GOLDEN_DIR + "saxtf002GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile);
            FileInputStream fis = new FileInputStream(XSLT_FILE)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory) TransformerFactory.newInstance();
        SAXSource ss = new SAXSource();
        ss.setInputSource(new InputSource(fis));

        TransformerHandler handler = saxTFactory.newTransformerHandler(ss);
        Result result = new StreamResult(fos);
        handler.setResult(result);
        reader.setContentHandler(handler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 23
Project: tomcat7   File: Digester.java   Source Code and License 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 24
Project: apache-tomcat-7.0.73-with-comment   File: Digester.java   Source Code and License 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 25
Project: OpenJSharp   File: UnmarshallerImpl.java   Source Code and License 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 26
Project: bdf2   File: XSSFParser.java   Source Code and License 6 votes vote down vote up
public void execute(InputStream inputStream, IParseExcelRowMapper parseExcelRowMapper) throws Exception {
	OPCPackage pkg = OPCPackage.open(inputStream);
	XSSFReader xssfReader = new XSSFReader(pkg);
	sst = xssfReader.getSharedStringsTable();
	stylesTable = xssfReader.getStylesTable();

	SAXParserFactory saxFactory = SAXParserFactory.newInstance();
	SAXParser saxParser = saxFactory.newSAXParser();
	XMLReader parser = saxParser.getXMLReader();
	parser.setContentHandler(new XSSFParserHandler());

	this.parseExcelRowMapper = parseExcelRowMapper;

	XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
	while (iter.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = iter.next();
		sheetName = iter.getSheetName();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}

}
 
Example 27
Project: ExcelKit   File: XlsxReader.java   Source Code and License 6 votes vote down vote up
private void processBySheet(int sheetIndex, OPCPackage pkg)
		throws IOException, OpenXML4JException, InvalidFormatException, SAXException {
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();

	XMLReader parser = fetchSheetParser(sst);

	// rId2 found by processing the Workbook
	// 根据 rId# 或 rSheet# 查找sheet
	InputStream sheet = r.getSheet("rId" + (sheetIndex + 1));
	mSheetIndex++;
	InputSource sheetSource = new InputSource(sheet);
	parser.parse(sheetSource);
	sheet.close();
	pkg.close();
}
 
Example 28
Project: jaffa-framework   File: HistoryNav.java   Source Code and License 6 votes vote down vote up
/** This will unmarshal the input XML into a List of FormKey objects.
 * @param historyNavXml The XML representation of the historyNavList.
 * @return The List of FormKey objects.
 */
public static List decode(String historyNavXml) {
    List historyNavList = null;
    try {
        // The following step may seem out of place.
        // And the correct thing to do is to probably do a convertToHtml() on the String returned by the encode() method.
        // However, on a Post, the browser implicitly converts all the entities to corresponding characters.
        // Hence the need for the following step !!
        historyNavXml = StringHelper.replace(historyNavXml, "&", "&amp;");

        if (log.isDebugEnabled())
            log.debug("Unmarshalling the historyNavXml " + historyNavXml);
        XMLReader reader = XMLReaderFactory.createXMLReader();
        HistoryNavHandler handler = new HistoryNavHandler();
        reader.setContentHandler(handler);
        reader.parse(new InputSource(new BufferedReader(new StringReader(historyNavXml))));
        historyNavList = handler.getHistoryNavList();
    } catch (Exception e) {
        if (log.isInfoEnabled())
            log.info("Error while parsing the historyNavXml " + historyNavXml, e);
    }
    if (log.isDebugEnabled())
        log.debug("Unmarshalled List: " + historyNavList);
    return historyNavList;
}
 
Example 29
Project: Equella   File: TextExtracter.java   Source Code and License 6 votes vote down vote up
public void download()
{
	UnicodeReader reader = new UnicodeReader(stream, "UTF-8"); //$NON-NLS-1$
	XMLReader r = new Parser();
	InputSource s = new InputSource();
	s.setCharacterStream(reader);
	try
	{
		r.setContentHandler(this);
		r.parse(s);
	}
	catch( Exception e )
	{
		throw new RuntimeException(e);
	}
}
 
Example 30
Project: Equella   File: ConvertHtmlServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public String modifyXml(Reader reader, HtmlContentHandler writer)
{
	InputSource s = new InputSource();
	s.setEncoding(Constants.UTF8);
	s.setCharacterStream(reader);
	try
	{
		XMLReader r = new Parser();
		r.setContentHandler(writer);
		r.parse(s);
		return writer.getOutput();
	}
	catch( Exception e )
	{
		throw new RuntimeException(e);
	}
}
 
Example 31
Project: Equella   File: ItemConverter.java   Source Code and License 6 votes vote down vote up
private String changeHardcodedUrls(String html, final URL oldUrl, final URL newUrl)
{
	final XMLReader p = new Parser();
	final InputSource s = new InputSource();
	final StringWriter w = new StringWriter();
	final ItemConverterHrefCallback cb = new ItemConverterHrefCallback(oldUrl, newUrl);
	final FindHrefHandler x = new FindHrefHandler(w, cb, true, true);

	p.setContentHandler(x);
	s.setCharacterStream(new StringReader(html));
	try
	{
		p.parse(s);
		if( cb.wasChanged() )
		{
			return w.toString();
		}
		return null;
	}
	catch( Exception e )
	{
		throw new RuntimeException(e);
	}
}
 
Example 32
Project: lams   File: Digester.java   Source Code and License 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.setErrorHandler(this);
    return reader;
}
 
Example 33
Project: gradle-circle-style   File: FindBugsReportHandler.java   Source Code and License 5 votes vote down vote up
@Override
public List<Failure> loadFailures(InputStream report) {
    try {
        FindBugsReportHandler handler = new FindBugsReportHandler();
        XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(report));
        return handler.failures();
    } catch (SAXException | ParserConfigurationException | IOException e) {
        throw new AssertionError(e);
    }
}
 
Example 34
Project: openjdk-jdk10   File: XMLReaderTest.java   Source Code and License 5 votes vote down vote up
/**
 * getFeature returns true if a feature has not been preset when namespace
 * awareness is set.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void featureEGE01() throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    XMLReader xmlReader = spf.newSAXParser().getXMLReader();
    assertTrue(xmlReader.getFeature(EXTERNAL_G_ENTITIES));
}
 
Example 35
Project: iBase4J   File: Excel2007Reader.java   Source Code and License 5 votes vote down vote up
/**
 * 只遍历一个电子表格,其中sheetId为要遍历的sheet索引,从1开始,1-3
 * 
 * @param filename
 * @param sheetId
 * @throws Exception
 */
public void processOneSheet(String filename, int sheetId) throws Exception {
	OPCPackage pkg = OPCPackage.open(filename);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);

	// 根据 rId# 或 rSheet# 查找sheet
	InputStream sheet2 = r.getSheet("rId" + sheetId);
	sheetIndex++;
	InputSource sheetSource = new InputSource(sheet2);
	parser.parse(sheetSource);
	sheet2.close();
}
 
Example 36
Project: q-mail   File: HtmlConverter.java   Source Code and License 5 votes vote down vote up
@Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
    tag = tag.toLowerCase(Locale.US);
    if (tag.equals("hr") && opening) {
        // In the case of an <hr>, replace it with a bunch of underscores. This is roughly
        // the behaviour of Outlook in Rich Text mode.
        output.append("_____________________________________________\r\n");
    } else if (TAGS_WITH_IGNORED_CONTENT.contains(tag)) {
        handleIgnoredTag(opening, output);
    }
}
 
Example 37
Project: incubator-netbeans   File: RSSFeed.java   Source Code and License 5 votes vote down vote up
protected List<FeedItem> buildItemList() throws SAXException, ParserConfigurationException, IOException {
    XMLReader reader = XMLUtil.createXMLReader( false, true );
    FeedHandler handler = new FeedHandler( getMaxItemCount() );
    reader.setContentHandler( handler );
    reader.setEntityResolver( org.openide.xml.EntityCatalog.getDefault() );
    reader.setErrorHandler( new ErrorCatcher() );

    InputSource is = findInputSource(new URL(url));
    reader.parse( is );

    return handler.getItemList();
}
 
Example 38
Project: incubator-netbeans   File: PaletteEnvironmentProvider.java   Source Code and License 5 votes vote down vote up
private XMLReader getXMLReader() throws SAXException {
    XMLReader res = null == cachedReader ? null : cachedReader.get();
    if( null == res ) {
        res = XMLUtil.createXMLReader(true);
        res.setEntityResolver(EntityCatalog.getDefault());
        cachedReader = new WeakReference<XMLReader>(res);
    }
    return res;
}
 
Example 39
Project: incubator-netbeans   File: AutomaticDependencies.java   Source Code and License 5 votes vote down vote up
/**
 * The recognizer entry method taking an InputSource.
 * @param input InputSource to be parsed.
 * @throws IOException on I/O error.
 * @throws SAXException propagated exception thrown by a DocumentHandler.
 */
public void parse(final InputSource input) throws SAXException, IOException {
    XMLReader parser = XMLUtil.createXMLReader(false, false); // fastest mode
    parser.setContentHandler(this);
    parser.setErrorHandler(this);
    parser.setEntityResolver(this);
    parser.parse(input);
}
 
Example 40
Project: openjdk-jdk10   File: XMLReaderTest.java   Source Code and License 5 votes vote down vote up
/**
 * getFeature returns false if a feature has been preset as false when
 * namespace awareness is set.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void featureEPE02() throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    XMLReader xmlReader = spf.newSAXParser().getXMLReader();
    xmlReader.setFeature(EXTERNAL_P_ENTITIES, false);
    assertFalse(xmlReader.getFeature(EXTERNAL_P_ENTITIES));
}
 
Example 41
Project: openjdk-jdk10   File: Bug6509668.java   Source Code and License 5 votes vote down vote up
private XMLReader createXMLReader() throws ParserConfigurationException, SAXException {
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    if (!parserFactory.isNamespaceAware()) {
        parserFactory.setNamespaceAware(true);
    }

    return parserFactory.newSAXParser().getXMLReader();
}
 
Example 42
Project: JAVA-   File: Excel2007Reader.java   Source Code and License 5 votes vote down vote up
/**
 * 只遍历一个电子表格,其中sheetId为要遍历的sheet索引,从1开始,1-3
 * 
 * @param filename
 * @param sheetId
 * @throws Exception
 */
public void processOneSheet(String filename, int sheetId) throws Exception {
	OPCPackage pkg = OPCPackage.open(filename);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);

	// 根据 rId# 或 rSheet# 查找sheet
	InputStream sheet2 = r.getSheet("rId" + sheetId);
	sheetIndex++;
	InputSource sheetSource = new InputSource(sheet2);
	parser.parse(sheetSource);
	sheet2.close();
}
 
Example 43
Project: openjdk-jdk10   File: NSTableTest.java   Source Code and License 5 votes vote down vote up
/**
 * Here namespace processing is disabled. This will make namespace-prefixes
 * enabled. The testcase tests XMLReader for this.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void xrNSTable03() throws Exception {
    XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
    assertFalse(xmlReader.getFeature(NAMESPACES));
    assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES));
}
 
Example 44
Project: openjdk-jdk10   File: Bug4934208.java   Source Code and License 5 votes vote down vote up
private void parse(InputSource is) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(true);
    SAXParser parser = spf.newSAXParser();

    parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
    parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", Bug4934208.class.getResourceAsStream("test.xsd"));

    XMLReader r = parser.getXMLReader();

    r.setErrorHandler(new DraconianErrorHandler());
    r.parse(is);
}
 
Example 45
Project: incubator-netbeans   File: DefaultAttributes.java   Source Code and License 5 votes vote down vote up
/** Starts parsing document - if you have document`s InputStream
 * @param validate
 * @param is document`s InputStream
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException  */
public void parseXML(InputStream is, boolean validate)
throws IOException, SAXException, ParserConfigurationException, FactoryConfigurationError {
    InputSource iSource = new InputSource(is);
    XMLReader parser = getParser(validate);
    parser.parse(iSource);
}
 
Example 46
Project: incubator-netbeans   File: DescriptionReader.java   Source Code and License 5 votes vote down vote up
/**
 * Parse the xml determined by systemId and update the languageData.
 *  @param languageData update the language data by updating/adding mutable
 *   tokenIds. If there is an TokenId element with a name not yet present
 *   in the languageData it will be added. Otherwise the attributes of existing
 *   mutable tokenId will be updated.
 * @throws javax.xml.parsers.SAXException (also encapsulates ParserConfigurationException)
 *   and IOException
 */
public synchronized void applyTo(LanguageData languageData) throws SAXException, IOException {
    
    this.languageData = languageData;

    try {
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        
        processingHiddenTokenTypes = true;
        
        XMLReader reader = parser.getXMLReader();
        reader.setContentHandler(this);
        reader.parse(new InputSource(systemId)); // process hidden token types only
    
        processingHiddenTokenTypes = false;

        reader.parse(new InputSource(systemId)); // process tokenId elements

    } catch (ParserConfigurationException e) {
        throw new SAXException(e);
    }
    
    this.languageData = null;
}
 
Example 47
Project: openjdk-jdk10   File: Sources.java   Source Code and License 5 votes vote down vote up
/**
 * Returns an instance of XMLReader.
 *
 * @return an instance of XMLReader.
 */
private XMLReader getXMLReader() {
    XMLReader reader = null;
    try {
        reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
    } catch (ParserConfigurationException | SAXException ex) {}
    return reader;
}
 
Example 48
Project: OpenJSharp   File: ConfigReader.java   Source Code and License 5 votes vote down vote up
/**
 * Parses an xml config file and returns a Config object.
 *
 * @param xmlFile
 *        The xml config file which is passed by the user to annotation processing
 * @return
 *        A non null Config object
 */
private Config parseAndGetConfig (File xmlFile, ErrorHandler errorHandler, boolean disableSecureProcessing) throws SAXException, IOException {
    XMLReader reader;
    try {
        SAXParserFactory factory = XmlFactory.createParserFactory(disableSecureProcessing);
        reader = factory.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException e) {
        // in practice this will never happen
        throw new Error(e);
    }
    NGCCRuntimeEx runtime = new NGCCRuntimeEx(errorHandler);

    // set up validator
    ValidatorHandler validator = configSchema.newValidator();
    validator.setErrorHandler(errorHandler);

    // the validator will receive events first, then the parser.
    reader.setContentHandler(new ForkContentHandler(validator,runtime));

    reader.setErrorHandler(errorHandler);
    Config config = new Config(runtime);
    runtime.setRootHandler(config);
    reader.parse(new InputSource(xmlFile.toURL().toExternalForm()));
    runtime.reset();

    return config;
}
 
Example 49
Project: mobile-store   File: RepoUpdater.java   Source Code and License 5 votes vote down vote up
public void processDownloadedFile(File downloadedFile) throws UpdateException {
    InputStream indexInputStream = null;
    try {
        if (downloadedFile == null || !downloadedFile.exists()) {
            throw new UpdateException(repo, downloadedFile + " does not exist!");
        }

        // Due to a bug in Android 5.0 Lollipop, the inclusion of spongycastle causes
        // breakage when verifying the signature of the downloaded .jar. For more
        // details, check out https://gitlab.com/fdroid/fdroidclient/issues/111.
        FDroidApp.disableSpongyCastleOnLollipop();

        JarFile jarFile = new JarFile(downloadedFile, true);
        JarEntry indexEntry = (JarEntry) jarFile.getEntry("index.xml");
        indexInputStream = new ProgressBufferedInputStream(jarFile.getInputStream(indexEntry),
                processIndexListener, new URL(repo.address), (int) indexEntry.getSize());

        // Process the index...
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        final SAXParser parser = factory.newSAXParser();
        final XMLReader reader = parser.getXMLReader();
        final RepoXMLHandler repoXMLHandler = new RepoXMLHandler(repo, createIndexReceiver());
        reader.setContentHandler(repoXMLHandler);
        reader.parse(new InputSource(indexInputStream));

        long timestamp = repoDetailsToSave.getAsLong(RepoTable.Cols.TIMESTAMP);
        if (timestamp < repo.timestamp) {
            throw new UpdateException(repo, "index.jar is older that current index! "
                    + timestamp + " < " + repo.timestamp);
        }

        signingCertFromJar = getSigningCertFromJar(indexEntry);

        // JarEntry can only read certificates after the file represented by that JarEntry
        // has been read completely, so verification cannot run until now...
        assertSigningCertFromXmlCorrect();
        commitToDb();
    } catch (SAXException | ParserConfigurationException | IOException e) {
        throw new UpdateException(repo, "Error parsing index", e);
    } finally {
        FDroidApp.enableSpongyCastleOnLollipop();
        Utils.closeQuietly(indexInputStream);
        if (downloadedFile != null) {
            if (!downloadedFile.delete()) {
                Log.w(TAG, "Couldn't delete file: " + downloadedFile.getAbsolutePath());
            }
        }
    }
}
 
Example 50
Project: mobile-store   File: Utils.java   Source Code and License 5 votes vote down vote up
@Override
public void handleTag(boolean opening, String tag, Editable output,
                      XMLReader reader) {
    switch (tag) {
        case "ul":
            if (opening) {
                listNum = -1;
            } else {
                output.append('\n');
            }
            break;
        case "ol":
            if (opening) {
                listNum = 1;
            } else {
                output.append('\n');
            }
            break;
        case "li":
            if (opening) {
                if (listNum == -1) {
                    output.append("\t• ");
                } else {
                    output.append("\t").append(Integer.toString(listNum)).append(". ");
                    listNum++;
                }
            } else {
                output.append('\n');
            }
            break;
    }
}
 
Example 51
Project: Aequorea   File: HtmlTagHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
    if (opening) {
        startTag(tag, output, xmlReader);
        stack.push(output.length());
    } else {
        int len;
        if (stack.isEmpty()) {
            len = 0;
        } else {
            len = stack.pop();
        }
        reallyHandler(len, output.length(), tag.toLowerCase(), output, xmlReader);
    }
}
 
Example 52
Project: Android_Code_Arbiter   File: XmlReaderSafeProperty.java   Source Code and License 5 votes vote down vote up
public static void receiveXMLStreamDoctypeDisabled(final InputStream inStream)
        throws ParserConfigurationException, SAXException, IOException {

    XMLReader reader = XMLReaderFactory.createXMLReader();
    // Secure processing enabled
    reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true);
    reader.setContentHandler(new PrintHandler());
    reader.parse(new InputSource(inStream));
}
 
Example 53
Project: cornerstone   File: Analyzer.java   Source Code and License 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();
    }
 
Example 54
Project: openjdk-jdk10   File: SAXTFactoryTest.java   Source Code and License 5 votes vote down vote up
/**
 * Unit test for contentHandler setter/getter with parent.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase11() throws Exception {
    String outputFile = USER_DIR + "saxtf011.out";
    String goldFile = GOLDEN_DIR + "saxtf011GF.out";
    // The transformer will use a SAX parser as it's reader.
    XMLReader reader = XMLReaderFactory.createXMLReader();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    Document document = docBuilder.parse(new File(XSLT_FILE));
    Node node = (Node)document;
    DOMSource domSource= new DOMSource(node);

    SAXTransformerFactory saxTFactory
            = (SAXTransformerFactory)TransformerFactory.newInstance();
    XMLFilter filter = saxTFactory.newXMLFilter(domSource);

    filter.setParent(reader);
    filter.setContentHandler(new MyContentHandler(outputFile));

    // Now, when you call transformer.parse, it will set itself as
    // the content handler for the parser object (it's "parent"), and
    // will then call the parse method on the parser.
    filter.parse(new InputSource(XML_FILE));
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 55
Project: openjdk-jdk10   File: XMLFilterTest.java   Source Code and License 5 votes vote down vote up
/**
 * By default true is expected get namespaces feature.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void getFeature01() throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    XMLReader xmlReader = spf.newSAXParser().getXMLReader();

    XMLFilterImpl xmlFilter = new XMLFilterImpl();
    xmlFilter.setParent(xmlReader);
    assertTrue(xmlFilter.getFeature(NAMESPACES));
}
 
Example 56
Project: AboutView   File: BaseCustomTagHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void handleTag(boolean opening, String tag, Editable output, Map<String, String> attrs, XMLReader xmlReader) {
    switch (tag){
        case "li":
            if (opening){
                startLi(output, xmlReader);
            }else{
                endLi(output, xmlReader);
            }
            break;
        case "code":
            if (opening){
                startCode(output, xmlReader);
            }else{
                endCode(output, xmlReader);
            }
            break;
        case "ul":
            if (opening){
                startUl(output, xmlReader);
            }else{
                endUl(output, xmlReader);
            }
            break;
        default:
    }
}
 
Example 57
Project: MKAPP   File: ActivitySettings.java   Source Code and License 5 votes vote down vote up
private void xmlImport(InputStream in) throws IOException, SAXException, ParserConfigurationException {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.unregisterOnSharedPreferenceChangeListener(this);
    prefs.edit().putBoolean("enabled", false).apply();
    ServiceSinkhole.stop("import", this);

    XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
    XmlImportHandler handler = new XmlImportHandler(this);
    reader.setContentHandler(handler);
    reader.parse(new InputSource(in));

    xmlImport(handler.application, prefs);
    xmlImport(handler.wifi, getSharedPreferences("wifi", Context.MODE_PRIVATE));
    xmlImport(handler.mobile, getSharedPreferences("other", Context.MODE_PRIVATE));
    xmlImport(handler.screen_wifi, getSharedPreferences("screen_wifi", Context.MODE_PRIVATE));
    xmlImport(handler.screen_other, getSharedPreferences("screen_other", Context.MODE_PRIVATE));
    xmlImport(handler.roaming, getSharedPreferences("roaming", Context.MODE_PRIVATE));
    xmlImport(handler.lockdown, getSharedPreferences("lockdown", Context.MODE_PRIVATE));
    xmlImport(handler.apply, getSharedPreferences("apply", Context.MODE_PRIVATE));
    xmlImport(handler.notify, getSharedPreferences("notify", Context.MODE_PRIVATE));

    // Upgrade imported settings
    Receiver.upgrade(true, this);

    DatabaseHelper.clearCache();

    // Refresh UI
    prefs.edit().putBoolean("imported", true).apply();
    prefs.registerOnSharedPreferenceChangeListener(this);
}
 
Example 58
Project: openjdk-jdk10   File: SAXInputSource.java   Source Code and License 5 votes vote down vote up
public SAXInputSource(XMLReader reader, InputSource inputSource) {
    super(inputSource != null ? inputSource.getPublicId() : null,
            inputSource != null ? inputSource.getSystemId() : null, null,
            false);
    if (inputSource != null) {
        setByteStream(inputSource.getByteStream());
        setCharacterStream(inputSource.getCharacterStream());
        setEncoding(inputSource.getEncoding());
    }
    fInputSource = inputSource;
    fXMLReader = reader;
}
 
Example 59
Project: openjdk-jdk10   File: ConfigReader.java   Source Code and License 5 votes vote down vote up
/**
 * Parses an xml config file and returns a Config object.
 *
 * @param xmlFile
 *        The xml config file which is passed by the user to annotation processing
 * @return
 *        A non null Config object
 */
private Config parseAndGetConfig (File xmlFile, ErrorHandler errorHandler, boolean disableSecureProcessing) throws SAXException, IOException {
    XMLReader reader;
    try {
        SAXParserFactory factory = XmlFactory.createParserFactory(disableSecureProcessing);
        reader = factory.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException e) {
        // in practice this will never happen
        throw new Error(e);
    }
    NGCCRuntimeEx runtime = new NGCCRuntimeEx(errorHandler);

    // set up validator
    ValidatorHandler validator = configSchema.newValidator();
    validator.setErrorHandler(errorHandler);

    // the validator will receive events first, then the parser.
    reader.setContentHandler(new ForkContentHandler(validator,runtime));

    reader.setErrorHandler(errorHandler);
    Config config = new Config(runtime);
    runtime.setRootHandler(config);
    reader.parse(new InputSource(xmlFile.toURL().toExternalForm()));
    runtime.reset();

    return config;
}
 
Example 60
Project: openjdk-jdk10   File: Bug5072946.java   Source Code and License 5 votes vote down vote up
/**
 * Tests if the identity transformer correctly sets the output node.
 */
@Test
public void test2() throws Exception {
    SAXTransformerFactory sf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler th = sf.newTransformerHandler();
    DOMResult r = new DOMResult();
    th.setResult(r);

    XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(th);
    reader.parse(new InputSource(Bug5072946.class.getResourceAsStream("Bug5072946.xml")));

    Assert.assertNotNull(r.getNode());
}