protected static String getXmlEncoding ( Reader reader ) { try { StringWriter sw = new StringWriter ( MAX_XMLDECL_SIZE ) ; int c ; int count = 0 ; for ( ; ( 6 > count ) && ( - 1 != ( c = reader . read ( ) ) ) ; count ++ ) { sw . write ( c ) ; } /* * Hmm, checking for the case when there is no XML declaration and * document begins with processing instruction whose target name * starts with "<?xml" ("<?xmlfoo"). Sounds like a nearly impossible * thing, but Xerces guys are checking for that somewhere in the * depths of their code :) */ if ( ( 6 > count ) || ( ! "<?xml " . equals ( sw . toString ( ) ) ) ) { if ( LOGGER . isLoggable ( Level . FINER ) ) { LOGGER . finer ( "Invalid(?) XML declaration: " + sw . toString ( ) + "." ) ; } return null ; } /* * Continuing reading declaration(?) til the first '>' ('\u003E') * encountered. Conversion from `int` to `char` should be safe * for our purposes, at least I'm not expecting any extended * (0x10000+) characters in xml declaration. I also limited * the total number of chars read this way to prevent any * malformed (no '>') input potentially forcing us to read * megabytes of useless data :) */ for ( ; ( MAX_XMLDECL_SIZE > count ) && ( - 1 != ( c = reader . read ( ) ) ) && ( RIGHT_ANGLE_BRACKET != ( char ) c ) ; count ++ ) { sw . write ( c ) ; } Matcher m = ENCODING_PATTERN . matcher ( sw . toString ( ) ) ; if ( m . find ( ) ) { String result = m . group ( 1 ) ; return result ; } else { return null ; } } catch ( IOException e ) { if ( LOGGER . isLoggable ( Level . WARNING ) ) { LOGGER . warning ( "Failed to extract charset info from XML " + "declaration due to IOException: " + e . getMessage ( ) ) ; } return null ; } }
Gets the encoding of the xml request made to the dispatcher . This works by reading the temp file where we are storing the request looking to match the header specified encoding that should be present on all xml files . This call should only be made after the temp file has been set . If no encoding is found or if an IOError is encountered then null shall be returned .