Java Code Examples for org.xml.sax.helpers.XMLReaderFactory

The following are top voted examples for showing how to use org.xml.sax.helpers.XMLReaderFactory. 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: 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 2
Project: hadoop   File: HftpFileSystem.java   View source code 7 votes vote down vote up
private FileChecksum getFileChecksum(String f) throws IOException {
  final HttpURLConnection connection = openConnection(
      "/fileChecksum" + ServletUtil.encodePath(f),
      "ugi=" + getEncodedUgiParameter());
  try {
    final XMLReader xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    xr.parse(new InputSource(connection.getInputStream()));
  } catch(SAXException e) {
    final Exception embedded = e.getException();
    if (embedded != null && embedded instanceof IOException) {
      throw (IOException)embedded;
    }
    throw new IOException("invalid xml directory content", e);
  } finally {
    connection.disconnect();
  }
  return filechecksum;
}
 
Example 3
Project: openjdk-jdk10   File: SAXTFactoryTest.java   View source code 7 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 4
Project: openjdk-jdk10   File: XMLFactoryHelper.java   View source code 7 votes vote down vote up
public static Object instantiateXMLService(String serviceName) throws Exception {
    ClassLoader backup = Thread.currentThread().getContextClassLoader();
    try {
        // set thread context class loader to module class loader
        Thread.currentThread().setContextClassLoader(XMLFactoryHelper.class.getClassLoader());
        if (serviceName.equals("org.xml.sax.XMLReader"))
            return XMLReaderFactory.createXMLReader();
        else if (serviceName.equals("javax.xml.validation.SchemaFactory"))
            return Class.forName(serviceName).getMethod("newInstance", String.class)
                    .invoke(null, W3C_XML_SCHEMA_NS_URI);
        else
            return Class.forName(serviceName).getMethod("newInstance").invoke(null);
    } finally {
        Thread.currentThread().setContextClassLoader(backup);
    }

}
 
Example 5
Project: intellij-ce-playground   File: UnsupportedFeaturesUtil.java   View source code 7 votes vote down vote up
private static void fillMaps() throws IOException {
  Logger log = Logger.getInstance(UnsupportedFeaturesUtil.class.getName());
  FileReader reader = new FileReader(PythonHelpersLocator.getHelperPath("/tools/versions.xml"));
  try {
    XMLReader xr = XMLReaderFactory.createXMLReader();
    VersionsParser parser = new VersionsParser();
    xr.setContentHandler(parser);
    xr.parse(new InputSource(reader));
  }
  catch (SAXException e) {
    log.error("Improperly formed \"versions.xml\". " + e.getMessage());
  }
  finally {
    reader.close();
  }
}
 
Example 6
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 7
Project: DocIT   File: SAXUtilities.java   View source code 6 votes vote down vote up
public static void parse(DefaultHandler handler, String file) throws SAXException, IOException {
	XMLReader xreader = XMLReaderFactory.createXMLReader();
	xreader.setContentHandler(handler);
	xreader.setErrorHandler(handler);
	FileReader reader = new FileReader(file);
    xreader.parse(new InputSource(reader));			
}
 
Example 8
Project: cornerstone   File: AnalyzerTest.java   View source code 6 votes vote down vote up
@Test
public void testAnalyzePom(){

    try {
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        PomDependencyHandler handler = new PomDependencyHandler();
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(this.getClass().getClassLoader().getResourceAsStream("testpom.xml")));
        assertEquals(4, handler.getDependencies().size());
        PomInfo pom = handler.getPomInfo();
        boolean hasVI=false;
        for (PomDependency d : handler.getDependencies()) {
            assertNotNull(d.artifactId);
            assertNotNull(d.groupId);
            assertNotNull(d.version);
            if("framework-validateinternals".equals(d.artifactId)){
                hasVI=true;
                assertEquals(d.version,"0.9");
            }
        }
        assertTrue(hasVI);
    }catch (Exception e){
        e.printStackTrace();
    }

}
 
