private static Document loadTemplateDocument ( String templateName , DocumentBuilder builder , Reader reader ) throws IOException { final int READ_AHEAD_SIZE = 5 ; BufferedReader bufferedReader = new BufferedReader ( reader ) ; bufferedReader . mark ( READ_AHEAD_SIZE ) ; char [ ] cbuf = new char [ READ_AHEAD_SIZE ] ; for ( int i = 0 ; i < READ_AHEAD_SIZE ; ++ i ) { int c = bufferedReader . read ( ) ; if ( c == - 1 ) { throw new IOException ( String . format ( "Invalid X(HT)ML template |%s|. Premature EOF." , templateName ) ) ; } cbuf [ i ] = ( char ) c ; } String header = new String ( cbuf ) ; if ( header . charAt ( 0 ) != ' ' ) { throw new TemplateException ( "Invalid X(HT)ML template |%s|. Seems not XML like document." , templateName ) ; } // trivial heuristic to determine file is XML or HTML; if is not explicitly HTML is considered XML boolean isXML = true ; if ( header . charAt ( 1 ) == ' ' ) { // HTML DOCTYPE always starts with <! isXML = false ; } else if ( header . charAt ( 1 ) == ' ' ) { // XML prolog always starts with <? isXML = true ; } else { // if not explicitly found HTML DOCTYPE or XML prolog uses root element to detect if HTML // if anything else but <html document is considered XML log . warn ( "No prolog found for X(HT)ML template |%s|. Uses root element to detect document type." , templateName ) ; if ( header . toLowerCase ( ) . startsWith ( "<html" ) ) { isXML = false ; } } bufferedReader . reset ( ) ; return isXML ? builder . loadXML ( bufferedReader ) : builder . loadHTML ( bufferedReader ) ; // do not attempt to close reader because DocumentBuilder.load[X|HT]ML() method takes care of that }
Loads and parses template document then returns it .