== How to fix it in Java SE

=== Code examples

include::../../common/fix/code-rationale.adoc[]

==== Noncompliant code example

[source,java,diff-id=1,diff-type=noncompliant]
----
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;

public void decode() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Noncompliant
}
----

[source,java,diff-id=2,diff-type=noncompliant]
----
import javax.xml.stream.XMLInputFactory;

public void decode() {
    XMLInputFactory factory = XMLInputFactory.newInstance(); // Noncompliant
}
----

==== Compliant solution

For `DocumentBuilderFactory`, `SAXParserFactory`, `TransformerFactory`, and
`SchemaFactory` set `XMLConstants.FEATURE_SECURE_PROCESSING` to `true`.

[source,java,diff-id=1,diff-type=compliant]
----
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;

public void decode() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
----

For `XMLInputFactory` set `SUPPORT_DTD` to `false`.

[source,java,diff-id=2,diff-type=compliant]
----
import javax.xml.stream.XMLInputFactory;

public void decode() {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
}
----

Other combinations of settings are secure, but in general, it is recommendable
to use the approaches shown here, as they are the most clear.

=== How does this work?

include::../../common/fix/xxe.adoc[]

=== Going the extra mile

==== Disable entity expansion

Specifically for `DocumentBuilderFactory`, it is possible to disable the entity
expansion. Note, however, that this does not prevent the retrieval of external
entities.

[source, java]
----
factory.setExpandEntityReferences(false);
----

