public static void validateHtml ( final File validationResultDir , final Configuration props , final File file ) throws IOException { Preconditions . checkArgument ( StringUtils . isNotBlank ( props . get ( WebConstants . W3C_MARKUP_VALIDATION_URL ) ) ) ; InputStream is = null ; BufferedReader br = null ; InputStream fis = null ; try { // Post HTML file to markup validation service as multipart/form-data URL url = new URL ( props . get ( WebConstants . W3C_MARKUP_VALIDATION_URL ) ) ; URLConnection uc = url . openConnection ( ) ; MultipartPostRequest request = new MultipartPostRequest ( uc ) ; fis = new FileInputStream ( file ) ; /* * See http://validator.w3.org/docs/api.html#requestformat for a description of all * parameters */ request . setParameter ( "uploaded_file" , file . getPath ( ) , fis ) ; is = request . post ( ) ; // Summary of validation is available in the HTTP headers String status = uc . getHeaderField ( STATUS ) ; int errors = Integer . parseInt ( uc . getHeaderField ( ERRORS ) ) ; LOG . info ( "Page " + file . getName ( ) + ": Number of HTML validation errors=" + errors ) ; int warnings = Integer . parseInt ( uc . getHeaderField ( WARNINGS ) ) ; LOG . info ( "Page " + file . getName ( ) + ": Number of HTML validation warnings=" + warnings ) ; // Check if result file has to be written String level = props . get ( WebConstants . W3C_MARKUP_VALIDATION_LEVEL , "ERROR" ) ; boolean validate = false ; if ( StringUtils . equalsIgnoreCase ( level , "WARNING" ) && ( warnings > 0 || errors > 0 ) ) { validate = true ; } else if ( StringUtils . equalsIgnoreCase ( level , "ERROR" ) && errors > 0 ) { validate = true ; } else if ( StringUtils . equalsIgnoreCase ( "Invalid" , status ) ) { validate = true ; } if ( validate ) { br = new BufferedReader ( new InputStreamReader ( is ) ) ; String line = null ; StringBuffer sb = new StringBuffer ( ) ; while ( ( line = br . readLine ( ) ) != null ) { sb . append ( line ) ; sb . append ( ' ' ) ; } PrintWriter writer = null ; String fileName = file . getName ( ) . substring ( 0 , file . getName ( ) . length ( ) - 5 ) + "_validation_result.html" ; FileUtils . forceMkdir ( validationResultDir ) ; File validationResultFile = new File ( validationResultDir , fileName ) ; try { writer = new PrintWriter ( validationResultFile , "UTF-8" ) ; writer . write ( sb . toString ( ) ) ; LOG . info ( "Validation result saved in file " + validationResultFile . getName ( ) ) ; } catch ( IOException ex ) { LOG . error ( "Could not write HTML file " + validationResultFile . getName ( ) + "to directory" , ex ) ; } finally { IOUtils . closeQuietly ( writer ) ; } } } finally { IOUtils . closeQuietly ( br ) ; IOUtils . closeQuietly ( fis ) ; } }
Validates an HTML file against the W3C markup validation service .