Java Code Examples for org.xml.sax.XMLReader.parse()

The following are Jave code examples for showing how to use parse() of the org.xml.sax.XMLReader class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: mobile-store   File: RepoDetails.java   Source Code and License Vote up 7 votes
@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 2
Project: OpenJSharp   File: XML_SAX_StAX_FI.java   Source Code and License Vote up 7 votes
public void parse(InputStream xml, OutputStream finf, String workingDirectory) throws Exception {
    StAXDocumentSerializer documentSerializer = new StAXDocumentSerializer();
    documentSerializer.setOutputStream(finf);

    SAX2StAXWriter saxTostax = new SAX2StAXWriter(documentSerializer);

    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setNamespaceAware(true);
    SAXParser saxParser = saxParserFactory.newSAXParser();

    XMLReader reader = saxParser.getXMLReader();
    reader.setProperty("http://xml.org/sax/properties/lexical-handler", saxTostax);
    reader.setContentHandler(saxTostax);

    if (workingDirectory != null) {
        reader.setEntityResolver(createRelativePathResolver(workingDirectory));
    }
    reader.parse(new InputSource(xml));

    xml.close();
    finf.close();
}
 
Example 3
Project: oscm   File: ServiceProvisioningServiceBeanImportExportSchemaIT.java   Source Code and License Vote up 6 votes
private void verifyXML(byte[] xml) throws IOException, SAXException,
        ParserConfigurationException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);

    SchemaFactory sf = SchemaFactory
            .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    ClassLoader classLoader = Thread.currentThread()
            .getContextClassLoader();
    if (classLoader == null) {
        classLoader = getClass().getClassLoader();
    }

    final Schema schema;
    try (InputStream inputStream = ResourceLoader.getResourceAsStream(
            getClass(), "TechnicalServices.xsd")) {
        schema = sf.newSchema(new StreamSource(inputStream));
    }
    spf.setSchema(schema);

    SAXParser saxParser = spf.newSAXParser();
    XMLReader reader = saxParser.getXMLReader();
    ErrorHandler errorHandler = new MyErrorHandler();
    reader.setErrorHandler(errorHandler);
    reader.parse(new InputSource(new ByteArrayInputStream(xml)));
}
 
Example 4
Project: iBase4J   File: Excel2007Reader.java   Source Code and License Vote up 6 votes
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @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 5
Project: OpenJSharp   File: SAXBufferCreator.java   Source Code and License Vote up 6 votes
public MutableXMLStreamBuffer create(XMLReader reader, InputStream in, String systemId) throws IOException, SAXException {
    if (_buffer == null) {
        createBuffer();
    }
    _buffer.setSystemId(systemId);
    reader.setContentHandler(this);
    reader.setProperty(Properties.LEXICAL_HANDLER_PROPERTY, this);

    try {
        setHasInternedStrings(reader.getFeature(Features.STRING_INTERNING_FEATURE));
    } catch (SAXException e) {
    }


    if (systemId != null) {
        InputSource s = new InputSource(systemId);
        s.setByteStream(in);
        reader.parse(s);
    } else {
        reader.parse(new InputSource(in));
    }

    return getXMLStreamBuffer();
}
 
Example 6
Project: Equella   File: ConvertHtmlServiceImpl.java   Source Code and License Vote up 6 votes
@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 7
Project: openjdk-jdk10   File: SAXTFactoryTest.java   Source Code and License Vote up 6 votes
/**
 * 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 8
Project: incubator-netbeans   File: LibraryDeclarationParser.java   Source Code and License Vote up 6 votes
/**
 * The recognizer entry method taking an InputSource.
 * @param input InputSource to be parsed.
 * @throws java.io.IOException on I/O error.
 * @throws SAXException propagated exception thrown by a DocumentHandler.
 * @throws javax.xml.parsers.ParserConfigurationException a parser satisfining requested configuration can not be created.
 * @throws javax.xml.parsers.FactoryConfigurationRrror if the implementation can not be instantiated.
 *
 */
public void parse(final InputSource input) throws SAXException, ParserConfigurationException, IOException {
    if (used.getAndSet(true)) {
        throw new IllegalStateException("The LibraryDeclarationParser was already used, create a new instance");  //NOI18N
    }
    try {
        final XMLReader parser = XMLUtil.createXMLReader(false, true);
        parser.setContentHandler(this);
        parser.setErrorHandler(getDefaultErrorHandler());
        parser.setEntityResolver(this);
        parser.parse(input);
    } finally {
        //Recover recognizer internal state from exceptions to be reusable
        if (!context.empty()) {
            context.clear();
        }
        if (buffer.length() > 0) {
            buffer.delete(0, buffer.length());
        }
        expectedNS = null;
    }
}
 
Example 9
Project: incubator-netbeans   File: LibrarySupport.java   Source Code and License Vote up 6 votes
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 10
Project: openjdk-jdk10   File: SAXParser.java   Source Code and License Vote up 6 votes
/**
 * Parse the content given {@link org.xml.sax.InputSource}
 * as XML using the specified
 * {@link org.xml.sax.helpers.DefaultHandler}.
 *
 * @param is The InputSource containing the content to be parsed.
 * @param dh The SAX DefaultHandler to use.
 *
 * @throws IllegalArgumentException If the <code>InputSource</code> object
 *   is <code>null</code>.
 * @throws IOException If any IO errors occur.
 * @throws SAXException If any SAX errors occur during processing.
 *
 * @see org.xml.sax.DocumentHandler
 */
