Java Code Examples for javax.xml.parsers.SAXParser#getXMLReader()

The following examples show how to use javax.xml.parsers.SAXParser#getXMLReader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XML_SAX_StAX_FI.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
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 2
Source File: XmlUtils.java    From teaching with Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> extractCustomAttributes(final String xml) {
    final SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(false);
    try {
        final SAXParser saxParser = spf.newSAXParser();
        final XMLReader xmlReader = saxParser.getXMLReader();
        final CustomAttributeHandler handler = new CustomAttributeHandler();
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(new StringReader(xml)));
        return handler.getAttributes();
    } catch (final Exception e) {
    	log.error(e.getMessage(), e);
        return Collections.emptyMap();
    }
}
 
Example 3
Source File: XML_SAX_StAX_FI.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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 4
Source File: IntentReceiver.java    From aptoide-client with GNU General Public License v2.0 6 votes vote down vote up
private void parseXmlString(String file) {

        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            XmlAppHandler handler = new XmlAppHandler();
            xr.setContentHandler(handler);

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(file));
            xr.parse(is);
            server = handler.getServers();
            app = handler.getApp();

        } catch (IOException | SAXException | ParserConfigurationException e) {
            Logger.printException(e);
        }
    }
 
Example 5
Source File: Issue682Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test() {
    try {
        Schema schema = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema").newSchema(new StreamSource(testFile));
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(true);
        saxParserFactory.setSchema(schema);
        // saxParserFactory.setFeature("http://java.sun.com/xml/schema/features/report-ignored-element-content-whitespace",
        // true);
        SAXParser saxParser = saxParserFactory.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setContentHandler(new DefaultHandler());
        // InputStream input =
        // ClassLoader.getSystemClassLoader().getResourceAsStream("test/test.xml");
        InputStream input = getClass().getResourceAsStream("Issue682.xml");
        System.out.println("Parse InputStream:");
        xmlReader.parse(new InputSource(input));
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail(ex.toString());
    }

}
 
Example 6
Source File: ResolverTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Unit test for entityResolver setter.
 *
 * @throws Exception If any errors occur.
 */
