Java Code Examples for org.xml.sax.XMLReader#setFeature()
The following examples show how to use
org.xml.sax.XMLReader#setFeature() .
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: SourceHttpMessageConverter.java From spring-analysis-note with MIT License | 6 votes |
@SuppressWarnings("deprecation") // on JDK 9 private SAXSource readSAXSource(InputStream body, HttpInputMessage inputMessage) throws IOException { try { XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities()); if (!isProcessExternalEntities()) { xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER); } byte[] bytes = StreamUtils.copyToByteArray(body); return new SAXSource(xmlReader, new InputSource(new ByteArrayInputStream(bytes))); } catch (SAXException ex) { throw new HttpMessageNotReadableException( "Could not parse document: " + ex.getMessage(), ex, inputMessage); } }
Example 2
Source File: Jaxb2Marshaller.java From spring4-understanding with Apache License 2.0 | 6 votes |
private Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException { if (logger.isDebugEnabled()) { logger.debug("Setting validation schema to " + StringUtils.arrayToCommaDelimitedString(this.schemaResources)); } Assert.notEmpty(resources, "No resources given"); Assert.hasLength(schemaLanguage, "No schema language provided"); Source[] schemaSources = new Source[resources.length]; XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); for (int i = 0; i < resources.length; i++) { Assert.notNull(resources[i], "Resource is null"); Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist"); InputSource inputSource = SaxResourceUtils.createInputSource(resources[i]); schemaSources[i] = new SAXSource(xmlReader, inputSource); } SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage); if (this.schemaResourceResolver != null) { schemaFactory.setResourceResolver(this.schemaResourceResolver); } return schemaFactory.newSchema(schemaSources); }
Example 3
Source File: SourceHttpMessageConverter.java From java-technology-stack with MIT License | 6 votes |
@SuppressWarnings("deprecation") // on JDK 9 private SAXSource readSAXSource(InputStream body, HttpInputMessage inputMessage) throws IOException { try { XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities()); if (!isProcessExternalEntities()) { xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER); } byte[] bytes = StreamUtils.copyToByteArray(body); return new SAXSource(xmlReader, new InputSource(new ByteArrayInputStream(bytes))); } catch (SAXException ex) { throw new HttpMessageNotReadableException( "Could not parse document: " + ex.getMessage(), ex, inputMessage); } }
Example 4
Source File: EXIficientCMD.java From exificient with MIT License | 6 votes |
protected XMLReader getXMLReader() throws SAXException { // create xml reader XMLReader xmlReader; // xmlReader = XMLReaderFactory // .createXMLReader("org.apache.xerces.parsers.SAXParser"); xmlReader = XMLReaderFactory.createXMLReader(); // set XMLReader features xmlReader.setFeature("http://xml.org/sax/features/namespaces", true); // do not report namespace declarations as attributes xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); // avoid validation xmlReader.setFeature("http://xml.org/sax/features/validation", false); // DTD xmlReader.setFeature("http://xml.org/sax/features/resolve-dtd-uris", false); // *skip* resolving entities like DTDs xmlReader.setEntityResolver(new NoEntityResolver()); return xmlReader; }
Example 5
Source File: EdfiRecordParser.java From secure-data-service with Apache License 2.0 | 6 votes |
/** * Parse and Validate an XML represented by the input stream against provided XSD and reports validation issues. * * @param input XML to parse and validate * @param vHandler Validator handler * @throws IOException If a IO error occurs during XML parsing. * @throws XmlParseException If a SAX error occurs during XML parsing. */ protected void parseAndValidate(InputStream input, ValidatorHandler vHandler) throws XmlParseException, IOException { vHandler.setErrorHandler(this); InputSource is = new InputSource(new InputStreamReader(input, "UTF-8")); is.setEncoding("UTF-8"); try { XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(vHandler); parser.setErrorHandler(this); vHandler.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false); // Commented out the following line, as Java 1.6.0_45 throws an exception on this. //parser.setFeature("http://apache.org/xml/features/validation/id-idref-checking", false); parser.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false); parser.setFeature("http://xml.org/sax/features/external-general-entities", false); parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false); parser.parse(is); } catch (SAXException e) { throw new XmlParseException(e.getMessage(), e); } }
Example 6
Source File: ProductImportParser.java From development with Apache License 2.0 | 6 votes |
/** * Parse the given XML string an create/update the corresponding entities * * @param xml * the XML string * @return the parse return code * @throws Exception */ public int parse(byte[] xml) throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SchemaFactory sf = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try (InputStream inputStream = ResourceLoader.getResourceAsStream( getClass(), getSchemaName())) { Schema schema = sf.newSchema(new StreamSource(inputStream)); spf.setSchema(schema); } SAXParser saxParser = spf.newSAXParser(); XMLReader reader = saxParser.getXMLReader(); reader.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.DISALLOW_DOCTYPE_DECL_FEATURE, true); reader.setContentHandler(this); reader.parse(new InputSource(new ByteArrayInputStream(xml))); return 0; }
Example 7
Source File: AbiWordParser.java From document-management-software with GNU Lesser General Public License v3.0 | 6 votes |
@Override public void internalParse(InputStream input, String filename, String encoding, Locale locale, String tenant, StringBuffer content) { try { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(false); SAXParser saxParser = saxParserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setFeature("http://xml.org/sax/features/validation", false); xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); AbiWordContentHandler contentHandler = new AbiWordContentHandler(); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(input)); content.append(StringUtil.writeToString(new StringReader(contentHandler.getContent()))); } catch (Exception e) { log.warn("Failed to extract AbiWord text content", e); } }
Example 8
Source File: mxGraphViewImageReader.java From blog-codes with Apache License 2.0 | 6 votes |
/** * Creates the image for the given display XML input source. (Note: The XML * is an encoded mxGraphView, not mxGraphModel.) * * @param inputSource * Input source that contains the display XML. * @return Returns an image representing the display XML input source. */ public static BufferedImage convert(InputSource inputSource, mxGraphViewImageReader viewReader) throws ParserConfigurationException, SAXException, IOException { BufferedImage result = null; XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.setContentHandler(viewReader); reader.parse(inputSource); if (viewReader.getCanvas() instanceof mxImageCanvas) { result = ((mxImageCanvas) viewReader.getCanvas()).destroy(); } return result; }
Example 9
Source File: Jaxb2RootElementHttpMessageConverter.java From spring-analysis-note with MIT License | 6 votes |
@SuppressWarnings("deprecation") // on JDK 9 protected Source processSource(Source source) { if (source instanceof StreamSource) { StreamSource streamSource = (StreamSource) source; InputSource inputSource = new InputSource(streamSource.getInputStream()); try { XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); 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 10
Source File: XMLParserUtilsTest.java From teamengine with Apache License 2.0 | 5 votes |
@Test public void xincludeParserNoBaseURIFixup() throws SAXException { SAXParser parser = XMLParserUtils.createXIncludeAwareSAXParser(false); assertNotNull(parser); XMLReader reader = parser.getXMLReader(); // Fortify mod to prevent External Entity Injections reader.setFeature("http://xml.org/sax/features/external-general-entities", false); boolean baseURIFixup = reader .getFeature(Constants.XERCES_FEATURE_PREFIX + Constants.XINCLUDE_FIXUP_BASE_URIS_FEATURE); assertFalse("Expected feature to be false: " + Constants.XINCLUDE_FIXUP_BASE_URIS_FEATURE, baseURIFixup); }
Example 11
Source File: SAXDecoder.java From feign with Apache License 2.0 | 5 votes |
@Override public Object decode(Response response, Type type) throws IOException, DecodeException { if (response.body() == null) return null; ContentHandlerWithResult.Factory<?> handlerFactory = handlerFactories.get(type); checkState(handlerFactory != null, "type %s not in configured handlers %s", type, handlerFactories.keySet()); ContentHandlerWithResult<?> handler = handlerFactory.create(); try { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://xml.org/sax/features/namespaces", false); xmlReader.setFeature("http://xml.org/sax/features/validation", false); /* Explicitly control sax configuration to prevent XXE attacks */ xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false); xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false); xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); xmlReader.setContentHandler(handler); InputStream inputStream = response.body().asInputStream(); try { xmlReader.parse(new InputSource(inputStream)); } finally { ensureClosed(inputStream); } return handler.result(); } catch (SAXException e) { throw new DecodeException(response.status(), e.getMessage(), response.request(), e); } }
Example 12
Source File: WikipediaIngestHelper.java From datawave with Apache License 2.0 | 5 votes |
@Override public Multimap<String,NormalizedContentInterface> getEventFields(RawRecordContainer event) { HashMultimap<String,String> fields = HashMultimap.create(); // Get the raw data String data = new String(event.getRawData()); // Wrap the data StringReader reader = new StringReader(data); InputSource source = new InputSource(reader); // Create an XML parser try { WikipediaContentHandler handler = new WikipediaContentHandler(fields, ignoreFields); XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false); parser.setFeature("http://xml.org/sax/features/external-general-entities", false); parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false); parser.setContentHandler(handler); parser.parse(source); } catch (Exception e) { // If error, return empty results map. log.error("Error processing Wikipedia XML document", e); event.addError(RawDataErrorNames.FIELD_EXTRACTION_ERROR); } extractWikipediaTypeInformation(event, fields); return normalize(fields); }
Example 13
Source File: XMLReaderAdapterTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * To test the parse method. The specification says that this method * will throw an exception if the embedded XMLReader does not support * the http://xml.org/sax/features/namespace-prefixes property. * * @throws Exception If any errors occur. */ @Test public void parse01() throws Exception { try (FileInputStream fis = new FileInputStream(XML_DIR + "namespace1.xml")) { XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); if (!xmlReader.getFeature(NM_PREFIXES_PROPERTY)) { xmlReader.setFeature(NM_PREFIXES_PROPERTY, true); } XMLReaderAdapter xmlRA = new XMLReaderAdapter(xmlReader); xmlRA.setDocumentHandler(new HandlerBase()); xmlRA.parse(new InputSource(fis)); } }
Example 14
Source File: XmlReaderSafeProperty.java From Android_Code_Arbiter with GNU Lesser General Public License v3.0 | 5 votes |
public static void receiveXMLStreamSecureProcessing(final InputStream inStream) throws ParserConfigurationException, SAXException, IOException { XMLReader reader = XMLReaderFactory.createXMLReader(); // Secure processing enabled reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,true); reader.setContentHandler(new PrintHandler()); reader.parse(new InputSource(inStream)); }
Example 15
Source File: XMLReaderTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * getFeature returns false if a feature has been preset as false when * namespace awareness is set. * * @throws Exception If any errors occur. */ @Test public void featureEPE02() throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); xmlReader.setFeature(EXTERNAL_P_ENTITIES, false); assertFalse(xmlReader.getFeature(EXTERNAL_P_ENTITIES)); }
Example 16
Source File: NSTableTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Here namespace processing and namespace-prefixes are enabled. * The testcase tests XMLReader for this. * * @throws Exception If any errors occur. */ @Test public void xrNSTable01() throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SAXParser saxParser = spf.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setFeature(NAMESPACE_PREFIXES, true); assertTrue(xmlReader.getFeature(NAMESPACES)); assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); }
Example 17
Source File: XmlUtils.java From teaching with Apache License 2.0 | 5 votes |
/** * Get an instance of an XML reader from the XMLReaderFactory. * * @return the XMLReader. */ public static XMLReader getXmlReader() { try { final XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); reader.setFeature("http://xml.org/sax/features/namespaces", true); reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); return reader; } catch (final Exception e) { throw new RuntimeException("Unable to create XMLReader", e); } }
Example 18
Source File: JdkXmlUtils.java From Bytecoder with Apache License 2.0 | 5 votes |
/** * Returns an XMLReader instance. If overrideDefaultParser is requested, use * SAXParserFactory or XMLReaderFactory, otherwise use the system-default * SAXParserFactory to locate an XMLReader. * * @param overrideDefaultParser a flag indicating whether a 3rd party's * parser implementation may be used to override the system-default one * @param secureProcessing a flag indicating whether secure processing is * requested * @param useXMLReaderFactory a flag indicating when the XMLReader should be * created using XMLReaderFactory. True is a compatibility mode that honors * the property org.xml.sax.driver (see JDK-6490921). * @return an XMLReader instance */ public static XMLReader getXMLReader(boolean overrideDefaultParser, boolean secureProcessing) { SAXParserFactory saxFactory; XMLReader reader = null; String spSAXDriver = SecuritySupport.getSystemProperty(SAX_DRIVER); if (spSAXDriver != null) { reader = getXMLReaderWXMLReaderFactory(); } else if (overrideDefaultParser) { reader = getXMLReaderWSAXFactory(overrideDefaultParser); } if (reader != null) { if (secureProcessing) { try { reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, secureProcessing); } catch (SAXException e) { XMLSecurityManager.printWarning(reader.getClass().getName(), XMLConstants.FEATURE_SECURE_PROCESSING, e); } } try { reader.setFeature(NAMESPACES_FEATURE, true); reader.setFeature(NAMESPACE_PREFIXES_FEATURE, false); } catch (SAXException se) { // older version of a parser } return reader; } // use the system-default saxFactory = defaultSAXFactory; try { reader = saxFactory.newSAXParser().getXMLReader(); } catch (ParserConfigurationException | SAXException ex) { // shall not happen with the system-default reader } return reader; }
Example 19
Source File: XMLParserUtilsTest.java From teamengine with Apache License 2.0 | 5 votes |
@Test(expected = AssertionError.class) public void resolveXInclude_keepXMLBase() throws SAXException, IOException { File file = new File("src/test/resources/article.xml"); SAXParser parser = XMLParserUtils.createXIncludeAwareSAXParser(true); // Fortify mod to prevent External Entity Injections // The SAXParser contains an XMLReader. getXMLReader returns a handle to the // reader. By setting a Feature on the reader, we also set it on the Parser. XMLReader reader = parser.getXMLReader(); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); // End Fortify mods LegalNoticeHandler handler = new LegalNoticeHandler(); parser.parse(file, handler); }
Example 20
Source File: SAXDecoderTestCase.java From exificient with MIT License | 4 votes |
protected void _test(String xml, String xsdLoc, TestContentHandler tch, boolean namespacePrefixes, boolean preservePrefixes, CodingMode codingMode) throws SAXException, IOException, EXIException { try { EXIFactory factory = DefaultEXIFactory.newInstance(); // schema? if (xsdLoc != null) { GrammarFactory gf = GrammarFactory.newInstance(); Grammars g = gf.createGrammars(xsdLoc); factory.setGrammars(g); } factory.setCodingMode(codingMode); FidelityOptions fo = factory.getFidelityOptions(); fo.setFidelity(FidelityOptions.FEATURE_PREFIX, preservePrefixes); ByteArrayOutputStream os = new ByteArrayOutputStream(); // write EXI stream { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); EXIResult exiResult = new EXIResult(factory); exiResult.setOutputStream(os); xmlReader.setContentHandler(exiResult.getHandler()); xmlReader.parse(new InputSource(new StringReader(xml))); } // read EXI stream os.flush(); InputStream is = new ByteArrayInputStream(os.toByteArray()); XMLReader exiReader = new SAXFactory(factory).createEXIReader(); exiReader.setFeature("http://xml.org/sax/features/namespaces", namespaces); exiReader.setFeature( "http://xml.org/sax/features/namespace-prefixes", namespacePrefixes); exiReader.setContentHandler(tch); exiReader.parse(new InputSource(is)); } catch (Exception e) { throw new RuntimeException("namespacePrefixes=" + namespacePrefixes + ", preservePrefixes=" + preservePrefixes + ", codingMode=" + codingMode, e); } }