Example 9
Project: letv   File: BiliDanmukuParser.java   View source code 6 votes vote down vote up
public Danmakus parse() {
    if (this.mDataSource != null) {
        AndroidFileSource source = this.mDataSource;
        try {
            XMLReader xmlReader = XMLReaderFactory.createXMLReader();
            XmlContentHandler contentHandler = new XmlContentHandler();
            xmlReader.setContentHandler(contentHandler);
            xmlReader.parse(new InputSource(source.data()));
            return contentHandler.getResult();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
    }
    return null;
}
 
Example 10
Project: lams   File: Jaxb2RootElementHttpMessageConverter.java   View source code 6 votes vote down vote up
protected Source processSource(Source source) {
	if (source instanceof StreamSource) {
		StreamSource streamSource = (StreamSource) source;
		InputSource inputSource = new InputSource(streamSource.getInputStream());
		try {
			XMLReader xmlReader = XMLReaderFactory.createXMLReader();
			String featureName = "http://xml.org/sax/features/external-general-entities";
			xmlReader.setFeature(featureName, isProcessExternalEntities());
			if (!isProcessExternalEntities()) {
				xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
			}
			return new SAXSource(xmlReader, inputSource);
		}
		catch (SAXException ex) {
			logger.warn("Processing of external entities could not be disabled", ex);
			return source;
		}
	}
	else {
		return source;
	}
}
 
Example 11
Project: parabuild-ci   File: SAXBugCollectionHandler.java   View source code 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
	XMLReader xr = XMLReaderFactory.createXMLReader();

	BugCollection bugCollection = new SortedBugCollection();
	Project project = new Project();

	SAXBugCollectionHandler handler = new SAXBugCollectionHandler(bugCollection, project);
	xr.setContentHandler(handler);
	xr.setErrorHandler(handler);

	// Parse each file provided on the
	// command line.
	for (int i = 0; i < argv.length; i++) {
		FileReader r = new FileReader(argv[i]);
		xr.parse(new InputSource(r));
	}
}
 
Example 12
Project: hadoop   File: HftpFileSystem.java   View source code 6 votes vote down vote up
private void fetchList(String path, boolean recur) throws IOException {
  try {
    XMLReader xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    HttpURLConnection connection = openConnection(
        "/listPaths" + ServletUtil.encodePath(path),
        "ugi=" + getEncodedUgiParameter() + (recur ? "&recursive=yes" : ""));
    InputStream resp = connection.getInputStream();
    xr.parse(new InputSource(resp));
  } catch(SAXException e) {
    final Exception embedded = e.getException();
    if (embedded != null && embedded instanceof IOException) {
      throw (IOException)embedded;
    }
    throw new IOException("invalid xml directory content", e);
  }
}
 
Example 13
Project: hadoop   File: HftpFileSystem.java   View source code 6 votes vote down vote up
/**
 * Connect to the name node and get content summary.
 * @param path The path
 * @return The content summary for the path.
 * @throws IOException
 */
private ContentSummary getContentSummary(String path) throws IOException {
  final HttpURLConnection connection = openConnection(
      "/contentSummary" + ServletUtil.encodePath(path),
      "ugi=" + getEncodedUgiParameter());
  InputStream in = null;
  try {
    in = connection.getInputStream();

    final XMLReader xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    xr.parse(new InputSource(in));
  } catch(FileNotFoundException fnfe) {
    //the server may not support getContentSummary
    return null;
  } catch(SAXException saxe) {
    final Exception embedded = saxe.getException();
    if (embedded != null && embedded instanceof IOException) {
      throw (IOException)embedded;
    }
    throw new IOException("Invalid xml format", saxe);
  } finally {
    if (in != null) {
      in.close();
    }
    connection.disconnect();
  }
  return contentsummary;
}
 
Example 14
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 15
Project: openjdk-jdk10   File: EntityCharacterEventOrder.java   View source code 6 votes vote down vote up
/**
    public static void main(String[] args) {
        TestRunner.run(JDK6770436Test.class);
    }
*/
    @Test
    public void entityCallbackOrderJava() throws SAXException, IOException {
        final String input = "<element> &amp; some more text</element>";

        final MockContentHandler handler = new MockContentHandler();
        final XMLReader xmlReader = XMLReaderFactory.createXMLReader();

        xmlReader.setContentHandler(handler);
        xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

        xmlReader.parse(new InputSource(new StringReader(input)));

        final List<String> events = handler.getEvents();
        printEvents(events);
        assertCallbackOrder(events); //regression from JDK5
    }
 
Example 16
Project: openjdk-jdk10   File: Bug6925410Test.java   View source code 6 votes vote down vote up
@Test
public void test() throws DatatypeConfigurationException {
    try {
        int times = 100;
        long start = System.currentTimeMillis();
        for (int i = 0; i < times; i++) {
            XMLReaderFactory.createXMLReader();
        }
        long end = System.currentTimeMillis();
        double speed = ((end - start));
        System.out.println(speed + "ms");
    } catch (Throwable e) {
        e.printStackTrace();
        Assert.fail(e.toString());
    }

}
 
Example 17
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 transformer 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 testcase01() throws Exception {
    String outputFile = USER_DIR + "saxtf001.out";
    String goldFile = GOLDEN_DIR + "saxtf001GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory) TransformerFactory.newInstance();
        TransformerHandler handler = saxTFactory.newTransformerHandler(new StreamSource(XSLT_FILE));
        Result result = new StreamResult(fos);
        handler.setResult(result);
        reader.setContentHandler(handler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 18
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 19
Project: openjdk-jdk10   File: SAXTFactoryTest.java   View source code 6 votes vote down vote up
/**
 * Unit test for newTransformerhandler(Source). DcoumentBuilderFactory is
 * namespace awareness, DocumentBuilder parse xslt file as DOMSource.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase03() throws Exception {
    String outputFile = USER_DIR + "saxtf003.out";
    String goldFile = GOLDEN_DIR + "saxtf003GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        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);

        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory)TransformerFactory.newInstance();
        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 20
Project: openjdk-jdk10   File: SAXTFactoryTest.java   View source code 6 votes vote down vote up
/**
 * Test newTransformerHandler with a Template Handler along with a relative
 * URI in the style-sheet file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase09() throws Exception {
    String outputFile = USER_DIR + "saxtf009.out";
    String goldFile = GOLDEN_DIR + "saxtf009GF.out";

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

        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        thandler.setSystemId("file:///" + XML_DIR);
        reader.setContentHandler(thandler);
        reader.parse(XSLT_INCL_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 21
Project: openjdk-jdk10   File: SAXTFactoryTest.java   View source code 6 votes vote down vote up
/**
 * Unit test for contentHandler setter/getter along reader as handler's
 * parent.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase10() throws Exception {
    String outputFile = USER_DIR + "saxtf010.out";
    String goldFile = GOLDEN_DIR + "saxtf010GF.out";
    // The transformer will use a SAX parser as it's reader.
    XMLReader reader = XMLReaderFactory.createXMLReader();
    SAXTransformerFactory saxTFactory
            = (SAXTransformerFactory)TransformerFactory.newInstance();
    XMLFilter filter =
        saxTFactory.newXMLFilter(new StreamSource(XSLT_FILE));
    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 22
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 23
Project: openjdk-jdk10   File: SAXTFactoryTest.java   View source code 6 votes vote down vote up
/**
 * Unit test for TemplatesHandler setter/getter.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase13() throws Exception {
    String outputFile = USER_DIR + "saxtf013.out";
    String goldFile = GOLDEN_DIR + "saxtf013GF.out";
    try(FileInputStream fis = new FileInputStream(XML_FILE)) {
        // The transformer will use a SAX parser as it's reader.
        XMLReader reader = XMLReaderFactory.createXMLReader();

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

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

        filter.setContentHandler(new MyContentHandler(outputFile));
        filter.parse(new InputSource(fis));
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 24
Project: openjdk-jdk10   File: XMLReaderFactoryTest.java   View source code 6 votes vote down vote up
public void testLegacy() throws Exception {
    ClassLoader clBackup = Thread.currentThread().getContextClassLoader();
    try {
        URL[] classUrls = { LEGACY_DIR.toUri().toURL() };
        URLClassLoader loader = new URLClassLoader(classUrls, ClassLoader.getSystemClassLoader().getParent());

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

        // now point to a random URL
        Thread.currentThread().setContextClassLoader(
                new URLClassLoader(new URL[0], ClassLoader.getSystemClassLoader().getParent()));
        // ClassNotFoundException if also trying to load class of reader1, which
        // would be the case before 8152912
        XMLReader reader2 = XMLReaderFactory.createXMLReader();
        assertEquals(reader2.getClass().getName(), "com.sun.org.apache.xerces.internal.parsers.SAXParser");
    } finally {
        Thread.currentThread().setContextClassLoader(clBackup);
    }
}
 
Example 25
Project: openjdk9   File: EntityCharacterEventOrder.java   View source code 6 votes vote down vote up
/**
    public static void main(String[] args) {
        TestRunner.run(JDK6770436Test.class);
    }
*/
    @Test
    public void entityCallbackOrderJava() throws SAXException, IOException {
        final String input = "<element> &amp; some more text</element>";

        final MockContentHandler handler = new MockContentHandler();
        final XMLReader xmlReader = XMLReaderFactory.createXMLReader();

        xmlReader.setContentHandler(handler);
        xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

        xmlReader.parse(new InputSource(new StringReader(input)));

        final List<String> events = handler.getEvents();
        printEvents(events);
        assertCallbackOrder(events); //regression from JDK5
    }
 
Example 26
Project: openjdk9   File: Bug6925410Test.java   View source code 6 votes vote down vote up
@Test
public void test() throws DatatypeConfigurationException {
    try {
        int times = 100;
        long start = System.currentTimeMillis();
        for (int i = 0; i < times; i++) {
            XMLReaderFactory.createXMLReader();
        }
        long end = System.currentTimeMillis();
        double speed = ((end - start));
        System.out.println(speed + "ms");
    } catch (Throwable e) {
        e.printStackTrace();
        Assert.fail(e.toString());
    }

}
 
Example 27
Project: openjdk9   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 transformer 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 testcase01() throws Exception {
    String outputFile = USER_DIR + "saxtf001.out";
    String goldFile = GOLDEN_DIR + "saxtf001GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory) TransformerFactory.newInstance();
        TransformerHandler handler = saxTFactory.newTransformerHandler(new StreamSource(XSLT_FILE));
        Result result = new StreamResult(fos);
        handler.setResult(result);
        reader.setContentHandler(handler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 28
Project: openjdk9   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 29
Project: openjdk9   File: SAXTFactoryTest.java   View source code 6 votes vote down vote up
/**
 * Unit test for newTransformerhandler(Source). DcoumentBuilderFactory is
 * namespace awareness, DocumentBuilder parse xslt file as DOMSource.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase03() throws Exception {
    String outputFile = USER_DIR + "saxtf003.out";
    String goldFile = GOLDEN_DIR + "saxtf003GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        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);

        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory)TransformerFactory.newInstance();
        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 30
Project: openjdk9   File: SAXTFactoryTest.java   View source code 6 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 31
Project: openjdk9   File: SAXTFactoryTest.java   View source code 6 votes vote down vote up
/**
 * Test newTransformerHandler with a Template Handler along with a relative
 * URI in the style-sheet file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase09() throws Exception {
    String outputFile = USER_DIR + "saxtf009.out";
    String goldFile = GOLDEN_DIR + "saxtf009GF.out";

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

        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        thandler.setSystemId("file:///" + XML_DIR);
        reader.setContentHandler(thandler);
        reader.parse(XSLT_INCL_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 32
Project: openjdk9   File: SAXTFactoryTest.java   View source code 6 votes vote down vote up
/**
 * Unit test for contentHandler setter/getter along reader as handler's
 * parent.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase10() throws Exception {
    String outputFile = USER_DIR + "saxtf010.out";
    String goldFile = GOLDEN_DIR + "saxtf010GF.out";
    // The transformer will use a SAX parser as it's reader.
    XMLReader reader = XMLReaderFactory.createXMLReader();
    SAXTransformerFactory saxTFactory
            = (SAXTransformerFactory)TransformerFactory.newInstance();
    XMLFilter filter =
        saxTFactory.newXMLFilter(new StreamSource(XSLT_FILE));
    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 33
Project: openjdk9   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 34
Project: openjdk9   File: SAXTFactoryTest.java   View source code 6 votes vote down vote up
/**
 * Unit test for TemplatesHandler setter/getter.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase13() throws Exception {
    String outputFile = USER_DIR + "saxtf013.out";
    String goldFile = GOLDEN_DIR + "saxtf013GF.out";
    try(FileInputStream fis = new FileInputStream(XML_FILE)) {
        // The transformer will use a SAX parser as it's reader.
        XMLReader reader = XMLReaderFactory.createXMLReader();

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

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

        filter.setContentHandler(new MyContentHandler(outputFile));
        filter.parse(new InputSource(fis));
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 35
Project: openjdk9   File: XMLReaderFactoryTest.java   View source code 6 votes vote down vote up
public void testLegacy() throws Exception {
    ClassLoader clBackup = Thread.currentThread().getContextClassLoader();
    try {
        URL[] classUrls = { LEGACY_DIR.toUri().toURL() };
        URLClassLoader loader = new URLClassLoader(classUrls, ClassLoader.getSystemClassLoader().getParent());

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

        // now point to a random URL
        Thread.currentThread().setContextClassLoader(
                new URLClassLoader(new URL[0], ClassLoader.getSystemClassLoader().getParent()));
        // ClassNotFoundException if also trying to load class of reader1, which
        // would be the case before 8152912
        XMLReader reader2 = XMLReaderFactory.createXMLReader();
        assertEquals(reader2.getClass().getName(), "com.sun.org.apache.xerces.internal.parsers.SAXParser");
    } finally {
        Thread.currentThread().setContextClassLoader(clBackup);
    }
}
 
Example 36
Project: openjdk9   File: XMLFactoryHelper.java   View source code 6 votes vote down vote up
public static Object instantiateXMLService(String serviceName) throws Exception {
    ClassLoader backup = Thread.currentThread().getContextClassLoader();
    try {
        // set thread context class loader to module class loader
        Thread.currentThread().setContextClassLoader(XMLFactoryHelper.class.getClassLoader());
        if (serviceName.equals("org.xml.sax.XMLReader"))
            return XMLReaderFactory.createXMLReader();
        else if (serviceName.equals("javax.xml.validation.SchemaFactory"))
            return Class.forName(serviceName).getMethod("newInstance", String.class)
                    .invoke(null, W3C_XML_SCHEMA_NS_URI);
        else
            return Class.forName(serviceName).getMethod("newInstance").invoke(null);
    } finally {
        Thread.currentThread().setContextClassLoader(backup);
    }

}
 
Example 37
Project: Peking-University-Open-Research-Data-Platform   File: XLSXFileReader.java   View source code 6 votes vote down vote up
public XMLReader fetchSheetParser(SharedStringsTable sst, DataTable dataTable, PrintWriter tempOut) throws SAXException {
    // An attempt to use org.apache.xerces.parsers.SAXParser resulted 
    // in some weird conflict in the app; the default XMLReader obtained 
    // from the XMLReaderFactory (from xml-apis.jar) appears to be working
    // just fine. however, 
    // TODO: verify why the app gets built with xml-apis-1.0.b2.jar; it's 
    // an old version - 1.4 seems to be the current release, and 2.0.2
    // (a new development?) appears to be available. We don't specifically
    // request this 1.0.* version, so another package must have it defined
    // as a dependency. We need to verify our dependencies, we most likely 
    // have some hard-coded versions in our pom.xml that are both old and 
    // unnecessary.
    // -- L.A. 4.0 alpha 1
 
    XMLReader xReader = XMLReaderFactory.createXMLReader();
    dbglog.fine("creating new SheetHandler;");
    ContentHandler handler = new SheetHandler(sst, dataTable, tempOut);
    xReader.setContentHandler(handler);
    return xReader;
}
 
Example 38
Project: CanReg5   File: MySAXApp.java   View source code 6 votes vote down vote up
/**
    * 
    * @param args
    * @throws java.lang.Exception
    */
   public static void main(String args[])
throws Exception
   {
XMLReader xr = XMLReaderFactory.createXMLReader();
MySAXApp handler = new MySAXApp();
xr.setContentHandler(handler);
xr.setErrorHandler(handler);

			// Parse each file provided on the
			// command line.
for (int i = 0; i < args.length; i++) {
    FileReader r = new FileReader(args[i]);
    xr.parse(new InputSource(r));
}
   }
 
Example 39
Project: mycore   File: MCRURIResolver.java   View source code 6 votes vote down vote up
@Override
public Source resolve(String href, String base) throws TransformerException {
    String path = href.substring(href.indexOf(":") + 1);
    URL resource = MCRConfigurationDir.getConfigResource(path);
    if (resource != null) {
        //have to use SAX here to resolve entities
        if (path.endsWith(".xsl")) {
            XMLReader reader;
            try {
                reader = XMLReaderFactory.createXMLReader();
            } catch (SAXException e) {
                throw new TransformerException(e);
            }
            reader.setEntityResolver(MCREntityResolver.instance());
            InputSource input = new InputSource(resource.toString());
            SAXSource saxSource = new SAXSource(reader, input);
            LOGGER.debug("include stylesheet: {}", saxSource.getSystemId());
            return saxSource;
        }
        return MCRURIResolver.instance().resolve(resource.toString(), base);
    }
    return null;
}
 
Example 40
Project: STEM   File: ConfigLoader.java   View source code 6 votes vote down vote up
/**
 * Note that if file starts with 'classpath:' the resource is looked
 * up on the classpath instead.
 */
public static Configuration load(String file)
  throws IOException, SAXException {
  ConfigurationImpl cfg = new ConfigurationImpl();

  XMLReader parser = XMLReaderFactory.createXMLReader();
  parser.setContentHandler(new ConfigHandler(cfg, file));
  if (file.startsWith("classpath:")) {
    String resource = file.substring("classpath:".length());
    ClassLoader cloader = Thread.currentThread().getContextClassLoader();
    InputStream istream = cloader.getResourceAsStream(resource);
    parser.parse(new InputSource(istream));
  } else
    parser.parse(file);

  return cfg;
}