public void testResolver() throws Exception {
    String outputFile = USER_DIR + "EntityResolver.out";
    String goldFile = GOLDEN_DIR + "EntityResolverGF.out";
    String xmlFile = XML_DIR + "publish.xml";

    Files.copy(Paths.get(XML_DIR + "publishers.dtd"),
            Paths.get(USER_DIR + "publishers.dtd"), REPLACE_EXISTING);
    Files.copy(Paths.get(XML_DIR + "familytree.dtd"),
            Paths.get(USER_DIR + "familytree.dtd"), REPLACE_EXISTING);

    try(FileInputStream instream = new FileInputStream(xmlFile);
            MyEntityResolver eResolver = new MyEntityResolver(outputFile)) {
        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setEntityResolver(eResolver);
        InputSource is = new InputSource(instream);
        xmlReader.parse(is);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 7
Source File: JAXPParser.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public void parse( InputSource source, ContentHandler handler,
    ErrorHandler errorHandler, EntityResolver entityResolver )

    throws SAXException, IOException {

    try {
        SAXParser saxParser = allowFileAccess(factory.newSAXParser(), false);
        XMLReader reader = new XMLReaderEx(saxParser.getXMLReader());

        reader.setContentHandler(handler);
        if(errorHandler!=null)
            reader.setErrorHandler(errorHandler);
        if(entityResolver!=null)
            reader.setEntityResolver(entityResolver);
        reader.parse(source);
    } catch( ParserConfigurationException e ) {
        // in practice this won't happen
        SAXParseException spe = new SAXParseException(e.getMessage(),null,e);
        errorHandler.fatalError(spe);
        throw spe;
    }
}
 
Example 8
Source File: EHFatalTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Error Handler to capture all error events to output file. Verifies the
 * output file is same as golden file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testEHFatal() throws Exception {
    String outputFile = USER_DIR + "EHFatal.out";
    String goldFile = GOLDEN_DIR + "EHFatalGF.out";
    String xmlFile = XML_DIR + "invalid.xml";

    try(MyErrorHandler eHandler = new MyErrorHandler(outputFile);
            FileInputStream instream = new FileInputStream(xmlFile)) {
        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setErrorHandler(eHandler);
        InputSource is = new InputSource(instream);
        xmlReader.parse(is);
        fail("Parse should throw SAXException");
    } catch (SAXException expected) {
        // This is expected.
    }
    // Need close the output file before we compare it with golden file.
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 9
Source File: TunedDocumentLoader.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
                             ErrorHandler errorHandler, int validationMode, boolean namespaceAware)
    throws Exception {
    if (validationMode == XmlBeanDefinitionReader.VALIDATION_NONE) {
        SAXParserFactory parserFactory =
            namespaceAware ? nsasaxParserFactory : saxParserFactory;
        SAXParser parser = parserFactory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setEntityResolver(entityResolver);
        reader.setErrorHandler(errorHandler);
        SAXSource saxSource = new SAXSource(reader, inputSource);
        W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
        StaxUtils.copy(saxSource, writer);
        return writer.getDocument();
    }
    return super.loadDocument(inputSource, entityResolver, errorHandler, validationMode,
                              namespaceAware);
}
 
Example 10
Source File: DigestHtml.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public static String digest(String todigest)
{
	Digester d = new Digester();
	try
	{
		SAXParser parser = saxParserFactory.newSAXParser();
		XMLReader reader = parser.getXMLReader();
		reader.setContentHandler(d);
		reader.parse(new InputSource(new StringReader("<content>" //$NON-NLS-1$
				+ todigest + "</content>"))); //$NON-NLS-1$
		return d.toString();
	}
	catch (Exception ex)
	{
		return d.toString() + Messages.getString("DigestHtml.3") + ex.getMessage(); //$NON-NLS-1$
	}
}
 
Example 11
Source File: Providers.java    From LicenseScout with Apache License 2.0 5 votes vote down vote up
/**
 * Reads providers from an XML file.
 * 
 * @param inputStream an input stream to read the file contents from
 * @param validateXml true if the XML content read should be validated, false otherwise
 * @param log the logger
 * @throws IOException
 * @throws SAXException 
 * @throws ParserConfigurationException 
 */
public void readProviders(final InputStream inputStream, boolean validateXml, final ILSLog log)
        throws IOException, ParserConfigurationException, SAXException {

    final SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(validateXml);
    final SAXParser saxParser = spf.newSAXParser();
    final XMLReader xmlReader = saxParser.getXMLReader();
    xmlReader.setContentHandler(new ProviderSaxHandler(log));
    xmlReader.parse(MiscUtil.getInputSource(inputStream));
}
 
Example 12
Source File: Dom4j.java    From cuba with Apache License 2.0 5 votes vote down vote up
public static SAXParser getParser() {
    SAXParser parser;
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(false);
    XMLReader xmlReader;
    try {
        parser = factory.newSAXParser();
        xmlReader = parser.getXMLReader();
    } catch (ParserConfigurationException | SAXException e) {
        throw new RuntimeException("Unable to create SAX parser", e);
    }

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

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

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

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

    return parser;
}
 
Example 13
Source File: SvgHelper.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
public static Bitmap getBitmap(File file, int width, int height, boolean white) {
    try (FileInputStream stream = new FileInputStream(file)) {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        SVGHandler handler = new SVGHandler(width, height, white);
        xr.setContentHandler(handler);
        xr.parse(new InputSource(stream));
        return handler.getBitmap();
    } catch (Exception e) {
        FileLog.e(e);
        throw null;
    }
}
 
Example 14
Source File: JaxbJavaee.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 * validate the inputStream, which should be a Java EE standard deployment descriptor against its schema type
 * Note, this method will use the new Java EE 6 schema to validate the old descriptors after changing their namespace and version.
 *
 * @param type
 * @param in
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static void validateJavaee(final JavaeeSchema type, final InputStream in) throws ParserConfigurationException, SAXException, IOException {
    final URL javaeeSchemaURL = resolveJavaeeSchemaURL(type);
    if (javaeeSchemaURL == null) {
        throw new IllegalArgumentException("Can not find the xsd file against type:" + type);
    }

    final URL xmlSchemaURL = JaxbJavaee.getSchemaURL("xml.xsd");
    if (xmlSchemaURL == null) {
        throw new IllegalArgumentException("Can not find the xml.xsd file");
    }

    // get the parser
    final SAXParserFactory parserfactory = SAXParserFactory.newInstance();
    parserfactory.setNamespaceAware(true);
    parserfactory.setValidating(false);
    final SAXParser parser = parserfactory.newSAXParser();

    // get the xml filter
    final Javaee6SchemaFilter xmlFilter = new Javaee6SchemaFilter(parser.getXMLReader());

    // get the source
    final SAXSource sourceForValidate = new SAXSource(xmlFilter, new InputSource(in));

    // get the schema
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    final JaxbJavaeeSchemaResourceResolver resourceResolver = new JaxbJavaeeSchemaResourceResolver();
    schemaFactory.setResourceResolver(resourceResolver);

    final Schema schema = schemaFactory.newSchema(
            new Source[]{
                    new StreamSource(xmlSchemaURL.openStream()),
                    new StreamSource(javaeeSchemaURL.openStream())
            });

    // validate
    schema.newValidator().validate(sourceForValidate);
}
 
Example 15
Source File: XMLConfigReader.java    From cms with Apache License 2.0 5 votes vote down vote up
public CmsConfiguration readConfiguration(InputStream is) throws Exception 
{
	SAXParserFactory spf = SAXParserFactory.newInstance();
	spf.setNamespaceAware(true);
	SAXParser saxParser = spf.newSAXParser();
	XMLReader xmlReader = saxParser.getXMLReader();
	XMLConfigContentHandler contentHandler = new XMLConfigContentHandler();
	xmlReader.setContentHandler(contentHandler);
	xmlReader.parse(new InputSource(is));
	return contentHandler.getConfiguration();
}
 
Example 16
Source File: Bug6594813.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private String runTransform(SAXParser sp) throws Exception {
    // Run identity transform using SAX parser
    SAXSource src = new SAXSource(sp.getXMLReader(), new InputSource(new StringReader(TESTXML)));
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StringWriter sw = new StringWriter();
    transformer.transform(src, new StreamResult(sw));

    String result = sw.getBuffer().toString();
    // System.out.println(result);
    return result;
}
 
Example 17
Source File: SanitizedXmlSourceSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void prepare() throws Exception {
  super.prepare();
  checkState(content == null);
  ByteArrayOutputStream stream = new ByteArrayOutputStream();
  try (InputStream input = new BufferedInputStream(new FileInputStream(file))) {
    try (OutputStream output = new BufferedOutputStream(stream)) {

      StreamSource styleSource = new StreamSource(new StringReader(stylesheet));
      TransformerFactory transformerFactory = SafeXml.newTransformerFactory();
      Transformer transformer = transformerFactory.newTransformer(styleSource);

      SAXParserFactory parserFactory = SafeXml.newSaxParserFactory();
      parserFactory.setNamespaceAware(true);

      SAXParser parser = parserFactory.newSAXParser();
      parser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
      parser.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");

      XMLReader reader = parser.getXMLReader();
      reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
      reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

      transformer.transform(new SAXSource(reader, new InputSource(input)), new StreamResult(output));
    }
  }
  content = stream.toByteArray();
}
 
Example 18
Source File: SaxParserSafeEntityResolver.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void receiveXMLStream(final InputStream inStream,
                                     final DefaultHandler defHandler)
        throws ParserConfigurationException, SAXException, IOException {
    // ...
    SAXParserFactory spf = SAXParserFactory.newInstance();
    final SAXParser saxParser = spf.newSAXParser();

    XMLReader reader = saxParser.getXMLReader();
    reader.setEntityResolver(new CustomResolver()); //Custom resolver
    InputSource is = new InputSource(inStream);
    reader.parse(is);
}
 
Example 19
Source File: SvgHelper.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
public static Bitmap getBitmap(File file, int width, int height, boolean white) {
    try (FileInputStream stream = new FileInputStream(file)) {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        SVGHandler handler = new SVGHandler(width, height, white);
        xr.setContentHandler(handler);
        xr.parse(new InputSource(stream));
        return handler.getBitmap();
    } catch (Exception e) {
        FileLog.e(e);
        throw null;
    }
}
 
Example 20
Source File: ValidataXMLTest.java    From bulbasaur with Apache License 2.0 4 votes vote down vote up
/**
 * 通过XSD(XML Schema)校验XML
 */
@Test
public void validateXMLByXSD() {
	String path = this.getClass().getResource("/").getPath();
	int index = path.lastIndexOf("/");
	path = path.substring(0, index);

	String xmlFileName = path + "/processCore.xml";
	// String xsdFileName =
	// "/Users/user/workspace/bulbasaur/core/src/test/resources/process_bak.xsd";
	String xsdFileName = path + "/test.xsd";
	try {
		// 创建默认的XML错误处理器
		XMLErrorHandler errorHandler = new XMLErrorHandler();
		// 获取基于 SAX 的解析器的实例
		SAXParserFactory factory = SAXParserFactory.newInstance();
		// 解析器在解析时验证 XML 内容。
		factory.setValidating(true);
		// 指定由此代码生成的解析器将提供对 XML 名称空间的支持。
		factory.setNamespaceAware(true);
		// 使用当前配置的工厂参数创建 SAXParser 的一个新实例。
		SAXParser parser = factory.newSAXParser();
		// 创建一个读取工具
		SAXReader xmlReader = new SAXReader();
		// 获取要校验xml文档实例
		Document xmlDocument = xmlReader.read(new File(xmlFileName));
		// 设置 XMLReader 的基础实现中的特定属性。核心功能和属性列表可以在
		// [url]http://sax.sourceforge.net/?selected=get-set[/url] 中找到。
		parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
		parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:" + xsdFileName);
		// 创建一个SAXValidator校验工具,并设置校验工具的属性
		SAXValidator validator = new SAXValidator(parser.getXMLReader());
		// 设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。
		validator.setErrorHandler(errorHandler);
		// 校验
		validator.validate(xmlDocument);

		XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
		// 如果错误信息不为空,说明校验失败,打印错误信息
		if (errorHandler.getErrors().hasContent()) {
			System.out.println("XML文件通过XSD文件校验失败!");
			writer.write(errorHandler.getErrors());
		} else {
			System.out.println("Good! XML文件通过XSD文件校验成功!");
		}
	} catch (Exception ex) {
		System.out.println("XML文件: " + xmlFileName + " 通过XSD文件:" + xsdFileName + "检验失败。\n原因: " + ex.getMessage());
		ex.printStackTrace();
	}
}