Fix a crash in checkstyle.py when passing in non UTF-8 characters.

1. The language printed by the style checker depend on locale.
   There might be differnt language other than english.
   Use xml ending tag to handle the footer instead of use footer itself.
2. Use system encoding for printed text, if it is ascii, set it to
   UTF-8.
3. Fix the print out to only have one "ERRORS:" and "WARNINGS:" header.
   (Bug was introduced in r.android.com/661701)

Bug: 122443089
Test: None
Change-Id: I6c985ce656c7a55d35ea66f8b6d727d21544e6ad
diff --git a/checkstyle.py b/checkstyle.py
index 420f256..a73c7da 100755
--- a/checkstyle.py
+++ b/checkstyle.py
@@ -152,10 +152,13 @@
 
 def _PrintErrorsAndWarnings(errors, warnings):
   """Prints given errors and warnings."""
+  system_encoding = sys.getdefaultencoding()
+  if (system_encoding == 'ascii'):
+    system_encoding = 'UTF-8'
   if errors:
-    print('ERRORS:\n'.join(errors))
+    print('ERRORS:\n' + '\n'.join(map(lambda x: x.encode(system_encoding), errors)))
   if warnings:
-    print('WARNINGS:\n%s'.join(warnings))
+    print('WARNINGS:\n' + '\n'.join(map(lambda x: x.encode(system_encoding), warnings)))
 
 
 def _ExecuteCheckstyle(java_files, classpath, config_xml):
@@ -180,7 +183,7 @@
                              stdout=subprocess.PIPE, env=checkstyle_env)
     stdout, _ = check.communicate()
     # A work-around for Checkstyle printing error count to stdio.
-    if 'Checkstyle ends with' in stdout.splitlines()[-1]:
+    if '</checkstyle>' in stdout.splitlines()[-2]:
       stdout = '\n'.join(stdout.splitlines()[:-1])
     return stdout
   except OSError as e: