spotbugs fixes and cleanups

git-svn-id: https://svn.apache.org/repos/asf/xmlbeans/trunk@1881669 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/main/java/org/apache/xmlbeans/XmlBeans.java b/src/main/java/org/apache/xmlbeans/XmlBeans.java
index d7ae860..5c131a2 100644
--- a/src/main/java/org/apache/xmlbeans/XmlBeans.java
+++ b/src/main/java/org/apache/xmlbeans/XmlBeans.java
@@ -33,8 +33,7 @@
  * for managing XML Bean types, type systems, QNames, paths,
  * and queries.
  */
-public final class XmlBeans
-{
+public final class XmlBeans {
     private static final String HOLDER_CLASS_NAME = "TypeSystemHolder";
     private static final String TYPE_SYSTEM_FIELD = "typeSystem";
 
@@ -42,8 +41,7 @@
     private static String XMLBEANS_VERSION = "4.0.0";
     private static String XMLBEANS_VENDOR = "Apache Software Foundation";
 
-    static
-    {
+    static {
         Package pkg = XmlBeans.class.getPackage();
         if (pkg != null && pkg.getImplementationVersion() != null) {
             XMLBEANS_TITLE = pkg.getImplementationTitle();
@@ -57,8 +55,7 @@
      * the value of
      * {@link Package#getImplementationTitle() XmlBeans.class.getPackage().getImplementationTitle()}.
      */
-    public static final String getTitle()
-    {
+    public static final String getTitle() {
         return XMLBEANS_TITLE;
     }
 
@@ -67,8 +64,7 @@
      * the value of
      * {@link Package#getImplementationVendor() XmlBeans.class.getPackage().getImplementationVendor()}.
      */
-    public static final String getVendor()
-    {
+    public static final String getVendor() {
         return XMLBEANS_VENDOR;
     }
 
@@ -77,8 +73,7 @@
      * the value of
      * {@link Package#getImplementationVersion() XmlBeans.class.getPackage().getImplementationVersion()}.
      */
-    public static final String getVersion()
-    {
+    public static final String getVersion() {
         return XMLBEANS_VERSION;
     }
 
@@ -86,11 +81,9 @@
      * Thread local QName cache for general use
      */
     private static final ThreadLocal _threadLocalLoaderQNameCache =
-        new ThreadLocal()
-        {
-            protected Object initialValue()
-            {
-                return new SoftReference(new QNameCache( 32 ));
+        new ThreadLocal() {
+            protected Object initialValue() {
+                return new SoftReference(new QNameCache(32));
             }
         };
 
@@ -102,13 +95,11 @@
     /**
      * Returns a thread local QNameCache
      */
-    public static QNameCache getQNameCache ( )
-    {
-        SoftReference softRef = (SoftReference)_threadLocalLoaderQNameCache.get();
+    public static QNameCache getQNameCache() {
+        SoftReference softRef = (SoftReference) _threadLocalLoaderQNameCache.get();
         QNameCache qnameCache = (QNameCache) (softRef).get();
-        if (qnameCache==null)
-        {
-            qnameCache = new QNameCache( 32 );
+        if (qnameCache == null) {
+            qnameCache = new QNameCache(32);
             _threadLocalLoaderQNameCache.set(new SoftReference(qnameCache));
         }
         return qnameCache;
@@ -117,23 +108,20 @@
     /**
      * Obtains a name from the thread local QNameCache
      */
-    public static QName getQName ( String localPart )
-    {
-        return getQNameCache().getName( "",  localPart );
+    public static QName getQName(String localPart) {
+        return getQNameCache().getName("", localPart);
     }
 
     /**
      * Obtains a name from the thread local QNameCache
      */
 
-    public static QName getQName ( String namespaceUri, String localPart )
-    {
-        return getQNameCache().getName( namespaceUri,  localPart );
+    public static QName getQName(String namespaceUri, String localPart) {
+        return getQNameCache().getName(namespaceUri, localPart);
     }
 
-    private static RuntimeException causedException ( RuntimeException e, Throwable cause )
-    {
-        e.initCause( cause );
+    private static RuntimeException causedException(RuntimeException e, Throwable cause) {
+        e.initCause(cause);
 
         return e;
     }
@@ -142,9 +130,8 @@
      * Compiles an XPath, returning a String equal to that which was passed,
      * but whose identity is that of one which has been precompiled and cached.
      */
-    public static String compilePath ( String pathExpr ) throws XmlException
-    {
-        return compilePath( pathExpr, null );
+    public static String compilePath(String pathExpr) throws XmlException {
+        return compilePath(pathExpr, null);
     }
 
     /**
@@ -153,24 +140,22 @@
      * takes an option for specifying text that indicates the name of context node.
      * The default is "this", as in "$this".
      *
-     * @param  options  Options for the path. For example, you can call
-     * the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)}
-     * method to specify a particular name for the expression
-     * variable that indicates the context node.
+     * @param options Options for the path. For example, you can call
+     *                the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)}
+     *                method to specify a particular name for the expression
+     *                variable that indicates the context node.
      */
-    public static String compilePath ( String pathExpr, XmlOptions options )
-        throws XmlException
-    {
-        return getContextTypeLoader().compilePath( pathExpr, options );
+    public static String compilePath(String pathExpr, XmlOptions options)
+        throws XmlException {
+        return getContextTypeLoader().compilePath(pathExpr, options);
     }
 
     /**
      * Compiles an XQuery, returning a String equal to that which was passed,
      * but whose identity is that of one which has been precompiled and cached.
      */
-    public static String compileQuery ( String queryExpr ) throws XmlException
-    {
-        return compileQuery( queryExpr, null );
+    public static String compileQuery(String queryExpr) throws XmlException {
+        return compileQuery(queryExpr, null);
     }
 
     /**
@@ -178,17 +163,16 @@
      * but whose identity is that of one which has been precompiled and cached;
      * takes an option for specifying text that indicates the context node.
      *
-     * @param  options  Options for the query. For example, you can call
-     * the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)}
-     * method to specify a particular name for the expression
-     * variable that indicates the context node and the
-     * {@link XmlOptions#setXqueryVariables(java.util.Map) XmlOptions.setXqueryVariables(Map)}
-     * method to map external variable names to values.
+     * @param options Options for the query. For example, you can call
+     *                the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)}
+     *                method to specify a particular name for the expression
+     *                variable that indicates the context node and the
+     *                {@link XmlOptions#setXqueryVariables(java.util.Map) XmlOptions.setXqueryVariables(Map)}
+     *                method to map external variable names to values.
      */
-    public static String compileQuery ( String queryExpr, XmlOptions options )
-        throws XmlException
-    {
-        return getContextTypeLoader().compileQuery( queryExpr, options );
+    public static String compileQuery(String queryExpr, XmlOptions options)
+        throws XmlException {
+        return getContextTypeLoader().compileQuery(queryExpr, options);
     }
 
     /**
@@ -215,28 +199,28 @@
     /**
      * Creates an XmlCursor for a DOM node which is implemented by XmlBwans
      */
-    public static XmlCursor nodeToCursor ( Node n ) {
+    public static XmlCursor nodeToCursor(Node n) {
         return Locale.nodeToCursor(n);
     }
 
     /**
      * Creates an XmlObject for a DOM node which is implemented by XmlBwans
      */
-    public static XmlObject nodeToXmlObject ( Node n ) {
+    public static XmlObject nodeToXmlObject(Node n) {
         return Locale.nodeToXmlObject(n);
     }
 
     /**
      * Creates an XmlObject for a DOM node which is implemented by XmlBwans
      */
-    public static XMLStreamReader nodeToXmlStreamReader ( Node n ) {
+    public static XMLStreamReader nodeToXmlStreamReader(Node n) {
         return Locale.nodeToXmlStream(n);
     }
 
     /**
      * Returns the XmlObject for a DOM node which is implemented by XmlBwans
      */
-    public static Node streamToNode ( XMLStreamReader xs ) {
+    public static Node streamToNode(XMLStreamReader xs) {
         return Locale.streamToNode(xs);
     }
 
@@ -248,8 +232,7 @@
      * linking, and returns a unioned typeloader that is suitable for
      * creating instances.
      */
-    public static SchemaTypeLoader loadXsd(XmlObject[] schemas) throws XmlException
-    {
+    public static SchemaTypeLoader loadXsd(XmlObject[] schemas) throws XmlException {
         return loadXsd(schemas, null);
     }
 
@@ -306,12 +289,11 @@
      * as described in {@link XmlOptions#setCompileNoValidation}.</li>
      * </ul>
      *
-     * @param schemas The schema definitions from which to build the schema type system.
+     * @param schemas  The schema definitions from which to build the schema type system.
      * @param typepath The path to already-compiled schema types for linking while processing.
-     * @param options Options specifying an error listener and/or validation behavior.
+     * @param options  Options specifying an error listener and/or validation behavior.
      */
-    public static SchemaTypeSystem compileXsd(XmlObject[] schemas, SchemaTypeLoader typepath, XmlOptions options) throws XmlException
-    {
+    public static SchemaTypeSystem compileXsd(XmlObject[] schemas, SchemaTypeLoader typepath, XmlOptions options) throws XmlException {
         return compileXmlBeans(null, null, schemas, null, typepath, null, options);
     }
 
@@ -354,12 +336,11 @@
      * as described in {@link XmlOptions#setCompileNoValidation}.</li>
      * </ul>
      *
-     * @param schemas The schema definitions from which to build the schema type system.
+     * @param schemas  The schema definitions from which to build the schema type system.
      * @param typepath The path to already-compiled schema types for linking while processing.
-     * @param options Options specifying an error listener and/or validation behavior.
+     * @param options  Options specifying an error listener and/or validation behavior.
      */
-    public static SchemaTypeSystem compileXsd(SchemaTypeSystem system, XmlObject[] schemas, SchemaTypeLoader typepath, XmlOptions options) throws XmlException
-    {
+    public static SchemaTypeSystem compileXsd(SchemaTypeSystem system, XmlObject[] schemas, SchemaTypeLoader typepath, XmlOptions options) throws XmlException {
         return compileXmlBeans(null, system, schemas, null, typepath, null, options);
     }
 
@@ -414,13 +395,13 @@
      * as described in {@link XmlOptions#setCompileNoValidation}.</li>
      * </ul>
      *
-     * @param name The type system name or null to use a randomly generated name.
-     * @param system A pre-existing SchemaTypeSystem used in incremental compilation.
-     * @param schemas The schema definitions from which to build the schema type system.
-     * @param config The configuration controls the code generation shape.
+     * @param name     The type system name or null to use a randomly generated name.
+     * @param system   A pre-existing SchemaTypeSystem used in incremental compilation.
+     * @param schemas  The schema definitions from which to build the schema type system.
+     * @param config   The configuration controls the code generation shape.
      * @param typepath The path to already-compiled schema types for linking while processing.
-     * @param filer The Filer instance used to create binary binding files and source text files.
-     * @param options Options specifying an error listener and/or validation behavior.
+     * @param filer    The Filer instance used to create binary binding files and source text files.
+     * @param options  Options specifying an error listener and/or validation behavior.
      */
     public static SchemaTypeSystem compileXmlBeans(String name, SchemaTypeSystem system, XmlObject[] schemas, BindingConfig config, SchemaTypeLoader typepath, Filer filer, XmlOptions options) throws XmlException {
         return SchemaTypeSystemCompiler.compile(name, system, schemas, config, typepath != null ? typepath : getContextTypeLoader(), filer, options);
@@ -461,40 +442,31 @@
      * Note: you will almost always need typeLoaderForClassLoader()
      * instead (see {@link XmlBeans#typeLoaderForClassLoader}).
      */
-    public static SchemaTypeSystem typeSystemForClassLoader(ClassLoader loader, String stsName)
-    {
-        try
-        {
+    public static SchemaTypeSystem typeSystemForClassLoader(ClassLoader loader, String stsName) {
+        try {
             ClassLoader cl = loader == null ? Thread.currentThread().getContextClassLoader() : loader;
             Class clazz = cl.loadClass(stsName + "." + HOLDER_CLASS_NAME);
             SchemaTypeSystem sts = (SchemaTypeSystem)
                 (clazz.getDeclaredField(TYPE_SYSTEM_FIELD).get(null));
-            if (sts == null)
-            {
+            if (sts == null) {
                 throw new RuntimeException("SchemaTypeSystem is null for field " +
-                    TYPE_SYSTEM_FIELD + " on class with name " + stsName +
-                    "." + HOLDER_CLASS_NAME +
-                    ". Please verify the version of xmlbeans.jar is correct.");
+                                           TYPE_SYSTEM_FIELD + " on class with name " + stsName +
+                                           "." + HOLDER_CLASS_NAME +
+                                           ". Please verify the version of xmlbeans.jar is correct.");
             }
             return sts;
-        }
-        catch (ClassNotFoundException e)
-        {
+        } catch (ClassNotFoundException e) {
             throw causedException(new RuntimeException("Cannot load SchemaTypeSystem. " +
-                "Unable to load class with name " + stsName + "." + HOLDER_CLASS_NAME +
-                ". Make sure the generated binary files are on the classpath."), e);
-        }
-        catch (NoSuchFieldException e)
-        {
+                                                       "Unable to load class with name " + stsName + "." + HOLDER_CLASS_NAME +
+                                                       ". Make sure the generated binary files are on the classpath."), e);
+        } catch (NoSuchFieldException e) {
             throw causedException(new RuntimeException("Cannot find field " +
-                TYPE_SYSTEM_FIELD + " on class " + stsName + "." + HOLDER_CLASS_NAME +
-                ". Please verify the version of xmlbeans.jar is correct."), e);
-        }
-        catch (IllegalAccessException e)
-        {
+                                                       TYPE_SYSTEM_FIELD + " on class " + stsName + "." + HOLDER_CLASS_NAME +
+                                                       ". Please verify the version of xmlbeans.jar is correct."), e);
+        } catch (IllegalAccessException e) {
             throw causedException(new RuntimeException("Field " +
-                TYPE_SYSTEM_FIELD + " on class " + stsName + "." + HOLDER_CLASS_NAME +
-                "is not accessible. Please verify the version of xmlbeans.jar is correct."), e);
+                                                       TYPE_SYSTEM_FIELD + " on class " + stsName + "." + HOLDER_CLASS_NAME +
+                                                       "is not accessible. Please verify the version of xmlbeans.jar is correct."), e);
         }
     }
 
@@ -510,22 +482,20 @@
      * Returns the SchemaType from a corresponding XmlObject subclass,
      * or null if none.
      */
-    public static SchemaType typeForClass(Class c)
-    {
-        if (c == null || !XmlObject.class.isAssignableFrom(c))
+    public static SchemaType typeForClass(Class c) {
+        if (c == null || !XmlObject.class.isAssignableFrom(c)) {
             return null;
+        }
 
-        try
-        {
+        try {
             Field typeField = c.getField("type");
 
-            if (typeField == null)
+            if (typeField == null) {
                 return null;
+            }
 
-            return (SchemaType)typeField.get(null);
-        }
-        catch (Exception e)
-        {
+            return (SchemaType) typeField.get(null);
+        } catch (Exception e) {
             return null;
         }
     }
@@ -544,7 +514,8 @@
      * which is the universal base type from which all other types
      * can be derived, and of which all instances are valid.)
      */
-    public static SchemaType NO_TYPE = getNoType();
+    public static final SchemaType NO_TYPE = getNoType();
 
-    private XmlBeans ( ) { }
+    private XmlBeans() {
+    }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/Diff.java b/src/main/java/org/apache/xmlbeans/impl/tool/Diff.java
index 504eb46..49adb83 100644
--- a/src/main/java/org/apache/xmlbeans/impl/tool/Diff.java
+++ b/src/main/java/org/apache/xmlbeans/impl/tool/Diff.java
@@ -19,69 +19,56 @@
 import org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl;
 
 import java.io.*;
-import java.util.List;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.ArrayList;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.jar.JarEntry;
 import java.util.jar.JarFile;
-import java.util.Enumeration;
 import java.util.zip.ZipEntry;
 
-public class Diff
-{
-    public static void main(String[] args)
-    {
-        if (args.length != 2)
-        {
+public class Diff {
+    public static void main(String[] args) {
+        if (args.length != 2) {
             System.out.println("Usage: diff <jarname1> <jarname2> to compare two jars");
             System.out.println("  or   diff <dirname1> <dirname2> to compare two dirs");
             return;
         }
         File file1 = new File(args[0]);
-        if (!file1.exists())
-        {
+        if (!file1.exists()) {
             System.out.println("File \"" + args[0] + "\" not found.");
             return;
         }
         File file2 = new File(args[1]);
-        if (!file2.exists())
-        {
+        if (!file2.exists()) {
             System.out.println("File \"" + args[1] + "\" not found.");
             return;
         }
-        List result = new ArrayList();
-        if (file1.isDirectory())
-        {
-            if (!file2.isDirectory())
-            {
+        List<String> result = new ArrayList<>();
+        if (file1.isDirectory()) {
+            if (!file2.isDirectory()) {
                 System.out.println("Both parameters have to be directories if the first parameter is a directory.");
                 return;
             }
             dirsAsTypeSystems(file1, file2, result);
-        }
-        else
-        {
-            if (file2.isDirectory())
-            {
+        } else {
+            if (file2.isDirectory()) {
                 System.out.println("Both parameters have to be jar files if the first parameter is a jar file.");
                 return;
             }
-            try
-            {
-            JarFile jar1 = new JarFile(file1);
-            JarFile jar2 = new JarFile(file2);
-            jarsAsTypeSystems(jar1, jar2, result);
+            try {
+                JarFile jar1 = new JarFile(file1);
+                JarFile jar2 = new JarFile(file2);
+                jarsAsTypeSystems(jar1, jar2, result);
+            } catch (IOException ioe) {
+                ioe.printStackTrace();
             }
-            catch (IOException ioe)
-            { ioe.printStackTrace(); }
         }
-        if (result.size() < 1)
+        if (result.size() < 1) {
             System.out.println("No differences encountered.");
-        else
-        {
+        } else {
             System.out.println("Differences:");
-            for (int i = 0; i < result.size(); i++)
-                System.out.println(result.get(i).toString());
+            for (String s : result) {
+                System.out.println(s);
+            }
         }
     }
 
@@ -89,69 +76,61 @@
      * Diffs the contents of two jars, looking only at the schema typesystems
      * saved inside those jars
      */
-    public static void jarsAsTypeSystems(JarFile jar1, JarFile jar2, List diffs)
-    {
-        Enumeration entries1 = jar1.entries();
-        Enumeration entries2 = jar2.entries();
-        List list1 = new ArrayList();
-        List list2 = new ArrayList();
-        for (; entries1.hasMoreElements(); )
-        {
-            ZipEntry ze = (ZipEntry) entries1.nextElement();
+    public static void jarsAsTypeSystems(JarFile jar1, JarFile jar2, List<String> diffs) {
+        Enumeration<JarEntry> entries1 = jar1.entries();
+        Enumeration<JarEntry> entries2 = jar2.entries();
+        List<ZipEntry> list1 = new ArrayList<>();
+        List<ZipEntry> list2 = new ArrayList<>();
+        while (entries1.hasMoreElements()) {
+            ZipEntry ze = entries1.nextElement();
             String name = ze.getName();
-            if (name.startsWith(SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/system/s") && name.endsWith(".xsb"))
+            if (name.startsWith(SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/system/s") && name.endsWith(".xsb")) {
                 list1.add(ze);
+            }
         }
-        for (; entries2.hasMoreElements(); )
-        {
-            ZipEntry ze = (ZipEntry) entries2.nextElement();
+        while (entries2.hasMoreElements()) {
+            ZipEntry ze = entries2.nextElement();
             String name = ze.getName();
-            if (name.startsWith(SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/system/s") && name.endsWith(".xsb"))
+            if (name.startsWith(SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/system/s") && name.endsWith(".xsb")) {
                 list2.add(ze);
+            }
         }
-        ZipEntry[] files1 = (ZipEntry[]) list1.toArray(new ZipEntry[list1.size()]);
-        ZipEntry[] files2 = (ZipEntry[]) list2.toArray(new ZipEntry[list2.size()]);
-        ZipEntryNameComparator comparator = new ZipEntryNameComparator();
+        ZipEntry[] files1 = list1.toArray(new ZipEntry[0]);
+        ZipEntry[] files2 = list2.toArray(new ZipEntry[0]);
+        Comparator<ZipEntry> comparator = Comparator.comparing(ZipEntry::getName);
         Arrays.sort(files1, comparator);
         Arrays.sort(files2, comparator);
         int i1 = 0;
         int i2 = 0;
-        while (i1 < files1.length && i2 < files2.length)
-        {
+        while (i1 < files1.length && i2 < files2.length) {
             String name1 = files1[i1].getName();
             String name2 = files2[i2].getName();
             int dif = name1.compareTo(name2);
-            if (dif == 0)
-            {
+            if (dif == 0) {
                 // Compare the files
                 zipEntriesAsXsb(files1[i1], jar1, files2[i2], jar2, diffs);
-                i1++; i2++; // Move to next pair
-            }
-            else if (dif < 0)
-            {
+                i1++;
+                i2++; // Move to next pair
+            } else if (dif < 0) {
                 // dir1 contains a file that dir2 doesn't
                 diffs.add("Jar \"" + jar1.getName() + "\" contains an extra file: \"" +
-                    name1 + "\"");
+                          name1 + "\"");
                 i1++;
-            }
-            else if (dif > 0)
-            {
+            } else {
                 // dir2 contains a file that dir1 doesn't
                 diffs.add("Jar \"" + jar2.getName() + "\" contains an extra file: \"" +
-                    name2 + "\"");
+                          name2 + "\"");
                 i2++;
             }
         }
-        while (i1 < files1.length)
-        {
+        while (i1 < files1.length) {
             diffs.add("Jar \"" + jar1.getName() + "\" contains an extra file: \"" +
-                files1[i1].getName() + "\"");
+                      files1[i1].getName() + "\"");
             i1++;
         }
-        while (i2 < files2.length)
-        {
+        while (i2 < files2.length) {
             diffs.add("Jar \"" + jar2.getName() + "\" contains an extra file: \"" +
-                files2[i2].getName() + "\"");
+                      files2[i2].getName() + "\"");
             i2++;
         }
     }
@@ -162,223 +141,155 @@
      * Updated diffs with a list of differences (for the time being, strings
      * describing the difference)
      */
-    public static void dirsAsTypeSystems(File dir1, File dir2, List diffs)
-    {
+    public static void dirsAsTypeSystems(File dir1, File dir2, List<String> diffs) {
         assert dir1.isDirectory() : "Parameters must be directories";
         assert dir2.isDirectory() : "Parameters must be directories";
 
-        /**
-         * Navigate three directories deep to get to the type system.
-         * Assume the schema[METADATA_PACKAGE_LOAD]/system/* structure
+        /*
+          Navigate three directories deep to get to the type system.
+          Assume the schema[METADATA_PACKAGE_LOAD]/system/* structure
          */
         File temp1 = new File(dir1, SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/system");
         File temp2 = new File(dir2, SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/system");
-        if (temp1.exists() && temp2.exists())
-        {
+        if (temp1.exists() && temp2.exists()) {
             File[] files1 = temp1.listFiles();
             File[] files2 = temp2.listFiles();
-            if (files1.length == 1 && files2.length == 1)
-            {
+
+            assert (files1 != null && files2 != null);
+
+            if (files1.length == 1 && files2.length == 1) {
                 temp1 = files1[0];
                 temp2 = files2[0];
-            }
-            else
-            {
-                if (files1.length == 0)
+            } else {
+                if (files1.length == 0) {
                     temp1 = null;
-                if (files2.length == 0)
+                }
+                if (files2.length == 0) {
                     temp2 = null;
-                if (files1.length > 1)
-                {
+                }
+                if (files1.length > 1) {
                     diffs.add("More than one typesystem found in dir \"" +
-                        dir1.getName() + "\"");
+                              dir1.getName() + "\"");
                     return;
                 }
-                if (files2.length > 1)
-                {
+                if (files2.length > 1) {
                     diffs.add("More than one typesystem found in dir \"" +
-                        dir2.getName() + "\"");
+                              dir2.getName() + "\"");
                     return;
-                }                    
+                }
+            }
+        } else {
+            if (!temp1.exists()) {
+                temp1 = null;
+            }
+            if (!temp2.exists()) {
+                temp2 = null;
             }
         }
-        else
-        {
-            if (!temp1.exists())
-                temp1 = null;
-            if (!temp2.exists())
-                temp2 = null;
-        }
-        if (temp1 == null && temp2 == null)
+        if (temp1 == null && temp2 == null) {
             return;
-        else if (temp1 == null || temp2 == null)
-        {
-            if (temp1 == null)
+        } else if (temp1 == null || temp2 == null) {
+            if (temp1 == null) {
                 diffs.add("No typesystems found in dir \"" + dir1 + "\"");
-            if (temp2 == null)
+            }
+            if (temp2 == null) {
                 diffs.add("No typesystems found in dir \"" + dir2 + "\"");
+            }
             return;
-        }
-        else
-        {
+        } else {
             dir1 = temp1;
             dir2 = temp2;
         }
 
         boolean diffIndex = isDiffIndex();
-        XsbFilenameFilter xsbName = new XsbFilenameFilter();
+        FilenameFilter xsbName = (dir, name) -> name.endsWith(".xsb");
         File[] files1 = dir1.listFiles(xsbName);
         File[] files2 = dir2.listFiles(xsbName);
-        FileNameComparator comparator = new FileNameComparator();
+
+        assert (files1 != null && files2 != null);
+
+        Comparator<File> comparator = Comparator.comparing(File::getName);
         Arrays.sort(files1, comparator);
         Arrays.sort(files2, comparator);
         int i1 = 0;
         int i2 = 0;
-        while (i1 < files1.length && i2 < files2.length)
-        {
+        while (i1 < files1.length && i2 < files2.length) {
             String name1 = files1[i1].getName();
             String name2 = files2[i2].getName();
             int dif = name1.compareTo(name2);
-            if (dif == 0)
-            {
-                if (diffIndex || !files1[i1].getName().equals("index.xsb"))
+            if (dif == 0) {
+                if (diffIndex || !files1[i1].getName().equals("index.xsb")) {
                     filesAsXsb(files1[i1], files2[i2], diffs); // Compare the files
-                i1++; i2++; // Move to next pair
-            }
-            else if (dif < 0)
-            {
+                }
+                i1++;
+                i2++; // Move to next pair
+            } else if (dif < 0) {
                 // dir1 contains a file that dir2 doesn't
                 diffs.add("Dir \"" + dir1.getName() + "\" contains an extra file: \"" +
-                    name1 + "\"");
+                          name1 + "\"");
                 i1++;
-            }
-            else if (dif > 0)
-            {
+            } else {
                 // dir2 contains a file that dir1 doesn't
                 diffs.add("Dir \"" + dir2.getName() + "\" contains an extra file: \"" +
-                    name2 + "\"");
+                          name2 + "\"");
                 i2++;
             }
         }
-        while (i1 < files1.length)
-        {
+        while (i1 < files1.length) {
             diffs.add("Dir \"" + dir1.getName() + "\" contains an extra file: \"" +
-                files1[i1].getName() + "\"");
+                      files1[i1].getName() + "\"");
             i1++;
         }
-        while (i2 < files2.length)
-        {
+        while (i2 < files2.length) {
             diffs.add("Dir \"" + dir2.getName() + "\" contains an extra file: \"" +
-                files2[i2].getName() + "\"");
+                      files2[i2].getName() + "\"");
             i2++;
         }
     }
 
-    private static boolean isDiffIndex()
-    {
+    private static boolean isDiffIndex() {
         String prop = SystemProperties.getProperty("xmlbeans.diff.diffIndex");
-        if (prop == null)
-            return true;
-        if ("0".equals(prop) || "false".equalsIgnoreCase(prop))
-            return false;
-        return true;
+        return prop == null || !"0".equals(prop) && !"false".equalsIgnoreCase(prop);
     }
 
     /**
      * Diffs the two given files assuming they are in xsb format
      * Updates diffs with differences in string format
      */
-    public static void filesAsXsb(File file1, File file2, List diffs)
-    {
+    public static void filesAsXsb(File file1, File file2, List<String> diffs) {
         assert file1.exists() : "File \"" + file1.getAbsolutePath() + "\" does not exist.";
         assert file2.exists() : "File \"" + file2.getAbsolutePath() + "\" does not exist.";
-        try
-        {
-        FileInputStream stream1 = new FileInputStream(file1);
-        FileInputStream stream2 = new FileInputStream(file2);
-        streamsAsXsb(stream1, file1.getName(), stream2, file2.getName(), diffs);
+        try (FileInputStream stream1 = new FileInputStream(file1);
+             FileInputStream stream2 = new FileInputStream(file2)) {
+            streamsAsXsb(stream1, file1.getName(), stream2, file2.getName(), diffs);
+        } catch (IOException ignored) {
         }
-        catch (FileNotFoundException fnfe)
-        { }
-        catch (IOException ioe)
-        { }
     }
 
     public static void zipEntriesAsXsb(ZipEntry file1, JarFile jar1,
-        ZipEntry file2, JarFile jar2, List diffs)
-    {
-        try
-        {
-        InputStream stream1 = jar1.getInputStream(file1);
-        InputStream stream2 = jar2.getInputStream(file2);
-        streamsAsXsb(stream1, file1.getName(), stream2, file2.getName(), diffs);
+                                       ZipEntry file2, JarFile jar2, List<String> diffs) {
+        try (InputStream stream1 = jar1.getInputStream(file1);
+             InputStream stream2 = jar2.getInputStream(file2)) {
+            streamsAsXsb(stream1, file1.getName(), stream2, file2.getName(), diffs);
+        } catch (IOException ignored) {
         }
-        catch (IOException ioe)
-        { }
     }
 
     public static void streamsAsXsb(InputStream stream1, String name1,
-        InputStream stream2, String name2, List diffs)
-        throws IOException
-    {
+                                    InputStream stream2, String name2, List<String> diffs)
+        throws IOException {
+        String charset = StandardCharsets.UTF_8.name();
         ByteArrayOutputStream buf1 = new ByteArrayOutputStream();
         ByteArrayOutputStream buf2 = new ByteArrayOutputStream();
-        XsbDumper.dump(stream1, "", new PrintStream(buf1));
-        XsbDumper.dump(stream2, "", new PrintStream(buf2));
-        stream1.close();
-        stream2.close();
-        readersAsText(new StringReader(buf1.toString()), name1,
-            new StringReader(buf2.toString()), name2, diffs);
+        XsbDumper.dump(stream1, "", new PrintStream(buf1, true, charset));
+        XsbDumper.dump(stream2, "", new PrintStream(buf2, true, charset));
+        readersAsText(new StringReader(buf1.toString(charset)), name1,
+            new StringReader(buf2.toString(charset)), name2, diffs);
     }
 
     public static void readersAsText(Reader r1, String name1, Reader r2, String name2,
-        List diffs)
-        throws IOException
-    {
+                                     List<String> diffs)
+        throws IOException {
         org.apache.xmlbeans.impl.util.Diff.readersAsText(r1, name1, r2, name2, diffs);
     }
-
-    private static class XsbFilenameFilter implements FilenameFilter
-    {
-        public boolean accept(File dir, String name)
-        {
-            return name.endsWith(".xsb");
-        }
-    }
-
-    private static class ZipEntryNameComparator implements Comparator
-    {
-        public boolean equals(Object object)
-        {
-            return this == object;
-        }
-
-        public int compare(Object object1, Object object2)
-        {
-            assert (object1 instanceof ZipEntry) : "Must pass in a java.util.zip.ZipEntry as argument";
-            assert (object2 instanceof ZipEntry) : "Must pass in a java.util.zip.ZipEntry as argument";
-
-            String name1 = ((ZipEntry) object1).getName();
-            String name2 = ((ZipEntry) object2).getName();
-            return name1.compareTo(name2);
-        }
-    }
-
-    private static class FileNameComparator implements Comparator
-    {
-        public boolean equals(Object object)
-        {
-            return this == object;
-        }
-
-        public int compare(Object object1, Object object2)
-        {
-            assert (object1 instanceof File) : "Must pass in a java.io.File as argument";
-            assert (object2 instanceof File) : "Must pass in a java.io.File as argument";
-
-            String name1 = ((File) object1).getName();
-            String name2 = ((File) object2).getName();
-            return name1.compareTo(name2);
-        }
-    }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/Extension.java b/src/main/java/org/apache/xmlbeans/impl/tool/Extension.java
index ffd7b8d..34e6103 100644
--- a/src/main/java/org/apache/xmlbeans/impl/tool/Extension.java
+++ b/src/main/java/org/apache/xmlbeans/impl/tool/Extension.java
@@ -15,56 +15,57 @@
 
 package org.apache.xmlbeans.impl.tool;
 
-import java.util.List;
 import java.util.ArrayList;
+import java.util.List;
 
 
- /**
-  * An extension is a javabean that represents a SchemaCompilerExtension to be passed for callback into the
-  *  XmlBeans Schema Compiler.
-  */
+/**
+ * An extension is a javabean that represents a SchemaCompilerExtension to be passed for callback into the
+ * XmlBeans Schema Compiler.
+ */
 public class Extension {
-        private Class className;
-        private List params = new ArrayList();
+    private Class className;
+    private List<Param> params = new ArrayList<>();
 
-        public Class getClassName() {
-            return className;
+    public Class getClassName() {
+        return className;
+    }
+
+    public void setClassName(Class className) {
+        this.className = className;
+    }
+
+    public List<Param> getParams() {
+        return params;
+    }
+
+    public Param createParam() {
+        Param p = new Param();
+        params.add(p);
+        return p;
+    }
+
+    /**
+     * A Param is just a name value pair applicable to the extension.
+     */
+    public class Param {
+        private String name;
+        private String value;
+
+        public String getName() {
+            return name;
         }
 
-        public void setClassName(Class className) {
-            this.className = className;
-        }
-        public List getParams() {
-            return params;
+        public void setName(String name) {
+            this.name = name;
         }
 
-        public Param createParam() {
-            Param p = new Param();
-            params.add(p);
-            return p;
+        public String getValue() {
+            return value;
         }
 
-        /**
-         * A Param is just a name value pair applicable to the extension.
-         */
-        public class Param {
-            private String name;
-            private String value;
-
-            public String getName() {
-                return name;
-            }
-
-            public void setName(String name) {
-                this.name = name;
-            }
-
-            public String getValue() {
-                return value;
-            }
-
-            public void setValue(String value) {
-                this.value = value;
-            }
+        public void setValue(String value) {
+            this.value = value;
         }
-    }
\ No newline at end of file
+    }
+}
\ No newline at end of file
diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/RunXQuery.java b/src/main/java/org/apache/xmlbeans/impl/tool/RunXQuery.java
index b782a1f..9ffe860 100644
--- a/src/main/java/org/apache/xmlbeans/impl/tool/RunXQuery.java
+++ b/src/main/java/org/apache/xmlbeans/impl/tool/RunXQuery.java
@@ -15,14 +15,21 @@
 
 package org.apache.xmlbeans.impl.tool;
 
-import java.io.*;
-import java.util.*;
-import org.apache.xmlbeans.*;
+import org.apache.xmlbeans.XmlBeans;
+import org.apache.xmlbeans.XmlObject;
+import org.apache.xmlbeans.XmlOptions;
 
-public class RunXQuery
-{
-    public static void printUsage()
-    {
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+public class RunXQuery {
+    public static void printUsage() {
         System.out.println("Run an XQuery against an XML instance");
         System.out.println("Usage:");
         System.out.println("xquery [-verbose] [-pretty] [-q <query> | -qf query.xq] [file.xml]*");
@@ -31,12 +38,11 @@
         System.out.println(" -pretty pretty-prints the results");
         System.out.println(" -license prints license information");
         System.out.println(" the query is run on each XML file specified");
-        System.out.println("");
+        System.out.println();
     }
 
-    public static void main ( String[] args ) throws Exception
-    {
-        Set flags = new HashSet();
+    public static void main(String[] args) throws Exception {
+        Set<String> flags = new HashSet<>();
         flags.add("h");
         flags.add("help");
         flags.add("usage");
@@ -48,90 +54,82 @@
         CommandLine cl =
             new CommandLine(
                 args, flags,
-                Arrays.asList( new String[] { "q", "qf" } ) );
-        
-        if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null)
-        {
+                Arrays.asList("q", "qf"));
+
+        if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null) {
             printUsage();
             System.exit(0);
             return;
         }
 
         String[] badopts = cl.getBadOpts();
-        if (badopts.length > 0)
-        {
-            for (int i = 0; i < badopts.length; i++)
-                System.out.println("Unrecognized option: " + badopts[i]);
+        if (badopts.length > 0) {
+            for (String badopt : badopts) {
+                System.out.println("Unrecognized option: " + badopt);
+            }
             printUsage();
             System.exit(0);
             return;
         }
 
-        if (cl.getOpt("license") != null)
-        {
+        if (cl.getOpt("license") != null) {
             CommandLine.printLicense();
             System.exit(0);
             return;
         }
 
-        if (cl.getOpt("version") != null)
-        {
+        if (cl.getOpt("version") != null) {
             CommandLine.printVersion();
             System.exit(0);
             return;
         }
 
         args = cl.args();
-        
-        if (args.length == 0)
-        {
+
+        if (args.length == 0) {
             printUsage();
             System.exit(0);
             return;
         }
 
-        boolean verbose = cl.getOpt( "verbose" ) != null;
-        boolean pretty = cl.getOpt( "pretty" ) != null;
+        boolean verbose = cl.getOpt("verbose") != null;
+        boolean pretty = cl.getOpt("pretty") != null;
 
         //
         // Get and compile the query
         //
-        
-        String query = cl.getOpt( "q" );
-        String queryfile = cl.getOpt( "qf" );
 
-        if (query == null && queryfile == null)
-        {
-            System.err.println( "No query specified" );
+        String query = cl.getOpt("q");
+        String queryfile = cl.getOpt("qf");
+
+        if (query == null && queryfile == null) {
+            System.err.println("No query specified");
             System.exit(0);
             return;
         }
-        
-        if (query != null && queryfile != null)
-        {
-            System.err.println( "Specify -qf or -q, not both." );
+
+        if (query != null && queryfile != null) {
+            System.err.println("Specify -qf or -q, not both.");
             System.exit(0);
             return;
         }
-        
-        try
-        {
-            if (queryfile != null)
-            {
-                File queryFile = new File( queryfile );
-                FileInputStream is = new FileInputStream( queryFile );
-                InputStreamReader r = new InputStreamReader( is );
-                
+
+        try {
+            if (queryfile != null) {
+                File queryFile = new File(queryfile);
+                FileInputStream is = new FileInputStream(queryFile);
+                InputStreamReader r = new InputStreamReader(is, StandardCharsets.ISO_8859_1);
+
                 StringBuilder sb = new StringBuilder();
 
-                for ( ; ; )
-                {
+                for (; ; ) {
                     int ch = r.read();
 
-                    if (ch < 0)
+                    if (ch < 0) {
                         break;
+                    }
 
-                    sb.append( (char) ch );
+                    sb.append((char) ch);
                 }
 
                 r.close();
@@ -139,28 +137,22 @@
 
                 query = sb.toString();
             }
-        }
-        catch ( Throwable e )
-        {
-            System.err.println( "Cannot read query file: " + e.getMessage() );
+        } catch (Throwable e) {
+            System.err.println("Cannot read query file: " + e.getMessage());
             System.exit(1);
             return;
         }
 
-        if (verbose)
-        {
-            System.out.println( "Compile Query:" );
-            System.out.println( query );
+        if (verbose) {
+            System.out.println("Compile Query:");
+            System.out.println(query);
             System.out.println();
         }
-            
-        try
-        {
-            query= XmlBeans.compileQuery( query );
-        }
-        catch ( Exception e )
-        {
-            System.err.println( "Error compiling query: " + e.getMessage() );
+
+        try {
+            query = XmlBeans.compileQuery(query);
+        } catch (Exception e) {
+            System.err.println("Error compiling query: " + e.getMessage());
             System.exit(1);
             return;
         }
@@ -168,75 +160,65 @@
         //
         // Get the instance
         //
-        
-        File[] files = cl.getFiles();
-        
-        for (int i = 0; i < files.length; i++)
-        {
-            XmlObject x;
-                
-            try
-            {
-                if (verbose)
-                {
-                    InputStream is = new FileInputStream( files[i] );
 
-                    for ( ; ; )
-                    {
+        File[] files = cl.getFiles();
+
+        for (File file : files) {
+            XmlObject x;
+
+            try {
+                if (verbose) {
+                    InputStream is = new FileInputStream(file);
+
+                    for (; ; ) {
                         int ch = is.read();
 
-                        if (ch < 0)
+                        if (ch < 0) {
                             break;
+                        }
 
-                        System.out.write( ch );
+                        System.out.write(ch);
                     }
-                    
+
                     is.close();
 
                     System.out.println();
                 }
-                
-                x = XmlObject.Factory.parse( files[i] );
-            }
-            catch ( Throwable e )
-            {
-                System.err.println( "Error parsing instance: " + e.getMessage() );
+
+                x = XmlObject.Factory.parse(file);
+            } catch (Throwable e) {
+                System.err.println("Error parsing instance: " + e.getMessage());
                 System.exit(1);
                 return;
             }
-            
-            if (verbose)
-            {
-                System.out.println( "Executing Query..." );
+
+            if (verbose) {
+                System.out.println("Executing Query...");
                 System.err.println();
             }
-    
-            XmlObject[] result = null;
-    
-            try
-            {
-                result = x.execQuery( query );
-            }
-            catch ( Throwable e )
-            {
-                System.err.println( "Error executing query: " + e.getMessage() );
+
+            XmlObject[] result;
+
+            try {
+                result = x.execQuery(query);
+            } catch (Throwable e) {
+                System.err.println("Error executing query: " + e.getMessage());
                 System.exit(1);
                 return;
             }
-    
-            if (verbose)
-            {
-                System.out.println( "Query Result:" );
+
+            if (verbose) {
+                System.out.println("Query Result:");
             }
-            
+
             XmlOptions opts = new XmlOptions();
             opts.setSaveOuter();
-            if (pretty)
+            if (pretty) {
                 opts.setSavePrettyPrint();
-            
-            for (int j = 0; j < result.length; j++)
-            {
-                result[j].save( System.out, opts );
+            }
+
+            for (XmlObject xmlObject : result) {
+                xmlObject.save(System.out, opts);
                 System.out.println();
             }
         }
diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCompiler.java b/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCompiler.java
index 04d4259..6a6a920 100644
--- a/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCompiler.java
+++ b/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCompiler.java
@@ -25,6 +25,7 @@
 import org.apache.xmlbeans.impl.xb.xmlconfig.ConfigDocument;
 import org.apache.xmlbeans.impl.xb.xmlconfig.Extensionconfig;
 import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
+import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema;
 import org.xml.sax.EntityResolver;
 
 import java.io.File;
@@ -141,7 +142,6 @@
             return;
         }
 
-        args = cl.args();
         boolean verbose = (cl.getOpt("verbose") != null);
         boolean quiet = (cl.getOpt("quiet") != null);
         if (verbose) {
@@ -589,20 +589,6 @@
             this.javasource = javasource;
         }
 
-        /**
-         * @deprecated
-         */
-        public String getJar() {
-            return null;
-        }
-
-        /**
-         * @deprecated
-         */
-        public void setJar(String jar) {
-            // no op
-        }
-
         public Collection<XmlError> getErrorListener() {
             return errorListener;
         }
@@ -663,7 +649,7 @@
     private static SchemaTypeSystem loadTypeSystem(String name, File[] xsdFiles, File[] wsdlFiles, URL[] urlFiles, File[] configFiles,
                                                    File[] javaFiles, ResourceLoader cpResourceLoader,
                                                    boolean download, boolean noUpa, boolean noPvr, boolean noAnn, boolean noVDoc, boolean noExt,
-                                                   Set<String> mdefNamespaces, File baseDir, Map sourcesToCopyMap,
+                                                   Set<String> mdefNamespaces, File baseDir, Map<String, String> sourcesToCopyMap,
                                                    Collection<XmlError> outerErrorListener, File schemasDir, EntityResolver entResolver, File[] classpath, String javasource) {
         XmlErrorWatcher errorListener = new XmlErrorWatcher(outerErrorListener);
 
@@ -681,7 +667,7 @@
             SchemaTypeLoader loader = XmlBeans.typeLoaderForClassLoader(SchemaDocument.class.getClassLoader());
 
             // step 1, parse all the XSD files.
-            ArrayList<SchemaDocument.Schema> scontentlist = new ArrayList<>();
+            ArrayList<Schema> scontentlist = new ArrayList<>();
             if (xsdFiles != null) {
                 for (File xsdFile : xsdFiles) {
                     try {
@@ -766,7 +752,7 @@
                 }
             }
 
-            SchemaDocument.Schema[] sdocs = (SchemaDocument.Schema[]) scontentlist.toArray(new SchemaDocument.Schema[0]);
+            Schema[] sdocs = scontentlist.toArray(new Schema[0]);
 
             // now the config files.
             ArrayList<ConfigDocument.Config> cdoclist = new ArrayList<>();
@@ -855,7 +841,7 @@
     }
 
     private static void addSchema(String name, SchemaDocument schemadoc,
-                                  XmlErrorWatcher errorListener, boolean noVDoc, List<SchemaDocument.Schema> scontentlist) {
+                                  XmlErrorWatcher errorListener, boolean noVDoc, List<Schema> scontentlist) {
         StscState.addInfo(errorListener, "Loading schema file " + name);
         XmlOptions opts = new XmlOptions().setErrorListener(errorListener);
         if (noVDoc) {
@@ -868,7 +854,7 @@
 
     private static void addWsdlSchemas(String name,
                                        org.apache.xmlbeans.impl.xb.substwsdl.DefinitionsDocument wsdldoc,
-                                       XmlErrorWatcher errorListener, boolean noVDoc, List scontentlist) {
+                                       XmlErrorWatcher errorListener, boolean noVDoc, List<Schema> scontentlist) {
         if (wsdlContainsEncoded(wsdldoc)) {
             StscState.addWarning(errorListener, "The WSDL " + name + " uses SOAP encoding. SOAP encoding is not compatible with literal XML Schema.", XmlErrorCodes.GENERIC_ERROR, wsdldoc);
         }
@@ -879,18 +865,17 @@
         }
         XmlObject[] types = wsdldoc.getDefinitions().getTypesArray();
         int count = 0;
-        for (int j = 0; j < types.length; j++) {
-            XmlObject[] schemas = types[j].selectPath("declare namespace xs=\"http://www.w3.org/2001/XMLSchema\" xs:schema");
+        for (XmlObject type : types) {
+            Schema[] schemas = (Schema[]) type.selectPath("declare namespace xs=\"http://www.w3.org/2001/XMLSchema\" xs:schema");
             if (schemas.length == 0) {
                 StscState.addWarning(errorListener, "The WSDL " + name + " did not have any schema documents in namespace 'http://www.w3.org/2001/XMLSchema'", XmlErrorCodes.GENERIC_ERROR, wsdldoc);
                 continue;
             }
 
-            for (int k = 0; k < schemas.length; k++) {
-                if (schemas[k] instanceof SchemaDocument.Schema &&
-                    schemas[k].validate(opts)) {
+            for (Schema schema : schemas) {
+                if (schema.validate(opts)) {
                     count++;
-                    scontentlist.add(schemas[k]);
+                    scontentlist.add(schema);
                 }
             }
         }
@@ -924,7 +909,7 @@
         boolean noVDoc = params.isNoVDoc();
         boolean noExt = params.isNoExt();
         boolean incrSrcGen = params.isIncrementalSrcGen();
-        Collection outerErrorListener = params.getErrorListener();
+        Collection<XmlError> outerErrorListener = params.getErrorListener();
 
         String repackage = params.getRepackage();
 
@@ -941,8 +926,8 @@
         }
 
         SchemaCodePrinter codePrinter = params.getSchemaCodePrinter();
-        List extensions = params.getExtensions();
-        Set mdefNamespaces = params.getMdefNamespaces();
+        List<Extension> extensions = params.getExtensions();
+        Set<String> mdefNamespaces = params.getMdefNamespaces();
 
         EntityResolver cmdLineEntRes = params.getEntityResolver() == null ?
             ResolverUtil.resolverForCatalog(params.getCatalogFile()) : params.getEntityResolver();
@@ -955,12 +940,14 @@
 
         // Calculate the usenames based on the relativized filenames on the filesystem
         if (baseDir == null) {
-            baseDir = new File(SystemProperties.getProperty("user.dir"));
+            String userDir = SystemProperties.getProperty("user.dir");
+            assert (userDir != null);
+            baseDir = new File(userDir);
         }
 
         ResourceLoader cpResourceLoader = null;
 
-        Map sourcesToCopyMap = new HashMap();
+        Map<String, String> sourcesToCopyMap = new HashMap<>();
 
         if (classpath != null) {
             cpResourceLoader = new PathResourceLoader(classpath);
@@ -1005,12 +992,12 @@
             system.save(filer);
 
             // gen source files
-            result &= SchemaTypeSystemCompiler.generateTypes(system, filer, options);
+            result = SchemaTypeSystemCompiler.generateTypes(system, filer, options);
 
             if (incrSrcGen) {
                 // We have to delete extra source files that may be out of date
                 SchemaCodeGenerator.deleteObsoleteFiles(srcDir, srcDir,
-                    new HashSet(filer.getSourceFiles()));
+                    new HashSet<>(filer.getSourceFiles()));
             }
 
             if (result) {
@@ -1024,7 +1011,7 @@
             if (result && !nojavac) {
                 start = System.currentTimeMillis();
 
-                List sourcefiles = filer.getSourceFiles();
+                List<File> sourcefiles = filer.getSourceFiles();
 
                 if (javaFiles != null) {
                     sourcefiles.addAll(java.util.Arrays.asList(javaFiles));
@@ -1067,12 +1054,12 @@
         return result;
     }
 
-    private static void runExtensions(List extensions, SchemaTypeSystem system, File classesDir) {
+    private static void runExtensions(List<Extension> extensions, SchemaTypeSystem system, File classesDir) {
         if (extensions != null && extensions.size() > 0) {
-            SchemaCompilerExtension sce = null;
-            Iterator i = extensions.iterator();
-            Map extensionParms = null;
-            String classesDirName = null;
+            SchemaCompilerExtension sce;
+            Iterator<Extension> i = extensions.iterator();
+            Map<String, String> extensionParms;
+            String classesDirName;
             try {
                 classesDirName = classesDir.getCanonicalPath();
             } catch (java.io.IOException e) {
@@ -1081,7 +1068,7 @@
             }
 
             while (i.hasNext()) {
-                Extension extension = (Extension) i.next();
+                Extension extension = i.next();
                 try {
                     sce = (SchemaCompilerExtension) extension.getClassName().newInstance();
                 } catch (InstantiationException e) {
@@ -1095,10 +1082,8 @@
                 }
 
                 System.out.println("Running Extension: " + sce.getExtensionName());
-                extensionParms = new HashMap();
-                Iterator parmsi = extension.getParams().iterator();
-                while (parmsi.hasNext()) {
-                    Extension.Param p = (Extension.Param) parmsi.next();
+                extensionParms = new HashMap<>();
+                for (Extension.Param p : extension.getParams()) {
                     extensionParms.put(p.getName(), p.getValue());
                 }
                 extensionParms.put("classesDir", classesDirName);
@@ -1113,8 +1098,8 @@
         XmlObject[] useAttrs = wsdldoc.selectPath(
             "declare namespace soap='http://schemas.xmlsoap.org/wsdl/soap/' " +
             ".//soap:body/@use|.//soap:header/@use|.//soap:fault/@use");
-        for (int i = 0; i < useAttrs.length; i++) {
-            if ("encoded".equals(((SimpleValue) useAttrs[i]).getStringValue())) {
+        for (XmlObject useAttr : useAttrs) {
+            if ("encoded".equals(((SimpleValue) useAttr).getStringValue())) {
                 return true;
             }
         }
@@ -1123,10 +1108,6 @@
 
     private static final String CONFIG_URI = "http://xml.apache.org/xmlbeans/2004/02/xbean/config";
     private static final String COMPATIBILITY_CONFIG_URI = "http://www.bea.com/2002/09/xbean/config";
-    private static final Map MAP_COMPATIBILITY_CONFIG_URIS;
-
-    static {
-        MAP_COMPATIBILITY_CONFIG_URIS = new HashMap();
-        MAP_COMPATIBILITY_CONFIG_URIS.put(COMPATIBILITY_CONFIG_URI, CONFIG_URI);
-    }
+    private static final Map<String, String> MAP_COMPATIBILITY_CONFIG_URIS
+        = Collections.singletonMap(COMPATIBILITY_CONFIG_URI, CONFIG_URI);
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/XMLBeanXSTCHarness.java b/src/main/java/org/apache/xmlbeans/impl/tool/XMLBeanXSTCHarness.java
index bf87c72..a73782a 100644
--- a/src/main/java/org/apache/xmlbeans/impl/tool/XMLBeanXSTCHarness.java
+++ b/src/main/java/org/apache/xmlbeans/impl/tool/XMLBeanXSTCHarness.java
@@ -15,95 +15,76 @@
 
 package org.apache.xmlbeans.impl.tool;
 
-import org.apache.xmlbeans.SchemaTypeLoader;
-import org.apache.xmlbeans.XmlBeans;
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.XmlOptions;
-import org.apache.xmlbeans.SchemaTypeSystem;
-import org.apache.xmlbeans.XmlException;
+import org.apache.xmlbeans.*;
 
-import java.util.Collection;
-import java.util.ArrayList;
-import java.util.Collections;
 import java.io.PrintWriter;
 import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
 
-public class XMLBeanXSTCHarness implements XSTCTester.Harness
-{
-    public void runTestCase(XSTCTester.TestCaseResult result)
-    {
+public class XMLBeanXSTCHarness implements XSTCTester.Harness {
+    public void runTestCase(XSTCTester.TestCaseResult result) {
         XSTCTester.TestCase testCase = result.getTestCase();
-        
-        // System.out.println("Running case " + testCase.getDescription());
-        
-        try
-        {
-            Collection errors = new ArrayList();
-            boolean schemaValid = true;
-            boolean instanceValid = true;
-            
-            if (testCase.getSchemaFile() == null)
-                return;
-            
-            // step 1, load schema file etc.
-            SchemaTypeLoader loader = null;
-            try
-            {
-                XmlObject schema = XmlObject.Factory.parse(testCase.getSchemaFile(), new XmlOptions().setErrorListener(errors).setLoadLineNumbers());
-                XmlObject schema2 = null;
-                if (testCase.getResourceFile() != null)
-                    schema2 = XmlObject.Factory.parse(testCase.getResourceFile(), new XmlOptions().setErrorListener(errors).setLoadLineNumbers());
-                XmlObject[] schemas = schema2 == null ? new XmlObject[] { schema } : new XmlObject[] { schema, schema2 };
-                SchemaTypeSystem system = XmlBeans.compileXsd(schemas, XmlBeans.getBuiltinTypeSystem(), new XmlOptions().setErrorListener(errors));
-                loader = XmlBeans.typeLoaderUnion(new SchemaTypeLoader[] { system, XmlBeans.getBuiltinTypeSystem() });
+
+        Collection<XmlError> errors = new ArrayList<>();
+        boolean schemaValid = true;
+        boolean instanceValid = true;
+
+        if (testCase.getSchemaFile() == null) {
+            return;
+        }
+
+        // step 1, load schema file etc.
+        SchemaTypeLoader loader = null;
+        try {
+            XmlObject schema = XmlObject.Factory.parse(testCase.getSchemaFile(), new XmlOptions().setErrorListener(errors).setLoadLineNumbers());
+            XmlObject schema2 = null;
+            if (testCase.getResourceFile() != null) {
+                schema2 = XmlObject.Factory.parse(testCase.getResourceFile(), new XmlOptions().setErrorListener(errors).setLoadLineNumbers());
             }
-            catch (Exception e)
-            {
-                schemaValid = false;
-                if (!(e instanceof XmlException) || errors.isEmpty())
-                {
-                    result.setCrash(true);
-                    StringWriter sw = new StringWriter();
-                    e.printStackTrace(new PrintWriter(sw));
-                    result.addSvMessages(Collections.singleton(sw.toString()));
-                }
+            XmlObject[] schemas = schema2 == null ? new XmlObject[]{schema} : new XmlObject[]{schema, schema2};
+            SchemaTypeSystem system = XmlBeans.compileXsd(schemas, XmlBeans.getBuiltinTypeSystem(), new XmlOptions().setErrorListener(errors));
+            loader = XmlBeans.typeLoaderUnion(system, XmlBeans.getBuiltinTypeSystem());
+        } catch (Exception e) {
+            schemaValid = false;
+            if (!(e instanceof XmlException) || errors.isEmpty()) {
+                result.setCrash(true);
+                StringWriter sw = new StringWriter();
+                e.printStackTrace(new PrintWriter(sw));
+                result.addSvMessages(Collections.singleton(XmlError.forMessage(sw.toString())));
             }
-            
-            result.addSvMessages(errors);
-            result.setSvActual(schemaValid);
-            errors.clear();
-            
-            if (loader == null)
-                return;
-            
-            if (testCase.getInstanceFile() == null)
-                return;
-            
-            // step 2, load instance file and validate
-            try
-            {
-                XmlObject instance = loader.parse(testCase.getInstanceFile(), null, new XmlOptions().setErrorListener(errors).setLoadLineNumbers());
-                if (!instance.validate(new XmlOptions().setErrorListener(errors)))
-                    instanceValid = false;
-            }
-            catch (Exception e)
-            {
+        }
+
+        result.addSvMessages(errors);
+        result.setSvActual(schemaValid);
+        errors.clear();
+
+        if (loader == null) {
+            return;
+        }
+
+        if (testCase.getInstanceFile() == null) {
+            return;
+        }
+
+        // step 2, load instance file and validate
+        try {
+            XmlObject instance = loader.parse(testCase.getInstanceFile(), null, new XmlOptions().setErrorListener(errors).setLoadLineNumbers());
+            if (!instance.validate(new XmlOptions().setErrorListener(errors))) {
                 instanceValid = false;
-                if (!(e instanceof XmlException) || errors.isEmpty())
-                {
-                    result.setCrash(true);
-                    StringWriter sw = new StringWriter();
-                    e.printStackTrace(new PrintWriter(sw));
-                    result.addIvMessages(Collections.singleton(sw.toString()));
-                }
             }
-            result.addIvMessages(errors);
-            result.setIvActual(instanceValid);
-                    
+        } catch (Exception e) {
+            instanceValid = false;
+            if (!(e instanceof XmlException) || errors.isEmpty()) {
+                result.setCrash(true);
+                StringWriter sw = new StringWriter();
+                e.printStackTrace(new PrintWriter(sw));
+                result.addIvMessages(Collections.singleton(XmlError.forMessage(sw.toString())));
+            }
         }
-        finally
-        {
-            // System.out.println(result.succeeded() ? "Success.": "Failure.");
-        }
+        result.addIvMessages(errors);
+        result.setIvActual(instanceValid);
+
     }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/XSTCTester.java b/src/main/java/org/apache/xmlbeans/impl/tool/XSTCTester.java
index b88fd9c..11b0f29 100644
--- a/src/main/java/org/apache/xmlbeans/impl/tool/XSTCTester.java
+++ b/src/main/java/org/apache/xmlbeans/impl/tool/XSTCTester.java
@@ -15,38 +15,26 @@
 
 package org.apache.xmlbeans.impl.tool;
 
-import org.apache.xmlbeans.SystemProperties;
-import org.apache.xmlbeans.impl.xb.ltgfmt.TestsDocument;
+import org.apache.xmlbeans.*;
 import org.apache.xmlbeans.impl.xb.ltgfmt.FileDesc;
-import org.apache.xmlbeans.XmlOptions;
-import org.apache.xmlbeans.XmlException;
-import org.apache.xmlbeans.XmlError;
-import org.apache.xmlbeans.XmlCalendar;
+import org.apache.xmlbeans.impl.xb.ltgfmt.TestsDocument;
 
 import java.io.File;
-import java.io.PrintWriter;
-import java.io.FileWriter;
 import java.io.IOException;
-import java.util.Collection;
-import java.util.ArrayList;
-import java.util.Set;
-import java.util.HashSet;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.Date;
-import java.util.regex.Pattern;
+import java.io.PrintWriter;
 import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.*;
+import java.util.regex.Pattern;
 
-public class XSTCTester
-{
-    public static void printUsage()
-    {
+public class XSTCTester {
+    public static void printUsage() {
         System.out.println("Usage: xstc [-showpass] [-errcode] foo_LTGfmt.xml ...");
     }
 
-    public static void main(String[] args) throws IOException
-    {
-        Set flags = new HashSet();
+    public static void main(String[] args) throws IOException {
+        Set<String> flags = new HashSet<>();
         flags.add("h");
         flags.add("help");
         flags.add("usage");
@@ -55,27 +43,25 @@
         flags.add("errcode");
 
         long start = System.currentTimeMillis();
-        
+
         CommandLine cl = new CommandLine(args, flags, Collections.EMPTY_SET);
-        if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null)
-        {
+        if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null) {
             printUsage();
             System.exit(0);
             return;
         }
 
-        if (cl.getOpt("version") != null)
-        {
+        if (cl.getOpt("version") != null) {
             CommandLine.printVersion();
             System.exit(0);
             return;
         }
 
         String[] badopts = cl.getBadOpts();
-        if (badopts.length > 0)
-        {
-            for (int i = 0; i < badopts.length; i++)
-                System.out.println("Unrecognized option: " + badopts[i]);
+        if (badopts.length > 0) {
+            for (String badopt : badopts) {
+                System.out.println("Unrecognized option: " + badopt);
+            }
             printUsage();
             System.exit(0);
             return;
@@ -90,103 +76,101 @@
         boolean errcode = (cl.getOpt("errcode") != null);
 
         File[] allFiles = cl.getFiles();
-        Collection ltgFiles = new ArrayList();
+        Collection<File> ltgFiles = new ArrayList<>();
         Harness harness = new XMLBeanXSTCHarness();
-        
-        for (int i = 0; i < allFiles.length; i++)
-        {
-            if (allFiles[i].getName().indexOf("LTG") >= 0)
-                ltgFiles.add(allFiles[i]);
+
+        for (File allFile : allFiles) {
+            if (allFile.getName().contains("LTG")) {
+                ltgFiles.add(allFile);
+            }
         }
-        
+
         File resultsFile = new File("out.html");
-        PrintWriter writer = new PrintWriter(new FileWriter(resultsFile));
-        writer.println("<html>");
-        writer.println("<style>td {border-bottom: 1px solid black} xmp {white-space: normal; word-wrap: break-word; word-break: break-all} </style>");
-        writer.println("<body>");
+        try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(resultsFile.toPath(), StandardCharsets.ISO_8859_1))) {
+            writer.println("<html>");
+            writer.println("<style>td {border-bottom: 1px solid black} xmp {white-space: normal; word-wrap: break-word; word-break: break-all} </style>");
+            writer.println("<body>");
 
-        writer.println("<script language='JavaScript' type='text/javascript'>");
-        writer.println("var w;");
-        writer.println("function openWindow(schema, instance) {");
-        writer.println("  if (w == null) {");
-        writer.println("    w = window.open('about:blank', 'xstc');");
-        writer.println("  }");
-        writer.println("  if (w.closed) {");
-        writer.println("    w = window.open('about:blank', 'xstc');");
-        writer.println("  }");
-        writer.println("  w.document.open();");
-        writer.println("  w.document.write(\"<frameset rows=*,*><frame src='\" + schema + \"'><frame src='\" + instance + \"'></frameset>\");");
-        writer.println("  w.document.close();");
-        writer.println("  w.focus();");
-        writer.println("}");
-        writer.println("</script>");
+            writer.println("<script language='JavaScript' type='text/javascript'>");
+            writer.println("var w;");
+            writer.println("function openWindow(schema, instance) {");
+            writer.println("  if (w == null) {");
+            writer.println("    w = window.open('about:blank', 'xstc');");
+            writer.println("  }");
+            writer.println("  if (w.closed) {");
+            writer.println("    w = window.open('about:blank', 'xstc');");
+            writer.println("  }");
+            writer.println("  w.document.open();");
+            writer.println("  w.document.write(\"<frameset rows=*,*><frame src='\" + schema + \"'><frame src='\" + instance + \"'></frameset>\");");
+            writer.println("  w.document.close();");
+            writer.println("  w.focus();");
+            writer.println("}");
+            writer.println("</script>");
 
-        writer.println("<h1>XML Schema Test Collection Results</h1>");
-        writer.println("<p>Run on " + (new XmlCalendar(new Date())) + "</p>");
-        writer.println("<p>Values in schema or instance valid columns are results from compiling or validating respectively.");
-        writer.println("Red or orange background mean the test failed.</p>");
-        writer.println("<table style='border: 1px solid black' cellpadding=0 cellspacing=0>");
-        writer.println("<tr><td witdh=10%>id</td><td width=70%>Description</td><td width=10%>sch v</td><td width=10%>ins v</td></tr>");
-        int failures = 0;
-        int cases = 0;
-        for (Iterator i = ltgFiles.iterator(); i.hasNext(); )
-        {
-            File ltgFile = (File)i.next();
-            System.out.println("Processing test cases in " + ltgFile);
-            Collection ltgErrors = new ArrayList();
-            TestCase[] testCases = parseLTGFile(ltgFile, ltgErrors);
-            Collection results = new ArrayList();
-            if (testCases != null) for (int j = 0; j < testCases.length; j++)
-            {
-                TestCaseResult result = new TestCaseResult();
-                result.testCase = testCases[j];
-                harness.runTestCase(result);
-                cases += 1;
-                if (!result.succeeded(errcode))
-                    failures += 1;
-                else if (!showpass)
-                    continue;
-                results.add(result);
+            writer.println("<h1>XML Schema Test Collection Results</h1>");
+            writer.println("<p>Run on " + (new XmlCalendar(new Date())) + "</p>");
+            writer.println("<p>Values in schema or instance valid columns are results from compiling or validating respectively.");
+            writer.println("Red or orange background mean the test failed.</p>");
+            writer.println("<table style='border: 1px solid black' cellpadding=0 cellspacing=0>");
+            writer.println("<tr><td witdh=10%>id</td><td width=70%>Description</td><td width=10%>sch v</td><td width=10%>ins v</td></tr>");
+            int failures = 0;
+            int cases = 0;
+            for (File ltgFile : ltgFiles) {
+                System.out.println("Processing test cases in " + ltgFile);
+                Collection<String> ltgErrors = new ArrayList<>();
+                TestCase[] testCases = parseLTGFile(ltgFile, ltgErrors);
+                final Collection<TestCaseResult> results = new ArrayList<>();
+                if (testCases != null) {
+                    for (TestCase testCase : testCases) {
+                        TestCaseResult result = new TestCaseResult();
+                        result.testCase = testCase;
+                        harness.runTestCase(result);
+                        cases += 1;
+                        if (!result.succeeded(errcode)) {
+                            failures += 1;
+                        } else if (!showpass) {
+                            continue;
+                        }
+                        results.add(result);
+                    }
+                }
+                writer.println("<tr><td colspan=4 bgcolor=skyblue>" + ltgFile + "</td></tr>");
+                if (!ltgErrors.isEmpty()) {
+                    writer.println("<tr><td>Errors within the LTG file:");
+                    writer.println("<xmp>");
+                    for (String ltgError : ltgErrors) {
+                        writer.println(ltgError);
+                    }
+                    writer.println("</xmp>");
+                    writer.println("</td></tr>");
+                } else {
+                    if (results.size() == 0) {
+                        writer.println("<tr><td colspan=4 bgcolor=green>Nothing to report</td></tr>");
+                    }
+                }
+                for (TestCaseResult result : results) {
+                    summarizeResultAsHTMLTableRows(result, writer, errcode);
+                }
             }
-            writer.println("<tr><td colspan=4 bgcolor=skyblue>" + ltgFile + "</td></tr>");
-            if (!ltgErrors.isEmpty())
-            {
-                writer.println("<tr><td>Errors within the LTG file:");
-                writer.println("<xmp>");
-                for (Iterator j = ltgErrors.iterator(); j.hasNext(); )
-                    writer.println(j.next());
-                writer.println("</xmp>");
-                writer.println("</td></tr>");
-            }
-            else
-            {
-                if (results.size() == 0)
-                    writer.println("<tr><td colspan=4 bgcolor=green>Nothing to report</td></tr>");
-            }
-            if (results == null)
-                continue;
-            for (Iterator j = results.iterator(); j.hasNext() ;)
-            {
-                summarizeResultAsHTMLTableRows((TestCaseResult)j.next(), writer, errcode);
-            }
+            writer.println("<tr><td colspan=4>Summary: " + failures + " failures out of " + cases + " cases run.</td></tr>");
+            writer.println("</table>");
         }
-        writer.println("<tr><td colspan=4>Summary: " + failures + " failures out of " + cases + " cases run.</td></tr>");
-        writer.println("</table>");
-        writer.close();
-        
+
         long finish = System.currentTimeMillis();
-        System.out.println("Time run tests: " + ((double)(finish - start) / 1000.0) + " seconds" );
-        
+        System.out.println("Time run tests: " + ((double) (finish - start) / 1000.0) + " seconds");
+
         // Launch results
         System.out.println("Results output to " + resultsFile);
-        if (SystemProperties.getProperty("os.name").toLowerCase().indexOf("windows") >= 0)
+        String osName = SystemProperties.getProperty("os.name");
+        assert (osName != null);
+        if (osName.toLowerCase(Locale.ROOT).contains("windows")) {
             Runtime.getRuntime().exec("cmd /c start iexplore \"" + resultsFile.getAbsolutePath() + "\"");
-        else
+        } else {
             Runtime.getRuntime().exec("mozilla file://" + resultsFile.getAbsolutePath());
+        }
     }
-    
-    public static class TestCase
-    {
+
+    public static class TestCase {
         private File ltgFile;
         private String id;
         private String origin;
@@ -199,176 +183,152 @@
         private boolean rvExpected;
         private String errorCode;
 
-        public File getLtgFile()
-        {
+        public File getLtgFile() {
             return ltgFile;
         }
 
-        public String getId()
-        {
+        public String getId() {
             return id;
         }
 
-        public String getOrigin()
-        {
+        public String getOrigin() {
             return origin;
         }
 
-        public String getDescription()
-        {
+        public String getDescription() {
             return description;
         }
 
-        public File getSchemaFile()
-        {
+        public File getSchemaFile() {
             return schemaFile;
         }
 
-        public File getInstanceFile()
-        {
+        public File getInstanceFile() {
             return instanceFile;
         }
 
-        public File getResourceFile()
-        {
+        public File getResourceFile() {
             return resourceFile;
         }
 
-        public boolean isSvExpected()
-        {
+        public boolean isSvExpected() {
             return svExpected;
         }
 
-        public boolean isIvExpected()
-        {
+        public boolean isIvExpected() {
             return ivExpected;
         }
 
-        public boolean isRvExpected()
-        {
+        public boolean isRvExpected() {
             return rvExpected;
         }
 
-        public String getErrorCode()
-        {
+        public String getErrorCode() {
             return errorCode;
         }
 
     }
-    
-    public static class TestCaseResult
-    {
+
+    public static class TestCaseResult {
         private TestCase testCase;
         private boolean svActual;
-        private Collection svMessages = new ArrayList();
+        private final Collection<XmlError> svMessages = new ArrayList<>();
         private boolean ivActual;
-        private Collection ivMessages = new ArrayList();
+        private final Collection<XmlError> ivMessages = new ArrayList<>();
         private boolean crash;
 
-        public TestCase getTestCase()
-        {
+        public TestCase getTestCase() {
             return testCase;
         }
 
-        public boolean isSvActual()
-        {
+        public boolean isSvActual() {
             return svActual;
         }
 
-        public void setSvActual(boolean svActual)
-        {
+        public void setSvActual(boolean svActual) {
             this.svActual = svActual;
         }
 
-        public boolean isIvActual()
-        {
+        public boolean isIvActual() {
             return ivActual;
         }
 
-        public void setIvActual(boolean ivActual)
-        {
+        public void setIvActual(boolean ivActual) {
             this.ivActual = ivActual;
         }
 
-        public Collection getSvMessages()
-        {
+        public Collection<XmlError> getSvMessages() {
             return Collections.unmodifiableCollection(svMessages);
         }
 
-        public void addSvMessages(Collection svMessages)
-        {
+        public void addSvMessages(Collection<XmlError> svMessages) {
             this.svMessages.addAll(svMessages);
         }
 
-        public Collection getIvMessages()
-        {
+        public Collection<XmlError> getIvMessages() {
             return Collections.unmodifiableCollection(ivMessages);
         }
 
-        public void addIvMessages(Collection ivMessages)
-        {
+        public void addIvMessages(Collection<XmlError> ivMessages) {
             this.ivMessages.addAll(ivMessages);
         }
-        
-        public void setCrash(boolean crash)
-        {
+
+        public void setCrash(boolean crash) {
             this.crash = crash;
         }
-        
-        public boolean isCrash()
-        {
+
+        public boolean isCrash() {
             return crash;
         }
-        
-        public boolean succeeded(boolean errcode)
-        {
+
+        public boolean succeeded(boolean errcode) {
             boolean success = !crash &&
-                (isIvActual() == testCase.isIvExpected()) &&
-                (isSvActual() == testCase.isSvExpected());
-            if (errcode && testCase.getErrorCode() != null)
+                              (isIvActual() == testCase.isIvExpected()) &&
+                              (isSvActual() == testCase.isSvExpected());
+            if (errcode && testCase.getErrorCode() != null) {
                 success &= errorReported(testCase.getErrorCode(), svMessages) || errorReported(testCase.getErrorCode(), ivMessages);
+            }
             return success;
         }
 
     }
-    
-    public static interface Harness
-    {
-        public void runTestCase(TestCaseResult result);
+
+    public interface Harness {
+        void runTestCase(TestCaseResult result);
     }
-    
-    public static String makeHTMLLink(File file, boolean value)
-    {
-        if (file == null)
+
+    public static String makeHTMLLink(File file, boolean value) {
+        if (file == null) {
             return "&nbsp;";
+        }
         URI uri = file.getAbsoluteFile().toURI();
-        return "<a href=\"" + uri + "\" target=_blank>" + Boolean.toString(value) + "</a>";
+        return "<a href=\"" + uri + "\" target=_blank>" + value + "</a>";
     }
-    
+
     private static final Pattern leadingSpace = Pattern.compile("^\\s+", Pattern.MULTILINE);
-    
-    public static String makeHTMLDescription(TestCase testCase)
-    {
+
+    public static String makeHTMLDescription(TestCase testCase) {
         StringBuilder sb = new StringBuilder();
         sb.append("<a class=noline href='javascript:openWindow(\"");
-        if (testCase.getSchemaFile() == null)
+        if (testCase.getSchemaFile() == null) {
             sb.append("about:No schema");
-        else
+        } else {
             sb.append(testCase.getSchemaFile().getAbsolutePath().replaceAll("\\\\", "\\\\\\\\"));
+        }
 
         sb.append("\", \"");
-        if (testCase.getInstanceFile() == null)
+        if (testCase.getInstanceFile() == null) {
             sb.append("about:No instance");
-        else
+        } else {
             sb.append(testCase.getInstanceFile().getAbsolutePath().replaceAll("\\\\", "\\\\\\\\"));
+        }
         sb.append("\")'><xmp>");
         sb.append(leadingSpace.matcher(testCase.getDescription()).replaceAll(""));
         sb.append("</xmp></a>");
         return sb.toString();
     }
-    
-    public static void summarizeResultAsHTMLTableRows(TestCaseResult result, PrintWriter out, boolean errcode)
-    {
+
+    public static void summarizeResultAsHTMLTableRows(TestCaseResult result, PrintWriter out, boolean errcode) {
         TestCase testCase = result.getTestCase();
 
         boolean errorRow = errcode && testCase.getErrorCode() != null;
@@ -377,131 +337,134 @@
         boolean sRight = testCase.getSchemaFile() == null || testCase.isSvExpected() == result.isSvActual();
         boolean iRight = testCase.getInstanceFile() == null || testCase.isIvExpected() == result.isIvActual();
         boolean codeRight = true;
-        if (errorRow)
+        if (errorRow) {
             codeRight = (errorReported(testCase.getErrorCode(), result.svMessages) || errorReported(testCase.getErrorCode(), result.ivMessages));
+        }
 
         out.println(result.isCrash() ? "<tr bgcolor=black color=white>" : "<tr>");
         int idRowSpan = 1 + (errorRow ? 1 : 0) + (messagesRow ? 1 : 0);
         out.println("<td rowspan=" + idRowSpan + " valign=top>" + testCase.getId() + "</td>");
         out.println("<td valign=top>" + makeHTMLDescription(testCase) + "</td>");
         String sLinks;
-        if (testCase.getResourceFile() == null)
+        if (testCase.getResourceFile() == null) {
             sLinks = makeHTMLLink(testCase.getSchemaFile(), result.isSvActual());
-        else
+        } else {
             sLinks = makeHTMLLink(testCase.getSchemaFile(), result.isSvActual()) + "<br>" + makeHTMLLink(testCase.getResourceFile(), result.isSvActual());
-        
+        }
+
         out.println((sRight ? "<td valign=top>" : result.isSvActual() ? "<td bgcolor=orange valign=top>" : "<td bgcolor=red valign=top>") + sLinks + "</td>");
         out.println((iRight ? "<td valign=top>" : result.isIvActual() ? "<td bgcolor=orange valign=top>" : "<td bgcolor=red valign=top>") + makeHTMLLink(testCase.getInstanceFile(), result.isIvActual()) + "</td>");
         out.println("</tr>");
-        if (errorRow)
-        {
+        if (errorRow) {
             out.println("<tr>");
             out.println((codeRight ? "<td colspan=4 valid=top>" : "<td colspan=4 bgcolor=orange valign=top>") + "expected error: " + testCase.getErrorCode() + "</td>");
             out.println("</tr>");
         }
-        if (messagesRow)
-        {
-            if (!result.succeeded(errcode))
+        if (messagesRow) {
+            if (!result.succeeded(errcode)) {
                 out.println("<tr><td colspan=4 bgcolor=yellow><xmp>");
-            else
+            } else {
                 out.println("<tr><td colspan=4><xmp>");
-            for (Iterator j = result.getSvMessages().iterator(); j.hasNext(); )
-                out.println(j.next());
-            for (Iterator j = result.getIvMessages().iterator(); j.hasNext(); )
-                out.println(j.next());
+            }
+            for (XmlError s : result.getSvMessages()) {
+                out.println(s);
+            }
+            for (XmlError xmlError : result.getIvMessages()) {
+                out.println(xmlError);
+            }
             out.println("</xmp></tr></td>");
         }
     }
-    
-    public static TestCase[] parseLTGFile(File ltgFile, Collection outerErrors)
-    {
-        Collection errors = new ArrayList();
-        try
-        {
+
+    public static TestCase[] parseLTGFile(File ltgFile, Collection<String> outerErrors) {
+        Collection<XmlError> errors = new ArrayList<>();
+        try {
             XmlOptions ltgOptions = new XmlOptions();
             ltgOptions.setLoadSubstituteNamespaces(Collections.singletonMap("", "http://www.bea.com/2003/05/xmlbean/ltgfmt"));
             ltgOptions.setErrorListener(errors);
             ltgOptions.setLoadLineNumbers();
             TestsDocument doc = TestsDocument.Factory.parse(ltgFile, ltgOptions);
-            if (!doc.validate(ltgOptions))
+            if (!doc.validate(ltgOptions)) {
                 throw new Exception("Document " + ltgFile + " not valid.");
-            
+            }
+
             org.apache.xmlbeans.impl.xb.ltgfmt.TestCase[] testCases = doc.getTests().getTestArray();
-            
-            Collection result = new ArrayList();
-            for (int i = 0; i < testCases.length; i++)
-            {
+
+            Collection<TestCase> result = new ArrayList<>();
+            for (org.apache.xmlbeans.impl.xb.ltgfmt.TestCase testCase : testCases) {
                 TestCase newCase = new TestCase();
                 newCase.ltgFile = ltgFile;
-                newCase.id = testCases[i].getId();
-                newCase.origin = testCases[i].getOrigin();
-                newCase.description = testCases[i].getDescription();
-                FileDesc[] filedescs = testCases[i].getFiles().getFileArray();
-                testCases[i].getOrigin();
-                for (int j = 0; j < filedescs.length; j++)
-                {
-                    String dir = filedescs[j].getFolder();
-                    String filename = filedescs[j].getFileName();
+                newCase.id = testCase.getId();
+                newCase.origin = testCase.getOrigin();
+                newCase.description = testCase.getDescription();
+                FileDesc[] filedescs = testCase.getFiles().getFileArray();
+                testCase.getOrigin();
+                for (FileDesc filedesc : filedescs) {
+                    String dir = filedesc.getFolder();
+                    String filename = filedesc.getFileName();
                     File theFile = new File(ltgFile.getParentFile(), dir + "/" + filename);
-                    if (!theFile.exists() || !theFile.isFile() || !theFile.canRead())
-                    {
-                        outerErrors.add(XmlError.forObject("Can't read file " + theFile, filedescs[j]).toString());
+                    if (!theFile.exists() || !theFile.isFile() || !theFile.canRead()) {
+                        outerErrors.add(XmlError.forObject("Can't read file " + theFile, filedesc).toString());
                         continue;
                     }
-                    
-                    switch (filedescs[j].getRole().intValue())
-                    {
+
+                    switch (filedesc.getRole().intValue()) {
                         case FileDesc.Role.INT_INSTANCE:
-                            if (newCase.instanceFile != null)
-                                outerErrors.add(XmlError.forObject("More than one instance file speicifed - ignoring all but last", filedescs[j]).toString());
+                            if (newCase.instanceFile != null) {
+                                outerErrors.add(XmlError.forObject("More than one instance file speicifed - ignoring all but last", filedesc).toString());
+                            }
                             newCase.instanceFile = theFile;
-                            newCase.ivExpected = filedescs[j].getValidity();
+                            newCase.ivExpected = filedesc.getValidity();
                             break;
-                            
+
                         case FileDesc.Role.INT_SCHEMA:
-                            if (newCase.schemaFile != null)
-                                outerErrors.add(XmlError.forObject("More than one schema file speicifed - ignoring all but last", filedescs[j]).toString());
+                            if (newCase.schemaFile != null) {
+                                outerErrors.add(XmlError.forObject("More than one schema file speicifed - ignoring all but last", filedesc).toString());
+                            }
                             newCase.schemaFile = theFile;
-                            newCase.svExpected = filedescs[j].getValidity();
+                            newCase.svExpected = filedesc.getValidity();
                             break;
-                            
+
                         case FileDesc.Role.INT_RESOURCE:
-                            if (newCase.resourceFile != null)
-                                outerErrors.add(XmlError.forObject("More than one resource file speicifed - ignoring all but last", filedescs[j]).toString());
+                            if (newCase.resourceFile != null) {
+                                outerErrors.add(XmlError.forObject("More than one resource file speicifed - ignoring all but last", filedesc).toString());
+                            }
                             newCase.resourceFile = theFile;
-                            newCase.rvExpected = filedescs[j].getValidity();
+                            newCase.rvExpected = filedesc.getValidity();
                             break;
-                        
+
                         default:
-                            throw new XmlException(XmlError.forObject("Unexpected file role", filedescs[j]));
+                            throw new XmlException(XmlError.forObject("Unexpected file role", filedesc));
                     }
 
-                    if (filedescs[j].getCode() != null)
-                        newCase.errorCode = filedescs[j].getCode().getID();
+                    if (filedesc.getCode() != null) {
+                        newCase.errorCode = filedesc.getCode().getID();
+                    }
                 }
                 result.add(newCase);
             }
-            return (TestCase[])result.toArray(new TestCase[result.size()]);
-        }
-        catch (Exception e)
-        {
-            if (errors.isEmpty())
+            return result.toArray(new TestCase[0]);
+        } catch (Exception e) {
+            if (errors.isEmpty()) {
                 outerErrors.add(e.getMessage());
-            else for (Iterator i = errors.iterator(); i.hasNext(); )
-                outerErrors.add(i.next().toString());
+            } else {
+                for (XmlError error : errors) {
+                    outerErrors.add(error.toString());
+                }
+            }
             return null;
         }
     }
 
-    public static boolean errorReported(String errorCode, Collection set)
-    {
-        if (errorCode == null || set == null || set.size() == 0)
+    public static boolean errorReported(String errorCode, Collection<XmlError> set) {
+        if (errorCode == null || set == null || set.size() == 0) {
             return false;
+        }
 
-        for (Iterator i = set.iterator(); i.hasNext(); )
-        {
-            if (errorCode.equals(((XmlError)i.next()).getErrorCode()))
+        for (XmlError xmlError : set) {
+            if (errorCode.equals(xmlError.getErrorCode())) {
                 return true;
+            }
         }
 
         return false;
diff --git a/src/main/java/org/apache/xmlbeans/impl/util/FilerImpl.java b/src/main/java/org/apache/xmlbeans/impl/util/FilerImpl.java
index 5e4d9b0..14e9b3b 100755
--- a/src/main/java/org/apache/xmlbeans/impl/util/FilerImpl.java
+++ b/src/main/java/org/apache/xmlbeans/impl/util/FilerImpl.java
@@ -1,77 +1,66 @@
 /*   Copyright 2004 The Apache Software Foundation
-*
-*   Licensed under the Apache License, Version 2.0 (the "License");
-*   you may not use this file except in compliance with the License.
-*   You may obtain a copy of the License at
-*
-*       http://www.apache.org/licenses/LICENSE-2.0
-*
-*   Unless required by applicable law or agreed to in writing, software
-*   distributed under the License is distributed on an "AS IS" BASIS,
-*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-*   See the License for the specific language governing permissions and
-*  limitations under the License.
-*/
+ *
+ *   Licensed under the Apache License, Version 2.0 (the "License");
+ *   you may not use this file except in compliance with the License.
+ *   You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *   Unless required by applicable law or agreed to in writing, software
+ *   distributed under the License is distributed on an "AS IS" BASIS,
+ *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *   See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
 
 package org.apache.xmlbeans.impl.util;
 
 import org.apache.xmlbeans.Filer;
+import org.apache.xmlbeans.impl.repackage.Repackager;
 
-import java.io.IOException;
-import java.io.File;
-import java.io.Writer;
-import java.io.FileReader;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.StringReader;
-import java.io.StringWriter;
+import java.io.*;
 import java.nio.charset.Charset;
 import java.nio.charset.CharsetEncoder;
 import java.nio.charset.CodingErrorAction;
-import java.util.Set;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
-import java.util.ArrayList;
-
-import org.apache.xmlbeans.impl.repackage.Repackager;
+import java.util.Set;
 
 /**
  * This implementation of Filer writes to disk.
  */
-public class FilerImpl implements Filer
-{
-    private File classdir;
-    private File srcdir;
-    private Repackager repackager;
-    private boolean verbose;
-    private List sourceFiles;
-    private boolean incrSrcGen;
-    private Set seenTypes;
+public class FilerImpl implements Filer {
+    private final File classdir;
+    private final File srcdir;
+    private final Repackager repackager;
+    private final boolean verbose;
+    private final List<File> sourceFiles;
+    private final boolean incrSrcGen;
+    private Set<String> seenTypes;
     private static final Charset CHARSET;
 
-    static
-    {
+    static {
         Charset temp = null;
-        try
-        {
+        try {
             temp = Charset.forName(System.getProperty("file.encoding"));
+        } catch (Exception ignored) {
         }
-        catch (Exception e) {}
         CHARSET = temp;
     }
 
-    public FilerImpl(File classdir, File srcdir, Repackager repackager, boolean verbose, boolean incrSrcGen)
-    {
+    public FilerImpl(File classdir, File srcdir, Repackager repackager, boolean verbose, boolean incrSrcGen) {
         this.classdir = classdir;
         this.srcdir = srcdir;
         this.repackager = repackager;
         this.verbose = verbose;
-        this.sourceFiles = (sourceFiles != null ? sourceFiles : new ArrayList());
+        this.sourceFiles = new ArrayList<>();
         this.incrSrcGen = incrSrcGen;
-        if (this.incrSrcGen)
-            seenTypes = new HashSet();
+        if (this.incrSrcGen) {
+            seenTypes = new HashSet<>();
+        }
     }
 
     /**
@@ -79,18 +68,17 @@
      *
      * @param typename fully qualified type name
      * @return a stream to write the type to
-     * @throws java.io.IOException
      */
-    public OutputStream createBinaryFile(String typename) throws IOException
-    {
-        if (verbose)
+    public OutputStream createBinaryFile(String typename) throws IOException {
+        if (verbose) {
             System.err.println("created binary: " + typename);
+        }
         // KHK: for now the typename will already be a relative filename for the binary
         //String filename = typename.replace('.', File.separatorChar) + ".xsb";
         File source = new File(classdir, typename);
         source.getParentFile().mkdirs();
 
-        return new FileOutputStream( source );
+        return new FileOutputStream(source);
     }
 
     /**
@@ -98,57 +86,51 @@
      *
      * @param typename fully qualified type name
      * @return a stream to write the type to
-     * @throws java.io.IOException
      */
-    public Writer createSourceFile(String typename) throws IOException
-    {
-        if (incrSrcGen)
+    public Writer createSourceFile(String typename) throws IOException {
+        if (incrSrcGen) {
             seenTypes.add(typename);
+        }
 
-        if (typename.indexOf('$') > 0)
-        {
+        if (typename.indexOf('$') > 0) {
             typename =
-                typename.substring( 0, typename.lastIndexOf( '.' ) ) + "." +
-                typename.substring( typename.indexOf( '$' ) + 1 );
+                typename.substring(0, typename.lastIndexOf('.')) + "." +
+                typename.substring(typename.indexOf('$') + 1);
         }
 
         String filename = typename.replace('.', File.separatorChar) + ".java";
 
         File sourcefile = new File(srcdir, filename);
         sourcefile.getParentFile().mkdirs();
-        if (verbose)
+        if (verbose) {
             System.err.println("created source: " + sourcefile.getAbsolutePath());
+        }
 
         sourceFiles.add(sourcefile);
 
-        if (incrSrcGen && sourcefile.exists())
-        {
+        if (incrSrcGen && sourcefile.exists()) {
             // Generate the file in a buffer and then compare it to the
             // file already on disk
             return new IncrFileWriter(sourcefile, repackager);
-        }
-        else
-        {
+        } else {
             return repackager == null ?
-                (Writer) writerForFile( sourcefile ) :
-                (Writer) new RepackagingWriter( sourcefile, repackager );
+                writerForFile(sourcefile) :
+                new RepackagingWriter(sourcefile, repackager);
         }
     }
 
-    public List getSourceFiles()
-    {
-        return new ArrayList(sourceFiles);
+    public List<File> getSourceFiles() {
+        return new ArrayList<>(sourceFiles);
     }
 
-    public Repackager getRepackager()
-    {
+    public Repackager getRepackager() {
         return repackager;
     }
 
-    private static final Writer writerForFile(File f) throws IOException
-    {
-        if (CHARSET == null)
-            return new FileWriter(f);
+    private static Writer writerForFile(File f) throws IOException {
+        if (CHARSET == null) {
+            return Files.newBufferedWriter(f.toPath(), StandardCharsets.ISO_8859_1);
+        }
 
         FileOutputStream fileStream = new FileOutputStream(f);
         CharsetEncoder ce = CHARSET.newEncoder();
@@ -156,19 +138,16 @@
         return new OutputStreamWriter(fileStream, ce);
     }
 
-    static class IncrFileWriter extends StringWriter
-    {
-        private File _file;
-        private Repackager _repackager;
+    static class IncrFileWriter extends StringWriter {
+        private final File _file;
+        private final Repackager _repackager;
 
-        public IncrFileWriter(File file, Repackager repackager)
-        {
+        public IncrFileWriter(File file, Repackager repackager) {
             _file = file;
             _repackager = repackager;
         }
 
-        public void close() throws IOException
-        {
+        public void close() throws IOException {
             super.close();
 
             // This is where all the real work happens
@@ -176,56 +155,39 @@
                 _repackager.repackage(getBuffer()) :
                 getBuffer();
             String str = sb.toString();
-            List diffs = new ArrayList();
-            StringReader sReader = new StringReader(str);
-            FileReader fReader = new FileReader(_file);
+            List<String> diffs = new ArrayList<>();
 
-            try
-            {
+            try (StringReader sReader = new StringReader(str);
+                 FileReader fReader = new FileReader(_file)) {
                 Diff.readersAsText(sReader, "<generated>",
                     fReader, _file.getName(), diffs);
             }
-            finally
-            {
-                sReader.close();
-                fReader.close();
-            }
 
-            if (diffs.size() > 0)
-            {
+            if (diffs.size() > 0) {
                 // Diffs encountered, replace the file on disk with text from
                 // the buffer
-                Writer fw = writerForFile(_file);
-                try
-                {   fw.write(str); }
-                finally
-                {   fw.close(); }
+                try (Writer fw = writerForFile(_file)) {
+                    fw.write(str);
+                }
             }
-            else
-                ; // If no diffs, don't do anything
         }
     }
 
-    static class RepackagingWriter extends StringWriter
-    {
-        public RepackagingWriter ( File file, Repackager repackager )
-        {
+    static class RepackagingWriter extends StringWriter {
+        public RepackagingWriter(File file, Repackager repackager) {
             _file = file;
             _repackager = repackager;
         }
 
-        public void close ( ) throws IOException
-        {
+        public void close() throws IOException {
             super.close();
 
-            Writer fw = writerForFile( _file );
-            try
-            { fw.write( _repackager.repackage( getBuffer() ).toString() ); }
-            finally
-            { fw.close(); }
+            try (Writer fw = writerForFile(_file)) {
+                fw.write(_repackager.repackage(getBuffer()).toString());
+            }
         }
 
-        private File _file;
-        private Repackager _repackager;
+        private final File _file;
+        private final Repackager _repackager;
     }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java
index 331fa60..b3f59ef 100644
--- a/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java
+++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java
@@ -110,7 +110,7 @@
     //because computing hashcode is expensive we'll cache it
     protected boolean _hashcached = false;
     protected int hashcode = 0;
-    protected static MessageDigest md5;
+    protected static final MessageDigest md5;
 
     static {
         try {
diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java
index 6e7c5e2..112c03d 100644
--- a/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java
+++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java
@@ -111,7 +111,7 @@
     //because computing hashcode is expensive we'll cache it
     protected boolean _hashcached = false;
     protected int hashcode = 0;
-    protected static MessageDigest md5;
+    protected static final MessageDigest md5;
 
     static {
         try {