spotbugs and forbidden apis fixes
raw container -> use generics

git-svn-id: https://svn.apache.org/repos/asf/xmlbeans/trunk@1882308 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/main/java/org/apache/xmlbeans/GDate.java b/src/main/java/org/apache/xmlbeans/GDate.java
index 15e74d6..81fb6ef 100644
--- a/src/main/java/org/apache/xmlbeans/GDate.java
+++ b/src/main/java/org/apache/xmlbeans/GDate.java
@@ -17,6 +17,7 @@
 
 import java.math.BigDecimal;
 import java.math.BigInteger;
+import java.math.RoundingMode;
 import java.util.Calendar;
 import java.util.Date;
 import java.util.GregorianCalendar;
@@ -712,7 +713,7 @@
         if (_fs == null) {
             return 0;
         }
-        return _fs.setScale(3, BigDecimal.ROUND_DOWN).unscaledValue().intValue();
+        return _fs.setScale(3, RoundingMode.DOWN).unscaledValue().intValue();
     }
 
     /**
diff --git a/src/main/java/org/apache/xmlbeans/XmlOptions.java b/src/main/java/org/apache/xmlbeans/XmlOptions.java
index 1f67bcf..ff6b2e5 100644
--- a/src/main/java/org/apache/xmlbeans/XmlOptions.java
+++ b/src/main/java/org/apache/xmlbeans/XmlOptions.java
@@ -1408,7 +1408,7 @@
     }
 
     private XmlOptions set(XmlOptionsKeys option, int value) {
-        return set(option, new Integer(value));
+        return set(option, (Integer)value);
     }
 
     private XmlOptions set(XmlOptionsKeys option, boolean value) {
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/DocumentHelper.java b/src/main/java/org/apache/xmlbeans/impl/common/DocumentHelper.java
index f0d4746..f6e873a 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/DocumentHelper.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/DocumentHelper.java
@@ -15,27 +15,24 @@
 
 package org.apache.xmlbeans.impl.common;
 
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.Method;
-import java.util.concurrent.TimeUnit;
-
-import javax.xml.XMLConstants;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.stream.events.Namespace;
-
 import org.apache.xmlbeans.XmlOptionsBean;
 import org.w3c.dom.Document;
-import org.w3c.dom.Element;
 import org.xml.sax.ErrorHandler;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;
 import org.xml.sax.SAXParseException;
 
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Method;
+import java.util.concurrent.TimeUnit;
+
 public final class DocumentHelper {
-    private static XBLogger logger = XBLogFactory.getLogger(DocumentHelper.class);
+    private static final XBLogger logger = XBLogFactory.getLogger(DocumentHelper.class);
     private static long lastLog;
 
     private DocumentHelper() {}
@@ -58,7 +55,7 @@
         /** Prints the error message. */
         private void printError(int type, SAXParseException ex) {
             StringBuilder sb = new StringBuilder();
-            
+
             String systemId = ex.getSystemId();
             if (systemId != null) {
                 int index = systemId.lastIndexOf('/');
@@ -76,7 +73,7 @@
             logger.log(type, sb.toString(), ex);
         }
     }
