下面列出了javax.xml.parsers.SAXParserFactory#setFeature ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static SAXParserFactory newSAXParserFactory(boolean disableSecurity) {
SAXParserFactory factory = SAXParserFactory.newInstance();
String featureToSet = XMLConstants.FEATURE_SECURE_PROCESSING;
try {
boolean securityOn = !xmlSecurityDisabled(disableSecurity);
factory.setFeature(featureToSet, securityOn);
factory.setNamespaceAware(true);
if (securityOn) {
featureToSet = DISALLOW_DOCTYPE_DECL;
factory.setFeature(featureToSet, true);
featureToSet = EXTERNAL_GE;
factory.setFeature(featureToSet, false);
featureToSet = EXTERNAL_PE;
factory.setFeature(featureToSet, false);
featureToSet = LOAD_EXTERNAL_DTD;
factory.setFeature(featureToSet, false);
}
} catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) {
LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support "+featureToSet+" feature!", new Object[]{factory.getClass().getName()});
}
return factory;
}
public static Object unmarshal(Reader reader, String packageName) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
spf.setNamespaceAware(true);
Source xmlSource = new SAXSource(spf.newSAXParser().getXMLReader(), new InputSource(reader));
JAXBContext jc = JAXBContext.newInstance(packageName);
Unmarshaller um = jc.createUnmarshaller();
return ((javax.xml.bind.JAXBElement)um.unmarshal(xmlSource)).getValue();
} catch (Exception ex) {
log.warn("Failed to unmarshall object. Increase logging to debug for additional information. 3" + ex.getMessage());
log.debug(ex.getMessage(), ex);
}
return null;
}
/**
* namespace processing is enabled. namespace-prefix is also is enabled.
* So it is a True-True combination.
* The test is to test SAXParser with these conditions.
*
* @throws Exception If any errors occur.
*/
@Test
public void testWithTrueTrue() throws Exception {
String outputFile = USER_DIR + "SPNSTableTT.out";
String goldFile = GOLDEN_DIR + "NSTableTTGF.out";
String xmlFile = XML_DIR + "namespace1.xml";
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setFeature("http://xml.org/sax/features/namespace-prefixes",
true);
try (MyNSContentHandler handler = new MyNSContentHandler(outputFile)) {
spf.newSAXParser().parse(new File(xmlFile), handler);
}
assertTrue(compareWithGold(goldFile, outputFile));
}
public static void read(InputStream inputStream, FeedClient feedClient, AtomicInteger numSent) throws Exception {
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
// XXE prevention:
parserFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
parserFactory.setValidating(false);
parserFactory.setNamespaceAware(false);
SAXParser parser = parserFactory.newSAXParser();
SAXClientFeeder saxClientFeeder = new SAXClientFeeder(feedClient, numSent);
InputSource inputSource = new InputSource();
inputSource.setEncoding(StandardCharsets.UTF_8.displayName());
inputSource.setByteStream(inputStream);
// This is to send events about CDATA to the saxClientFeeder
// (https://docs.oracle.com/javase/tutorial/jaxp/sax/events.html)
parser.setProperty("http://xml.org/sax/properties/lexical-handler", saxClientFeeder);
parser.parse(inputSource, saxClientFeeder);
}
/**
* Unit test for Attributes interface. Prints all attributes into output
* file. Check it with golden file.
*
* @throws Exception If any errors occur.
*/
@Test
public void testcase01() throws Exception {
String outputFile = USER_DIR + "Attributes.out";
String goldFile = GOLDEN_DIR + "AttributesGF.out";
String xmlFile = XML_DIR + "family.xml";
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setFeature("http://xml.org/sax/features/namespace-prefixes",
true);
spf.setValidating(true);
SAXParser saxParser = spf.newSAXParser();
MyAttrCHandler myAttrCHandler = new MyAttrCHandler(outputFile);
saxParser.parse(new File(xmlFile), myAttrCHandler);
myAttrCHandler.flushAndClose();
assertTrue(compareWithGold(goldFile, outputFile));
}
/**
* Extract coverage data from a JaCoCo XML report file.
*
* @param xml the JaCoCo XML report file.
* @return the coverage data of each Java class registered in the JaCoCo XML report.
* @throws ParserConfigurationException if an error occurs during the parsing of the JaCoCo XML report.
* @throws SAXException if an error occurs during the parsing of the JaCoCo XML report.
* @throws IOException if an error occurs during the parsing of the JaCoCo XML report.
*/
public static Map<String, JavaClass> getCoverageData(File xml)
throws ParserConfigurationException,
SAXException,
IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://xml.org/sax/features/validation", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
SAXParser saxParser = factory.newSAXParser();
JaCoCoXmlReportParser handler = new JaCoCoXmlReportParser();
saxParser.parse(xml, handler);
return handler.getClasses();
}
public static SAXParserFactory newSAXParserFactory(boolean disableSecurity) {
SAXParserFactory factory = SAXParserFactory.newInstance();
String featureToSet = XMLConstants.FEATURE_SECURE_PROCESSING;
try {
boolean securityOn = !isXMLSecurityDisabled(disableSecurity);
factory.setFeature(featureToSet, securityOn);
factory.setNamespaceAware(true);
if (securityOn) {
featureToSet = DISALLOW_DOCTYPE_DECL;
factory.setFeature(featureToSet, true);
featureToSet = EXTERNAL_GE;
factory.setFeature(featureToSet, false);
featureToSet = EXTERNAL_PE;
factory.setFeature(featureToSet, false);
featureToSet = LOAD_EXTERNAL_DTD;
factory.setFeature(featureToSet, false);
}
} catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) {
LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support "+featureToSet+" feature!", new Object[]{factory.getClass().getName()});
}
return factory;
}
@Override
public Object decode(Response response, Type type) throws IOException {
if (response.status() == 204)
return Util.emptyValueOf(type);
if (response.body() == null)
return null;
while (type instanceof ParameterizedType) {
ParameterizedType ptype = (ParameterizedType) type;
type = ptype.getRawType();
}
if (!(type instanceof Class)) {
throw new UnsupportedOperationException(
"JAXB only supports decoding raw types. Found " + type);
}
try {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
/* Explicitly control sax configuration to prevent XXE attacks */
saxParserFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
saxParserFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
saxParserFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
saxParserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",
false);
saxParserFactory.setNamespaceAware(namespaceAware);
return jaxbContextFactory.createUnmarshaller((Class<?>) type).unmarshal(new SAXSource(
saxParserFactory.newSAXParser().getXMLReader(),
new InputSource(response.body().asInputStream())));
} catch (JAXBException | ParserConfigurationException | SAXException e) {
throw new DecodeException(response.status(), e.toString(), response.request(), e);
} finally {
if (response.body() != null) {
response.body().close();
}
}
}
/**
* Test the functionality of setFeature and getFeature methods
* for namespaces property.
* @throws Exception If any errors occur.
*/
@Test
public void testFeature02() throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature(NAMESPACES, true);
assertTrue(spf.getFeature(NAMESPACES));
spf.setFeature(NAMESPACES, false);
assertFalse(spf.getFeature(NAMESPACES));
}
private void checkWellFormedness(String xml) throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true); // Same as default
spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
SAXParser sp = spf.newSAXParser();
// Re-parse output to make sure that it is well formed
sp.parse(new InputSource(new StringReader(xml)), new DefaultHandler());
}
private static SAXParser getSAXParser() throws PcodeXMLException {
try {
SAXParserFactory saxParserFactory = XmlUtilities.createSecureSAXParserFactory(false);
saxParserFactory.setFeature("http://xml.org/sax/features/namespaces", false);
saxParserFactory.setFeature("http://xml.org/sax/features/validation", false);
return saxParserFactory.newSAXParser();
}
catch (Exception e) {
throw new PcodeXMLException("Failed to instantiate XML parser", e);
}
}
/**
* Setting the EntityExpansion Limit to 2 and checks if the XML
* document that has more than two levels of entity expansion is parsed or
* not. Previous system property was changed to jdk.xml.entityExpansionLimit
* see http://docs.oracle.com/javase/tutorial/jaxp/limits/limits.html.
*
* @throws Exception If any errors occur.
*/
@Test(expectedExceptions = SAXParseException.class)
public void testEntityExpansionSAXNeg() throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
// Secure processing will limit XML processing to conform to
// implementation limits.
factory.setFeature(FEATURE_SECURE_PROCESSING, true);
// Set entityExpansionLimit as 2 should expect SAXParseException.
setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(2));
SAXParser parser = factory.newSAXParser();
MyErrorHandler fatalHandler = new MyErrorHandler();
parser.parse(new File(ENTITY_XML), fatalHandler);
}
/**
* Hardens the provided factory to protect against an XML External Entity (XXE) attack.
*
* @param factory - The factory to be modified.
* @throws SAXNotRecognizedException
* @throws SAXNotSupportedException
* @throws ParserConfigurationException
*/
public static void harden(final SAXParserFactory factory)
throws SAXNotRecognizedException, SAXNotSupportedException, ParserConfigurationException {
// From: https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet
// To protect a Java SAXParserFactory from XXE, do this:
// This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
// If you can't completely disable DTDs, then at least do the following:
// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities
// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities
// JDK7+ - http://xml.org/sax/features/external-general-entities
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
// JDK7+ - http://xml.org/sax/features/external-parameter-entities
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
// Disable external DTDs as well
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
// and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks" (see reference
// below)
factory.setXIncludeAware(false);
}
/** internally formats the given file and computes their checksum
*
* @param file the file
* @param original checksum of the original file
* @param formatted checksum of the formatted file
* @return the formatted bytes
* @throws IOException if an error occurs */
private byte[] format(File file, Checksum original, Checksum formatted) throws IOException {
try (InputStream in = new CheckedInputStream(new BufferedInputStream(new FileInputStream(file)), original)) {
@SuppressWarnings("resource")
ByteArrayOutputStream buffer = formattingBuffer != null ? formattingBuffer.get() : null;
if (buffer == null) {
buffer = new ByteArrayOutputStream();
formattingBuffer = new WeakReference<>(buffer);
} else {
buffer.reset();
}
try (OutputStream out = new CheckedOutputStream(buffer, formatted);
FormattingXmlStreamWriter writer = FormattingXmlStreamWriter.create(out, format)) {
// cannot use XMlStreamReader due to comment handling:
// https://stackoverflow.com/questions/15792007/why-does-xmlstreamreader-staxsource-strip-comments-from-xml
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
SAXSource saxSource = new SAXSource(new InputSource(in));
SAXParserFactory sf = SAXParserFactory.newInstance();
sf.setNamespaceAware(true);
sf.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
sf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
saxSource.setXMLReader(new NormalizingSaxFilter(sf.newSAXParser().getXMLReader()));
Transformer t = tf.newTransformer();
StAXResult result = new StAXResult(writer);
t.transform(saxSource, result);
}
return buffer.toByteArray();
} catch (TransformerException | XMLStreamException | FactoryConfigurationError | ParserConfigurationException | SAXException ex) {
throw new IOException(ex);
}
}
/**
* Test the functionality of setFeature method for
* external-parameter-entitie property.
* @throws Exception If any errors occur.
*/
@Test
public void testFeature10() throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature(EXTERNAL_P_ENTITIES, false);
assertFalse(spf.getFeature(EXTERNAL_P_ENTITIES));
}
@NonNull
private Document parse(@NonNull String xml, @NonNull InputSource input, boolean checkBom)
throws ParserConfigurationException, SAXException, IOException {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature(NAMESPACE_FEATURE, true);
factory.setFeature(NAMESPACE_PREFIX_FEATURE, true);
factory.setFeature(PROVIDE_XMLNS_URIS, true);
SAXParser parser = factory.newSAXParser();
DomBuilder handler = new DomBuilder(xml);
XMLReader xmlReader = parser.getXMLReader();
xmlReader.setProperty(
"http://xml.org/sax/properties/lexical-handler",
handler
);
parser.parse(input, handler);
return handler.getDocument();
} catch (SAXException e) {
if (checkBom && e.getMessage().contains("Content is not allowed in prolog")) {
// Byte order mark in the string? Skip it. There are many markers
// (see http://en.wikipedia.org/wiki/Byte_order_mark) so here we'll
// just skip those up to the XML prolog beginning character, <
xml = xml.replaceFirst("^([\\W]+)<","<"); //$NON-NLS-1$ //$NON-NLS-2$
return parse(xml, new InputSource(new StringReader(xml)), false);
}
throw e;
}
}
@Test
public void test() throws Exception {
String invalidXml = "<a>";
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setFeature("http://apache.org/xml/features/continue-after-fatal-error", true);
SAXParser parser = saxParserFactory.newSAXParser();
parser.parse(new InputSource(new StringReader(invalidXml)), new DefaultHandler() {
@Override
public void fatalError(SAXParseException e) throws SAXException {
System.err.printf("%s%n", e.getMessage());
}
});
}
private void prossParser(Closeable closeable, Call call) throws IOException {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
factory.setFeature("http://xml.org/sax/features/namespaces", true);
call.parser(factory.newSAXParser());
} catch (Exception e) {
throw new IOException(e);
} finally {
IOUtils.closeQuietly(closeable);
}
}
public Element parse(InputStream stream) throws FHIRFormatError, DefinitionException, FHIRException, IOException {
Document doc = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// xxe protection
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
factory.setNamespaceAware(true);
if (policy == ValidationPolicy.EVERYTHING) {
// use a slower parser that keeps location data
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer nullTransformer = transformerFactory.newTransformer();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
doc = docBuilder.newDocument();
DOMResult domResult = new DOMResult(doc);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(false);
// xxe protection
spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
// xxe protection
xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
XmlLocationAnnotator locationAnnotator = new XmlLocationAnnotator(xmlReader, doc);
InputSource inputSource = new InputSource(stream);
SAXSource saxSource = new SAXSource(locationAnnotator, inputSource);
nullTransformer.transform(saxSource, domResult);
} else {
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(stream);
}
} catch (Exception e) {
logError(0, 0, "(syntax)", IssueType.INVALID, e.getMessage(), IssueSeverity.FATAL);
doc = null;
}
if (doc == null)
return null;
else
return parse(doc);
}
/**
* Here namespace processing is disabled, and namespace-prefixes is
* disabled. This will make namespace processing on.The testcase tests
* SAXParserFactory for this. This behavior only apply to crimson,
* not xerces.
*
* @throws Exception If any errors occur.
*/
@Test
public void spNSTable04() throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature(NAMESPACE_PREFIXES, false);
assertFalse(spf.getFeature(NAMESPACE_PREFIXES));
}