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: openjdk-jdk10   File: SAXTFactoryTest.java   View source code 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 2
Project: lams   File: JspDocumentParser.java   View source code 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 3
Project: poiji   File: XSSFUnmarshaller.java   View source code 7 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 4
Project: MakiLite   File: RssReader.java   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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));
}