-    
+
     /**
      * Creates a new document builder, with sensible defaults
      *
@@ -115,7 +112,7 @@
             logger.log(XBLogger.WARN, "Cannot set SAX feature because outdated XML parser in classpath", feature, ame);
         }
     }
-    
+
     private static void trySetXercesSecurityManager(DocumentBuilderFactory dbf, XmlOptionsBean options) {
         // Try built-in JVM one first, standalone if not
         for (String securityManagerClassName : new String[]{
@@ -123,7 +120,7 @@
                 "org.apache.xerces.util.SecurityManager"
         }) {
             try {
-                Object mgr = Class.forName(securityManagerClassName).newInstance();
+                Object mgr = Class.forName(securityManagerClassName).getDeclaredConstructor().newInstance();
                 Method setLimit = mgr.getClass().getMethod("setEntityExpansionLimit", Integer.TYPE);
                 setLimit.invoke(mgr, options.getEntityExpansionLimit());
                 dbf.setAttribute(XMLBeansConstants.SECURITY_MANAGER, mgr);
@@ -154,7 +151,7 @@
      * Parses the given stream via the default (sensible)
      * DocumentBuilder
      * @param inp Stream to read the XML data from
-     * @return the parsed Document 
+     * @return the parsed Document
      */
     public static Document readDocument(XmlOptionsBean xmlOptions, InputStream inp) throws IOException, SAXException {
         return newDocumentBuilder(xmlOptions).parse(inp);
@@ -164,7 +161,7 @@
      * Parses the given stream via the default (sensible)
      * DocumentBuilder
      * @param inp sax source to read the XML data from
-     * @return the parsed Document 
+     * @return the parsed Document
      */
     public static Document readDocument(XmlOptionsBean xmlOptions, InputSource inp) throws IOException, SAXException {
         return newDocumentBuilder(xmlOptions).parse(inp);
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/NameUtil.java b/src/main/java/org/apache/xmlbeans/impl/common/NameUtil.java
index da71017..c0e7c8a 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/NameUtil.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/NameUtil.java
@@ -29,76 +29,67 @@
     public final static char AYAH = '\u06DD';
     public final static char ELHIZB = '\u06DE';
 
-    private final static boolean DEBUG = false;
+    private final static Set<String> javaWords = new HashSet<>(Arrays.asList(
+        "assert",
+        "abstract",
+        "boolean",
+        "break",
+        "byte",
+        "case",
+        "catch",
+        "char",
+        "class",
+        "const",
+        "continue",
+        "default",
+        "do",
+        "double",
+        "else",
+        "enum", // since JDK1.5
+        "extends",
+        "false", // not a keyword
+        "final",
+        "finally",
+        "float",
+        "for",
+        "goto",
+        "if",
+        "implements",
+        "import",
+        "instanceof",
+        "int",
+        "interface",
+        "long",
+        "native",
+        "new",
+        "null", // not a keyword
+        "package",
+        "private",
+        "protected",
+        "public",
+        "return",
+        "short",
+        "static",
+        "strictfp",
+        "super",
+        "switch",
+        "synchronized",
+        "this",
+        "threadsafe",
+        "throw",
+        "throws",
+        "transient",
+        "true", // not a keyword
+        "try",
+        "void",
+        "volatile",
+        "while"));
 
-    private final static Set javaWords = new HashSet(Arrays.asList(
-        new String[]
-            {
-                "assert",
-                "abstract",
-                "boolean",
-                "break",
-                "byte",
-                "case",
-                "catch",
-                "char",
-                "class",
-                "const",
-                "continue",
-                "default",
-                "do",
-                "double",
-                "else",
-                "enum", // since JDK1.5
-                "extends",
-                "false", // not a keyword
-                "final",
-                "finally",
-                "float",
-                "for",
-                "goto",
-                "if",
-                "implements",
-                "import",
-                "instanceof",
-                "int",
-                "interface",
-                "long",
-                "native",
-                "new",
-                "null", // not a keyword
-                "package",
-                "private",
-                "protected",
-                "public",
-                "return",
-                "short",
-                "static",
-                "strictfp",
-                "super",
-                "switch",
-                "synchronized",
-                "this",
-                "threadsafe",
-                "throw",
-                "throws",
-                "transient",
-                "true", // not a keyword
-                "try",
-                "void",
-                "volatile",
-                "while",
-            }
-    ));
-
-    private final static Set extraWords = new HashSet(Arrays.asList(
-        new String[]
-            {
-                "i",          // used for indexes
-                "target",     // used for parameter
-                "org",        // used for package names
-                "com",        // used for package names
-            }
+    private final static Set<String> extraWords = new HashSet<>(Arrays.asList(
+        "i",          // used for indexes
+        "target",     // used for parameter
+        "org",        // used for package names
+        "com"        // used for package names
     ));
 
     /*
@@ -192,111 +183,107 @@
     ));
     */
 
-    private final static Set javaNames = new HashSet(Arrays.asList(
-        new String[]
-            {
-                // 1. all the Java.lang classes [1.4.1 JDK].
-                "CharSequence",
-                "Cloneable",
-                "Comparable",
-                "Runnable",
+    private final static Set<String> javaNames = new HashSet<>(Arrays.asList(
+        // 1. all the Java.lang classes [1.4.1 JDK].
+        "CharSequence",
+        "Cloneable",
+        "Comparable",
+        "Runnable",
 
-                "Boolean",
-                "Byte",
-                "Character",
-                "Class",
-                "ClassLoader",
-                "Compiler",
-                "Double",
-                "Float",
-                "InheritableThreadLocal",
-                "Integer",
-                "Long",
-                "Math",
-                "Number",
-                "Object",
-                "Package",
-                "Process",
-                "Runtime",
-                "RuntimePermission",
-                "SecurityManager",
-                "Short",
-                "StackTraceElement",
-                "StrictMath",
-                "String",
-                "StringBuffer",
-                "System",
-                "Thread",
-                "ThreadGroup",
-                "ThreadLocal",
-                "Throwable",
-                "Void",
+        "Boolean",
+        "Byte",
+        "Character",
+        "Class",
+        "ClassLoader",
+        "Compiler",
+        "Double",
+        "Float",
+        "InheritableThreadLocal",
+        "Integer",
+        "Long",
+        "Math",
+        "Number",
+        "Object",
+        "Package",
+        "Process",
+        "Runtime",
+        "RuntimePermission",
+        "SecurityManager",
+        "Short",
+        "StackTraceElement",
+        "StrictMath",
+        "String",
+        "StringBuffer",
+        "System",
+        "Thread",
+        "ThreadGroup",
+        "ThreadLocal",
+        "Throwable",
+        "Void",
 
-                "ArithmeticException",
-                "ArrayIndexOutOfBoundsException",
-                "ArrayStoreException",
-                "ClassCastException",
-                "ClassNotFoundException",
-                "CloneNotSupportedException",
-                "Exception",
-                "IllegalAccessException",
-                "IllegalArgumentException",
-                "IllegalMonitorStateException",
-                "IllegalStateException",
-                "IllegalThreadStateException",
-                "IndexOutOfBoundsException",
-                "InstantiationException",
-                "InterruptedException",
-                "NegativeArraySizeException",
-                "NoSuchFieldException",
-                "NoSuchMethodException",
-                "NullPointerException",
-                "NumberFormatException",
-                "RuntimeException",
-                "SecurityException",
-                "StringIndexOutOfBoundsException",
-                "UnsupportedOperationException",
+        "ArithmeticException",
+        "ArrayIndexOutOfBoundsException",
+        "ArrayStoreException",
+        "ClassCastException",
+        "ClassNotFoundException",
+        "CloneNotSupportedException",
+        "Exception",
+        "IllegalAccessException",
+        "IllegalArgumentException",
+        "IllegalMonitorStateException",
+        "IllegalStateException",
+        "IllegalThreadStateException",
+        "IndexOutOfBoundsException",
+        "InstantiationException",
+        "InterruptedException",
+        "NegativeArraySizeException",
+        "NoSuchFieldException",
+        "NoSuchMethodException",
+        "NullPointerException",
+        "NumberFormatException",
+        "RuntimeException",
+        "SecurityException",
+        "StringIndexOutOfBoundsException",
+        "UnsupportedOperationException",
 
-                "AbstractMethodError",
-                "AssertionError",
-                "ClassCircularityError",
-                "ClassFormatError",
-                "Error",
-                "ExceptionInInitializerError",
-                "IllegalAccessError",
-                "IncompatibleClassChangeError",
-                "InstantiationError",
-                "InternalError",
-                "LinkageError",
-                "NoClassDefFoundError",
-                "NoSuchFieldError",
-                "NoSuchMethodError",
-                "OutOfMemoryError",
-                "StackOverflowError",
-                "ThreadDeath",
-                "UnknownError",
-                "UnsatisfiedLinkError",
-                "UnsupportedClassVersionError",
-                "VerifyError",
-                "VirtualMachineError",
+        "AbstractMethodError",
+        "AssertionError",
+        "ClassCircularityError",
+        "ClassFormatError",
+        "Error",
+        "ExceptionInInitializerError",
+        "IllegalAccessError",
+        "IncompatibleClassChangeError",
+        "InstantiationError",
+        "InternalError",
+        "LinkageError",
+        "NoClassDefFoundError",
+        "NoSuchFieldError",
+        "NoSuchMethodError",
+        "OutOfMemoryError",
+        "StackOverflowError",
+        "ThreadDeath",
+        "UnknownError",
+        "UnsatisfiedLinkError",
+        "UnsupportedClassVersionError",
+        "VerifyError",
+        "VirtualMachineError",
 
-                // 2. other classes used as primitive types by xml beans
-                "BigInteger",
-                "BigDecimal",
-                "Enum",
-                "Date",
-                "GDate",
-                "GDuration",
-                "QName",
-                "List",
+        // 2. other classes used as primitive types by xml beans
+        "BigInteger",
+        "BigDecimal",
+        "Enum",
+        "Date",
+        "GDate",
+        "GDuration",
+        "QName",
+        "List",
 
-                // 3. the top few org.apache.xmlbeans names
-                "XmlObject",
-                "XmlCursor",
-                "XmlBeans",
-                "SchemaType",
-            }
-    ));
+        // 3. the top few org.apache.xmlbeans names
+        "XmlObject",
+        "XmlCursor",
+        "XmlBeans",
+        "SchemaType"));
 
     public static boolean isValidJavaIdentifier(String id) {
         if (id == null) {
@@ -333,9 +320,8 @@
         String java_type = upperCamelCase(qname.getLocalPart(), useJaxRpcRules);
 
         String uri = qname.getNamespaceURI();
-        String java_pkg = null;
 
-        java_pkg = getPackageFromNamespace(uri, useJaxRpcRules);
+        String java_pkg = getPackageFromNamespace(uri, useJaxRpcRules);
 
         if (java_pkg != null) {
             return java_pkg + "." + java_type;
@@ -345,10 +331,9 @@
     }
 
     private static final String JAVA_NS_PREFIX = "java:";
-    private static final String LANG_PREFIX = "java.";
 
-    public static String getNamespaceFromPackage(final Class clazz) {
-        Class curr_clazz = clazz;
+    public static String getNamespaceFromPackage(final Class<?> clazz) {
+        Class<?> curr_clazz = clazz;
 
         while (curr_clazz.isArray()) {
             curr_clazz = curr_clazz.getComponentType();
@@ -433,11 +418,11 @@
         return buf.toString();
     }
 
-    private static List splitDNS(String dns) {
+    private static List<String> splitDNS(String dns) {
         // JAXB says: only split+reverse DNS if TLD matches known TLDs or ISO 3166
         // We are ignoring this now (TH)
 
-        List result = new ArrayList();
+        List<String> result = new ArrayList<>();
 
         int end = dns.length();
         int begin = dns.lastIndexOf('.');
@@ -451,7 +436,7 @@
 
         // JAXB draft example implies removal of www
         if (result.size() >= 3 &&
-            ((String) result.get(result.size() - 1)).toLowerCase().equals("www")) {
+            result.get(result.size() - 1).toLowerCase(Locale.ROOT).equals("www")) {
             result.remove(result.size() - 1);
         }
 
@@ -465,7 +450,7 @@
         if (i > 0 && (
             i + 1 + 2 == filename.length() ||
             i + 1 + 3 == filename.length() ||
-            "html".equals(filename.substring(i + 1).toLowerCase()))) {
+            "html".equals(filename.substring(i + 1).toLowerCase(Locale.ROOT)))) {
             return filename.substring(0, i);
         }
 
@@ -485,16 +470,16 @@
         // apply draft JAXB rules
         int len = uri.length();
         int i = findSchemeColon(uri);
-        List result = null;
+        List<String> result;
 
         if (i == len - 1) {
             // XMLBEANS-57: colon is at end so just use scheme as the package name
-            result = new ArrayList();
+            result = new ArrayList<>();
             result.add(uri.substring(0, i));
         } else if (i >= 0 && uri.substring(0, i).equals("java")) {
             result = Arrays.asList(uri.substring(i + 1).split("\\."));
         } else {
-            result = new ArrayList();
+            result = new ArrayList<>();
             outer:
             for (i = i + 1; i < len; ) {
                 while (uri.charAt(i) == '/') {
@@ -512,19 +497,19 @@
                 result.add(uri.substring(start, end));
             }
             if (result.size() > 1) {
-                result.set(result.size() - 1, processFilename((String) result.get(result.size() - 1)));
+                result.set(result.size() - 1, processFilename(result.get(result.size() - 1)));
             }
 
             if (result.size() > 0) {
-                List splitdns = splitDNS((String) result.get(0));
+                List<String> splitdns = splitDNS(result.get(0));
                 result.remove(0);
                 result.addAll(0, splitdns);
             }
         }
 
         StringBuilder buf = new StringBuilder();
-        for (Iterator it = result.iterator(); it.hasNext(); ) {
-            String part = nonJavaKeyword(lowerCamelCase((String) it.next(), useJaxRpcRules, true));
+        for (String s : result) {
+            String part = nonJavaKeyword(lowerCamelCase(s, useJaxRpcRules, true));
             if (part.length() > 0) {
                 buf.append(part);
                 buf.append('.');
@@ -534,14 +519,14 @@
             return "noNamespace";
         }
         if (useJaxRpcRules) {
-            return buf.substring(0, buf.length() - 1).toLowerCase();
+            return buf.substring(0, buf.length() - 1).toLowerCase(Locale.ROOT);
         }
         return buf.substring(0, buf.length() - 1); // chop off extra dot
     }
 
     public static void main(String[] args) {
-        for (int i = 0; i < args.length; i++) {
-            System.out.println(upperCaseUnderbar(args[i]));
+        for (String arg : args) {
+            System.out.println(upperCaseUnderbar(arg));
         }
     }
 
@@ -553,20 +538,20 @@
      */
     public static String upperCaseUnderbar(String xml_name) {
         StringBuilder buf = new StringBuilder();
-        List words = splitWords(xml_name, false);
+        List<String> words = splitWords(xml_name, false);
 
         final int sz = words.size() - 1;
-        if (sz >= 0 && !Character.isJavaIdentifierStart(((String) words.get(0)).charAt(0))) {
+        if (sz >= 0 && !Character.isJavaIdentifierStart(words.get(0).charAt(0))) {
             buf.append("X_");
         }
 
         for (int i = 0; i < sz; i++) {
-            buf.append((String) words.get(i));
+            buf.append(words.get(i));
             buf.append(USCORE);
         }
 
         if (sz >= 0) {
-            buf.append((String) words.get(sz));
+            buf.append(words.get(sz));
         }
 
         //upcase entire buffer
@@ -595,16 +580,15 @@
      */
     public static String upperCamelCase(String xml_name, boolean useJaxRpcRules) {
         StringBuilder buf = new StringBuilder();
-        List words = splitWords(xml_name, useJaxRpcRules);
+        List<String> words = splitWords(xml_name, useJaxRpcRules);
 
         if (words.size() > 0) {
-            if (!Character.isJavaIdentifierStart(((String) words.get(0)).charAt(0))) {
+            if (!Character.isJavaIdentifierStart(words.get(0).charAt(0))) {
                 buf.append("X");
             }
 
-            Iterator itr = words.iterator();
-            while (itr.hasNext()) {
-                buf.append((String) itr.next());
+            for (String word : words) {
+                buf.append(word);
             }
         }
         return buf.toString();
@@ -629,20 +613,20 @@
     public static String lowerCamelCase(String xml_name, boolean useJaxRpcRules,
                                         boolean fixGeneratedName) {
         StringBuilder buf = new StringBuilder();
-        List words = splitWords(xml_name, useJaxRpcRules);
+        List<String> words = splitWords(xml_name, useJaxRpcRules);
 
         if (words.size() > 0) {
-            String first = ((String) words.get(0)).toLowerCase();
+            String first = words.get(0).toLowerCase(Locale.ROOT);
             char f = first.charAt(0);
             if (!Character.isJavaIdentifierStart(f) && fixGeneratedName) {
                 buf.append("x");
             }
             buf.append(first);
 
-            Iterator itr = words.iterator();
+            Iterator<String> itr = words.iterator();
             itr.next(); // skip already-lowercased word
             while (itr.hasNext()) {
-                buf.append((String) itr.next());
+                buf.append(itr.next());
             }
         }
         return buf.toString();
@@ -665,14 +649,14 @@
      * <p>
      * ncname is xml ncname (i.e. no colons).
      */
-    private static void addCapped(List list, String str) {
+    private static void addCapped(List<String> list, String str) {
         if (str.length() > 0) {
             list.add(upperCaseFirstLetter(str));
         }
     }
 
-    public static List splitWords(String name, boolean useJaxRpcRules) {
-        List list = new ArrayList();
+    public static List<String> splitWords(String name, boolean useJaxRpcRules) {
+        List<String> list = new ArrayList<>();
         int len = name.length();
         int start = 0;
         int prefix = START;
@@ -764,10 +748,7 @@
      * prepends the letter "x".
      */
     public static String nonExtraKeyword(String word) {
-        if (isExtraReservedWord(word, true)) {
-            return word + "Value";
-        }
-        return word;
+        return isExtraReservedWord(word) ? word + "Value" : word;
     }
 
     /**
@@ -783,21 +764,11 @@
     }
 
     private static boolean isJavaReservedWord(String word) {
-        return isJavaReservedWord(word, true);
+        return javaWords.contains(word.toLowerCase(Locale.ROOT));
     }
 
-    private static boolean isJavaReservedWord(String word, boolean ignore_case) {
-        if (ignore_case) {
-            word = word.toLowerCase();
-        }
-        return javaWords.contains(word);
-    }
-
-    private static boolean isExtraReservedWord(String word, boolean ignore_case) {
-        if (ignore_case) {
-            word = word.toLowerCase();
-        }
-        return extraWords.contains(word);
+    private static boolean isExtraReservedWord(String word) {
+        return extraWords.contains(word.toLowerCase(Locale.ROOT));
     }
 
     public static boolean isJavaCommonClassName(String word) {
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/QNameHelper.java b/src/main/java/org/apache/xmlbeans/impl/common/QNameHelper.java
index 8ca53ed..7617aaf 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/QNameHelper.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/QNameHelper.java
@@ -15,18 +15,18 @@
 
 package org.apache.xmlbeans.impl.common;
 
-import javax.xml.namespace.QName;
+import org.apache.xmlbeans.SchemaField;
+import org.apache.xmlbeans.SchemaType;
 import org.apache.xmlbeans.xml.stream.XMLName;
 
+import javax.xml.namespace.QName;
+import java.io.UnsupportedEncodingException;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
-import java.util.Map;
-import java.util.HashMap;
 import java.util.Collections;
-import java.io.UnsupportedEncodingException;
-
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.SchemaField;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
 
 public class QNameHelper
 {
@@ -36,10 +36,10 @@
     {
         if (qname == null)
             return null;
-        
+
         return XMLNameHelper.forLNS( qname.getLocalPart(), qname.getNamespaceURI() );
     }
-    
+
     public static QName forLNS(String localname, String uri)
     {
         if (uri == null)
@@ -67,7 +67,7 @@
 
         if (name.getNamespaceURI() == null || name.getNamespaceURI().length() == 0)
             return name.getLocalPart();
-        
+
         return name.getLocalPart() + "@" + name.getNamespaceURI();
     }
 
@@ -102,7 +102,7 @@
     //
     // The reason for the "shortening" is to avoid filenames longer than about
     // 256 characters, which are prohibited on Windows NT.
-   
+
     public static final int MAX_NAME_LENGTH = 64;
     public static final String URI_SHA1_PREFIX = "URI_SHA_1_";
 
@@ -136,11 +136,11 @@
                 }
             }
         }
-        
+
         // short enough? Done!
         if (result.length() <= MAX_NAME_LENGTH)
             return result.toString();
-        
+
         // too long? use SHA1
         try
         {
@@ -201,25 +201,25 @@
         {
             return readable(sType.getName(), nsPrefix);
         }
-        
+
         if (sType.isAttributeType())
         {
             return "attribute type " + readable(sType.getAttributeTypeAttributeName(), nsPrefix);
         }
-        
+
         if (sType.isDocumentType())
         {
             return "document type " + readable(sType.getDocumentElementName(), nsPrefix);
         }
-        
+
         if (sType.isNoType() || sType.getOuterType() == null)
         {
             return "invalid type";
         }
-        
+
         SchemaType outerType = sType.getOuterType();
         SchemaField container = sType.getContainerField();
-        
+
         if (outerType.isAttributeType())
         {
             return "type of attribute " + readable(container.getName(), nsPrefix);
@@ -228,7 +228,7 @@
         {
             return "type of element " + readable(container.getName(), nsPrefix);
         }
-            
+
         if (container != null)
         {
             if (container.isAttribute())
@@ -240,7 +240,7 @@
                 return "type of " + container.getName().getLocalPart() + " element in " + readable(outerType, nsPrefix);
             }
         }
-        
+
         if (outerType.getBaseType() == sType)
             return "base type of " + readable(outerType, nsPrefix);
         else if (outerType.getSimpleVariety() == SchemaType.LIST)
@@ -248,9 +248,9 @@
         else if (outerType.getSimpleVariety() == SchemaType.UNION)
             return "member type " + sType.getAnonymousUnionMemberOrdinal() + " of " + readable(outerType, nsPrefix);
         else
-            return "inner type in " + readable(outerType, nsPrefix); 
+            return "inner type in " + readable(outerType, nsPrefix);
     }
-    
+
     public static String readable(QName name)
     {
         return readable(name, WELL_KNOWN_PREFIXES);
@@ -265,13 +265,13 @@
             return prefix + ":" + name.getLocalPart();
         return name.getLocalPart() + " in namespace " + name.getNamespaceURI();
     }
-    
+
     public static String suggestPrefix(String namespace)
     {
         String result = (String)WELL_KNOWN_PREFIXES.get(namespace);
         if (result != null)
             return result;
-        
+
         int len = namespace.length();
         int i = namespace.lastIndexOf('/');
         if (i > 0 && i == namespace.length() - 1)
@@ -279,21 +279,21 @@
             len = i;
             i = namespace.lastIndexOf('/', i - 1);
         }
-        
+
         i += 1; // skip '/', also covers -1 case.
-        
+
         if (namespace.startsWith("www.", i))
         {
             i += 4; // "www.".length()
         }
-        
+
         while (i < len)
         {
             if (XMLChar.isNCNameStart(namespace.charAt(i)))
                 break;
             i += 1;
         }
-        
+
         for (int end = i + 1; end < len; end += 1)
         {
             if (!XMLChar.isNCName(namespace.charAt(end)) || !Character.isLetterOrDigit(namespace.charAt(end)))
@@ -302,7 +302,7 @@
                 break;
             }
         }
-        
+
         // prefixes starting with "xml" are forbidden, so change "xmls" -> "xs"
         if (namespace.length() >= i + 3 && startsWithXml(namespace, i))
         {
@@ -310,7 +310,7 @@
                 return "x" + Character.toLowerCase(namespace.charAt(i + 3));
             return "ns";
         }
-        
+
         if (len - i > 4) // four or less? leave it.
         {
             if (isVowel(namespace.charAt(i + 2)) && !isVowel(namespace.charAt(i + 3)))
@@ -318,28 +318,28 @@
             else
                 len = i + 3; // more than four? truncate to 3.
         }
-        
+
         if (len - i == 0)
             return "ns";
-        
-        return namespace.substring(i, len).toLowerCase();
+
+        return namespace.substring(i, len).toLowerCase(Locale.ROOT);
     }
-    
+
     private static boolean startsWithXml(String s, int i)
     {
         if (s.length() < i + 3)
             return false;
-        
+
         if (s.charAt(i) != 'X' && s.charAt(i) != 'x')
             return false;
         if (s.charAt(i + 1) != 'M' && s.charAt(i + 1) != 'm')
             return false;
         if (s.charAt(i + 2) != 'L' && s.charAt(i + 2) != 'l')
             return false;
-        
+
         return true;
     }
-    
+
     private static boolean isVowel(char ch)
     {
         switch (ch)
@@ -359,7 +359,7 @@
                 return false;
         }
     }
-    
+
     public static String namespace(SchemaType sType)
     {
         while (sType != null)
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/SAXHelper.java b/src/main/java/org/apache/xmlbeans/impl/common/SAXHelper.java
index a66f293..366cd86 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/SAXHelper.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/SAXHelper.java
@@ -100,7 +100,7 @@
             "org.apache.xerces.util.SecurityManager"
         }) {
             try {
-                Object mgr = Class.forName(securityManagerClassName).newInstance();
+                Object mgr = Class.forName(securityManagerClassName).getDeclaredConstructor().newInstance();
                 Method setLimit = mgr.getClass().getMethod("setEntityExpansionLimit", Integer.TYPE);
                 setLimit.invoke(mgr, options.getEntityExpansionLimit());
                 xmlReader.setProperty(XMLBeansConstants.SECURITY_MANAGER, mgr);
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/SystemCache.java b/src/main/java/org/apache/xmlbeans/impl/common/SystemCache.java
index 0520c59..a6d6f47 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/SystemCache.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/SystemCache.java
@@ -14,12 +14,12 @@
  */
 package org.apache.xmlbeans.impl.common;
 
-import java.lang.ref.SoftReference;
-import java.util.ArrayList;
-
 import org.apache.xmlbeans.SchemaTypeLoader;
 import org.apache.xmlbeans.SystemProperties;
 
+import java.lang.ref.SoftReference;
+import java.lang.reflect.InvocationTargetException;
+
 /**
  * This class encapsulates the caching strategy for XmlBeans.
  * By subclassing this, a client of XmlBeans can implement caches that are
@@ -28,88 +28,70 @@
  * <p/>
  * This class works as a singleton and as a default implementation for the cache.
  * You can set a particular implementation using the "xmlbean.systemcacheimpl"
- * system property or using the static {@link set} method.
+ * system property or using the static {@link #set(SystemCache)} method.
  * Subclasses of this need to be thread-safe. An implementation can be replaced
  * at any time, so use of static variables is discouraged to ensure proper cleanup.
  */
-public class SystemCache
-{
+public class SystemCache {
     private static SystemCache INSTANCE = new SystemCache();
 
-    static
-    {
+    static {
         String cacheClass = SystemProperties.getProperty("xmlbean.systemcacheimpl");
         Object impl = null;
-        if (cacheClass != null)
-        {
-            try
-            {
-                impl = Class.forName(cacheClass).newInstance();
-                if (!(impl instanceof SystemCache))
-                throw new ClassCastException("Value for system property " +
-                    "\"xmlbean.systemcacheimpl\" points to a class (" + cacheClass +
-                    ") which does not derive from SystemCache");
-            }
-            catch (ClassNotFoundException cnfe)
-            {
+        if (cacheClass != null) {
+            try {
+                impl = Class.forName(cacheClass).getDeclaredConstructor().newInstance();
+                if (!(impl instanceof SystemCache)) {
+                    throw new ClassCastException("Value for system property " +
+                                                 "\"xmlbean.systemcacheimpl\" points to a class (" + cacheClass +
+                                                 ") which does not derive from SystemCache");
+                }
+            } catch (ClassNotFoundException cnfe) {
                 throw new RuntimeException("Cache class " + cacheClass +
-                    " specified by \"xmlbean.systemcacheimpl\" was not found.",
+                                           " specified by \"xmlbean.systemcacheimpl\" was not found.",
                     cnfe);
-            }
-            catch (InstantiationException ie)
-            {
+            } catch (InstantiationException | NoSuchMethodException | InvocationTargetException ie) {
                 throw new RuntimeException("Could not instantiate class " +
-                    cacheClass + " as specified by \"xmlbean.systemcacheimpl\"." +
-                    " An empty constructor may be missing.", ie);
-            }
-            catch (IllegalAccessException iae)
-            {
+                                           cacheClass + " as specified by \"xmlbean.systemcacheimpl\"." +
+                                           " An empty constructor may be missing.", ie);
+            } catch (IllegalAccessException iae) {
                 throw new RuntimeException("Could not instantiate class " +
-                    cacheClass + " as specified by \"xmlbean.systemcacheimpl\"." +
-                    " A public empty constructor may be missing.", iae);
+                                           cacheClass + " as specified by \"xmlbean.systemcacheimpl\"." +
+                                           " A public empty constructor may be missing.", iae);
             }
         }
-        if (impl != null)
+        if (impl != null) {
             INSTANCE = (SystemCache) impl;
+        }
     }
 
-    public static synchronized final void set(SystemCache instance)
-    {
+    public static synchronized void set(SystemCache instance) {
         INSTANCE = instance;
     }
 
-    public static final SystemCache get()
-    {
+    public static SystemCache get() {
         return INSTANCE;
     }
 
-    public SchemaTypeLoader getFromTypeLoaderCache(ClassLoader cl)
-    {
+    public SchemaTypeLoader getFromTypeLoaderCache(ClassLoader cl) {
         return null;
     }
 
-    public void addToTypeLoaderCache(SchemaTypeLoader stl, ClassLoader cl)
-    {
-        return;
+    public void addToTypeLoaderCache(SchemaTypeLoader stl, ClassLoader cl) {
     }
 
-    private ThreadLocal tl_saxLoaders = new ThreadLocal();
+    private ThreadLocal<SoftReference> tl_saxLoaders = new ThreadLocal<>();
 
     public void clearThreadLocals() {
         tl_saxLoaders.remove();
     }
 
-    public Object getSaxLoader()
-    {
-        SoftReference s = (SoftReference) tl_saxLoaders.get();
-        if (s == null)
-            return null;
-        else
-            return s.get();
+    public Object getSaxLoader() {
+        SoftReference s = tl_saxLoaders.get();
+        return s == null ? null : s.get();
     }
 
-    public void setSaxLoader(Object saxLoader)
-    {
+    public void setSaxLoader(Object saxLoader) {
         tl_saxLoaders.set(new SoftReference(saxLoader));
     }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/XBLogFactory.java b/src/main/java/org/apache/xmlbeans/impl/common/XBLogFactory.java
index 0afac4d..f0b8840 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/XBLogFactory.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/XBLogFactory.java
@@ -101,7 +101,7 @@
                 @SuppressWarnings("unchecked")
                 Class<? extends XBLogger> loggerClass =
                     (Class<? extends XBLogger>) Class.forName(_loggerClassName);
-                logger = loggerClass.newInstance();
+                logger = loggerClass.getDeclaredConstructor().newInstance();
                 logger.initialize(cat);
             } catch(Exception e) {
                 // Give up and use the null logger
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java
index 1e30984..10318c4 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java
@@ -233,9 +233,9 @@
     private String getUserTypeStaticHandlerMethod(boolean encode, SchemaTypeImpl stype) {
         String unqualifiedName = stype.getName().getLocalPart();
         if (unqualifiedName.length() < 2) {
-            unqualifiedName = unqualifiedName.toUpperCase();
+            unqualifiedName = unqualifiedName.toUpperCase(Locale.ROOT);
         } else {
-            unqualifiedName = unqualifiedName.substring(0, 1).toUpperCase() + unqualifiedName.substring(1);
+            unqualifiedName = unqualifiedName.substring(0, 1).toUpperCase(Locale.ROOT) + unqualifiedName.substring(1);
         }
 
         if (encode) {
@@ -1513,7 +1513,7 @@
             final QName name = prop.getName();
             results.put(name, identifiers);
             final String javaName = prop.getJavaPropertyName();
-            identifiers[0] = (javaName + "$" + (i * 2)).toUpperCase();
+            identifiers[0] = (javaName + "$" + (i * 2)).toUpperCase(Locale.ROOT);
             final String uriString = "\"" + name.getNamespaceURI() + "\"";
 
             emit("private static final javax.xml.namespace.QName " + identifiers[0] +
@@ -1527,7 +1527,7 @@
                 final QName[] qnames = properties[i].acceptedNames();
 
                 if (qnames.length > 1) {
-                    identifiers[1] = (javaName + "$" + (i * 2 + 1)).toUpperCase();
+                    identifiers[1] = (javaName + "$" + (i * 2 + 1)).toUpperCase(Locale.ROOT);
 
                     emit("private static final org.apache.xmlbeans.QNameSet " + identifiers[1] +
                          " = org.apache.xmlbeans.QNameSet.forArray( new javax.xml.namespace.QName[] { ");
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java
index 904edca..5299026 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java
@@ -17,10 +17,12 @@
 
 import org.apache.xmlbeans.*;
 import org.apache.xmlbeans.impl.common.QNameHelper;
+import org.apache.xmlbeans.impl.common.XBeanDebug;
 import org.apache.xmlbeans.impl.values.*;
 
 import javax.xml.namespace.QName;
 import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
 import java.math.BigInteger;
 import java.util.*;
 
@@ -1903,30 +1905,13 @@
 
     private XmlObject createUnattachedSubclass(SchemaType sType) {
         if (!isBuiltinType() && !isNoType()) {
-            // System.out.println("Attempting to load impl class: " + getFullJavaImplName());
             Constructor<? extends XmlObjectBase> ctr = getJavaImplConstructor2();
-            if (ctr != null) {
-                boolean accessible = ctr.isAccessible();
-                try {
-                    ctr.setAccessible(true);
-                    try {
-                        return ctr.newInstance(sType, !sType.isSimpleType());
-                    } catch (Exception e) {
-                        System.out.println("Exception trying to instantiate impl class.");
-                        e.printStackTrace();
-                    } finally {
-                        // Make a best-effort try to set the accessibility back to what it was
-                        try {
-                            ctr.setAccessible(accessible);
-                        } catch (SecurityException ignored) {
-                        }
-                    }
-                } catch (Exception e) {
-                    System.out.println("Exception trying to instantiate impl class.");
-                    e.printStackTrace();
-                }
+            try {
+                return (ctr == null) ? null : ctr.newInstance(sType, !sType.isSimpleType());
+            } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
+                XBeanDebug.logException(e);
+                return null;
             }
-            return null;
         } else {
             return createBuiltinSubclass(sType);
         }
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java
index c9b19ec..1cd1d3e 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java
@@ -883,7 +883,8 @@
         }
 
         private String addUniqueHandle(SchemaComponent obj, String base) {
-            base = base.toLowerCase();  // we lowercase handles because of case-insensitive Windows filenames!!!
+            // we lowercase handles because of case-insensitive Windows filenames!!!
+            base = base.toLowerCase(Locale.ROOT);
             String handle = base;
             for (int index = 2; _handlesToRefs.containsKey(handle); index++) {
                 handle = base + index;
@@ -1016,7 +1017,7 @@
                 }
 
                 String baseName;
-                String uniq = Integer.toHexString(type.toString().hashCode() | 0x80000000).substring(4).toUpperCase();
+                String uniq = Integer.toHexString(type.toString().hashCode() | 0x80000000).substring(4).toUpperCase(Locale.ROOT);
                 if (name == null) {
                     baseName = "Anon" + uniq + "Type";
                 } else {
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SoapEncSchemaTypeSystem.java b/src/main/java/org/apache/xmlbeans/impl/schema/SoapEncSchemaTypeSystem.java
index 0bb9edb..361ae2c 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/SoapEncSchemaTypeSystem.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/SoapEncSchemaTypeSystem.java
@@ -15,39 +15,16 @@
 
 package org.apache.xmlbeans.impl.schema;
 
-import java.io.InputStream;
-import java.io.File;
-import java.math.BigInteger;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Collections;
-import javax.xml.namespace.QName;
+import org.apache.xmlbeans.*;
 
-import org.apache.xmlbeans.QNameSet;
-import org.apache.xmlbeans.SchemaAnnotation;
-import org.apache.xmlbeans.SchemaAttributeGroup;
-import org.apache.xmlbeans.SchemaAttributeGroup;
-import org.apache.xmlbeans.SchemaAttributeModel;
-import org.apache.xmlbeans.SchemaComponent;
-import org.apache.xmlbeans.SchemaGlobalAttribute;
-import org.apache.xmlbeans.SchemaGlobalAttribute;
-import org.apache.xmlbeans.SchemaGlobalElement;
-import org.apache.xmlbeans.SchemaGlobalElement;
-import org.apache.xmlbeans.SchemaIdentityConstraint;
-import org.apache.xmlbeans.SchemaLocalAttribute;
-import org.apache.xmlbeans.SchemaModelGroup;
-import org.apache.xmlbeans.SchemaModelGroup;
-import org.apache.xmlbeans.SchemaParticle;
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.SchemaTypeLoader;
-import org.apache.xmlbeans.SchemaTypeSystem;
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.Filer;
+import javax.xml.namespace.QName;
+import java.io.File;
+import java.io.InputStream;
+import java.math.BigInteger;
+import java.util.*;
 
 public class SoapEncSchemaTypeSystem extends SchemaTypeLoaderBase
-    implements SchemaTypeSystem
-{
+    implements SchemaTypeSystem {
     public static final String SOAPENC = "http://schemas.xmlsoap.org/soap/encoding/";
     public static final String SOAP_ARRAY = "Array";
     public static final String ARRAY_TYPE = "arrayType";
@@ -62,25 +39,25 @@
     private static final SchemaAnnotation[] EMPTY_SCHEMAANNOTATION_ARRAY = new SchemaAnnotation[0];
 
     // The global builtin type system
-    public static SchemaTypeSystem get()
-    {   return _global; }
+    public static SchemaTypeSystem get() {
+        return _global;
+    }
 
-    private static SoapEncSchemaTypeSystem _global = new SoapEncSchemaTypeSystem();
+    private static final SoapEncSchemaTypeSystem _global = new SoapEncSchemaTypeSystem();
 
-    private SchemaTypeImpl soapArray;
-    private SchemaGlobalAttributeImpl arrayType;
-    private Map _handlesToObjects = new HashMap();
-    private String soapArrayHandle;
-    private SchemaContainer _container = new SchemaContainer(SOAPENC);
+    private final SchemaTypeImpl soapArray;
+    private final SchemaGlobalAttributeImpl arrayType;
+    private final Map<String, SchemaComponent> _handlesToObjects = new HashMap<>();
+    private final String soapArrayHandle;
 
-    private SoapEncSchemaTypeSystem()
-    {
+    private SoapEncSchemaTypeSystem() {
         // soapenc:Array
+        SchemaContainer _container = new SchemaContainer(SOAPENC);
         _container.setTypeSystem(this);
         soapArray = new SchemaTypeImpl(_container, true);
         _container.addGlobalType(soapArray.getRef());
         soapArray.setName(new QName(SOAPENC, SOAP_ARRAY));
-        soapArrayHandle = SOAP_ARRAY.toLowerCase() + "type";
+        soapArrayHandle = SOAP_ARRAY.toLowerCase(Locale.ROOT) + "type";
         soapArray.setComplexTypeVariety(SchemaType.ELEMENT_CONTENT);
         soapArray.setBaseTypeRef(BuiltinSchemaTypeSystem.ST_ANY_TYPE.getRef());
         soapArray.setBaseDepth(1);
@@ -104,10 +81,9 @@
 
         SchemaAttributeModelImpl attrModel = new SchemaAttributeModelImpl();
         attrModel.setWildcardProcess(SchemaAttributeModel.LAX);
-        HashSet excludedURI = new HashSet();
+        HashSet<String> excludedURI = new HashSet<>();
         excludedURI.add(SOAPENC);
-        attrModel.setWildcardSet(QNameSet.forSets(excludedURI, null, Collections.EMPTY_SET,
-                Collections.EMPTY_SET));
+        attrModel.setWildcardSet(QNameSet.forSets(excludedURI, null, Collections.emptySet(), Collections.emptySet()));
         SchemaLocalAttributeImpl attr = new SchemaLocalAttributeImpl();
         attr.init(new QName("", ATTR_ID), BuiltinSchemaTypeSystem.ST_ID.getRef(),
             SchemaLocalAttribute.OPTIONAL, null, null, null, false, null, null, null);
@@ -124,7 +100,7 @@
         attr.init(new QName(SOAPENC, ATTR_OFFSET), BuiltinSchemaTypeSystem.ST_STRING.getRef(),
             SchemaLocalAttributeImpl.OPTIONAL, null, null, null, false, null, null, null);
         attrModel.addAttribute(attr);
-        soapArray.setContentModel(contentModel, attrModel, Collections.EMPTY_MAP, Collections.EMPTY_MAP, false);
+        soapArray.setContentModel(contentModel, attrModel, Collections.emptyMap(), Collections.emptyMap(), false);
 
         // soapenc:arrayType
         arrayType = new SchemaGlobalAttributeImpl(_container);
@@ -132,202 +108,172 @@
         arrayType.init(new QName(SOAPENC, ARRAY_TYPE), BuiltinSchemaTypeSystem.ST_STRING.getRef(),
             SchemaLocalAttributeImpl.OPTIONAL, null, null, null, false, null, null, null);
         _handlesToObjects.put(soapArrayHandle, soapArray);
-        _handlesToObjects.put(ARRAY_TYPE.toLowerCase() + "attribute", arrayType);
+        _handlesToObjects.put(ARRAY_TYPE.toLowerCase(Locale.ROOT) + "attribute", arrayType);
         _container.setImmutable();
     }
 
     /**
      * Returns the name of this loader.
      */
-    public String getName()
-    {
+    public String getName() {
         return "schema.typesystem.soapenc.builtin";
     }
 
-    public SchemaType findType(QName qName)
-    {
+    public SchemaType findType(QName qName) {
         if (SOAPENC.equals(qName.getNamespaceURI()) &&
-            SOAP_ARRAY.equals(qName.getLocalPart()))
+            SOAP_ARRAY.equals(qName.getLocalPart())) {
             return soapArray;
-        else
+        } else {
             return null;
+        }
     }
 
-    public SchemaType findDocumentType(QName qName)
-    {
+    public SchemaType findDocumentType(QName qName) {
         return null;
     }
 
-    public SchemaType findAttributeType(QName qName)
-    {
+    public SchemaType findAttributeType(QName qName) {
         return null;
     }
 
-    public SchemaGlobalElement findElement(QName qName)
-    {
+    public SchemaGlobalElement findElement(QName qName) {
         return null;
     }
 
-    public SchemaGlobalAttribute findAttribute(QName qName)
-    {
+    public SchemaGlobalAttribute findAttribute(QName qName) {
         if (SOAPENC.equals(qName.getNamespaceURI()) &&
-            ARRAY_TYPE.equals(qName.getLocalPart()))
+            ARRAY_TYPE.equals(qName.getLocalPart())) {
             return arrayType;
-        else
+        } else {
             return null;
+        }
     }
 
-    public SchemaModelGroup findModelGroup(QName qName)
-    {
+    public SchemaModelGroup findModelGroup(QName qName) {
         return null;
     }
 
-    public SchemaAttributeGroup findAttributeGroup(QName qName)
-    {
+    public SchemaAttributeGroup findAttributeGroup(QName qName) {
         return null;
     }
 
-    public boolean isNamespaceDefined(String string)
-    {
+    public boolean isNamespaceDefined(String string) {
         return SOAPENC.equals(string);
     }
 
-    public SchemaType.Ref findTypeRef(QName qName)
-    {
+    public SchemaType.Ref findTypeRef(QName qName) {
         SchemaType type = findType(qName);
         return (type == null ? null : type.getRef());
     }
 
-    public SchemaType.Ref findDocumentTypeRef(QName qName)
-    {
+    public SchemaType.Ref findDocumentTypeRef(QName qName) {
         return null;
     }
 
-    public SchemaType.Ref findAttributeTypeRef(QName qName)
-    {
+    public SchemaType.Ref findAttributeTypeRef(QName qName) {
         return null;
     }
 
-    public SchemaGlobalElement.Ref findElementRef(QName qName)
-    {
+    public SchemaGlobalElement.Ref findElementRef(QName qName) {
         return null;
     }
 
-    public SchemaGlobalAttribute.Ref findAttributeRef(QName qName)
-    {
+    public SchemaGlobalAttribute.Ref findAttributeRef(QName qName) {
         SchemaGlobalAttribute attr = findAttribute(qName);
         return (attr == null ? null : attr.getRef());
     }
 
-    public SchemaModelGroup.Ref findModelGroupRef(QName qName)
-    {
+    public SchemaModelGroup.Ref findModelGroupRef(QName qName) {
         return null;
     }
 
-    public SchemaAttributeGroup.Ref findAttributeGroupRef(QName qName)
-    {
+    public SchemaAttributeGroup.Ref findAttributeGroupRef(QName qName) {
         return null;
     }
 
-    public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName qName)
-    {
+    public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName qName) {
         return null;
     }
 
-    public SchemaType typeForClassname(String string)
-    {
+    public SchemaType typeForClassname(String string) {
         return null;
     }
 
-    public InputStream getSourceAsStream(String string)
-    {
+    public InputStream getSourceAsStream(String string) {
         return null;            // no source
     }
 
     /**
      * Returns the classloader used by this loader for resolving types.
      */
-    public ClassLoader getClassLoader()
-    {
+    public ClassLoader getClassLoader() {
         return SoapEncSchemaTypeSystem.class.getClassLoader();
     }
 
     /**
      * Describe <code>resolve</code> method here.
-     *
      */
-    public void resolve()
-    {
-                                // don't need to do anything; already resolved
+    public void resolve() {
+        // don't need to do anything; already resolved
     }
 
     /**
      * @return an array consisting of a single type
      */
-    public SchemaType[] globalTypes()
-    {
-        return new SchemaType[] {soapArray};
+    public SchemaType[] globalTypes() {
+        return new SchemaType[]{soapArray};
     }
 
-    public SchemaType[] documentTypes()
-    {
+    public SchemaType[] documentTypes() {
         return EMPTY_SCHEMATYPE_ARRAY;
     }
 
-    public SchemaType[] attributeTypes()
-    {
+    public SchemaType[] attributeTypes() {
         return EMPTY_SCHEMATYPE_ARRAY;
     }
 
-    public SchemaGlobalElement[] globalElements()
-    {
+    public SchemaGlobalElement[] globalElements() {
         return EMPTY_SCHEMAELEMENT_ARRAY;
     }
 
-    public SchemaGlobalAttribute[] globalAttributes()
-    {
-        return new SchemaGlobalAttribute[] {arrayType};
+    public SchemaGlobalAttribute[] globalAttributes() {
+        return new SchemaGlobalAttribute[]{arrayType};
     }
 
-    public SchemaModelGroup[] modelGroups()
-    {
+    public SchemaModelGroup[] modelGroups() {
         return EMPTY_SCHEMAMODELGROUP_ARRAY;
     }
 
-    public SchemaAttributeGroup[] attributeGroups()
-    {
+    public SchemaAttributeGroup[] attributeGroups() {
         return EMPTY_SCHEMAATTRIBUTEGROUP_ARRAY;
     }
 
-    public SchemaAnnotation[] annotations()
-    {
+    public SchemaAnnotation[] annotations() {
         return EMPTY_SCHEMAANNOTATION_ARRAY;
     }
 
     /**
      * Returns the handle for the given type within this loader.
      */
-    public String handleForType(SchemaType type)
-    {
-        if (soapArray.equals(type))
+    public String handleForType(SchemaType type) {
+        if (soapArray.equals(type)) {
             return soapArrayHandle;
-        else
+        } else {
             return null;
-    }
-
-    /**
-     * 
-     */
-    public SchemaComponent resolveHandle(String string)
-    {
-        return (SchemaComponent) _handlesToObjects.get(string);
+        }
     }
 
     /**
      *
      */
-    public SchemaType typeForHandle(String string)
-    {
+    public SchemaComponent resolveHandle(String string) {
+        return _handlesToObjects.get(string);
+    }
+
+    /**
+     *
+     */
+    public SchemaType typeForHandle(String string) {
         return (SchemaType) _handlesToObjects.get(string);
     }
 
@@ -336,13 +282,11 @@
      *
      * @param file a <code>File</code> value
      */
-    public void saveToDirectory(File file)
-    {
+    public void saveToDirectory(File file) {
         throw new UnsupportedOperationException("The builtin soap encoding schema type system cannot be saved.");
     }
 
-    public void save(Filer filer)
-    {
+    public void save(Filer filer) {
         throw new UnsupportedOperationException("The builtin soap encoding schema type system cannot be saved.");
     }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java
index 902cba6..d51db24 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java
@@ -1384,7 +1384,7 @@
     }
 
     private static <T> BinaryOperator<T> throwingMerger() {
-        return (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); };
+        return (u,v) -> { throw new IllegalStateException("Duplicate key "+u.toString()); };
     }
 
     static Map<QName, SchemaProperty> buildAttributePropertyModelByQName(SchemaAttributeModel attrModel, SchemaType owner) {
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscJavaizer.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscJavaizer.java
index 3ed0e75..f3c4b3a 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/StscJavaizer.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscJavaizer.java
@@ -98,12 +98,12 @@
 
         InterfaceExtension[] exts = config.getInterfaceExtensions();
         for (InterfaceExtension ext : exts) {
-            if (usedNames.contains(ext.getInterface().toLowerCase())) {
+            if (usedNames.contains(ext.getInterface().toLowerCase(Locale.ROOT))) {
                 state.error("InterfaceExtension interface '" + ext.getInterface() + "' creates a name collision with one of the generated interfaces or classes.", XmlError.SEVERITY_ERROR, null);
             }
 
             String handler = ext.getStaticHandler();
-            if (handler != null && usedNames.contains(handler.toLowerCase())) {
+            if (handler != null && usedNames.contains(handler.toLowerCase(Locale.ROOT))) {
                 state.error("InterfaceExtension handler class '" + handler + "' creates a name collision with one of the generated interfaces or classes.", XmlError.SEVERITY_ERROR, null);
             }
         }
@@ -111,7 +111,7 @@
         PrePostExtension[] prepost = config.getPrePostExtensions();
         for (PrePostExtension prePostExtension : prepost) {
             String handler = prePostExtension.getStaticHandler();
-            if (handler != null && usedNames.contains(handler.toLowerCase())) {
+            if (handler != null && usedNames.contains(handler.toLowerCase(Locale.ROOT))) {
                 state.error("PrePostExtension handler class '" + handler + "' creates a name collision with one of the generated interfaces or classes.", XmlError.SEVERITY_ERROR, null);
             }
         }
@@ -732,12 +732,12 @@
         } else {
             uniqName = base;
         }
-        while (usedNames.contains(uniqName.toLowerCase()) || uniqName.equals(outermostPkg)) {
+        while (usedNames.contains(uniqName.toLowerCase(Locale.ROOT)) || uniqName.equals(outermostPkg)) {
             index++;
             uniqName = base + index;
         }
 
-        usedNames.add(uniqName.toLowerCase());
+        usedNames.add(uniqName.toLowerCase(Locale.ROOT));
 
         return uniqName;
     }
@@ -773,12 +773,12 @@
 
         index = 1;
         String uniqName = base;
-        while (usedNames.contains(uniqName.toLowerCase())) {
+        while (usedNames.contains(uniqName.toLowerCase(Locale.ROOT))) {
             index++;
             uniqName = base + index;
         }
 
-        usedNames.add(uniqName.toLowerCase());
+        usedNames.add(uniqName.toLowerCase(Locale.ROOT));
 
         return uniqName;
     }
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java
index a3b51b8..e43c9fb 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java
@@ -15,32 +15,19 @@
 
 package org.apache.xmlbeans.impl.schema;
 
-import java.util.*;
-import java.util.List;
-import java.math.BigInteger;
-
-import javax.xml.namespace.QName;
-import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException;
-import org.apache.xmlbeans.impl.regex.RegularExpression;
-import org.apache.xmlbeans.impl.regex.ParseException;
+import org.apache.xmlbeans.*;
 import org.apache.xmlbeans.impl.common.QNameHelper;
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.SimpleValue;
-import org.apache.xmlbeans.XmlAnySimpleType;
-import org.apache.xmlbeans.XmlByte;
-import org.apache.xmlbeans.XmlCursor;
-import org.apache.xmlbeans.XmlErrorCodes;
-import org.apache.xmlbeans.XmlInteger;
-import org.apache.xmlbeans.XmlNonNegativeInteger;
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.XmlPositiveInteger;
-import org.apache.xmlbeans.XmlShort;
-import org.apache.xmlbeans.XmlUnsignedByte;
+import org.apache.xmlbeans.impl.regex.ParseException;
+import org.apache.xmlbeans.impl.regex.RegularExpression;
+import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException;
 import org.apache.xmlbeans.impl.xb.xsdschema.*;
 import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema;
 
-public class StscSimpleTypeResolver
-{
+import javax.xml.namespace.QName;
+import java.math.BigInteger;
+import java.util.*;
+
+public class StscSimpleTypeResolver {
 
     /**************************************************************************
      * SIMPLE TYPE RESOLUTION HERE
@@ -55,32 +42,28 @@
      * in the end to have their "fundamental facets" resolved.
      */
 
-    public static void resolveSimpleType(SchemaTypeImpl sImpl)
-    {
-        SimpleType parseSt = (SimpleType)sImpl.getParseObject();
-        
+    public static void resolveSimpleType(SchemaTypeImpl sImpl) {
+        SimpleType parseSt = (SimpleType) sImpl.getParseObject();
+
         assert sImpl.isSimpleType();
 
         Schema schema = StscComplexTypeResolver.getSchema(parseSt);
 
         // Verify: have list, union, or restriction, but not more than one
         int count =
-                (parseSt.isSetList() ? 1 : 0) +
-                (parseSt.isSetUnion() ? 1 : 0) +
-                (parseSt.isSetRestriction() ? 1 : 0);
-        if (count > 1)
-        {
+            (parseSt.isSetList() ? 1 : 0) +
+            (parseSt.isSetUnion() ? 1 : 0) +
+            (parseSt.isSetRestriction() ? 1 : 0);
+        if (count > 1) {
             StscState.get().error(
-                    "A simple type must define either a list, a union, or a restriction: more than one found.",
-                    XmlErrorCodes.MALFORMED_SIMPLE_TYPE_DEFN,
-                    parseSt);
+                "A simple type must define either a list, a union, or a restriction: more than one found.",
+                XmlErrorCodes.MALFORMED_SIMPLE_TYPE_DEFN,
+                parseSt);
             // recovery: treat it as the first of list, union, restr
-        }
-        else if (count < 1)
-        {
+        } else if (count < 1) {
             StscState.get().error("A simple type must define either a list, a union, or a restriction: none was found.",
-                    XmlErrorCodes.MALFORMED_SIMPLE_TYPE_DEFN,
-                    parseSt);
+                XmlErrorCodes.MALFORMED_SIMPLE_TYPE_DEFN,
+                parseSt);
             // recovery: treat it as restriction of anySimpleType
             resolveErrorSimpleType(sImpl);
             return;
@@ -92,72 +75,63 @@
         boolean finalUnion = false;
 
         Object finalValue = null;
-        if (parseSt.isSetFinal())
-        {
+        if (parseSt.isSetFinal()) {
             finalValue = parseSt.getFinal();
         }
         // Inspect the finalDefault attribute on the schema
-        else if (schema != null && schema.isSetFinalDefault())
-        {
+        else if (schema != null && schema.isSetFinalDefault()) {
             finalValue = schema.getFinalDefault();
         }
 
-        if (finalValue != null)
-        {
-            if (finalValue instanceof String)
-            {
-                if ("#all".equals((String)finalValue))
-                {
+        if (finalValue != null) {
+            if (finalValue instanceof String) {
+                if ("#all".equals(finalValue)) {
                     finalRest = finalList = finalUnion = true;
                 }
-            }
-            else if (finalValue instanceof List)
-            {
-                List lFinalValue = (List) finalValue;
-                if (lFinalValue.contains("restriction"))
+            } else if (finalValue instanceof List) {
+                @SuppressWarnings("unchecked")
+                List<String> lFinalValue = (List<String>) finalValue;
+                if (lFinalValue.contains("restriction")) {
                     finalRest = true;
+                }
 
-                if (lFinalValue.contains("list"))
+                if (lFinalValue.contains("list")) {
                     finalList = true;
+                }
 
-                if (lFinalValue.contains("union"))
-                    finalUnion= true;
+                if (lFinalValue.contains("union")) {
+                    finalUnion = true;
+                }
             }
         }
 
         sImpl.setSimpleFinal(finalRest, finalList, finalUnion);
 
-        List anonTypes = new ArrayList();
+        List<SchemaType> anonTypes = new ArrayList<>();
 
-        if (parseSt.getList() != null)
+        if (parseSt.getList() != null) {
             resolveListType(sImpl, parseSt.getList(), anonTypes);
-        else if (parseSt.getUnion() != null)
+        } else if (parseSt.getUnion() != null) {
             resolveUnionType(sImpl, parseSt.getUnion(), anonTypes);
-        else if (parseSt.getRestriction() != null)
+        } else if (parseSt.getRestriction() != null) {
             resolveSimpleRestrictionType(sImpl, parseSt.getRestriction(), anonTypes);
+        }
 
         sImpl.setAnonymousTypeRefs(makeRefArray(anonTypes));
     }
 
-    private static SchemaType.Ref[] makeRefArray(Collection typeList)
-    {
-        SchemaType.Ref[] result = new SchemaType.Ref[typeList.size()];
-        int j = 0;
-        for (Iterator i = typeList.iterator(); i.hasNext(); j++)
-            result[j] = ((SchemaType)i.next()).getRef();
-        return result;
+    private static SchemaType.Ref[] makeRefArray(List<? extends SchemaType> typeList) {
+        return typeList.stream().map(SchemaType::getRef).toArray(SchemaType.Ref[]::new);
     }
 
-    static void resolveErrorSimpleType(SchemaTypeImpl sImpl)
-    {
+    static void resolveErrorSimpleType(SchemaTypeImpl sImpl) {
         sImpl.setSimpleTypeVariety(SchemaType.ATOMIC);
         sImpl.setBaseTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef());
         sImpl.setBaseDepth(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getBaseDepth() + 1);
         sImpl.setPrimitiveTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef());
     }
 
-    static void resolveListType(SchemaTypeImpl sImpl, org.apache.xmlbeans.impl.xb.xsdschema.ListDocument.List parseList, List anonTypes)
-    {
+    static void resolveListType(SchemaTypeImpl sImpl, org.apache.xmlbeans.impl.xb.xsdschema.ListDocument.List parseList, List<SchemaType> anonTypes) {
         StscState state = StscState.get();
 
         sImpl.setSimpleTypeVariety(SchemaType.LIST);
@@ -165,18 +139,16 @@
         sImpl.setBaseDepth(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getBaseDepth() + 1);
         sImpl.setDerivationType(SchemaType.DT_RESTRICTION);
 
-        if (sImpl.isRedefinition())
-        {
+        if (sImpl.isRedefinition()) {
             state.error(XmlErrorCodes.SCHEMA_REDEFINE$EXTEND_OR_RESTRICT,
-                new Object[] { "list" }, parseList);
+                new Object[]{"list"}, parseList);
             // recovery: oh well.
         }
-        
+
         QName itemName = parseList.getItemType();
         LocalSimpleType parseInner = parseList.getSimpleType();
 
-        if (itemName != null && parseInner != null)
-        {
+        if (itemName != null && parseInner != null) {
             state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$LIST_HAS_BOTH_ITEM_OR_SIMPLE_TYPE, null, parseList);
             // recovery: ignore the inner simple type.
             parseInner = null;
@@ -185,26 +157,20 @@
         SchemaTypeImpl itemImpl;
         XmlObject errorLoc;
 
-        if (itemName != null)
-        {
+        if (itemName != null) {
             itemImpl = state.findGlobalType(itemName, sImpl.getChameleonNamespace(), sImpl.getTargetNamespace());
             errorLoc = parseList.xgetItemType();
-            if (itemImpl == null)
-            {
+            if (itemImpl == null) {
                 state.notFoundError(itemName, SchemaType.TYPE, parseList.xgetItemType(), true);
                 // recovery: treat it as a list of anySimpleType
                 itemImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE;
             }
-        }
-        else if (parseInner != null)
-        {
+        } else if (parseInner != null) {
             itemImpl = StscTranslator.translateAnonymousSimpleType(parseInner,
                 sImpl.getTargetNamespace(), sImpl.getChameleonNamespace() != null,
                 sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), anonTypes, sImpl);
             errorLoc = parseInner;
-        }
-        else
-        {
+        } else {
             state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$LIST_HAS_NEITHER_ITEM_OR_SIMPLE_TYPE, null, parseList);
             // recovery: treat it as an extension of anySimpleType
             resolveErrorSimpleType(sImpl);
@@ -212,29 +178,27 @@
         }
 
         // Verify final restrictions
-        if (itemImpl.finalList())
+        if (itemImpl.finalList()) {
             state.error(XmlErrorCodes.SIMPLE_TYPE_PROPERTIES$LIST_FINAL, null, parseList);
+        }
 
         // Recursion...
         StscResolver.resolveType(itemImpl);
 
-        if (!itemImpl.isSimpleType())
-        {
+        if (!itemImpl.isSimpleType()) {
             state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$LIST_ITEM_NOT_SIMPLE, null, errorLoc);
             // recovery: treat the item type as anySimpleType
             sImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE;
         }
 
-        switch (itemImpl.getSimpleVariety())
-        {
+        switch (itemImpl.getSimpleVariety()) {
             case SchemaType.LIST:
                 state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$LIST_ITEM_IS_LIST, null, errorLoc);
                 // recovery: treat the list as an anySimpleType
                 resolveErrorSimpleType(sImpl);
                 return;
             case SchemaType.UNION:
-                if (itemImpl.isUnionOfLists())
-                {
+                if (itemImpl.isUnionOfLists()) {
                     state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$LIST_ITEM_IS_UNION_OF_LIST, null, errorLoc);
                     resolveErrorSimpleType(sImpl);
                     return;
@@ -243,68 +207,63 @@
             case SchemaType.ATOMIC:
                 sImpl.setListItemTypeRef(itemImpl.getRef());
                 // Check that the item type is not a plan NOTATION
-                if (sImpl.getBuiltinTypeCode() == SchemaType.BTC_NOTATION)
+                if (sImpl.getBuiltinTypeCode() == SchemaType.BTC_NOTATION) {
                     state.recover(XmlErrorCodes.DATATYPE_ENUM_NOTATION, null, errorLoc);
+                }
                 break;
             default:
-                assert(false);
+                assert (false);
                 sImpl.setListItemTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef());
         }
 
         // now deal with facets
         sImpl.setBasicFacets(StscState.FACETS_LIST, StscState.FIXED_FACETS_LIST);
-        sImpl.setWhiteSpaceRule( SchemaType.WS_COLLAPSE );
+        sImpl.setWhiteSpaceRule(SchemaType.WS_COLLAPSE);
 
         // now compute our intrinsic properties
         resolveFundamentalFacets(sImpl);
     }
 
 
-
-
-    static void resolveUnionType(SchemaTypeImpl sImpl, UnionDocument.Union parseUnion, List anonTypes)
-    {
+    static void resolveUnionType(SchemaTypeImpl sImpl, UnionDocument.Union parseUnion, List<SchemaType> anonTypes) {
         sImpl.setSimpleTypeVariety(SchemaType.UNION);
         sImpl.setBaseTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef());
         sImpl.setBaseDepth(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getBaseDepth() + 1);
         sImpl.setDerivationType(SchemaType.DT_RESTRICTION);
 
         StscState state = StscState.get();
-        
-        if (sImpl.isRedefinition())
-        {
+
+        if (sImpl.isRedefinition()) {
             state.error(XmlErrorCodes.SCHEMA_REDEFINE$EXTEND_OR_RESTRICT,
-                new Object[] { "union" }, parseUnion);
+                new Object[]{"union"}, parseUnion);
             // recovery: oh well.
         }
-        
-        List memberTypes = parseUnion.getMemberTypes();
+
+        @SuppressWarnings("unchecked")
+        List<QName> memberTypes = (List<QName>) parseUnion.getMemberTypes();
         SimpleType[] simpleTypes = parseUnion.getSimpleTypeArray();
 
-        List memberImplList = new ArrayList();
-        
-        if (simpleTypes.length == 0 && (memberTypes == null || memberTypes.size() == 0))
-        {
+        List<SchemaTypeImpl> memberImplList = new ArrayList<>();
+
+        if (simpleTypes.length == 0 && (memberTypes == null || memberTypes.size() == 0)) {
             state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$UNION_HAS_MEMBER_TYPES_OR_SIMPLE_TYPES, null, parseUnion);
             // recovery: oh well, zero member types is fine.
         }
 
-        if (memberTypes != null)
-        {
-            for (Iterator mNames = memberTypes.iterator(); mNames.hasNext(); )
-            {
-                QName mName = (QName)mNames.next();
+        if (memberTypes != null) {
+            for (QName mName : memberTypes) {
                 SchemaTypeImpl memberImpl = state.findGlobalType(mName, sImpl.getChameleonNamespace(), sImpl.getTargetNamespace());
                 if (memberImpl == null)
-                    // recovery: skip member
+                // recovery: skip member
+                {
                     state.notFoundError(mName, SchemaType.TYPE, parseUnion.xgetMemberTypes(), true);
-                else
+                } else {
                     memberImplList.add(memberImpl);
+                }
             }
         }
 
-        for (int i = 0; i < simpleTypes.length; i++)
-        {
+        for (int i = 0; i < simpleTypes.length; i++) {
             // BUGBUG: see if non<simpleType> children can leak through
             SchemaTypeImpl mImpl = StscTranslator.translateAnonymousSimpleType(simpleTypes[i],
                 sImpl.getTargetNamespace(), sImpl.getChameleonNamespace() != null,
@@ -314,55 +273,44 @@
         }
 
         // Recurse and resolve all member types
-        for (Iterator mImpls = memberImplList.iterator(); mImpls.hasNext(); )
-        {
-            SchemaTypeImpl mImpl = (SchemaTypeImpl)mImpls.next();
-            if (!StscResolver.resolveType(mImpl))
-            {
+        for (Iterator<SchemaTypeImpl> mImpls = memberImplList.iterator(); mImpls.hasNext(); ) {
+            SchemaTypeImpl mImpl = mImpls.next();
+            if (!StscResolver.resolveType(mImpl)) {
                 // KHK: review
                 String memberName = "";
                 XmlObject errorLoc;
-                if (mImpl.getOuterType().equals(sImpl))
-                {
+                if (Objects.equals(mImpl.getOuterType(), sImpl)) {
                     errorLoc = mImpl.getParseObject();
-                }
-                else
-                {
+                } else {
                     memberName = QNameHelper.pretty(mImpl.getName()) + " ";
                     errorLoc = parseUnion.xgetMemberTypes();
                 }
 
-                state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$CYCLIC_UNION, new Object[] { memberName }, errorLoc);
+                state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$CYCLIC_UNION, new Object[]{memberName}, errorLoc);
 
                 // recovery: ignore the errant union member
                 mImpls.remove();
-                continue;
             }
         }
 
         // Now verify members
         boolean isUnionOfLists = false;
 
-        for (Iterator mImpls = memberImplList.iterator(); mImpls.hasNext(); )
-        {
-            SchemaTypeImpl mImpl = (SchemaTypeImpl)mImpls.next();
+        for (Iterator<SchemaTypeImpl> mImpls = memberImplList.iterator(); mImpls.hasNext(); ) {
+            SchemaTypeImpl mImpl = mImpls.next();
 
-            if (!mImpl.isSimpleType())
-            {
+            if (!mImpl.isSimpleType()) {
                 // KHK: review
                 String memberName = "";
                 XmlObject errorLoc;
-                if (mImpl.getOuterType() != null && mImpl.getOuterType().equals(sImpl))
-                {
+                if (mImpl.getOuterType() != null && mImpl.getOuterType().equals(sImpl)) {
                     errorLoc = mImpl.getParseObject();
-                }
-                else
-                {
+                } else {
                     memberName = QNameHelper.pretty(mImpl.getName()) + " ";
                     errorLoc = parseUnion.xgetMemberTypes();
                 }
 
-                state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$UNION_MEMBER_NOT_SIMPLE, new Object[] { memberName }, errorLoc);
+                state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$UNION_MEMBER_NOT_SIMPLE, new Object[]{memberName}, errorLoc);
 
                 // recovery: ignore the errant union member
                 mImpls.remove();
@@ -370,16 +318,16 @@
             }
 
             if (mImpl.getSimpleVariety() == SchemaType.LIST ||
-                mImpl.getSimpleVariety() == SchemaType.UNION && mImpl.isUnionOfLists())
+                mImpl.getSimpleVariety() == SchemaType.UNION && mImpl.isUnionOfLists()) {
                 isUnionOfLists = true;
+            }
         }
 
         // Verify any final restrictions
-        for (int i = 0 ; i < memberImplList.size() ; i++)
-        {
-            SchemaTypeImpl mImpl = (SchemaTypeImpl)memberImplList.get(i);
-            if (mImpl.finalUnion())
+        for (SchemaTypeImpl schemaType : memberImplList) {
+            if (schemaType.finalUnion()) {
                 state.error(XmlErrorCodes.SIMPLE_TYPE_PROPERTIES$UNION_FINAL, null, parseUnion);
+            }
         }
 
         sImpl.setUnionOfLists(isUnionOfLists);
@@ -393,14 +341,12 @@
         resolveFundamentalFacets(sImpl);
     }
 
-    static void resolveSimpleRestrictionType(SchemaTypeImpl sImpl, RestrictionDocument.Restriction parseRestr, List anonTypes)
-    {
+    static void resolveSimpleRestrictionType(SchemaTypeImpl sImpl, RestrictionDocument.Restriction parseRestr, List<SchemaType> anonTypes) {
         QName baseName = parseRestr.getBase();
         SimpleType parseInner = parseRestr.getSimpleType();
         StscState state = StscState.get();
 
-        if (baseName != null && parseInner != null)
-        {
+        if (baseName != null && parseInner != null) {
             state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$RESTRICTION_HAS_BOTH_BASE_OR_SIMPLE_TYPE, null, parseRestr);
             // recovery: ignore the inner simple type.
             parseInner = null;
@@ -408,68 +354,56 @@
 
         SchemaTypeImpl baseImpl;
 
-        if (baseName != null)
-        {
-            if (sImpl.isRedefinition())
-            {
+        if (baseName != null) {
+            if (sImpl.isRedefinition()) {
                 baseImpl = state.findRedefinedGlobalType(parseRestr.getBase(), sImpl.getChameleonNamespace(), sImpl);
-                if (baseImpl != null && !baseImpl.getName().equals(sImpl.getName()))
-                {
+                if (baseImpl != null && !baseImpl.getName().equals(sImpl.getName())) {
                     state.error(XmlErrorCodes.SCHEMA_REDEFINE$SAME_TYPE,
-                        new Object[] { "<simpleType>",
-                                       QNameHelper.pretty(baseName), 
-                                       QNameHelper.pretty(sImpl.getName())
+                        new Object[]{"<simpleType>",
+                            QNameHelper.pretty(baseName),
+                            QNameHelper.pretty(sImpl.getName())
                         },
                         parseRestr);
                 }
-            }
-            else
-            {
+            } else {
                 baseImpl = state.findGlobalType(baseName, sImpl.getChameleonNamespace(), sImpl.getTargetNamespace());
             }
-            if (baseImpl == null)
-            {
+            if (baseImpl == null) {
                 state.notFoundError(baseName, SchemaType.TYPE, parseRestr.xgetBase(), true);
                 // recovery: treat it as an extension of anySimpleType
                 baseImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE;
             }
-        }
-        else if (parseInner != null)
-        {
-            if (sImpl.isRedefinition())
-            {
+        } else if (parseInner != null) {
+            if (sImpl.isRedefinition()) {
                 StscState.get().error(XmlErrorCodes.SCHEMA_REDEFINE$EXTEND_OR_RESTRICT,
-                    new Object[] { "<simpleType>" }, parseInner);
+                    new Object[]{"<simpleType>"}, parseInner);
                 // recovery: oh well.
             }
-            
+
             baseImpl = StscTranslator.translateAnonymousSimpleType(parseInner,
                 sImpl.getTargetNamespace(), sImpl.getChameleonNamespace() != null,
                 sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), anonTypes, sImpl);
-        }
-        else
-        {
+        } else {
             state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$RESTRICTION_HAS_NEITHER_BASE_OR_SIMPLE_TYPE, null, parseRestr);
             // recovery: treat it as an extension of anySimpleType
             baseImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE;
         }
 
         // Recursion!
-        if (!StscResolver.resolveType(baseImpl))
-        {
+        if (!StscResolver.resolveType(baseImpl)) {
             // cyclic dependency recovery: treat it as an extension of anySimpleType
             baseImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE;
         }
 
-        if (baseImpl.finalRestriction())
+        if (baseImpl.finalRestriction()) {
             state.error(XmlErrorCodes.SIMPLE_TYPE_PROPERTIES$RESTRICTION_FINAL, null, parseRestr);
+        }
 
         sImpl.setBaseTypeRef(baseImpl.getRef());
         sImpl.setBaseDepth(baseImpl.getBaseDepth() + 1);
         sImpl.setDerivationType(SchemaType.DT_RESTRICTION);
 
-        if (!baseImpl.isSimpleType())
-        {
+        if (!baseImpl.isSimpleType()) {
             state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$ATOMIC_NOT_SIMPLE, null, parseRestr.xgetBase());
             // recovery: treat it as a restriction of anySimpleType
             resolveErrorSimpleType(sImpl);
@@ -479,8 +413,7 @@
         sImpl.setSimpleTypeVariety(baseImpl.getSimpleVariety());
 
         // copy variety-specific properties
-        switch (baseImpl.getSimpleVariety())
-        {
+        switch (baseImpl.getSimpleVariety()) {
             case SchemaType.ATOMIC:
                 sImpl.setPrimitiveTypeRef(baseImpl.getPrimitiveType().getRef());
                 break;
@@ -500,38 +433,36 @@
         resolveFundamentalFacets(sImpl);
     }
 
-    static int translateWhitespaceCode(XmlAnySimpleType value)
-    {
+    static int translateWhitespaceCode(XmlAnySimpleType value) {
         // BUGBUG: add whitespace rule to textvalue.
         String textval = value.getStringValue();
 
-        if (textval.equals("collapse"))
+        if (textval.equals("collapse")) {
             return SchemaType.WS_COLLAPSE;
+        }
 
-        if (textval.equals("preserve"))
+        if (textval.equals("preserve")) {
             return SchemaType.WS_PRESERVE;
+        }
 
-        if (textval.equals("replace"))
+        if (textval.equals("replace")) {
             return SchemaType.WS_REPLACE;
+        }
 
         // KHK: s4s
         StscState.get().error("Unrecognized whitespace value \"" + textval + "\"", XmlErrorCodes.FACET_VALUE_MALFORMED, value);
         return SchemaType.WS_UNSPECIFIED;
     }
 
-    static boolean isMultipleFacet(int facetcode)
-    {
+    static boolean isMultipleFacet(int facetcode) {
         return (facetcode == SchemaType.FACET_ENUMERATION ||
                 facetcode == SchemaType.FACET_PATTERN);
     }
 
-    static boolean facetAppliesToType(int facetCode, SchemaTypeImpl baseImpl)
-    {
-        switch (baseImpl.getSimpleVariety())
-        {
+    static boolean facetAppliesToType(int facetCode, SchemaTypeImpl baseImpl) {
+        switch (baseImpl.getSimpleVariety()) {
             case SchemaType.LIST:
-                switch (facetCode)
-                {
+                switch (facetCode) {
                     case SchemaType.FACET_LENGTH:
                     case SchemaType.FACET_MIN_LENGTH:
                     case SchemaType.FACET_MAX_LENGTH:
@@ -543,8 +474,7 @@
                 return false;
 
             case SchemaType.UNION:
-                switch (facetCode)
-                {
+                switch (facetCode) {
                     case SchemaType.FACET_ENUMERATION:
                     case SchemaType.FACET_PATTERN:
                         return true;
@@ -554,14 +484,12 @@
 
         // the atomic case
 
-        switch (baseImpl.getPrimitiveType().getBuiltinTypeCode())
-        {
+        switch (baseImpl.getPrimitiveType().getBuiltinTypeCode()) {
             case SchemaType.BTC_ANY_SIMPLE:
                 return false;
 
             case SchemaType.BTC_BOOLEAN:
-                switch (facetCode)
-                {
+                switch (facetCode) {
                     case SchemaType.FACET_PATTERN:
                     case SchemaType.FACET_WHITE_SPACE:
                         return true;
@@ -579,8 +507,7 @@
             case SchemaType.BTC_G_MONTH_DAY:
             case SchemaType.BTC_G_DAY:
             case SchemaType.BTC_G_MONTH:
-                switch (facetCode)
-                {
+                switch (facetCode) {
                     case SchemaType.FACET_MIN_EXCLUSIVE:
                     case SchemaType.FACET_MIN_INCLUSIVE:
                     case SchemaType.FACET_MAX_INCLUSIVE:
@@ -593,8 +520,7 @@
                 return false;
 
             case SchemaType.BTC_DECIMAL:
-                switch (facetCode)
-                {
+                switch (facetCode) {
                     case SchemaType.FACET_MIN_EXCLUSIVE:
                     case SchemaType.FACET_MIN_INCLUSIVE:
                     case SchemaType.FACET_MAX_INCLUSIVE:
@@ -614,8 +540,7 @@
             case SchemaType.BTC_QNAME:
             case SchemaType.BTC_NOTATION:
             case SchemaType.BTC_STRING:
-                switch (facetCode)
-                {
+                switch (facetCode) {
                     case SchemaType.FACET_LENGTH:
                     case SchemaType.FACET_MIN_LENGTH:
                     case SchemaType.FACET_MAX_LENGTH:
@@ -627,15 +552,13 @@
                 return false;
 
             default:
-                assert(false);
+                assert (false);
                 return false;
         }
     }
 
-    private static int other_similar_limit(int facetcode)
-    {
-        switch (facetcode)
-        {
+    private static int other_similar_limit(int facetcode) {
+        switch (facetcode) {
             case SchemaType.FACET_MIN_EXCLUSIVE:
                 return SchemaType.FACET_MIN_INCLUSIVE;
             case SchemaType.FACET_MIN_INCLUSIVE:
@@ -645,58 +568,51 @@
             case SchemaType.FACET_MAX_EXCLUSIVE:
                 return SchemaType.FACET_MAX_INCLUSIVE;
             default:
-                assert(false);
+                assert (false);
                 throw new IllegalStateException();
         }
     }
 
-    static void resolveFacets(SchemaTypeImpl sImpl, XmlObject restriction, SchemaTypeImpl baseImpl)
-    {
+    static void resolveFacets(SchemaTypeImpl sImpl, XmlObject restriction, SchemaTypeImpl baseImpl) {
         StscState state = StscState.get();
 
         boolean[] seenFacet = new boolean[SchemaType.LAST_FACET + 1];
         XmlAnySimpleType[] myFacets = baseImpl.getBasicFacets(); // makes a copy
         boolean[] fixedFacets = baseImpl.getFixedFacets();
         int wsr = SchemaType.WS_UNSPECIFIED;
-        List enumeratedValues = null;
-        List patterns = null;
+        List<XmlAnySimpleType> enumeratedValues = null;
+        List<RegularExpression> patterns = null;
 
-        if (restriction != null)
-        {
+        if (restriction != null) {
             XmlCursor cur = restriction.newCursor();
-            for (boolean more = cur.toFirstChild(); more; more = cur.toNextSibling())
-            {
+            for (boolean more = cur.toFirstChild(); more; more = cur.toNextSibling()) {
                 QName facetQName = cur.getName();
                 String facetName = facetQName.getLocalPart();
                 int code = translateFacetCode(facetQName);
-                if (code == -1)
+                if (code == -1) {
                     continue;
+                }
 
-                Facet facet = (Facet)cur.getObject();
+                Facet facet = (Facet) cur.getObject();
 
-                if (!facetAppliesToType(code, baseImpl))
-                {
+                if (!facetAppliesToType(code, baseImpl)) {
                     state.error(XmlErrorCodes.FACETS_APPLICABLE,
-                        new Object[] { facetName, QNameHelper.pretty(baseImpl.getName()) }, facet);
+                        new Object[]{facetName, QNameHelper.pretty(baseImpl.getName())}, facet);
                     continue;
-                }
-                else if (baseImpl.getSimpleVariety() == SchemaType.ATOMIC &&
-                    baseImpl.getPrimitiveType().getBuiltinTypeCode() == SchemaType.BTC_NOTATION
-                    && (code == SchemaType.FACET_LENGTH || code == SchemaType.FACET_MIN_LENGTH ||
-                    code == SchemaType.FACET_MAX_LENGTH))
-                {
+                } else if (baseImpl.getSimpleVariety() == SchemaType.ATOMIC &&
+                           baseImpl.getPrimitiveType().getBuiltinTypeCode() == SchemaType.BTC_NOTATION
+                           && (code == SchemaType.FACET_LENGTH || code == SchemaType.FACET_MIN_LENGTH ||
+                               code == SchemaType.FACET_MAX_LENGTH)) {
                     state.warning(XmlErrorCodes.FACETS_DEPRECATED_NOTATION,
-                        new Object[] {facetName, QNameHelper.pretty(baseImpl.getName()) }, facet);
+                        new Object[]{facetName, QNameHelper.pretty(baseImpl.getName())}, facet);
                 }
-                if (seenFacet[code] && !isMultipleFacet(code))
-                {
+                if (seenFacet[code] && !isMultipleFacet(code)) {
                     state.error(XmlErrorCodes.DATATYPE_SINGLE_FACET_VALUE, null, facet);
                     continue;
                 }
                 seenFacet[code] = true;
 
-                switch (code)
-                {
+                switch (code) {
                     case SchemaType.FACET_LENGTH:
 //                        if (myFacets[SchemaType.FACET_MIN_LENGTH] != null ||
 //                            myFacets[SchemaType.FACET_MAX_LENGTH] != null)
@@ -705,38 +621,32 @@
 //                            continue;
 //                        }
                         XmlInteger len = StscTranslator.buildNnInteger(facet.getValue());
-                        if (len == null)
-                        {
+                        if (len == null) {
                             state.error("Must be a nonnegative integer", XmlErrorCodes.FACET_VALUE_MALFORMED, facet);
                             continue;
                         }
-                        if (fixedFacets[code] && !myFacets[code].valueEquals(len))
-                        {
-                            state.error(XmlErrorCodes.FACET_FIXED, new Object[] { facetName }, facet);
+                        if (fixedFacets[code] && !myFacets[code].valueEquals(len)) {
+                            state.error(XmlErrorCodes.FACET_FIXED, new Object[]{facetName}, facet);
                             continue;
                         }
-                        if (myFacets[SchemaType.FACET_MIN_LENGTH] != null)
-                        {
+                        if (myFacets[SchemaType.FACET_MIN_LENGTH] != null) {
                             // An error for 'length' and 'minLength' to be specified at the same time
                             // except if the base type had the same value for 'minLength' also
                             XmlAnySimpleType baseMinLength = baseImpl.getFacet(SchemaType.FACET_MIN_LENGTH);
                             if (!(baseMinLength != null &&
-                                baseMinLength.valueEquals(myFacets[SchemaType.FACET_MIN_LENGTH]) &&
-                                baseMinLength.compareValue(len) <= 0))
-                            {
+                                  baseMinLength.valueEquals(myFacets[SchemaType.FACET_MIN_LENGTH]) &&
+                                  baseMinLength.compareValue(len) <= 0)) {
                                 state.error(XmlErrorCodes.DATATYPE_LENGTH, null, facet);
                                 continue;
                             }
                         }
-                        if (myFacets[SchemaType.FACET_MAX_LENGTH] != null)
-                        {
+                        if (myFacets[SchemaType.FACET_MAX_LENGTH] != null) {
                             // An error for 'length' and 'maxLength' to be specified at the same time
                             // except if the base type had the same value for 'maxLength' also
                             XmlAnySimpleType baseMaxLength = baseImpl.getFacet(SchemaType.FACET_MAX_LENGTH);
                             if (!(baseMaxLength != null &&
-                                baseMaxLength.valueEquals(myFacets[SchemaType.FACET_MAX_LENGTH]) &&
-                                baseMaxLength.compareValue(len) >= 0))
-                            {
+                                  baseMaxLength.valueEquals(myFacets[SchemaType.FACET_MAX_LENGTH]) &&
+                                  baseMaxLength.compareValue(len) >= 0)) {
                                 state.error(XmlErrorCodes.DATATYPE_LENGTH, null, facet);
                                 continue;
                             }
@@ -747,45 +657,37 @@
                     case SchemaType.FACET_MIN_LENGTH:
                     case SchemaType.FACET_MAX_LENGTH:
                         XmlInteger mlen = StscTranslator.buildNnInteger(facet.getValue());
-                        if (mlen == null)
-                        {
+                        if (mlen == null) {
                             state.error("Must be a nonnegative integer", XmlErrorCodes.FACET_VALUE_MALFORMED, facet);
                             continue;
                         }
-                        if (fixedFacets[code] && !myFacets[code].valueEquals(mlen))
-                        {
-                            state.error(XmlErrorCodes.FACET_FIXED, new Object[] { facetName }, facet);
+                        if (fixedFacets[code] && !myFacets[code].valueEquals(mlen)) {
+                            state.error(XmlErrorCodes.FACET_FIXED, new Object[]{facetName}, facet);
                             continue;
                         }
-                        if (myFacets[SchemaType.FACET_LENGTH] != null)
-                        {
+                        if (myFacets[SchemaType.FACET_LENGTH] != null) {
                             // It's an error for 'length' and 'minLength'/'maxLength' to be
                             // specified at the same time, except for the case when
                             // the base type had the same value for 'minLength'/'maxLength'
                             // and the two values are consistent
                             XmlAnySimpleType baseMinMaxLength = baseImpl.getFacet(code);
                             if (!(baseMinMaxLength != null &&
-                                baseMinMaxLength.valueEquals(mlen) &&
-                                (code == SchemaType.FACET_MIN_LENGTH ?
-                                    baseMinMaxLength.compareTo(myFacets[SchemaType.FACET_LENGTH]) <= 0 :
-                                    baseMinMaxLength.compareTo(myFacets[SchemaType.FACET_LENGTH]) >= 0)))
-                            {
+                                  baseMinMaxLength.valueEquals(mlen) &&
+                                  (code == SchemaType.FACET_MIN_LENGTH ?
+                                      baseMinMaxLength.compareTo(myFacets[SchemaType.FACET_LENGTH]) <= 0 :
+                                      baseMinMaxLength.compareTo(myFacets[SchemaType.FACET_LENGTH]) >= 0))) {
                                 state.error(XmlErrorCodes.DATATYPE_LENGTH, null, facet);
                                 continue;
                             }
                         }
-                        if (myFacets[SchemaType.FACET_MAX_LENGTH] != null)
-                        {
-                            if (mlen.compareValue(myFacets[SchemaType.FACET_MAX_LENGTH]) > 0)
-                            {
+                        if (myFacets[SchemaType.FACET_MAX_LENGTH] != null) {
+                            if (mlen.compareValue(myFacets[SchemaType.FACET_MAX_LENGTH]) > 0) {
                                 state.error(XmlErrorCodes.DATATYPE_MAX_LENGTH_RESTRICTION, null, facet);
                                 continue;
                             }
                         }
-                        if (myFacets[SchemaType.FACET_MIN_LENGTH] != null)
-                        {
-                            if (mlen.compareValue(myFacets[SchemaType.FACET_MIN_LENGTH]) < 0)
-                            {
+                        if (myFacets[SchemaType.FACET_MIN_LENGTH] != null) {
+                            if (mlen.compareValue(myFacets[SchemaType.FACET_MIN_LENGTH]) < 0) {
                                 state.error(XmlErrorCodes.DATATYPE_MIN_LENGTH_RESTRICTION, null, facet);
                                 continue;
                             }
@@ -795,45 +697,41 @@
 
                     case SchemaType.FACET_TOTAL_DIGITS:
                         XmlPositiveInteger dig = StscTranslator.buildPosInteger(facet.getValue());
-                        if (dig == null)
-                        {
+                        if (dig == null) {
                             state.error("Must be a positive integer", XmlErrorCodes.FACET_VALUE_MALFORMED, facet);
                             break;
                         }
-                        if (fixedFacets[code] && !myFacets[code].valueEquals(dig))
-                        {
-                            state.error(XmlErrorCodes.FACET_FIXED, new Object[] { facetName }, facet);
+                        if (fixedFacets[code] && !myFacets[code].valueEquals(dig)) {
+                            state.error(XmlErrorCodes.FACET_FIXED, new Object[]{facetName}, facet);
                             continue;
                         }
-                        if (myFacets[SchemaType.FACET_TOTAL_DIGITS] != null)
-                        {
-                            if (dig.compareValue(myFacets[SchemaType.FACET_TOTAL_DIGITS]) > 0)
+                        if (myFacets[SchemaType.FACET_TOTAL_DIGITS] != null) {
+                            if (dig.compareValue(myFacets[SchemaType.FACET_TOTAL_DIGITS]) > 0) {
                                 state.error(XmlErrorCodes.DATATYPE_TOTAL_DIGITS_RESTRICTION, null, facet);
+                            }
                         }
                         myFacets[code] = dig;
                         break;
 
                     case SchemaType.FACET_FRACTION_DIGITS:
                         XmlNonNegativeInteger fdig = StscTranslator.buildNnInteger(facet.getValue());
-                        if (fdig == null)
-                        {
+                        if (fdig == null) {
                             state.error("Must be a nonnegative integer", XmlErrorCodes.FACET_VALUE_MALFORMED, facet);
                             break;
                         }
-                        if (fixedFacets[code] && !myFacets[code].valueEquals(fdig))
-                        {
-                            state.error(XmlErrorCodes.FACET_FIXED, new Object[] { facetName }, facet);
+                        if (fixedFacets[code] && !myFacets[code].valueEquals(fdig)) {
+                            state.error(XmlErrorCodes.FACET_FIXED, new Object[]{facetName}, facet);
                             continue;
                         }
-                        if (myFacets[SchemaType.FACET_FRACTION_DIGITS] != null)
-                        {
-                            if (fdig.compareValue(myFacets[SchemaType.FACET_FRACTION_DIGITS]) > 0)
+                        if (myFacets[SchemaType.FACET_FRACTION_DIGITS] != null) {
+                            if (fdig.compareValue(myFacets[SchemaType.FACET_FRACTION_DIGITS]) > 0) {
                                 state.error(XmlErrorCodes.DATATYPE_FRACTION_DIGITS_RESTRICTION, null, facet);
+                            }
                         }
-                        if (myFacets[SchemaType.FACET_TOTAL_DIGITS] != null)
-                        {
-                            if (fdig.compareValue(myFacets[SchemaType.FACET_TOTAL_DIGITS]) > 0)
+                        if (myFacets[SchemaType.FACET_TOTAL_DIGITS] != null) {
+                            if (fdig.compareValue(myFacets[SchemaType.FACET_TOTAL_DIGITS]) > 0) {
                                 state.error(XmlErrorCodes.DATATYPE_FRACTION_DIGITS_LE_TOTAL_DIGITS, null, facet);
+                            }
                         }
                         myFacets[code] = fdig;
                         break;
@@ -843,8 +741,7 @@
                     case SchemaType.FACET_MAX_INCLUSIVE:
                     case SchemaType.FACET_MAX_EXCLUSIVE:
 
-                        if (seenFacet[other_similar_limit(code)])
-                        {
+                        if (seenFacet[other_similar_limit(code)]) {
                             state.error("Cannot define both inclusive and exclusive limit in the same restriciton", XmlErrorCodes.FACET_DUPLICATED, facet);
                             continue;
                         }
@@ -852,57 +749,49 @@
                         boolean isexclusive = (code == SchemaType.FACET_MIN_EXCLUSIVE || code == SchemaType.FACET_MAX_EXCLUSIVE);
 
                         XmlAnySimpleType limit;
-                        try
-                        {
+                        try {
                             limit = baseImpl.newValue(facet.getValue(), true);
-                        }
-                        catch (XmlValueOutOfRangeException e)
-                        {
+                        } catch (XmlValueOutOfRangeException e) {
                             // note: this guarantees that the limit is a valid number in the
                             // base data type!!
-                            switch (code)
-                            {
-                            case SchemaType.FACET_MIN_EXCLUSIVE:
-                                state.error(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_RESTRICTION,
-                                    new Object[] {e.getMessage()}, facet);
-                                break;
-                            case SchemaType.FACET_MIN_INCLUSIVE:
-                                state.error(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_RESTRICTION,
-                                    new Object[] {e.getMessage()}, facet);
-                                break;
-                            case SchemaType.FACET_MAX_INCLUSIVE:
-                                state.error(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_RESTRICTION,
-                                    new Object[] {e.getMessage()}, facet);
-                                break;
-                            case SchemaType.FACET_MAX_EXCLUSIVE:
-                                state.error(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_RESTRICTION,
-                                    new Object[] {e.getMessage()}, facet);
-                                break;
+                            switch (code) {
+                                case SchemaType.FACET_MIN_EXCLUSIVE:
+                                    state.error(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_RESTRICTION,
+                                        new Object[]{e.getMessage()}, facet);
+                                    break;
+                                case SchemaType.FACET_MIN_INCLUSIVE:
+                                    state.error(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_RESTRICTION,
+                                        new Object[]{e.getMessage()}, facet);
+                                    break;
+                                case SchemaType.FACET_MAX_INCLUSIVE:
+                                    state.error(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_RESTRICTION,
+                                        new Object[]{e.getMessage()}, facet);
+                                    break;
+                                case SchemaType.FACET_MAX_EXCLUSIVE:
+                                    state.error(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_RESTRICTION,
+                                        new Object[]{e.getMessage()}, facet);
+                                    break;
                             }
 
                             // BUGBUG: if there are actual schemas that redefine min/maxExclusive,
                             // they will need this rule relaxed for them!!
                             continue;
                         }
-                        if (fixedFacets[code] && !myFacets[code].valueEquals(limit))
-                        {
-                            state.error(XmlErrorCodes.FACET_FIXED, new Object[] { facetName }, facet);
+                        if (fixedFacets[code] && !myFacets[code].valueEquals(limit)) {
+                            state.error(XmlErrorCodes.FACET_FIXED, new Object[]{facetName}, facet);
                             continue;
                         }
-                        if (myFacets[code] != null)
-                        {
+                        if (myFacets[code] != null) {
                             SchemaType limitSType = limit.schemaType();
-                            if ( limitSType!=null && !limitSType.isSimpleType() &&
-                                    limitSType.getContentType()==SchemaType.SIMPLE_CONTENT)
-                            {
+                            if (limitSType != null && !limitSType.isSimpleType() &&
+                                limitSType.getContentType() == SchemaType.SIMPLE_CONTENT) {
                                 // in the case of complex types with simple content that has facets
                                 // we need to compare values based on the content type
                                 limit = baseImpl.getContentBasedOnType().newValue(facet.getValue());
                             }
 
                             int comparison = limit.compareValue(myFacets[code]);
-                            if (comparison == 2 || comparison == (ismin ? -1 : 1))
-                            {
+                            if (comparison == 2 || comparison == (ismin ? -1 : 1)) {
                                 state.error(ismin ?
                                         (isexclusive ?
                                             "Must be greater than or equal to previous minExclusive" :
@@ -910,7 +799,7 @@
                                         (isexclusive ?
                                             "Must be less than or equal to previous maxExclusive" :
                                             "Must be less than or equal to previous maxInclusive"),
-                                        XmlErrorCodes.FACET_VALUE_MALFORMED, facet);
+                                    XmlErrorCodes.FACET_VALUE_MALFORMED, facet);
                                 continue;
                             }
                         }
@@ -920,8 +809,7 @@
 
                     case SchemaType.FACET_WHITE_SPACE:
                         wsr = translateWhitespaceCode(facet.getValue());
-                        if (baseImpl.getWhiteSpaceRule() > wsr)
-                        {
+                        if (baseImpl.getWhiteSpaceRule() > wsr) {
                             wsr = SchemaType.WS_UNSPECIFIED;
                             state.error(XmlErrorCodes.DATATYPE_WHITESPACE_RESTRICTION, null, facet);
                             continue;
@@ -930,39 +818,39 @@
                         break;
 
                     case SchemaType.FACET_ENUMERATION:
-                        XmlObject enumval;
-                        try
-                        {
+                        XmlAnySimpleType enumval;
+                        try {
                             enumval = baseImpl.newValue(facet.getValue(), true);
                             // enumval.set(facet.getValue());
                             // ((XmlObjectBase)enumval).setImmutable();
-                        }
-                        catch (XmlValueOutOfRangeException e)
-                        {
-                            state.error(XmlErrorCodes.DATATYPE_ENUM_RESTRICTION, new Object[] { facet.getValue().getStringValue(), e.getMessage() }, facet);
+                        } catch (XmlValueOutOfRangeException e) {
+                            state.error(XmlErrorCodes.DATATYPE_ENUM_RESTRICTION, new Object[]{facet.getValue().getStringValue(), e.getMessage()}, facet);
                             continue;
                         }
-                        if (enumeratedValues == null)
-                            enumeratedValues = new ArrayList();
+                        if (enumeratedValues == null) {
+                            enumeratedValues = new ArrayList<>();
+                        }
                         enumeratedValues.add(enumval);
                         break;
 
                     case SchemaType.FACET_PATTERN:
                         RegularExpression p;
-                        try { p = new RegularExpression(facet.getValue().getStringValue(), "X"); }
-                        catch (ParseException e)
-                        {
-                            state.error(XmlErrorCodes.PATTERN_REGEX, new Object[] { facet.getValue().getStringValue(), e.getMessage() }, facet);
+                        try {
+                            p = new RegularExpression(facet.getValue().getStringValue(), "X");
+                        } catch (ParseException e) {
+                            state.error(XmlErrorCodes.PATTERN_REGEX, new Object[]{facet.getValue().getStringValue(), e.getMessage()}, facet);
                             continue;
                         }
-                        if (patterns == null)
-                            patterns = new ArrayList();
+                        if (patterns == null) {
+                            patterns = new ArrayList<>();
+                        }
                         patterns.add(p);
                         break;
                 }
 
-                if (facet.getFixed())
+                if (facet.getFixed()) {
                     fixedFacets[code] = true;
+                }
             }
         }
 
@@ -971,65 +859,59 @@
         sImpl.setBasicFacets(makeValueRefArray(myFacets), fixedFacets);
 
         // Update the numeric whitespace rule
-        if (wsr == SchemaType.WS_UNSPECIFIED)
+        if (wsr == SchemaType.WS_UNSPECIFIED) {
             wsr = baseImpl.getWhiteSpaceRule();
+        }
         sImpl.setWhiteSpaceRule(wsr);
 
         // store away the enumerated values
-        if (enumeratedValues != null)
-        {
-            sImpl.setEnumerationValues(makeValueRefArray((XmlAnySimpleType[])
-                enumeratedValues.toArray(new XmlAnySimpleType[enumeratedValues.size()])));
+        if (enumeratedValues != null) {
+            sImpl.setEnumerationValues(makeValueRefArray(enumeratedValues.toArray(new XmlAnySimpleType[0])));
 
             SchemaType beType = sImpl;
-            if ( ((SchemaTypeImpl)sImpl).isRedefinition() ){
+            if (sImpl.isRedefinition()) {
                 beType = sImpl.getBaseType().getBaseEnumType();
-                if( beType == null || sImpl.getBaseType() == beType ){
+                if (beType == null || sImpl.getBaseType() == beType) {
                     beType = sImpl;
                 }
-            }
-            else if (sImpl.getBaseType().getBaseEnumType() != null)
+            } else if (sImpl.getBaseType().getBaseEnumType() != null) {
                 beType = sImpl.getBaseType().getBaseEnumType();
+            }
             sImpl.setBaseEnumTypeRef(beType.getRef());
-        }
-        else
-        {
+        } else {
             sImpl.copyEnumerationValues(baseImpl);
         }
 
         // store the pattern list
-        org.apache.xmlbeans.impl.regex.RegularExpression[] patternArray;
-        if (patterns != null)
-            patternArray = (org.apache.xmlbeans.impl.regex.RegularExpression[])patterns.toArray(EMPTY_REGEX_ARRAY);
-        else
-            patternArray = EMPTY_REGEX_ARRAY;
+        RegularExpression[] patternArray = patterns != null ? patterns.toArray(EMPTY_REGEX_ARRAY) : EMPTY_REGEX_ARRAY;
         sImpl.setPatternFacet((patternArray.length > 0 || baseImpl.hasPatternFacet()));
         sImpl.setPatterns(patternArray);
 
         // Check that, if the base type is NOTATION, there is an enumeration facet
         // http://www.w3.org/TR/xmlschema-2/#NOTATION
-        if (baseImpl.getBuiltinTypeCode() == SchemaType.BTC_NOTATION)
-            if (sImpl.getEnumerationValues() == null)
+        if (baseImpl.getBuiltinTypeCode() == SchemaType.BTC_NOTATION) {
+            if (sImpl.getEnumerationValues() == null) {
                 state.recover(XmlErrorCodes.DATATYPE_ENUM_NOTATION, null, restriction);
+            }
+        }
     }
 
-    private static XmlValueRef[] makeValueRefArray(XmlAnySimpleType[] source)
-    {
+    private static XmlValueRef[] makeValueRefArray(XmlAnySimpleType[] source) {
         XmlValueRef[] result = new XmlValueRef[source.length];
-        for (int i = 0; i < result.length; i++)
+        for (int i = 0; i < result.length; i++) {
             result[i] = (source[i] == null ? null : new XmlValueRef(source[i]));
+        }
         return result;
     }
 
-    private static final org.apache.xmlbeans.impl.regex.RegularExpression[] EMPTY_REGEX_ARRAY = new org.apache.xmlbeans.impl.regex.RegularExpression[0];
+    private static final RegularExpression[] EMPTY_REGEX_ARRAY = new RegularExpression[0];
 
-    private static boolean isDiscreteType(SchemaTypeImpl sImpl)
-    {
-        if (sImpl.getFacet(SchemaType.FACET_FRACTION_DIGITS) != null)
+    private static boolean isDiscreteType(SchemaTypeImpl sImpl) {
+        if (sImpl.getFacet(SchemaType.FACET_FRACTION_DIGITS) != null) {
             return true;
+        }
         // BUGBUG: spec is silent on enumerations; they're finite too.
-        switch (sImpl.getPrimitiveType().getBuiltinTypeCode())
-        {
+        switch (sImpl.getPrimitiveType().getBuiltinTypeCode()) {
             case SchemaType.BTC_DATE:
             case SchemaType.BTC_G_YEAR_MONTH:
             case SchemaType.BTC_G_YEAR:
@@ -1042,10 +924,8 @@
         return false;
     }
 
-    private static boolean isNumericPrimitive(SchemaType sImpl)
-    {
-        switch (sImpl.getBuiltinTypeCode())
-        {
+    private static boolean isNumericPrimitive(SchemaType sImpl) {
+        switch (sImpl.getBuiltinTypeCode()) {
             case SchemaType.BTC_DECIMAL:
             case SchemaType.BTC_FLOAT:
             case SchemaType.BTC_DOUBLE:
@@ -1054,106 +934,125 @@
         return false;
     }
 
-    private static int decimalSizeOfType(SchemaTypeImpl sImpl)
-    {
+    private static int decimalSizeOfType(SchemaTypeImpl sImpl) {
         int size = mathematicalSizeOfType(sImpl);
-        
+
         // byte and short are inconvenient, because setByte((byte)4) requires a cast.
         // So use "int" unless you're really a xs:byte, xs:short, or an xs:unsignedByte
         // (the last case is included for alignment with JAXB)
-        
-        if (size == SchemaType.SIZE_BYTE && !XmlByte.type.isAssignableFrom(sImpl))
+
+        if (size == SchemaType.SIZE_BYTE && !XmlByte.type.isAssignableFrom(sImpl)) {
             size = SchemaType.SIZE_SHORT;
-        if (size == SchemaType.SIZE_SHORT && !XmlShort.type.isAssignableFrom(sImpl) && !XmlUnsignedByte.type.isAssignableFrom(sImpl))
+        }
+        if (size == SchemaType.SIZE_SHORT && !XmlShort.type.isAssignableFrom(sImpl) && !XmlUnsignedByte.type.isAssignableFrom(sImpl)) {
             size = SchemaType.SIZE_INT;
-        
+        }
+
         return size;
     }
-    
-    private static int mathematicalSizeOfType(SchemaTypeImpl sImpl)
-    {
-        if (sImpl.getPrimitiveType().getBuiltinTypeCode() != SchemaType.BTC_DECIMAL)
+
+    private static int mathematicalSizeOfType(SchemaTypeImpl sImpl) {
+        if (sImpl.getPrimitiveType().getBuiltinTypeCode() != SchemaType.BTC_DECIMAL) {
             return SchemaType.NOT_DECIMAL;
+        }
 
         if (sImpl.getFacet(SchemaType.FACET_FRACTION_DIGITS) == null ||
-            ((SimpleValue)sImpl.getFacet(SchemaType.FACET_FRACTION_DIGITS)).getBigIntegerValue().signum() != 0)
+            ((SimpleValue) sImpl.getFacet(SchemaType.FACET_FRACTION_DIGITS)).getBigIntegerValue().signum() != 0) {
             return SchemaType.SIZE_BIG_DECIMAL;
+        }
 
         BigInteger min = null;
         BigInteger max = null;
 
-        if (sImpl.getFacet(SchemaType.FACET_MIN_EXCLUSIVE) != null)
-            min = ((SimpleValue)sImpl.getFacet(SchemaType.FACET_MIN_EXCLUSIVE)).getBigIntegerValue(); // .add(BigInteger.ONE);
-        if (sImpl.getFacet(SchemaType.FACET_MIN_INCLUSIVE) != null)
-            min = ((SimpleValue)sImpl.getFacet(SchemaType.FACET_MIN_INCLUSIVE)).getBigIntegerValue();
-        if (sImpl.getFacet(SchemaType.FACET_MAX_INCLUSIVE) != null)
-            max = ((SimpleValue)sImpl.getFacet(SchemaType.FACET_MAX_INCLUSIVE)).getBigIntegerValue();
-        if (sImpl.getFacet(SchemaType.FACET_MAX_EXCLUSIVE) != null)
-            max = ((SimpleValue)sImpl.getFacet(SchemaType.FACET_MAX_EXCLUSIVE)).getBigIntegerValue(); // .subtract(BigInteger.ONE);
+        if (sImpl.getFacet(SchemaType.FACET_MIN_EXCLUSIVE) != null) {
+            min = ((SimpleValue) sImpl.getFacet(SchemaType.FACET_MIN_EXCLUSIVE)).getBigIntegerValue(); // .add(BigInteger.ONE);
+        }
+        if (sImpl.getFacet(SchemaType.FACET_MIN_INCLUSIVE) != null) {
+            min = ((SimpleValue) sImpl.getFacet(SchemaType.FACET_MIN_INCLUSIVE)).getBigIntegerValue();
+        }
+        if (sImpl.getFacet(SchemaType.FACET_MAX_INCLUSIVE) != null) {
+            max = ((SimpleValue) sImpl.getFacet(SchemaType.FACET_MAX_INCLUSIVE)).getBigIntegerValue();
+        }
+        if (sImpl.getFacet(SchemaType.FACET_MAX_EXCLUSIVE) != null) {
+            max = ((SimpleValue) sImpl.getFacet(SchemaType.FACET_MAX_EXCLUSIVE)).getBigIntegerValue(); // .subtract(BigInteger.ONE);
+        }
 
-        if (sImpl.getFacet(SchemaType.FACET_TOTAL_DIGITS) != null)
-        {
+        if (sImpl.getFacet(SchemaType.FACET_TOTAL_DIGITS) != null) {
             BigInteger peg = null;
-            try
-            {
-                BigInteger totalDigits = ((SimpleValue)sImpl.getFacet(SchemaType.FACET_TOTAL_DIGITS)).getBigIntegerValue();
+            try {
+                BigInteger totalDigits = ((SimpleValue) sImpl.getFacet(SchemaType.FACET_TOTAL_DIGITS)).getBigIntegerValue();
 
-                switch (totalDigits.intValue())
-                {
-                    case 0: case 1: case 2:
-                         peg = BigInteger.valueOf(99L); // BYTE size
-                         break;
-                    case 3: case 4:
-                         peg = BigInteger.valueOf(9999L); // SHORT size
-                         break;
-                    case 5: case 6: case 7: case 8: case 9:
-                         peg = BigInteger.valueOf(999999999L); // INT size
-                         break;
-                    case 10: case 11: case 12: case 13: case 14:
-                    case 15: case 16: case 17: case 18:
-                         peg = BigInteger.valueOf(999999999999999999L); // LONG size
-                         break;
+                switch (totalDigits.intValue()) {
+                    case 0:
+                    case 1:
+                    case 2:
+                        peg = BigInteger.valueOf(99L); // BYTE size
+                        break;
+                    case 3:
+                    case 4:
+                        peg = BigInteger.valueOf(9999L); // SHORT size
+                        break;
+                    case 5:
+                    case 6:
+                    case 7:
+                    case 8:
+                    case 9:
+                        peg = BigInteger.valueOf(999999999L); // INT size
+                        break;
+                    case 10:
+                    case 11:
+                    case 12:
+                    case 13:
+                    case 14:
+                    case 15:
+                    case 16:
+                    case 17:
+                    case 18:
+                        peg = BigInteger.valueOf(999999999999999999L); // LONG size
+                        break;
                 }
+            } catch (XmlValueOutOfRangeException ignored) {
             }
-            catch (XmlValueOutOfRangeException e) {}
-            if (peg != null)
-            {
+            if (peg != null) {
                 min = (min == null ? peg.negate() : min.max(peg.negate()));
                 max = (max == null ? peg : max.min(peg));
             }
         }
 
-        if (min != null && max != null)
-        {
+        if (min != null && max != null) {
             // find the largest "absolute value" number that must be dealt with
-            if (min.signum() < 0)
+            if (min.signum() < 0) {
                 min = min.negate().subtract(BigInteger.ONE);
-            if (max.signum() < 0)
+            }
+            if (max.signum() < 0) {
                 max = max.negate().subtract(BigInteger.ONE);
+            }
 
             max = max.max(min);
-            if (max.compareTo(BigInteger.valueOf(Byte.MAX_VALUE)) <= 0)
+            if (max.compareTo(BigInteger.valueOf(Byte.MAX_VALUE)) <= 0) {
                 return SchemaType.SIZE_BYTE;
-            if (max.compareTo(BigInteger.valueOf(Short.MAX_VALUE)) <= 0)
+            }
+            if (max.compareTo(BigInteger.valueOf(Short.MAX_VALUE)) <= 0) {
                 return SchemaType.SIZE_SHORT;
-            if (max.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) <= 0)
+            }
+            if (max.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) <= 0) {
                 return SchemaType.SIZE_INT;
-            if (max.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) <= 0)
+            }
+            if (max.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) <= 0) {
                 return SchemaType.SIZE_LONG;
+            }
         }
 
         return SchemaType.SIZE_BIG_INTEGER;
     }
 
 
-    static void resolveFundamentalFacets(SchemaTypeImpl sImpl)
-    {
+    static void resolveFundamentalFacets(SchemaTypeImpl sImpl) {
         // deal with, isOrdered, isBounded, isFinite, isNumeric
         // also deal with
-        switch (sImpl.getSimpleVariety())
-        {
+        switch (sImpl.getSimpleVariety()) {
             case SchemaType.ATOMIC:
-                SchemaTypeImpl baseImpl = (SchemaTypeImpl)sImpl.getBaseType();
+                SchemaTypeImpl baseImpl = (SchemaTypeImpl) sImpl.getBaseType();
                 sImpl.setOrdered(baseImpl.ordered());
                 sImpl.setBounded(
                     (sImpl.getFacet(SchemaType.FACET_MIN_EXCLUSIVE) != null ||
@@ -1163,7 +1062,7 @@
                 sImpl.setFinite(baseImpl.isFinite() ||
                                 sImpl.isBounded() && isDiscreteType(sImpl));
                 sImpl.setNumeric(baseImpl.isNumeric() ||
-                                isNumericPrimitive(sImpl.getPrimitiveType()));
+                                 isNumericPrimitive(sImpl.getPrimitiveType()));
                 sImpl.setDecimalSize(decimalSizeOfType(sImpl));
                 break;
             case SchemaType.UNION:
@@ -1173,16 +1072,19 @@
                 boolean isFinite = true;
                 boolean isNumeric = true;
                 // ordered if any is ordered, bounded if all are bounded.
-                for (int i = 0; i < mTypes.length; i++)
-                {
-                    if (mTypes[i].ordered() != SchemaType.UNORDERED)
+                for (SchemaType mType : mTypes) {
+                    if (mType.ordered() != SchemaType.UNORDERED) {
                         ordered = SchemaType.PARTIAL_ORDER;
-                    if (!mTypes[i].isBounded())
+                    }
+                    if (!mType.isBounded()) {
                         isBounded = false;
-                    if (!mTypes[i].isFinite())
+                    }
+                    if (!mType.isFinite()) {
                         isFinite = false;
-                    if (!mTypes[i].isNumeric())
+                    }
+                    if (!mType.isNumeric()) {
                         isNumeric = false;
+                    }
                 }
                 sImpl.setOrdered(ordered);
                 sImpl.setBounded(isBounded);
@@ -1194,7 +1096,7 @@
                 sImpl.setOrdered(SchemaType.UNORDERED);
                 // BUGBUG: the schema spec is wrong here: MIN_LENGTH is not needed, beause len >=0
                 sImpl.setBounded(sImpl.getFacet(SchemaType.FACET_LENGTH) != null ||
-                    sImpl.getFacet(SchemaType.FACET_MAX_LENGTH) != null);
+                                 sImpl.getFacet(SchemaType.FACET_MAX_LENGTH) != null);
                 // BUGBUG: the schema spec is wrong here: finite cardinality requires item type is finite
                 sImpl.setFinite(sImpl.getListItemType().isFinite() && sImpl.isBounded());
                 sImpl.setNumeric(false);
@@ -1203,16 +1105,17 @@
         }
     }
 
-    private static class CodeForNameEntry
-    {
-        CodeForNameEntry(QName name, int code)
-            { this.name = name; this.code = code; }
+    private static class CodeForNameEntry {
+        CodeForNameEntry(QName name, int code) {
+            this.name = name;
+            this.code = code;
+        }
+
         public QName name;
         public int code;
     }
 
-    private static CodeForNameEntry[] facetCodes = new CodeForNameEntry[]
-    {
+    private static final CodeForNameEntry[] facetCodes = {
         new CodeForNameEntry(QNameHelper.forLNS("length", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_LENGTH),
         new CodeForNameEntry(QNameHelper.forLNS("minLength", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_MIN_LENGTH),
         new CodeForNameEntry(QNameHelper.forLNS("maxLength", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_MAX_LENGTH),
@@ -1227,21 +1130,17 @@
         new CodeForNameEntry(QNameHelper.forLNS("fractionDigits", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_FRACTION_DIGITS),
     };
 
-    private static final Map facetCodeMap = buildFacetCodeMap();
+    private static final Map<QName, Integer> facetCodeMap = buildFacetCodeMap();
 
-    private static Map buildFacetCodeMap()
-    {
-        Map result = new HashMap();
-        for (int i = 0; i < facetCodes.length; i++)
-            result.put(facetCodes[i].name,  new Integer(facetCodes[i].code));
+    private static Map<QName, Integer> buildFacetCodeMap() {
+        Map<QName, Integer> result = new HashMap<>();
+        for (CodeForNameEntry facetCode : facetCodes) {
+            result.put(facetCode.name, facetCode.code);
+        }
         return result;
     }
 
-    private static int translateFacetCode(QName name)
-    {
-        Integer result = ((Integer)facetCodeMap.get(name));
-        if (result == null)
-            return -1;
-        return result.intValue();
+    private static int translateFacetCode(QName name) {
+        return facetCodeMap.getOrDefault(name, -1);
     }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscState.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscState.java
index 570ca18..f9227c9 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/StscState.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscState.java
@@ -611,7 +611,7 @@
 
     private static String crunchName(QName name) {
         // lowercase, and drop namespace.
-        return name.getLocalPart().toLowerCase();
+        return name.getLocalPart().toLowerCase(Locale.ROOT);
     }
 
     void addSpelling(QName name, SchemaComponent comp) {
@@ -1269,9 +1269,9 @@
                     expected,
                     expectedName,
                     found,
-                    (foundName == null ? new Integer(0) : new Integer(1)),
+                    (foundName == null ? 0 : 1),
                     foundName,
-                    (sourceName == null ? new Integer(0) : new Integer(1)),
+                    (sourceName == null ? 0 : 1),
                     sourceName
                 },
                 loc);
diff --git a/src/main/java/org/apache/xmlbeans/impl/soap/FactoryFinder.java b/src/main/java/org/apache/xmlbeans/impl/soap/FactoryFinder.java
index 3330228..b5798a4 100644
--- a/src/main/java/org/apache/xmlbeans/impl/soap/FactoryFinder.java
+++ b/src/main/java/org/apache/xmlbeans/impl/soap/FactoryFinder.java
@@ -15,15 +15,12 @@
 
 package org.apache.xmlbeans.impl.soap;
 
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-
-import java.util.Properties;
 import org.apache.xmlbeans.SystemProperties;
 
+import java.io.*;
+import java.nio.charset.StandardCharsets;
+import java.util.Properties;
+
 /**
  * This class is used to locate factory classes for javax.xml.soap.
  * It has package scope since it is not part of JAXM and should not
@@ -38,7 +35,7 @@
      * @throws SOAPException
      */
     private static Object newInstance(String factoryClassName) throws SOAPException {
-        ClassLoader classloader = null;
+        ClassLoader classloader;
         try {
             classloader = Thread.currentThread().getContextClassLoader();
         } catch (Exception exception) {
@@ -52,13 +49,14 @@
             } else {
                 try {
                     factory = classloader.loadClass(factoryClassName);
-                } catch (ClassNotFoundException cnfe) {}
+                } catch (ClassNotFoundException ignored) {
+                }
             }
             if (factory == null) {
                 classloader = FactoryFinder.class.getClassLoader();
                 factory = classloader.loadClass(factoryClassName);
             }
-            return factory.newInstance();
+            return factory.getDeclaredConstructor().newInstance();
         } catch (ClassNotFoundException classnotfoundexception) {
             throw new SOAPException("Provider " + factoryClassName + " not found", classnotfoundexception);
         } catch (Exception exception) {
@@ -81,7 +79,8 @@
             if (factoryClassName != null) {
                 return newInstance(factoryClassName);
             }
-        } catch (SecurityException securityexception) {}
+        } catch (SecurityException ignored) {
+        }
 
         try {
             String propertiesFileName = SystemProperties.getProperty("java.home")
@@ -96,21 +95,23 @@
                 String factoryClassName = properties.getProperty(factoryPropertyName);
                 return newInstance(factoryClassName);
             }
-        } catch (Exception exception1) {}
+        } catch (Exception ignored) {
+        }
 
         String factoryResource = "META-INF/services/" + factoryPropertyName;
 
         try {
             InputStream inputstream = getResource(factoryResource);
             if (inputstream != null) {
-                BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(inputstream, "UTF-8"));
+                BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(inputstream, StandardCharsets.UTF_8));
                 String factoryClassName = bufferedreader.readLine();
                 bufferedreader.close();
                 if ((factoryClassName != null) && !"".equals(factoryClassName)) {
                     return newInstance(factoryClassName);
                 }
             }
-        } catch (Exception exception2) {}
+        } catch (Exception ignored) {
+        }
 
         if (defaultFactoryClassName == null) {
             throw new SOAPException("Provider for " + factoryPropertyName + " cannot be found", null);
@@ -129,15 +130,16 @@
      * <code>getResourceAsStream()</code> on
      * <code>FactoryFinder.class.getClassLoader()</code>.
      *
-     * @param factoryResource  the resource name
-     * @return  an InputStream that can be used to read that resource, or
-     *              <code>null</code> if the resource could not be resolved
+     * @param factoryResource the resource name
+     * @return an InputStream that can be used to read that resource, or
+     * <code>null</code> if the resource could not be resolved
      */
     private static InputStream getResource(String factoryResource) {
         ClassLoader classloader = null;
         try {
             classloader = Thread.currentThread().getContextClassLoader();
-        } catch (SecurityException securityexception) {}
+        } catch (SecurityException ignored) {
+        }
 
         InputStream inputstream;
         if (classloader == null) {
diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Locale.java b/src/main/java/org/apache/xmlbeans/impl/store/Locale.java
index c6aa984..8376ac0 100755
--- a/src/main/java/org/apache/xmlbeans/impl/store/Locale.java
+++ b/src/main/java/org/apache/xmlbeans/impl/store/Locale.java
@@ -958,7 +958,7 @@
                     String attrName = a.getNodeName();
                     String attrValue = a.getNodeValue();
 
-                    if (attrName.toLowerCase().startsWith("xmlns")) {
+                    if (attrName.toLowerCase(java.util.Locale.ROOT).startsWith("xmlns")) {
                         if (attrName.length() == 5) {
                             context.xmlns(null, attrValue);
                         } else {
@@ -1728,7 +1728,7 @@
 
         for (String prefix : namespaces.keySet()) {
             // Usually, this is the predefined xml namespace
-            if (!prefix.toLowerCase().startsWith("xml")) {
+            if (!prefix.toLowerCase(java.util.Locale.ROOT).startsWith("xml")) {
                 if (c.namespaceForPrefix(prefix, false) == null) {
                     c.push();
 
diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java b/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java
index ce42f7a..082eb62 100644
--- a/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java
+++ b/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java
@@ -1494,7 +1494,7 @@
         // Sanitize the suggestion.
 
         if (suggestion != null &&
-            (suggestion.length() == 0 || suggestion.toLowerCase().startsWith("xml") ||
+            (suggestion.length() == 0 || suggestion.toLowerCase(java.util.Locale.ROOT).startsWith("xml") ||
              base.findXmlnsForPrefix(suggestion) != null)) {
             suggestion = null;
         }
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 041cf9e..0ab9824 100644
--- a/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCompiler.java
+++ b/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCompiler.java
@@ -30,6 +30,7 @@
 
 import java.io.File;
 import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
 import java.net.URI;
 import java.net.URL;
 import java.util.*;
@@ -159,7 +160,7 @@
         if (codePrinterClass != null) {
             try {
                 codePrinter = (SchemaCodePrinter)
-                    Class.forName(codePrinterClass).newInstance();
+                    Class.forName(codePrinterClass).getDeclaredConstructor().newInstance();
             } catch (Exception e) {
                 System.err.println
                     ("Failed to load SchemaCodePrinter class " +
@@ -1050,12 +1051,12 @@
             while (i.hasNext()) {
                 Extension extension = i.next();
                 try {
-                    sce = (SchemaCompilerExtension) extension.getClassName().newInstance();
-                } catch (InstantiationException e) {
+                    sce = (SchemaCompilerExtension) extension.getClassName().getDeclaredConstructor().newInstance();
+                } catch (NoSuchMethodException | InstantiationException e) {
                     System.out.println("UNABLE to instantiate schema compiler extension:" + extension.getClassName().getName());
                     System.out.println("EXTENSION Class was not run");
                     break;
-                } catch (IllegalAccessException e) {
+                } catch (InvocationTargetException | IllegalAccessException e) {
                     System.out.println("ILLEGAL ACCESS Exception when attempting to instantiate schema compiler extension: " + extension.getClassName().getName());
                     System.out.println("EXTENSION Class was not run");
                     break;
diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/XMLBean.java b/src/main/java/org/apache/xmlbeans/impl/tool/XMLBean.java
index bd7dd10..337a47a 100644
--- a/src/main/java/org/apache/xmlbeans/impl/tool/XMLBean.java
+++ b/src/main/java/org/apache/xmlbeans/impl/tool/XMLBean.java
@@ -309,7 +309,7 @@
         for (String s : paths) {
             int dot = s.lastIndexOf('.');
             if (dot > -1) {
-                String possExt = s.substring(dot).toLowerCase();
+                String possExt = s.substring(dot).toLowerCase(Locale.ROOT);
                 Set<File> set = _extRouter.get(possExt);
 
                 if (set != null) {
diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/XsbDumper.java b/src/main/java/org/apache/xmlbeans/impl/tool/XsbDumper.java
index 3aa4205..7d85166 100644
--- a/src/main/java/org/apache/xmlbeans/impl/tool/XsbDumper.java
+++ b/src/main/java/org/apache/xmlbeans/impl/tool/XsbDumper.java
@@ -45,22 +45,20 @@
             return;
         }
 
-        for (int i = 0; i < args.length; i++) {
-            dump(new File(args[i]), true);
+        for (String arg : args) {
+            dump(new File(arg), true);
         }
     }
 
     private static void dump(File file, boolean force) {
         if (file.isDirectory()) {
             File[] files = file.listFiles(
-                new FileFilter() {
-                    public boolean accept(File file) {
-                        return file.isDirectory() || file.isFile() && file.getName().endsWith(".xsb");
-                    }
-                }
+                file1 -> file1.isDirectory() || file1.isFile() && file1.getName().endsWith(".xsb")
             );
-            for (int i = 0; i < files.length; i++) {
-                dump(files[i], false);
+            if (files != null) {
+                for (File value : files) {
+                    dump(value, false);
+                }
             }
         } else if (file.getName().endsWith(".jar") || file.getName().endsWith(".zip")) {
             dumpZip(file);
@@ -78,9 +76,9 @@
     public static void dumpZip(File file) {
         try {
             ZipFile zipFile = new ZipFile(file);
-            Enumeration e = zipFile.entries();
+            Enumeration<? extends ZipEntry> e = zipFile.entries();
             while (e.hasMoreElements()) {
-                ZipEntry entry = (ZipEntry) e.nextElement();
+                ZipEntry entry = e.nextElement();
                 if (entry.getName().endsWith(".xsb")) {
                     System.out.println(entry.getName());
                     dump(zipFile.getInputStream(entry), "  ");
@@ -120,28 +118,20 @@
         flush();
     }
 
-    void emit() {
-        _out.println();
-        flush();
-    }
-
     void error(Exception e) {
         _out.println(e.toString());
         flush();
-        IllegalStateException e2 = new IllegalStateException(e.getMessage());
-        e2.initCause(e);
-        throw e2;
+        throw new IllegalStateException(e.getMessage(), e);
     }
 
     void error(String str) {
         _out.println(str);
         flush();
-        IllegalStateException e2 = new IllegalStateException(str);
-        throw e2;
+        throw new IllegalStateException(str);
     }
 
     private String _indent;
-    private PrintStream _out;
+    private final PrintStream _out;
 
     void indent() {
         _indent += "  ";
@@ -485,8 +475,8 @@
 
 
     class StringPool {
-        private List intsToStrings = new ArrayList();
-        private Map stringsToInts = new HashMap();
+        private final List<String> intsToStrings = new ArrayList<>();
+        private final Map<String, Integer> stringsToInts = new HashMap<>();
 
         StringPool() {
             intsToStrings.add(null);
@@ -496,20 +486,20 @@
             if (code == 0) {
                 return null;
             }
-            return (String) intsToStrings.get(code);
+            return intsToStrings.get(code);
         }
 
         int codeForString(String str) {
             if (str == null) {
                 return 0;
             }
-            Integer result = (Integer) stringsToInts.get(str);
+            Integer result = stringsToInts.get(str);
             if (result == null) {
-                result = new Integer(intsToStrings.size());
+                result = intsToStrings.size();
                 intsToStrings.add(str);
                 stringsToInts.put(str, result);
             }
-            return result.intValue();
+            return result;
         }
 
         void readFrom(DataInputStream input) {
@@ -1313,19 +1303,19 @@
     QNameSet readQNameSet() {
         int flag = readShort();
 
-        Set uriSet = new HashSet();
+        Set<String> uriSet = new HashSet<>();
         int uriCount = readShort();
         for (int i = 0; i < uriCount; i++) {
             uriSet.add(readString());
         }
 
-        Set qnameSet1 = new HashSet();
+        Set<QName> qnameSet1 = new HashSet<>();
         int qncount1 = readShort();
         for (int i = 0; i < qncount1; i++) {
             qnameSet1.add(readQName());
         }
 
-        Set qnameSet2 = new HashSet();
+        Set<QName> qnameSet2 = new HashSet<>();
         int qncount2 = readShort();
         for (int i = 0; i < qncount2; i++) {
             qnameSet2.add(readQName());
@@ -1364,8 +1354,6 @@
         return new BigInteger(result);
     }
 
-    static final byte[] SINGLE_ZERO_BYTE = new byte[]{(byte) 0};
-
     private int _majorver;
     private int _minorver;
     private int _releaseno;