Builds a document from the content of the web response. A warning is logged if an exception is thrown while parsing the XML content (for instance when the content is not a valid XML and can't be parsed). @param webResponse the response from the server @throws IOException if the page could not be cr
(final WebResponse webResponse)
| 119 | * @throws ParserConfigurationException if a DocumentBuilder cannot be created |
| 120 | */ |
| 121 | public static Document buildDocument(final WebResponse webResponse) |
| 122 | throws IOException, SAXException, ParserConfigurationException { |
| 123 | |
| 124 | final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); |
| 125 | |
| 126 | if (webResponse == null) { |
| 127 | return factory.newDocumentBuilder().newDocument(); |
| 128 | } |
| 129 | |
| 130 | factory.setNamespaceAware(true); |
| 131 | |
| 132 | Charset charset = webResponse.getContentCharset(); |
| 133 | try (InputStream is = webResponse.getContentAsStreamWithBomIfApplicable()) { |
| 134 | if (is instanceof BOMInputStream stream) { |
| 135 | final String bomCharsetName = stream.getBOMCharsetName(); |
| 136 | if (bomCharsetName != null) { |
| 137 | charset = Charset.forName(bomCharsetName); |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | try (InputStreamReader reader = new InputStreamReader(is, charset)) { |
| 142 | // we have to do the blank input check and the parsing in one step |
| 143 | final TrackBlankContentAndSkipLeadingWhitespaceReader tracker |
| 144 | = new TrackBlankContentAndSkipLeadingWhitespaceReader(reader); |
| 145 | |
| 146 | final InputSource source = new InputSource(tracker); |
| 147 | final DocumentBuilder builder = factory.newDocumentBuilder(); |
| 148 | builder.setErrorHandler(DISCARD_MESSAGES_HANDLER); |
| 149 | builder.setEntityResolver((publicId, systemId) -> new InputSource(new StringReader(""))); |
| 150 | try { |
| 151 | // this closes the input source/stream |
| 152 | return builder.parse(source); |
| 153 | } |
| 154 | catch (final SAXException e) { |
| 155 | if (tracker.wasBlank()) { |
| 156 | return factory.newDocumentBuilder().newDocument(); |
| 157 | } |
| 158 | throw e; |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | /** |
| 165 | * Helper for memory and performance optimization. |
no test coverage detected