public void parse(InputSource is, DefaultHandler dh)
    throws SAXException, IOException {
    if (is == null) {
        throw new IllegalArgumentException("InputSource cannot be null");
    }

    XMLReader reader = this.getXMLReader();
    if (dh != null) {
        reader.setContentHandler(dh);
        reader.setEntityResolver(dh);
        reader.setErrorHandler(dh);
        reader.setDTDHandler(dh);
    }
    reader.parse(is);
}
 
Example 11
Project: Phoenicia   File: LocaleLoader.java   Source Code and License Vote up 6 votes
/**
 * Load and read the manifest.xml for a Locale.
 * @param locale_manifest_in
 * @return
 */
public Locale load(InputStream locale_manifest_in) {
    LocaleParser localeParser = new LocaleParser();
    try {
        final SAXParserFactory spf = SAXParserFactory.newInstance();
        final SAXParser sp = spf.newSAXParser();
        final XMLReader xr = sp.getXMLReader();
        xr.setContentHandler(localeParser);
        xr.parse(new InputSource(new BufferedInputStream(locale_manifest_in)));
    } catch (Exception e) {
        Debug.e(e);
    }
    return localeParser.getLocale();
}
 
Example 12
Project: openjdk-jdk10   File: CDataChunkSizeTest.java   Source Code and License Vote up 6 votes
@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 13
Project: cyberduck   File: XmlBookmarkCollection.java   Source Code and License Vote up 5 votes
protected void read(final ProtocolFactory protocols, final Local child) throws AccessDeniedException {
    try {
        final BufferedReader in = new BufferedReader(new InputStreamReader(child.getInputStream(),
                Charset.forName("UTF-8")));
        AbstractHandler handler = this.getHandler(protocols);
        final XMLReader xr = XMLReaderFactory.createXMLReader();
        xr.setContentHandler(handler);
        xr.setErrorHandler(handler);
        xr.parse(new InputSource(in));
    }
    catch(SAXException | IOException e) {
        log.error(String.format("Error reading %s:%s", this.getFile(), e.getMessage()));
    }
}
 
Example 14
Project: iBase4J-Common   File: Excel2007Reader.java   Source Code and License Vote up 5 votes
/**
 * 只遍历一个电子表格,其中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 15
Project: openjdk-jdk10   File: CatalogSupportBase.java   Source Code and License Vote up 5 votes
public void testXMLReader(boolean setUseCatalog, boolean useCatalog, String catalog,
        String xml, MyHandler handler, String expected) throws Exception {
    XMLReader reader = getXMLReader(setUseCatalog, useCatalog, catalog);

    reader.setContentHandler(handler);
    reader.setEntityResolver(handler);
    reader.parse(xml);
    Assert.assertEquals(handler.getResult().trim(), expected);
}
 
Example 16
Project: stroom-stats   File: XMLUtil.java   Source Code and License Vote up 5 votes
private static void prettyPrintXML(final Reader reader, final Writer writer) {
    try {
        final TransformerHandler handler = createTransformerHandler(new FatalErrorListener(), true);
        handler.setResult(new StreamResult(writer));

        final SAXParser parser = PARSER_FACTORY.newSAXParser();
        final XMLReader xmlReader = parser.getXMLReader();
        xmlReader.setErrorHandler(new FatalErrorHandler());
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(reader));

    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 17
Project: mobile-store   File: RepoUpdater.java   Source Code and License Vote up 5 votes
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 18
Project: openjdk-jdk10   File: SAXTFactoryTest.java   Source Code and License Vote up 5 votes
/**
 * Unit test newTransformerHandler with a DOMSource.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase06() throws Exception {
    String outputFile = USER_DIR + "saxtf006.out";
    String goldFile = GOLDEN_DIR + "saxtf006GF.out";

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

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Node node = (Node)docBuilder.parse(new File(XSLT_INCL_FILE));

        DOMSource domSource = new DOMSource(node, "file:///" + XML_DIR);
        TransformerHandler handler =
                    saxTFactory.newTransformerHandler(domSource);

        Result result = new StreamResult(fos);
        handler.setResult(result);
        reader.setContentHandler(handler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 19
Project: chordatlas   File: GMLReader.java   Source Code and License Vote up 5 votes
public GMLReader (InputSource input, CoordinateReferenceSystem target, CoordinateReferenceSystem sourceCS) throws IOException, SAXException {
	
	this.targetCRS = target;
	this.sourceCRS = sourceCS;
	
    XMLReader reader = XMLReaderFactory.createXMLReader();
    
    Callback callback = new Callback();
    GMLFilterGeometry geometryCallback = new GMLFilterGeometry( callback );	    
    GMLFilterDocument gmlCallback = new GMLFilterDocument( geometryCallback );	    
	reader.setContentHandler( gmlCallback );
	
    reader.parse(input);
}
 
Example 20
Project: openjdk-jdk10   File: Bug4970402.java   Source Code and License Vote up 4 votes
private void parse(XMLReader xmlReader, String xml) throws SAXException, IOException {
    StringReader reader = new StringReader(xml);
    InputSource inSource = new InputSource(reader);

    xmlReader.parse(inSource);
}