I have the following code (works OK) and I must secure it adding some restrictions to the unmarshaling process
public static Response getObjectBinResponse1(String xml) throws JAXBException{
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(xml);
Response rsp=(Response) unmarshaller.unmarshal(reader);
reader.close();
return rsp;
}
I tried this:
public static Response getObjectBinResponse2(String xml) throws JAXBException, ParserConfigurationException, SAXException, UnsupportedEncodingException{
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
spf.setFeature("http://xml.org/sax/features/validation", false);
XMLReader xmlReader = spf.newSAXParser().getXMLReader();
InputSource inputSource = new InputSource(new StringReader(xml));
SAXSource source = new SAXSource(xmlReader, inputSource);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Response rsp=(Response) unmarshaller.unmarshal(source);
return rsp;
}
But this code raises the following error:
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"ns0:Response"). Expected elements are <{http://www.xxx.yy/aaa/vbb/v1}Response>
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:726)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:247)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:242)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:109)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1131)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:556)
I tried the code of this answer by changing a source file to a string. How to disable DTD fetching using JAXB2.0
The name of class is correct
@XmlRootElement(name = "Response")
public class Response {
I have the file package-info.java correct
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.xxx.yy/aaa/vbb/v1")
package my.generated.package.from.xsd.with.jaxb;
And the xml string looks like
String xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?><ns0:Response xmlns:ns0=\"http://www.xxx.yy/aaa/vbb/v1\"><enca......
If I change this line
SAXSource source = new SAXSource(xmlReader, inputSource);
To this
SAXSource source = new SAXSource(inputSource);
Works, but I need the xmlReader because of restrictions
Resolved, after SAXParserFactory it is necessary to place setNamespaceAware=true
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);